bl-trtc-callkit-vue 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,169 @@
1
+ (function(wn,Ie){typeof exports=="object"&&typeof module<"u"?Ie(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],Ie):(wn=typeof globalThis<"u"?globalThis:wn||self,Ie(wn.BlTrtcCallkitVue={},wn.Vue))})(this,(function(wn,Ie){"use strict";var xE=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function uP(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var Ru={exports:{}},dP=Ru.exports,UE;function hP(){return UE||(UE=1,(function(a,u){(function(d,p){a.exports=p()})(dP,function(){function d(e,t){return t.forEach(function(i){i&&typeof i!="string"&&!Array.isArray(i)&&Object.keys(i).forEach(function(r){if(r!=="default"&&!(r in e)){var n=Object.getOwnPropertyDescriptor(i,r);Object.defineProperty(e,r,n.get?n:{enumerable:!0,get:function(){return i[r]}})}})}),Object.freeze(e)}var p=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof xE<"u"?xE:typeof self<"u"?self:{};function v(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var g=function(e){return e&&e.Math===Math&&e},y=g(typeof globalThis=="object"&&globalThis)||g(typeof window=="object"&&window)||g(typeof self=="object"&&self)||g(typeof p=="object"&&p)||g(typeof p=="object"&&p)||(function(){return this})()||Function("return this")(),I={},S=function(e){try{return!!e()}catch{return!0}},E=!S(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),R=!S(function(){var e=(function(){}).bind();return typeof e!="function"||e.hasOwnProperty("prototype")}),k=R,N=Function.prototype.call,A=k?N.bind(N):function(){return N.apply(N,arguments)},O={},M={}.propertyIsEnumerable,w=Object.getOwnPropertyDescriptor,U=w&&!M.call({1:2},1);O.f=U?function(e){var t=w(this,e);return!!t&&t.enumerable}:M;var L,V,F=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},q=R,K=Function.prototype,z=K.call,J=q&&K.bind.bind(z,z),X=q?J:function(e){return function(){return z.apply(e,arguments)}},W=X,Q=W({}.toString),ge=W("".slice),ne=function(e){return ge(Q(e),8,-1)},Te=S,ke=ne,Ve=Object,We=X("".split),we=Te(function(){return!Ve("z").propertyIsEnumerable(0)})?function(e){return ke(e)==="String"?We(e,""):Ve(e)}:Ve,tt=function(e){return e==null},Nt=tt,le=TypeError,se=function(e){if(Nt(e))throw new le("Can't call method on "+e);return e},oe=we,ue=se,bt=function(e){return oe(ue(e))},ci=typeof document=="object"&&document.all,$e=ci===void 0&&ci!==void 0?function(e){return typeof e=="function"||e===ci}:function(e){return typeof e=="function"},Pi=$e,Et=function(e){return typeof e=="object"?e!==null:Pi(e)},en=y,Fi=$e,Mt=function(e,t){return arguments.length<2?(i=en[e],Fi(i)?i:void 0):en[e]&&en[e][t];var i},Lt=X({}.isPrototypeOf),tn=y.navigator,Or=tn&&tn.userAgent,ae=Or?String(Or):"",ye=y,ze=ae,Qe=ye.process,Le=ye.Deno,Yt=Qe&&Qe.versions||Le&&Le.version,Hn=Yt&&Yt.v8;Hn&&(V=(L=Hn.split("."))[0]>0&&L[0]<4?1:+(L[0]+L[1])),!V&&ze&&(!(L=ze.match(/Edge\/(\d+)/))||L[1]>=74)&&(L=ze.match(/Chrome\/(\d+)/))&&(V=+L[1]);var Ei=V,vl=Ei,Wn=S,Hs=y.String,Xu=!!Object.getOwnPropertySymbols&&!Wn(function(){var e=Symbol("symbol detection");return!Hs(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&vl&&vl<41}),El=Xu&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Qu=Mt,Gn=$e,Ws=Lt,jm=Object,ja=El?function(e){return typeof e=="symbol"}:function(e){var t=Qu("Symbol");return Gn(t)&&Ws(t.prototype,jm(e))},Zu=String,jn=function(e){try{return Zu(e)}catch{return"Object"}},zm=$e,$u=jn,Km=TypeError,Oi=function(e){if(zm(e))return e;throw new Km($u(e)+" is not a function")},rn=Oi,Jm=tt,zn=function(e,t){var i=e[t];return Jm(i)?void 0:rn(i)},yl=A,Tl=$e,Sl=Et,ed=TypeError,td={exports:{}},id=y,rd=Object.defineProperty,Il=function(e,t){try{rd(id,e,{value:t,configurable:!0,writable:!0})}catch{id[e]=t}return t},nd=y,Gs=Il,Rl="__core-js_shared__",WT=td.exports=nd[Rl]||Gs(Rl,{});(WT.versions||(WT.versions=[])).push({version:"3.47.0",mode:"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru), 2025 CoreJS Company (core-js.io)",license:"https://github.com/zloirock/core-js/blob/v3.47.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Ym=td.exports,GT=Ym,qm=function(e,t){return GT[e]||(GT[e]=t||{})},_M=se,gM=Object,pr=function(e){return gM(_M(e))},vM=pr,EM=X({}.hasOwnProperty),ui=Object.hasOwn||function(e,t){return EM(vM(e),t)},yM=X,TM=0,SM=Math.random(),IM=yM(1.1.toString),Xm=function(e){return"Symbol("+(e===void 0?"":e)+")_"+IM(++TM+SM,36)},RM=qm,jT=ui,AM=Xm,bM=Xu,CM=El,za=y.Symbol,Qm=RM("wks"),kM=CM?za.for||za:za&&za.withoutSetter||AM,xt=function(e){return jT(Qm,e)||(Qm[e]=bM&&jT(za,e)?za[e]:kM("Symbol."+e)),Qm[e]},wM=A,zT=Et,KT=ja,DM=zn,NM=function(e,t){var i,r;if(t==="string"&&Tl(i=e.toString)&&!Sl(r=yl(i,e))||Tl(i=e.valueOf)&&!Sl(r=yl(i,e))||t!=="string"&&Tl(i=e.toString)&&!Sl(r=yl(i,e)))return r;throw new ed("Can't convert object to primitive value")},PM=TypeError,OM=xt("toPrimitive"),JT=function(e,t){if(!zT(e)||KT(e))return e;var i,r=DM(e,OM);if(r){if(t===void 0&&(t="default"),i=wM(r,e,t),!zT(i)||KT(i))return i;throw new PM("Can't convert object to primitive value")}return t===void 0&&(t="number"),NM(e,t)},MM=JT,LM=ja,Zm=function(e){var t=MM(e,"string");return LM(t)?t:t+""},YT=Et,$m=y.document,xM=YT($m)&&YT($m.createElement),sd=function(e){return xM?$m.createElement(e):{}},UM=sd,qT=!E&&!S(function(){return Object.defineProperty(UM("div"),"a",{get:function(){return 7}}).a!==7}),VM=E,FM=A,BM=O,HM=F,WM=bt,GM=Zm,jM=ui,zM=qT,XT=Object.getOwnPropertyDescriptor;I.f=VM?XT:function(e,t){if(e=WM(e),t=GM(t),zM)try{return XT(e,t)}catch{}if(jM(e,t))return HM(!FM(BM.f,e,t),e[t])};var Xi={},QT=E&&S(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),KM=Et,JM=String,YM=TypeError,yi=function(e){if(KM(e))return e;throw new YM(JM(e)+" is not an object")},qM=E,XM=qT,QM=QT,ad=yi,ZT=Zm,ZM=TypeError,ef=Object.defineProperty,$M=Object.getOwnPropertyDescriptor,tf="enumerable",rf="configurable",nf="writable";Xi.f=qM?QM?function(e,t,i){if(ad(e),t=ZT(t),ad(i),typeof e=="function"&&t==="prototype"&&"value"in i&&nf in i&&!i[nf]){var r=$M(e,t);r&&r[nf]&&(e[t]=i.value,i={configurable:rf in i?i[rf]:r[rf],enumerable:tf in i?i[tf]:r[tf],writable:!1})}return ef(e,t,i)}:ef:function(e,t,i){if(ad(e),t=ZT(t),ad(i),XM)try{return ef(e,t,i)}catch{}if("get"in i||"set"in i)throw new ZM("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var eL=Xi,tL=F,nn=E?function(e,t,i){return eL.f(e,t,tL(1,i))}:function(e,t,i){return e[t]=i,e},$T={exports:{}},sf=E,iL=ui,eS=Function.prototype,rL=sf&&Object.getOwnPropertyDescriptor,tS=iL(eS,"name"),Ka={PROPER:tS&&(function(){}).name==="something",CONFIGURABLE:tS&&(!sf||sf&&rL(eS,"name").configurable)},nL=$e,af=Ym,sL=X(Function.toString);nL(af.inspectSource)||(af.inspectSource=function(e){return sL(e)});var od,Al,ld,of=af.inspectSource,aL=$e,iS=y.WeakMap,oL=aL(iS)&&/native code/.test(String(iS)),lL=Xm,rS=qm("keys"),lf=function(e){return rS[e]||(rS[e]=lL(e))},cf={},cL=oL,nS=y,uL=Et,dL=nn,uf=ui,df=Ym,hL=lf,pL=cf,sS="Object already initialized",hf=nS.TypeError,mL=nS.WeakMap;if(cL||df.state){var Mr=df.state||(df.state=new mL);Mr.get=Mr.get,Mr.has=Mr.has,Mr.set=Mr.set,od=function(e,t){if(Mr.has(e))throw new hf(sS);return t.facade=e,Mr.set(e,t),t},Al=function(e){return Mr.get(e)||{}},ld=function(e){return Mr.has(e)}}else{var Ja=hL("state");pL[Ja]=!0,od=function(e,t){if(uf(e,Ja))throw new hf(sS);return t.facade=e,dL(e,Ja,t),t},Al=function(e){return uf(e,Ja)?e[Ja]:{}},ld=function(e){return uf(e,Ja)}}var Mi={set:od,get:Al,has:ld,enforce:function(e){return ld(e)?Al(e):od(e,{})},getterFor:function(e){return function(t){var i;if(!uL(t)||(i=Al(t)).type!==e)throw new hf("Incompatible receiver, "+e+" required");return i}}},pf=X,fL=S,_L=$e,cd=ui,mf=E,gL=Ka.CONFIGURABLE,vL=of,EL=Mi.enforce,yL=Mi.get,aS=String,ud=Object.defineProperty,TL=pf("".slice),SL=pf("".replace),IL=pf([].join),RL=mf&&!fL(function(){return ud(function(){},"length",{value:8}).length!==8}),AL=String(String).split("String"),bL=$T.exports=function(e,t,i){TL(aS(t),0,7)==="Symbol("&&(t="["+SL(aS(t),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!cd(e,"name")||gL&&e.name!==t)&&(mf?ud(e,"name",{value:t,configurable:!0}):e.name=t),RL&&i&&cd(i,"arity")&&e.length!==i.arity&&ud(e,"length",{value:i.arity});try{i&&cd(i,"constructor")&&i.constructor?mf&&ud(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch{}var r=EL(e);return cd(r,"source")||(r.source=IL(AL,typeof t=="string"?t:"")),e};Function.prototype.toString=bL(function(){return _L(this)&&yL(this).source||vL(this)},"toString");var oS=$T.exports,CL=$e,kL=Xi,wL=oS,DL=Il,Qi=function(e,t,i,r){r||(r={});var n=r.enumerable,s=r.name!==void 0?r.name:t;if(CL(i)&&wL(i,s,r),r.global)n?e[t]=i:DL(t,i);else{try{r.unsafe?e[t]&&(n=!0):delete e[t]}catch{}n?e[t]=i:kL.f(e,t,{value:i,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},dd={},NL=Math.ceil,PL=Math.floor,OL=Math.trunc||function(e){var t=+e;return(t>0?PL:NL)(t)},ML=OL,Kn=function(e){var t=+e;return t!=t||t===0?0:ML(t)},LL=Kn,xL=Math.max,UL=Math.min,hd=function(e,t){var i=LL(e);return i<0?xL(i+t,0):UL(i,t)},VL=Kn,FL=Math.min,js=function(e){var t=VL(e);return t>0?FL(t,9007199254740991):0},BL=js,Lr=function(e){return BL(e.length)},HL=bt,WL=hd,GL=Lr,lS=function(e){return function(t,i,r){var n=HL(t),s=GL(n);if(s===0)return!e&&-1;var o,l=WL(r,s);if(e&&i!=i){for(;s>l;)if((o=n[l++])!=o)return!0}else for(;s>l;l++)if((e||l in n)&&n[l]===i)return e||l||0;return!e&&-1}},cS={includes:lS(!0),indexOf:lS(!1)},ff=ui,jL=bt,zL=cS.indexOf,KL=cf,uS=X([].push),dS=function(e,t){var i,r=jL(e),n=0,s=[];for(i in r)!ff(KL,i)&&ff(r,i)&&uS(s,i);for(;t.length>n;)ff(r,i=t[n++])&&(~zL(s,i)||uS(s,i));return s},_f=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],JL=dS,YL=_f.concat("length","prototype");dd.f=Object.getOwnPropertyNames||function(e){return JL(e,YL)};var gf={};gf.f=Object.getOwnPropertySymbols;var qL=Mt,XL=dd,QL=gf,ZL=yi,$L=X([].concat),e3=qL("Reflect","ownKeys")||function(e){var t=XL.f(ZL(e)),i=QL.f;return i?$L(t,i(e)):t},hS=ui,t3=e3,i3=I,r3=Xi,vf=function(e,t,i){for(var r=t3(t),n=r3.f,s=i3.f,o=0;o<r.length;o++){var l=r[o];hS(e,l)||i&&hS(i,l)||n(e,l,s(t,l))}},n3=S,s3=$e,a3=/#|\.prototype\./,bl=function(e,t){var i=l3[o3(e)];return i===u3||i!==c3&&(s3(t)?n3(t):!!t)},o3=bl.normalize=function(e){return String(e).replace(a3,".").toLowerCase()},l3=bl.data={},c3=bl.NATIVE="N",u3=bl.POLYFILL="P",Ef=bl,pd=y,d3=I.f,h3=nn,p3=Qi,m3=Il,f3=vf,_3=Ef,It=function(e,t){var i,r,n,s,o,l=e.target,c=e.global,h=e.stat;if(i=c?pd:h?pd[l]||m3(l,{}):pd[l]&&pd[l].prototype)for(r in t){if(s=t[r],n=e.dontCallGetSet?(o=d3(i,r))&&o.value:i[r],!_3(c?r:l+(h?".":"#")+r,e.forced)&&n!==void 0){if(typeof s==typeof n)continue;f3(s,n)}(e.sham||n&&n.sham)&&h3(s,"sham",!0),p3(i,r,s,e)}},pS={};pS[xt("toStringTag")]="z";var g3=String(pS)==="[object z]",v3=$e,md=ne,E3=xt("toStringTag"),y3=Object,T3=md((function(){return arguments})())==="Arguments",Jn=g3?md:function(e){var t,i,r;return e===void 0?"Undefined":e===null?"Null":typeof(i=(function(n,s){try{return n[s]}catch{}})(t=y3(e),E3))=="string"?i:T3?md(t):(r=md(t))==="Object"&&v3(t.callee)?"Arguments":r},S3=Jn,I3=String,Bi=function(e){if(S3(e)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return I3(e)},mS=oS,R3=Xi,zs=function(e,t,i){return i.get&&mS(i.get,t,{getter:!0}),i.set&&mS(i.set,t,{setter:!0}),R3.f(e,t,i)},A3=It,b3=E,fd=X,C3=ui,k3=$e,w3=Lt,D3=Bi,N3=zs,P3=vf,sn=y.Symbol,Ks=sn&&sn.prototype;if(b3&&k3(sn)&&(!("description"in Ks)||sn().description!==void 0)){var fS={},_d=function(){var e=arguments.length<1||arguments[0]===void 0?void 0:D3(arguments[0]),t=w3(Ks,this)?new sn(e):e===void 0?sn():sn(e);return e===""&&(fS[t]=!0),t};P3(_d,sn),_d.prototype=Ks,Ks.constructor=_d;var O3=String(sn("description detection"))==="Symbol(description detection)",M3=fd(Ks.valueOf),L3=fd(Ks.toString),x3=/^Symbol\((.*)\)[^)]+$/,U3=fd("".replace),V3=fd("".slice);N3(Ks,"description",{configurable:!0,get:function(){var e=M3(this);if(C3(fS,e))return"";var t=L3(e),i=O3?V3(t,7,-1):U3(t,x3,"$1");return i===""?void 0:i}}),A3({global:!0,constructor:!0,forced:!0},{Symbol:_d})}var _S={},F3=dS,B3=_f,gS=Object.keys||function(e){return F3(e,B3)},H3=E,W3=QT,G3=Xi,j3=yi,z3=bt,K3=gS;_S.f=H3&&!W3?Object.defineProperties:function(e,t){j3(e);for(var i,r=z3(t),n=K3(t),s=n.length,o=0;s>o;)G3.f(e,i=n[o++],r[i]);return e};var gd,vS=Mt("document","documentElement"),J3=yi,Y3=_S,ES=_f,q3=cf,X3=vS,Q3=sd,yf="prototype",Tf="script",yS=lf("IE_PROTO"),Sf=function(){},TS=function(e){return"<"+Tf+">"+e+"</"+Tf+">"},SS=function(e){e.write(TS("")),e.close();var t=e.parentWindow.Object;return e=null,t},vd=function(){try{gd=new ActiveXObject("htmlfile")}catch{}vd=typeof document<"u"?document.domain&&gd?SS(gd):(function(){var t,i=Q3("iframe"),r="java"+Tf+":";return i.style.display="none",X3.appendChild(i),i.src=String(r),(t=i.contentWindow.document).open(),t.write(TS("document.F=Object")),t.close(),t.F})():SS(gd);for(var e=ES.length;e--;)delete vd[yf][ES[e]];return vd()};q3[yS]=!0;var Ya=Object.create||function(e,t){var i;return e!==null?(Sf[yf]=J3(e),i=new Sf,Sf[yf]=null,i[yS]=e):i=vd(),t===void 0?i:Y3.f(i,t)},Z3=xt,$3=Ya,ex=Xi.f,If=Z3("unscopables"),Rf=Array.prototype;Rf[If]===void 0&&ex(Rf,If,{configurable:!0,value:$3(null)});var IS=function(e){Rf[If][e]=!0},tx=cS.includes,ix=IS;It({target:"Array",proto:!0,forced:S(function(){return!Array(1).includes()})},{includes:function(e){return tx(this,e,arguments.length>1?arguments[1]:void 0)}}),ix("includes");var Js,RS,AS,Cl={},rx=!S(function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}),nx=ui,sx=$e,ax=pr,ox=rx,bS=lf("IE_PROTO"),Af=Object,lx=Af.prototype,Ed=ox?Af.getPrototypeOf:function(e){var t=ax(e);if(nx(t,bS))return t[bS];var i=t.constructor;return sx(i)&&t instanceof i?i.prototype:t instanceof Af?lx:null},cx=S,ux=$e,dx=Et,CS=Ed,hx=Qi,bf=xt("iterator"),kS=!1;[].keys&&("next"in(AS=[].keys())?(RS=CS(CS(AS)))!==Object.prototype&&(Js=RS):kS=!0);var px=!dx(Js)||cx(function(){var e={};return Js[bf].call(e)!==e});px&&(Js={}),ux(Js[bf])||hx(Js,bf,function(){return this});var Cf={IteratorPrototype:Js,BUGGY_SAFARI_ITERATORS:kS},mx=Xi.f,fx=ui,wS=xt("toStringTag"),Ys=function(e,t,i){e&&!i&&(e=e.prototype),e&&!fx(e,wS)&&mx(e,wS,{configurable:!0,value:t})},_x=Cf.IteratorPrototype,gx=Ya,vx=F,Ex=Ys,yx=Cl,Tx=function(){return this},DS=function(e,t,i,r){var n=t+" Iterator";return e.prototype=gx(_x,{next:vx(+!r,i)}),Ex(e,n,!1),yx[n]=Tx,e},Sx=X,Ix=Oi,Rx=Et,Ax=function(e){return Rx(e)||e===null},bx=String,Cx=TypeError,kx=function(e,t,i){try{return Sx(Ix(Object.getOwnPropertyDescriptor(e,t)[i]))}catch{}},wx=Et,Dx=se,Nx=function(e){if(Ax(e))return e;throw new Cx("Can't set "+bx(e)+" as a prototype")},qa=Object.setPrototypeOf||("__proto__"in{}?(function(){var e,t=!1,i={};try{(e=kx(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch{}return function(r,n){return Dx(r),Nx(n),wx(r)&&(t?e(r,n):r.__proto__=n),r}})():void 0),Px=It,Ox=A,Mx=$e,Lx=DS,NS=Ed,PS=qa,xx=Ys,Ux=nn,kf=Qi,Vx=Cl,Fx=Ka.PROPER,Bx=Ka.CONFIGURABLE,OS=Cf.IteratorPrototype,yd=Cf.BUGGY_SAFARI_ITERATORS,kl=xt("iterator"),MS="keys",wl="values",LS="entries",Hx=function(){return this},xS=function(e,t,i,r,n,s,o){Lx(i,t,r);var l,c,h,_=function(Y){if(Y===n&&x)return x;if(!yd&&Y&&Y in b)return b[Y];switch(Y){case MS:case wl:case LS:return function(){return new i(this,Y)}}return function(){return new i(this)}},f=t+" Iterator",T=!1,b=e.prototype,C=b[kl]||b["@@iterator"]||n&&b[n],x=!yd&&C||_(n),B=t==="Array"&&b.entries||C;if(B&&(l=NS(B.call(new e)))!==Object.prototype&&l.next&&(NS(l)!==OS&&(PS?PS(l,OS):Mx(l[kl])||kf(l,kl,Hx)),xx(l,f,!0)),Fx&&n===wl&&C&&C.name!==wl&&(Bx?Ux(b,"name",wl):(T=!0,x=function(){return Ox(C,this)})),n)if(c={values:_(wl),keys:s?x:_(MS),entries:_(LS)},o)for(h in c)(yd||T||!(h in b))&&kf(b,h,c[h]);else Px({target:t,proto:!0,forced:yd||T},c);return b[kl]!==x&&kf(b,kl,x,{name:n}),Vx[t]=x,c},wf=function(e,t){return{value:e,done:t}},Wx=bt,Df=IS,US=Cl,VS=Mi,Gx=Xi.f,jx=xS,Td=wf,zx=E,FS="Array Iterator",Kx=VS.set,Jx=VS.getterFor(FS),Yx=jx(Array,"Array",function(e,t){Kx(this,{type:FS,target:Wx(e),index:0,kind:t})},function(){var e=Jx(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,Td(void 0,!0);switch(e.kind){case"keys":return Td(i,!1);case"values":return Td(t[i],!1)}return Td([i,t[i]],!1)},"values"),BS=US.Arguments=US.Array;if(Df("keys"),Df("values"),Df("entries"),zx&&BS.name!=="values")try{Gx(BS,"name",{value:"values"})}catch{}var qx=Oi,Xx=pr,Qx=we,Zx=Lr,HS=TypeError,WS="Reduce of empty array with no initial value",GS=function(e){return function(t,i,r,n){var s=Xx(t),o=Qx(s),l=Zx(s);if(qx(i),l===0&&r<2)throw new HS(WS);var c=e?l-1:0,h=e?-1:1;if(r<2)for(;;){if(c in o){n=o[c],c+=h;break}if(c+=h,e?c<0:l<=c)throw new HS(WS)}for(;e?c>=0:l>c;c+=h)c in o&&(n=i(n,o[c],c,s));return n}},jS={left:GS(!1),right:GS(!0)},$x=S,Sd=function(e,t){var i=[][e];return!!i&&$x(function(){i.call(null,t||function(){return 1},1)})},Dl=y,e4=ae,t4=ne,Id=function(e){return e4.slice(0,e.length)===e},Nf=Id("Bun/")?"BUN":Id("Cloudflare-Workers")?"CLOUDFLARE":Id("Deno/")?"DENO":Id("Node.js/")?"NODE":Dl.Bun&&typeof Bun.version=="string"?"BUN":Dl.Deno&&typeof Deno.version=="object"?"DENO":t4(Dl.process)==="process"?"NODE":Dl.window&&Dl.document?"BROWSER":"REST",Nl=Nf==="NODE",i4=jS.left;It({target:"Array",proto:!0,forced:!Nl&&Ei>79&&Ei<83||!Sd("reduce")},{reduce:function(e){var t=arguments.length;return i4(this,e,t,t>1?arguments[1]:void 0)}});var r4=jS.right;It({target:"Array",proto:!0,forced:!Nl&&Ei>79&&Ei<83||!Sd("reduceRight")},{reduceRight:function(e){return r4(this,e,arguments.length,arguments.length>1?arguments[1]:void 0)}});var n4=ne,zS=Array.isArray||function(e){return n4(e)==="Array"},s4=It,a4=zS,o4=X([].reverse),KS=[1,2];s4({target:"Array",proto:!0,forced:String(KS)===String(KS.reverse())},{reverse:function(){return a4(this)&&(this.length=this.length),o4(this)}});var JS=jn,l4=TypeError,Pl=X([].slice),YS=Pl,c4=Math.floor,Pf=function(e,t){var i=e.length;if(i<8)for(var r,n,s=1;s<i;){for(n=s,r=e[s];n&&t(e[n-1],r)>0;)e[n]=e[--n];n!==s++&&(e[n]=r)}else for(var o=c4(i/2),l=Pf(YS(e,0,o),t),c=Pf(YS(e,o),t),h=l.length,_=c.length,f=0,T=0;f<h||T<_;)e[f+T]=f<h&&T<_?t(l[f],c[T])<=0?l[f++]:c[T++]:f<h?l[f++]:c[T++];return e},Of=Pf,qS=ae.match(/firefox\/(\d+)/i),XS=!!qS&&+qS[1],QS=/MSIE|Trident/.test(ae),ZS=ae.match(/AppleWebKit\/(\d+)\./),$S=!!ZS&&+ZS[1],u4=It,eI=X,d4=Oi,h4=pr,tI=Lr,p4=function(e,t){if(!delete e[t])throw new l4("Cannot delete property "+JS(t)+" of "+JS(e))},iI=Bi,Mf=S,m4=Of,f4=Sd,rI=XS,_4=QS,nI=Ei,sI=$S,Yn=[],aI=eI(Yn.sort),g4=eI(Yn.push),v4=Mf(function(){Yn.sort(void 0)}),E4=Mf(function(){Yn.sort(null)}),y4=f4("sort"),oI=!Mf(function(){if(nI)return nI<70;if(!(rI&&rI>3)){if(_4)return!0;if(sI)return sI<603;var e,t,i,r,n="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:i=3;break;case 68:case 71:i=4;break;default:i=2}for(r=0;r<47;r++)Yn.push({k:t+r,v:i})}for(Yn.sort(function(s,o){return o.v-s.v}),r=0;r<Yn.length;r++)t=Yn[r].k.charAt(0),n.charAt(n.length-1)!==t&&(n+=t);return n!=="DGBEFHACIJK"}});u4({target:"Array",proto:!0,forced:v4||!E4||!y4||!oI},{sort:function(e){e!==void 0&&d4(e);var t=h4(this);if(oI)return e===void 0?aI(t):aI(t,e);var i,r,n=[],s=tI(t);for(r=0;r<s;r++)r in t&&g4(n,t[r]);for(m4(n,(function(o){return function(l,c){return c===void 0?-1:l===void 0?1:o!==void 0?+o(l,c)||0:iI(l)>iI(c)?1:-1}})(e)),i=tI(n),r=0;r<i;)t[r]=n[r++];for(;r<s;)p4(t,r++);return t}});var lI=typeof ArrayBuffer<"u"&&typeof DataView<"u",T4=Qi,cI=function(e,t,i){for(var r in t)T4(e,r,t[r],i);return e},S4=Lt,I4=TypeError,Ol=function(e,t){if(S4(t,e))return e;throw new I4("Incorrect invocation")},R4=Kn,A4=js,b4=RangeError,uI=function(e){if(e===void 0)return 0;var t=R4(e),i=A4(t);if(t!==i)throw new b4("Wrong length or index");return i},C4=Math.sign||function(e){var t=+e;return t===0||t!=t?t:t<0?-1:1},dI=4503599627370496,k4=C4,w4=function(e){return e+dI-dI},D4=Math.abs,N4=function(e,t,i,r){var n=+e,s=D4(n),o=k4(n);if(s<r)return o*w4(s/r/t)*r*t;var l=(1+t/2220446049250313e-31)*s,c=l-(l-s);return c>i||c!=c?1/0*o:o*c},P4=Math.fround||function(e){return N4(e,11920928955078125e-23,34028234663852886e22,11754943508222875e-54)},O4=Array,M4=Math.abs,an=Math.pow,L4=Math.floor,x4=Math.log,U4=Math.LN2,V4={pack:function(e,t,i){var r,n,s,o=O4(i),l=8*i-t-1,c=(1<<l)-1,h=c>>1,_=t===23?an(2,-24)-an(2,-77):0,f=e<0||e===0&&1/e<0?1:0,T=0;for((e=M4(e))!=e||e===1/0?(n=e!=e?1:0,r=c):(r=L4(x4(e)/U4),e*(s=an(2,-r))<1&&(r--,s*=2),(e+=r+h>=1?_/s:_*an(2,1-h))*s>=2&&(r++,s/=2),r+h>=c?(n=0,r=c):r+h>=1?(n=(e*s-1)*an(2,t),r+=h):(n=e*an(2,h-1)*an(2,t),r=0));t>=8;)o[T++]=255&n,n/=256,t-=8;for(r=r<<t|n,l+=t;l>0;)o[T++]=255&r,r/=256,l-=8;return o[T-1]|=128*f,o},unpack:function(e,t){var i,r=e.length,n=8*r-t-1,s=(1<<n)-1,o=s>>1,l=n-7,c=r-1,h=e[c--],_=127&h;for(h>>=7;l>0;)_=256*_+e[c--],l-=8;for(i=_&(1<<-l)-1,_>>=-l,l+=t;l>0;)i=256*i+e[c--],l-=8;if(_===0)_=1-o;else{if(_===s)return i?NaN:h?-1/0:1/0;i+=an(2,t),_-=o}return(h?-1:1)*i*an(2,_-t)}},F4=pr,hI=hd,B4=Lr,pI=function(e){for(var t=F4(this),i=B4(t),r=arguments.length,n=hI(r>1?arguments[1]:void 0,i),s=r>2?arguments[2]:void 0,o=s===void 0?i:hI(s,i);o>n;)t[n++]=e;return t},H4=$e,W4=Et,mI=qa,Lf=function(e,t,i){var r,n;return mI&&H4(r=t.constructor)&&r!==i&&W4(n=r.prototype)&&n!==i.prototype&&mI(e,n),e},Rd=y,xf=X,Uf=E,G4=lI,j4=nn,z4=zs,fI=cI,Vf=S,Ad=Ol,K4=Kn,J4=js,bd=uI,Y4=P4,_I=V4,q4=Ed,gI=qa,X4=pI,Q4=Pl,Z4=Lf,$4=vf,vI=Ys,Ff=Mi,e5=Ka.PROPER,EI=Ka.CONFIGURABLE,Xa="ArrayBuffer",Cd="DataView",Qa="prototype",yI="Wrong index",TI=Ff.getterFor(Xa),Ml=Ff.getterFor(Cd),SI=Ff.set,mr=Rd[Xa],fr=mr,Za=fr&&fr[Qa],on=Rd[Cd],qs=on&&on[Qa],II=Object.prototype,t5=Rd.Array,kd=Rd.RangeError,i5=xf(X4),r5=xf([].reverse),RI=_I.pack,AI=_I.unpack,bI=function(e){return[255&e]},CI=function(e){return[255&e,e>>8&255]},kI=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},wI=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},n5=function(e){return RI(Y4(e),23,4)},s5=function(e){return RI(e,52,8)},wd=function(e,t,i){z4(e[Qa],t,{configurable:!0,get:function(){return i(this)[t]}})},qn=function(e,t,i,r){var n=Ml(e),s=bd(i),o=!!r;if(s+t>n.byteLength)throw new kd(yI);var l=n.bytes,c=s+n.byteOffset,h=Q4(l,c,c+t);return o?h:r5(h)},Xn=function(e,t,i,r,n,s){var o=Ml(e),l=bd(i),c=r(+n),h=!!s;if(l+t>o.byteLength)throw new kd(yI);for(var _=o.bytes,f=l+o.byteOffset,T=0;T<t;T++)_[f+T]=c[h?T:t-T-1]};if(G4){var DI=e5&&mr.name!==Xa;Vf(function(){mr(1)})&&Vf(function(){new mr(-1)})&&!Vf(function(){return new mr,new mr(1.5),new mr(NaN),mr.length!==1||DI&&!EI})?DI&&EI&&j4(mr,"name",Xa):((fr=function(e){return Ad(this,Za),Z4(new mr(bd(e)),this,fr)})[Qa]=Za,Za.constructor=fr,$4(fr,mr)),gI&&q4(qs)!==II&&gI(qs,II);var Dd=new on(new fr(2)),NI=xf(qs.setInt8);Dd.setInt8(0,2147483648),Dd.setInt8(1,2147483649),!Dd.getInt8(0)&&Dd.getInt8(1)||fI(qs,{setInt8:function(e,t){NI(this,e,t<<24>>24)},setUint8:function(e,t){NI(this,e,t<<24>>24)}},{unsafe:!0})}else Za=(fr=function(e){Ad(this,Za);var t=bd(e);SI(this,{type:Xa,bytes:i5(t5(t),0),byteLength:t}),Uf||(this.byteLength=t,this.detached=!1)})[Qa],qs=(on=function(e,t,i){Ad(this,qs),Ad(e,Za);var r=TI(e),n=r.byteLength,s=K4(t);if(s<0||s>n)throw new kd("Wrong offset");if(s+(i=i===void 0?n-s:J4(i))>n)throw new kd("Wrong length");SI(this,{type:Cd,buffer:e,byteLength:i,byteOffset:s,bytes:r.bytes}),Uf||(this.buffer=e,this.byteLength=i,this.byteOffset=s)})[Qa],Uf&&(wd(fr,"byteLength",TI),wd(on,"buffer",Ml),wd(on,"byteLength",Ml),wd(on,"byteOffset",Ml)),fI(qs,{getInt8:function(e){return qn(this,1,e)[0]<<24>>24},getUint8:function(e){return qn(this,1,e)[0]},getInt16:function(e){var t=qn(this,2,e,arguments.length>1&&arguments[1]);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=qn(this,2,e,arguments.length>1&&arguments[1]);return t[1]<<8|t[0]},getInt32:function(e){return wI(qn(this,4,e,arguments.length>1&&arguments[1]))},getUint32:function(e){return wI(qn(this,4,e,arguments.length>1&&arguments[1]))>>>0},getFloat32:function(e){return AI(qn(this,4,e,arguments.length>1&&arguments[1]),23)},getFloat64:function(e){return AI(qn(this,8,e,arguments.length>1&&arguments[1]),52)},setInt8:function(e,t){Xn(this,1,e,bI,t)},setUint8:function(e,t){Xn(this,1,e,bI,t)},setInt16:function(e,t){Xn(this,2,e,CI,t,arguments.length>2&&arguments[2])},setUint16:function(e,t){Xn(this,2,e,CI,t,arguments.length>2&&arguments[2])},setInt32:function(e,t){Xn(this,4,e,kI,t,arguments.length>2&&arguments[2])},setUint32:function(e,t){Xn(this,4,e,kI,t,arguments.length>2&&arguments[2])},setFloat32:function(e,t){Xn(this,4,e,n5,t,arguments.length>2&&arguments[2])},setFloat64:function(e,t){Xn(this,8,e,s5,t,arguments.length>2&&arguments[2])}});vI(fr,Xa),vI(on,Cd);var Nd={ArrayBuffer:fr,DataView:on},a5=Mt,o5=zs,l5=E,PI=xt("species"),Pd=function(e){var t=a5(e);l5&&t&&!t[PI]&&o5(t,PI,{configurable:!0,get:function(){return this}})},c5=Pd,Bf="ArrayBuffer",OI=Nd[Bf];It({global:!0,constructor:!0,forced:y[Bf]!==OI},{ArrayBuffer:OI}),c5(Bf);var u5=ne,d5=X,Od=function(e){if(u5(e)==="Function")return d5(e)},h5=It,Hf=Od,p5=S,MI=yi,LI=hd,m5=js,Wf=Nd.ArrayBuffer,Gf=Nd.DataView,xI=Gf.prototype,UI=Hf(Wf.prototype.slice),f5=Hf(xI.getUint8),_5=Hf(xI.setUint8);h5({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:p5(function(){return!new Wf(2).slice(1,void 0).byteLength})},{slice:function(e,t){if(UI&&t===void 0)return UI(MI(this),e);for(var i=MI(this).byteLength,r=LI(e,i),n=LI(t===void 0?i:t,i),s=new Wf(m5(n-r)),o=new Gf(this),l=new Gf(s),c=0;r<n;)_5(l,c++,f5(o,r++));return s}});var g5=y,v5=X,E5=S,VI=$e,y5=Jn,T5=of,FI=function(){},BI=Mt("Reflect","construct"),jf=/^\s*(?:class|function)\b/,S5=v5(jf.exec),I5=!jf.test(FI),Ll=function(e){if(!VI(e))return!1;try{return BI(FI,[],e),!0}catch{return!1}},HI=function(e){if(!VI(e))return!1;switch(y5(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return I5||!!S5(jf,T5(e))}catch{return!0}};HI.sham=!0;var xl,$a,WI,zf,Kf=!BI||E5(function(){var e;return Ll(Ll.call)||!Ll(Object)||!Ll(function(){e=!0})||e})?HI:Ll,R5=Kf,A5=jn,b5=TypeError,GI=function(e){if(R5(e))return e;throw new b5(A5(e)+" is not a constructor")},jI=yi,C5=GI,k5=tt,w5=xt("species"),zI=function(e,t){var i,r=jI(e).constructor;return r===void 0||k5(i=jI(r)[w5])?t:C5(i)},D5=R,KI=Function.prototype,JI=KI.apply,YI=KI.call,Jf=typeof Reflect=="object"&&Reflect.apply||(D5?YI.bind(JI):function(){return YI.apply(JI,arguments)}),N5=Oi,P5=R,O5=Od(Od.bind),Qn=function(e,t){return N5(e),t===void 0?e:P5?O5(e,t):function(){return e.apply(t,arguments)}},M5=TypeError,Md=function(e,t){if(e<t)throw new M5("Not enough arguments");return e},qI=/(?:ipad|iphone|ipod).*applewebkit/i.test(ae),Hi=y,L5=Jf,x5=Qn,XI=$e,U5=ui,QI=S,ZI=vS,V5=Pl,$I=sd,F5=Md,B5=qI,H5=Nl,Yf=Hi.setImmediate,qf=Hi.clearImmediate,W5=Hi.process,Xf=Hi.Dispatch,G5=Hi.Function,eR=Hi.MessageChannel,j5=Hi.String,Qf=0,Ul={},tR="onreadystatechange";QI(function(){xl=Hi.location});var Zf=function(e){if(U5(Ul,e)){var t=Ul[e];delete Ul[e],t()}},$f=function(e){return function(){Zf(e)}},iR=function(e){Zf(e.data)},rR=function(e){Hi.postMessage(j5(e),xl.protocol+"//"+xl.host)};Yf&&qf||(Yf=function(e){F5(arguments.length,1);var t=XI(e)?e:G5(e),i=V5(arguments,1);return Ul[++Qf]=function(){L5(t,void 0,i)},$a(Qf),Qf},qf=function(e){delete Ul[e]},H5?$a=function(e){W5.nextTick($f(e))}:Xf&&Xf.now?$a=function(e){Xf.now($f(e))}:eR&&!B5?(zf=(WI=new eR).port2,WI.port1.onmessage=iR,$a=x5(zf.postMessage,zf)):Hi.addEventListener&&XI(Hi.postMessage)&&!Hi.importScripts&&xl&&xl.protocol!=="file:"&&!QI(rR)?($a=rR,Hi.addEventListener("message",iR,!1)):$a=tR in $I("script")?function(e){ZI.appendChild($I("script"))[tR]=function(){ZI.removeChild(this),Zf(e)}}:function(e){setTimeout($f(e),0)});var Ld={set:Yf,clear:qf},nR=y,z5=E,K5=Object.getOwnPropertyDescriptor,sR=function(e){if(!z5)return nR[e];var t=K5(nR,e);return t&&t.value},aR=function(){this.head=null,this.tail=null};aR.prototype={add:function(e){var t={item:e,next:null},i=this.tail;i?i.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return(this.head=e.next)===null&&(this.tail=null),e.item}};var eo,e_,t_,i_,oR,lR=aR,J5=/ipad|iphone|ipod/i.test(ae)&&typeof Pebble<"u",Y5=/web0s(?!.*chrome)/i.test(ae),to=y,q5=sR,cR=Qn,r_=Ld.set,X5=lR,Q5=qI,Z5=J5,$5=Y5,n_=Nl,uR=to.MutationObserver||to.WebKitMutationObserver,dR=to.document,hR=to.process,xd=to.Promise,s_=q5("queueMicrotask");if(!s_){var Ud=new X5,Vd=function(){var e,t;for(n_&&(e=hR.domain)&&e.exit();t=Ud.get();)try{t()}catch(i){throw Ud.head&&eo(),i}e&&e.enter()};Q5||n_||$5||!uR||!dR?!Z5&&xd&&xd.resolve?((i_=xd.resolve(void 0)).constructor=xd,oR=cR(i_.then,i_),eo=function(){oR(Vd)}):n_?eo=function(){hR.nextTick(Vd)}:(r_=cR(r_,to),eo=function(){r_(Vd)}):(e_=!0,t_=dR.createTextNode(""),new uR(Vd).observe(t_,{characterData:!0}),eo=function(){t_.data=e_=!e_}),s_=function(e){Ud.head||eo(),Ud.add(e)}}var e6=s_,a_=function(e){try{return{error:!1,value:e()}}catch(t){return{error:!0,value:t}}},Vl=y.Promise,t6=y,Fl=Vl,i6=$e,r6=Ef,n6=of,s6=xt,pR=Nf,o_=Ei;Fl&&Fl.prototype;var a6=s6("species"),mR=!1,fR=i6(t6.PromiseRejectionEvent),o6=r6("Promise",function(){var e=n6(Fl),t=e!==String(Fl);if(!t&&o_===66)return!0;if(!o_||o_<51||!/native code/.test(e)){var i=new Fl(function(n){n(1)}),r=function(n){n(function(){},function(){})};if((i.constructor={})[a6]=r,!(mR=i.then(function(){})instanceof r))return!0}return!(t||pR!=="BROWSER"&&pR!=="DENO"||fR)}),Xs={CONSTRUCTOR:o6,REJECTION_EVENT:fR,SUBCLASSING:mR},io={},_R=Oi,l6=TypeError,c6=function(e){var t,i;this.promise=new e(function(r,n){if(t!==void 0||i!==void 0)throw new l6("Bad Promise constructor");t=r,i=n}),this.resolve=_R(t),this.reject=_R(i)};io.f=function(e){return new c6(e)};var l_,gR,vR,ER,u6=It,Fd=Nl,Zn=y,d6=g5,ro=A,yR=Qi,TR=qa,h6=Ys,p6=Pd,m6=Oi,Bd=$e,f6=Et,_6=Ol,g6=zI,SR=Ld.set,c_=e6,v6=function(e,t){try{arguments.length===1?console.error(e):console.error(e,t)}catch{}},E6=a_,y6=lR,IR=Mi,Hd=Vl,RR=io,Wd="Promise",AR=Xs.CONSTRUCTOR,T6=Xs.REJECTION_EVENT,S6=Xs.SUBCLASSING,u_=IR.getterFor(Wd),I6=IR.set,no=Hd&&Hd.prototype,so=Hd,Gd=no,bR=Zn.TypeError,d_=Zn.document,h_=Zn.process,p_=RR.f,R6=p_,A6=!!(d_&&d_.createEvent&&Zn.dispatchEvent),CR="unhandledrejection",kR=function(e){var t;return!(!f6(e)||!Bd(t=e.then))&&t},wR=function(e,t){var i,r,n,s=t.value,o=t.state===1,l=o?e.ok:e.fail,c=e.resolve,h=e.reject,_=e.domain;try{l?(o||(t.rejection===2&&C6(t),t.rejection=1),l===!0?i=s:(_&&_.enter(),i=l(s),_&&(_.exit(),n=!0)),i===e.promise?h(new bR("Promise-chain cycle")):(r=kR(i))?ro(r,i,c,h):c(i)):h(s)}catch(f){_&&!n&&_.exit(),h(f)}},DR=function(e,t){e.notified||(e.notified=!0,c_(function(){for(var i,r=e.reactions;i=r.get();)wR(i,e);e.notified=!1,t&&!e.rejection&&b6(e)}))},NR=function(e,t,i){var r,n;A6?((r=d_.createEvent("Event")).promise=t,r.reason=i,r.initEvent(e,!1,!0),Zn.dispatchEvent(r)):r={promise:t,reason:i},!T6&&(n=Zn["on"+e])?n(r):e===CR&&v6("Unhandled promise rejection",i)},b6=function(e){ro(SR,Zn,function(){var t,i=e.facade,r=e.value;if(PR(e)&&(t=E6(function(){Fd?h_.emit("unhandledRejection",r,i):NR(CR,i,r)}),e.rejection=Fd||PR(e)?2:1,t.error))throw t.value})},PR=function(e){return e.rejection!==1&&!e.parent},C6=function(e){ro(SR,Zn,function(){var t=e.facade;Fd?h_.emit("rejectionHandled",t):NR("rejectionhandled",t,e.value)})},ao=function(e,t,i){return function(r){e(t,r,i)}},oo=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,DR(e,!0))},m_=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw new bR("Promise can't be resolved itself");var r=kR(t);r?c_(function(){var n={done:!1};try{ro(r,t,ao(m_,n,e),ao(oo,n,e))}catch(s){oo(n,s,e)}}):(e.value=t,e.state=1,DR(e,!1))}catch(n){oo({done:!1},n,e)}}};if(AR&&(Gd=(so=function(e){_6(this,Gd),m6(e),ro(l_,this);var t=u_(this);try{e(ao(m_,t),ao(oo,t))}catch(i){oo(t,i)}}).prototype,(l_=function(e){I6(this,{type:Wd,done:!1,notified:!1,parent:!1,reactions:new y6,rejection:!1,state:0,value:null})}).prototype=yR(Gd,"then",function(e,t){var i=u_(this),r=p_(g6(this,so));return i.parent=!0,r.ok=!Bd(e)||e,r.fail=Bd(t)&&t,r.domain=Fd?h_.domain:void 0,i.state===0?i.reactions.add(r):c_(function(){wR(r,i)}),r.promise}),gR=function(){var e=new l_,t=u_(e);this.promise=e,this.resolve=ao(m_,t),this.reject=ao(oo,t)},RR.f=p_=function(e){return e===so||e===vR?new gR(e):R6(e)},Bd(Hd)&&no!==Object.prototype)){ER=no.then,S6||yR(no,"then",function(e,t){var i=this;return new so(function(r,n){ro(ER,i,r,n)}).then(e,t)},{unsafe:!0});try{delete no.constructor}catch{}TR&&TR(no,Gd)}u6({global:!0,constructor:!0,wrap:!0,forced:AR},{Promise:so}),vR=d6.Promise,h6(so,Wd,!1),p6(Wd);var k6=Cl,w6=xt("iterator"),D6=Array.prototype,f_=function(e){return e!==void 0&&(k6.Array===e||D6[w6]===e)},N6=Jn,OR=zn,P6=tt,O6=Cl,M6=xt("iterator"),Bl=function(e){if(!P6(e))return OR(e,M6)||OR(e,"@@iterator")||O6[N6(e)]},L6=A,x6=Oi,U6=yi,V6=jn,F6=Bl,B6=TypeError,jd=function(e,t){var i=arguments.length<2?F6(e):t;if(x6(i))return U6(L6(i,e));throw new B6(V6(e)+" is not iterable")},H6=A,MR=yi,W6=zn,LR=function(e,t,i){var r,n;MR(e);try{if(!(r=W6(e,"return"))){if(t==="throw")throw i;return i}r=H6(r,e)}catch(s){n=!0,r=s}if(t==="throw")throw i;if(n)throw r;return MR(r),i},G6=Qn,j6=A,z6=yi,K6=jn,J6=f_,Y6=Lr,xR=Lt,q6=jd,X6=Bl,UR=LR,Q6=TypeError,zd=function(e,t){this.stopped=e,this.result=t},VR=zd.prototype,FR=function(e,t,i){var r,n,s,o,l,c,h,_=i&&i.that,f=!(!i||!i.AS_ENTRIES),T=!(!i||!i.IS_RECORD),b=!(!i||!i.IS_ITERATOR),C=!(!i||!i.INTERRUPTED),x=G6(t,_),B=function(G){return r&&UR(r,"normal"),new zd(!0,G)},Y=function(G){return f?(z6(G),C?x(G[0],G[1],B):x(G[0],G[1])):C?x(G,B):x(G)};if(T)r=e.iterator;else if(b)r=e;else{if(!(n=X6(e)))throw new Q6(K6(e)+" is not iterable");if(J6(n)){for(s=0,o=Y6(e);o>s;s++)if((l=Y(e[s]))&&xR(VR,l))return l;return new zd(!1)}r=q6(e,n)}for(c=T?e.next:r.next;!(h=j6(c,r)).done;){try{l=Y(h.value)}catch(G){UR(r,"throw",G)}if(typeof l=="object"&&l&&xR(VR,l))return l}return new zd(!1)},BR=xt("iterator"),HR=!1;try{var Z6=0,WR={next:function(){return{done:!!Z6++}},return:function(){HR=!0}};WR[BR]=function(){return this},Array.from(WR,function(){throw 2})}catch{}var GR=function(e,t){try{if(!t&&!HR)return!1}catch{return!1}var i=!1;try{var r={};r[BR]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch{}return i},$6=Vl,jR=Xs.CONSTRUCTOR||!GR(function(e){$6.all(e).then(void 0,function(){})}),eU=A,tU=Oi,iU=io,rU=a_,nU=FR;It({target:"Promise",stat:!0,forced:jR},{all:function(e){var t=this,i=iU.f(t),r=i.resolve,n=i.reject,s=rU(function(){var o=tU(t.resolve),l=[],c=0,h=1;nU(e,function(_){var f=c++,T=!1;h++,eU(o,t,_).then(function(b){T||(T=!0,l[f]=b,--h||r(l))},n)}),--h||r(l)});return s.error&&n(s.value),i.promise}});var sU=It,aU=Xs.CONSTRUCTOR,__=Vl,oU=Mt,lU=$e,cU=Qi,zR=__&&__.prototype;if(sU({target:"Promise",proto:!0,forced:aU,real:!0},{catch:function(e){return this.then(void 0,e)}}),lU(__)){var KR=oU("Promise").prototype.catch;zR.catch!==KR&&cU(zR,"catch",KR,{unsafe:!0})}var uU=A,dU=Oi,hU=io,pU=a_,mU=FR;It({target:"Promise",stat:!0,forced:jR},{race:function(e){var t=this,i=hU.f(t),r=i.reject,n=pU(function(){var s=dU(t.resolve);mU(e,function(o){uU(s,t,o).then(i.resolve,r)})});return n.error&&r(n.value),i.promise}});var fU=io;It({target:"Promise",stat:!0,forced:Xs.CONSTRUCTOR},{reject:function(e){var t=fU.f(this);return(0,t.reject)(e),t.promise}});var _U=yi,gU=Et,vU=io,JR=function(e,t){if(_U(e),gU(t)&&t.constructor===e)return t;var i=vU.f(e);return(0,i.resolve)(t),i.promise},EU=It,yU=Xs.CONSTRUCTOR,TU=JR;Mt("Promise"),EU({target:"Promise",stat:!0,forced:yU},{resolve:function(e){return TU(this,e)}});var SU=It,Kd=Vl,IU=S,YR=Mt,qR=$e,RU=zI,XR=JR,AU=Qi,g_=Kd&&Kd.prototype;if(SU({target:"Promise",proto:!0,real:!0,forced:!!Kd&&IU(function(){g_.finally.call({then:function(){}},function(){})})},{finally:function(e){var t=RU(this,YR("Promise")),i=qR(e);return this.then(i?function(r){return XR(t,e()).then(function(){return r})}:e,i?function(r){return XR(t,e()).then(function(){throw r})}:e)}}),qR(Kd)){var QR=YR("Promise").prototype.finally;g_.finally!==QR&&AU(g_,"finally",QR,{unsafe:!0})}var bU=Et,CU=ne,kU=xt("match"),ZR=function(e){var t;return bU(e)&&((t=e[kU])!==void 0?!!t:CU(e)==="RegExp")},wU=S,$R=y.RegExp,DU=!wU(function(){var e=!0;try{$R(".","d")}catch{e=!1}var t={},i="",r=e?"dgimsy":"gimsy",n=function(l,c){Object.defineProperty(t,l,{get:function(){return i+=c,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};for(var o in e&&(s.hasIndices="d"),s)n(o,s[o]);return Object.getOwnPropertyDescriptor($R.prototype,"flags").get.call(t)!==r||i!==r}),NU=yi,eA=function(){var e=NU(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},PU=A,OU=ui,MU=Lt,tA={correct:DU},LU=eA,xU=RegExp.prototype,v_=tA.correct?function(e){return e.flags}:function(e){return tA.correct||!MU(xU,e)||OU(e,"flags")?e.flags:PU(LU,e)},E_=S,y_=y.RegExp,T_=E_(function(){var e=y_("a","y");return e.lastIndex=2,e.exec("abcd")!==null}),UU=T_||E_(function(){return!y_("a","y").sticky}),VU=T_||E_(function(){var e=y_("^r","gy");return e.lastIndex=2,e.exec("str")!==null}),iA={BROKEN_CARET:VU,MISSED_STICKY:UU,UNSUPPORTED_Y:T_},FU=Xi.f,BU=S,HU=y.RegExp,rA=BU(function(){var e=HU(".","s");return!(e.dotAll&&e.test(`
2
+ `)&&e.flags==="s")}),WU=S,GU=y.RegExp,nA=WU(function(){var e=GU("(?<a>b)","g");return e.exec("b").groups.a!=="b"||"b".replace(e,"$<a>c")!=="bc"}),jU=E,S_=y,Hl=X,zU=Ef,KU=Lf,JU=nn,YU=Ya,qU=dd.f,sA=Lt,XU=ZR,aA=Bi,QU=v_,oA=iA,ZU=function(e,t,i){i in e||FU(e,i,{configurable:!0,get:function(){return t[i]},set:function(r){t[i]=r}})},$U=Qi,eV=S,tV=ui,iV=Mi.enforce,rV=Pd,lA=rA,cA=nA,nV=xt("match"),$n=S_.RegExp,lo=$n.prototype,sV=S_.SyntaxError,aV=Hl(lo.exec),Jd=Hl("".charAt),uA=Hl("".replace),dA=Hl("".indexOf),hA=Hl("".slice),oV=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,Qs=/a/g,I_=/a/g,lV=new $n(Qs)!==Qs,pA=oA.MISSED_STICKY,cV=oA.UNSUPPORTED_Y,uV=jU&&(!lV||pA||lA||cA||eV(function(){return I_[nV]=!1,$n(Qs)!==Qs||$n(I_)===I_||String($n(Qs,"i"))!=="/a/i"}));if(zU("RegExp",uV)){for(var Zs=function(e,t){var i,r,n,s,o,l,c=sA(lo,this),h=XU(e),_=t===void 0,f=[],T=e;if(!c&&h&&_&&e.constructor===Zs)return e;if((h||sA(lo,e))&&(e=e.source,_&&(t=QU(T))),e=e===void 0?"":aA(e),t=t===void 0?"":aA(t),T=e,lA&&"dotAll"in Qs&&(r=!!t&&dA(t,"s")>-1)&&(t=uA(t,/s/g,"")),i=t,pA&&"sticky"in Qs&&(n=!!t&&dA(t,"y")>-1)&&cV&&(t=uA(t,/y/g,"")),cA&&(s=(function(b){for(var C,x=b.length,B=0,Y="",G=[],he=YU(null),H=!1,Z=!1,de=0,pe="";B<=x;B++){if((C=Jd(b,B))==="\\")C+=Jd(b,++B);else if(C==="]")H=!1;else if(!H)switch(!0){case C==="[":H=!0;break;case C==="(":if(Y+=C,hA(b,B+1,B+3)==="?:")continue;aV(oV,hA(b,B+1))&&(B+=2,Z=!0),de++;continue;case(C===">"&&Z):if(pe===""||tV(he,pe))throw new sV("Invalid capture group name");he[pe]=!0,G[G.length]=[pe,de],Z=!1,pe="";continue}Z?pe+=C:Y+=C}return[Y,G]})(e),e=s[0],f=s[1]),o=KU($n(e,t),c?this:lo,Zs),(r||n||f.length)&&(l=iV(o),r&&(l.dotAll=!0,l.raw=Zs((function(b){for(var C,x=b.length,B=0,Y="",G=!1;B<=x;B++)(C=Jd(b,B))!=="\\"?G||C!=="."?(C==="["?G=!0:C==="]"&&(G=!1),Y+=C):Y+="[\\s\\S]":Y+=C+Jd(b,++B);return Y})(e),i)),n&&(l.sticky=!0),f.length&&(l.groups=f)),e!==T)try{JU(o,"source",T===""?"(?:)":T)}catch{}return o},mA=qU($n),fA=0;mA.length>fA;)ZU(Zs,$n,mA[fA++]);lo.constructor=Zs,Zs.prototype=lo,$U(S_,"RegExp",Zs,{constructor:!0})}rV("RegExp");var co=A,Yd=X,dV=Bi,hV=eA,pV=iA,mV=Ya,fV=Mi.get,_V=rA,gV=nA,vV=qm("native-string-replace",String.prototype.replace),qd=RegExp.prototype.exec,R_=qd,EV=Yd("".charAt),yV=Yd("".indexOf),TV=Yd("".replace),A_=Yd("".slice),b_=(function(){var e=/a/,t=/b*/g;return co(qd,e,"a"),co(qd,t,"a"),e.lastIndex!==0||t.lastIndex!==0})(),_A=pV.BROKEN_CARET,C_=/()??/.exec("")[1]!==void 0;(b_||C_||_A||_V||gV)&&(R_=function(e){var t,i,r,n,s,o,l,c=this,h=fV(c),_=dV(e),f=h.raw;if(f)return f.lastIndex=c.lastIndex,t=co(R_,f,_),c.lastIndex=f.lastIndex,t;var T=h.groups,b=_A&&c.sticky,C=co(hV,c),x=c.source,B=0,Y=_;if(b&&(C=TV(C,"y",""),yV(C,"g")===-1&&(C+="g"),Y=A_(_,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&EV(_,c.lastIndex-1)!==`
3
+ `)&&(x="(?: "+x+")",Y=" "+Y,B++),i=new RegExp("^(?:"+x+")",C)),C_&&(i=new RegExp("^"+x+"$(?!\\s)",C)),b_&&(r=c.lastIndex),n=co(qd,b?i:c,Y),b?n?(n.input=A_(n.input,B),n[0]=A_(n[0],B),n.index=c.lastIndex,c.lastIndex+=n[0].length):c.lastIndex=0:b_&&n&&(c.lastIndex=c.global?n.index+n[0].length:r),C_&&n&&n.length>1&&co(vV,n[0],i,function(){for(s=1;s<arguments.length-2;s++)arguments[s]===void 0&&(n[s]=void 0)}),n&&T)for(n.groups=o=mV(null),s=0;s<T.length;s++)o[(l=T[s])[0]]=n[l[1]];return n});var Xd=R_;It({target:"RegExp",proto:!0,forced:/./.exec!==Xd},{exec:Xd});var SV=Kn,IV=Bi,RV=se,AV=RangeError,gA=X,bV=js,vA=Bi,CV=function(e){var t=IV(RV(this)),i="",r=SV(e);if(r<0||r===1/0)throw new AV("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i},kV=se,wV=gA(CV),DV=gA("".slice),NV=Math.ceil,PV=function(e){return function(t,i,r){var n,s,o=vA(kV(t)),l=bV(i),c=o.length,h=r===void 0?" ":vA(r);return l<=c||h===""?o:((s=wV(h,NV((n=l-c)/h.length))).length>n&&(s=DV(s,0,n)),e?o+s:s+o)}},OV={start:PV(!1)},MV=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(ae),LV=OV.start;It({target:"String",proto:!0,forced:MV},{padStart:function(e){return LV(this,e,arguments.length>1?arguments[1]:void 0)}});var EA=A,yA=Qi,xV=Xd,TA=S,SA=xt,bz=SA("species"),IA=RegExp.prototype,k_=X,UV=Kn,VV=Bi,FV=se,BV=k_("".charAt),RA=k_("".charCodeAt),HV=k_("".slice),AA=function(e){return function(t,i){var r,n,s=VV(FV(t)),o=UV(i),l=s.length;return o<0||o>=l?e?"":void 0:(r=RA(s,o))<55296||r>56319||o+1===l||(n=RA(s,o+1))<56320||n>57343?e?BV(s,o):r:e?HV(s,o,o+2):n-56320+(r-55296<<10)+65536}},w_={codeAt:AA(!1),charAt:AA(!0)},WV=w_.charAt,D_=X,GV=pr,jV=Math.floor,N_=D_("".charAt),zV=D_("".replace),P_=D_("".slice),KV=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,JV=/\$([$&'`]|\d{1,2})/g,bA=function(e,t,i,r,n,s){var o=i+e.length,l=r.length,c=JV;return n!==void 0&&(n=GV(n),c=KV),zV(s,c,function(h,_){var f;switch(N_(_,0)){case"$":return"$";case"&":return e;case"`":return P_(t,0,i);case"'":return P_(t,o);case"<":f=n[P_(_,1,-1)];break;default:var T=+_;if(T===0)return h;if(T>l){var b=jV(T/10);return b===0?h:b<=l?r[b-1]===void 0?N_(_,1):r[b-1]+N_(_,1):h}f=r[T-1]}return f===void 0?"":f})},CA=A,YV=yi,qV=$e,XV=ne,QV=Xd,ZV=TypeError,$V=Jf,kA=A,Qd=X,e8=function(e,t,i,r){var n=SA(e),s=!TA(function(){var h={};return h[n]=function(){return 7},""[e](h)!==7}),o=s&&!TA(function(){var h=!1,_=/a/,f;return _.exec=function(){return h=!0,null},_[n](""),!h});if(!s||!o||i){var l=/./[n],c=t(n,""[e],function(h,_,f,T,b){var C=_.exec;return C===xV||C===IA.exec?s&&!b?{done:!0,value:EA(l,_,f,T)}:{done:!0,value:EA(h,f,_,T)}:{done:!1}});yA(String.prototype,e,c[0]),yA(IA,n,c[1])}},t8=S,i8=yi,r8=$e,n8=Et,s8=Kn,a8=js,$s=Bi,o8=se,l8=function(e,t,i){return t+(i?WV(e,t).length:1)},c8=zn,u8=bA,d8=v_,h8=function(e,t){var i=e.exec;if(qV(i)){var r=CA(i,e,t);return r!==null&&YV(r),r}if(XV(e)==="RegExp")return CA(QV,e,t);throw new ZV("RegExp#exec called on incompatible receiver")},O_=xt("replace"),p8=Math.max,m8=Math.min,f8=Qd([].concat),M_=Qd([].push),Zd=Qd("".indexOf),wA=Qd("".slice),_8=function(e){return e===void 0?e:String(e)},g8="a".replace(/./,"$0")==="$0",DA=!!/./[O_]&&/./[O_]("a","$0")==="",v8=!t8(function(){var e=/./;return e.exec=function(){var t=[];return t.groups={a:"7"},t},"".replace(e,"$<a>")!=="7"});e8("replace",function(e,t,i){var r=DA?"$":"$0";return[function(n,s){var o=o8(this),l=n8(n)?c8(n,O_):void 0;return l?kA(l,n,o,s):kA(t,$s(o),n,s)},function(n,s){var o=i8(this),l=$s(n);if(typeof s=="string"&&Zd(s,r)===-1&&Zd(s,"$<")===-1){var c=i(t,o,l,s);if(c.done)return c.value}var h=r8(s);h||(s=$s(s));var _,f=$s(d8(o)),T=Zd(f,"g")!==-1;T&&(_=Zd(f,"u")!==-1,o.lastIndex=0);for(var b,C=[];(b=h8(o,l))!==null&&(M_(C,b),T);)$s(b[0])===""&&(o.lastIndex=l8(l,a8(o.lastIndex),_));for(var x="",B=0,Y=0;Y<C.length;Y++){for(var G,he=$s((b=C[Y])[0]),H=p8(m8(s8(b.index),l.length),0),Z=[],de=1;de<b.length;de++)M_(Z,_8(b[de]));var pe=b.groups;if(h){var Pe=f8([he],Z,H,l);pe!==void 0&&M_(Pe,pe),G=$s($V(s,void 0,Pe))}else G=u8(he,l,H,Z,pe,s);H>=B&&(x+=wA(l,B,H)+G,B=H+he.length)}return x+wA(l,B)}]},!v8||!g8||DA);var NA=`
4
+ \v\f\r                 \u2028\u2029\uFEFF`,E8=se,y8=Bi,L_=NA,PA=X("".replace),T8=RegExp("^["+L_+"]+"),S8=RegExp("(^|[^"+L_+"])["+L_+"]+$"),I8=function(e){return function(t){var i=y8(E8(t));return 1&e&&(i=PA(i,T8,"")),2&e&&(i=PA(i,S8,"$1")),i}},R8={trim:I8(3)},A8=Ka.PROPER,b8=S,OA=NA,C8=R8.trim;It({target:"String",proto:!0,forced:(function(e){return b8(function(){return!!OA[e]()||"​…᠎"[e]()!=="​…᠎"||A8&&OA[e].name!==e})})("trim")},{trim:function(){return C8(this)}});var Li,uo,$d,x_={exports:{}},k8=lI,U_=E,Ti=y,MA=$e,LA=Et,Wl=ui,xA=Jn,w8=jn,D8=nn,V_=Qi,N8=zs,P8=Lt,F_=Ed,ho=qa,O8=xt,M8=Xm,UA=Mi.enforce,eh=Ti.Int8Array,B_=eh&&eh.prototype,VA=Ti.Uint8ClampedArray,FA=VA&&VA.prototype,xr=eh&&F_(eh),_r=B_&&F_(B_),L8=Object.prototype,H_=Ti.TypeError,BA=O8("toStringTag"),W_=M8("TYPED_ARRAY_TAG"),HA="TypedArrayConstructor",ln=k8&&!!ho&&xA(Ti.opera)!=="Opera",WA=!1,es={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},GA={BigInt64Array:8,BigUint64Array:8},jA=function(e){if(!LA(e))return!1;var t=xA(e);return Wl(es,t)||Wl(GA,t)};for(Li in es)($d=(uo=Ti[Li])&&uo.prototype)?UA($d)[HA]=uo:ln=!1;for(Li in GA)($d=(uo=Ti[Li])&&uo.prototype)&&(UA($d)[HA]=uo);if((!ln||!MA(xr)||xr===Function.prototype)&&(xr=function(){throw new H_("Incorrect invocation")},ln))for(Li in es)Ti[Li]&&ho(Ti[Li],xr);if((!ln||!_r||_r===L8)&&(_r=xr.prototype,ln))for(Li in es)Ti[Li]&&ho(Ti[Li].prototype,_r);if(ln&&F_(FA)!==_r&&ho(FA,_r),U_&&!Wl(_r,BA))for(Li in WA=!0,N8(_r,BA,{configurable:!0,get:function(){return LA(this)?this[W_]:void 0}}),es)Ti[Li]&&D8(Ti[Li],W_,Li);var cn={NATIVE_ARRAY_BUFFER_VIEWS:ln,TYPED_ARRAY_TAG:WA&&W_,aTypedArray:function(e){if(jA(e))return e;throw new H_("Target is not a typed array")},aTypedArrayConstructor:function(e){if(MA(e)&&(!ho||P8(xr,e)))return e;throw new H_(w8(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(U_){if(i)for(var n in es){var s=Ti[n];if(s&&Wl(s.prototype,e))try{delete s.prototype[e]}catch{try{s.prototype[e]=t}catch{}}}_r[e]&&!i||V_(_r,e,i?t:ln&&B_[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,n;if(U_){if(ho){if(i){for(r in es)if((n=Ti[r])&&Wl(n,e))try{delete n[e]}catch{}}if(xr[e]&&!i)return;try{return V_(xr,e,i?t:ln&&xr[e]||t)}catch{}}for(r in es)!(n=Ti[r])||n[e]&&!i||V_(n,e,t)}},isTypedArray:jA,TypedArray:xr,TypedArrayPrototype:_r},zA=y,G_=S,x8=GR,U8=cn.NATIVE_ARRAY_BUFFER_VIEWS,V8=zA.ArrayBuffer,ea=zA.Int8Array,KA=!U8||!G_(function(){ea(1)})||!G_(function(){new ea(-1)})||!x8(function(e){new ea,new ea(null),new ea(1.5),new ea(e)},!0)||G_(function(){return new ea(new V8(2),1,void 0).length!==1}),F8=Et,B8=Math.floor,H8=Number.isInteger||function(e){return!F8(e)&&isFinite(e)&&B8(e)===e},W8=Kn,G8=RangeError,j8=function(e){var t=W8(e);if(t<0)throw new G8("The argument can't be less than 0");return t},z8=RangeError,JA=function(e,t){var i=j8(e);if(i%t)throw new z8("Wrong offset");return i},K8=Math.round,J8=Jn,Y8=JT,q8=TypeError,YA=function(e){var t=Y8(e,"number");if(typeof t=="number")throw new q8("Can't convert number to bigint");return BigInt(t)},X8=Qn,Q8=A,Z8=GI,$8=pr,e7=Lr,t7=jd,i7=Bl,r7=f_,n7=function(e){var t=J8(e);return t==="BigInt64Array"||t==="BigUint64Array"},s7=cn.aTypedArrayConstructor,a7=YA,qA=function(e){var t,i,r,n,s,o,l,c,h=Z8(this),_=$8(e),f=arguments.length,T=f>1?arguments[1]:void 0,b=T!==void 0,C=i7(_);if(C&&!r7(C))for(c=(l=t7(_,C)).next,_=[];!(o=Q8(c,l)).done;)_.push(o.value);for(b&&f>2&&(T=X8(T,arguments[2])),i=e7(_),r=new(s7(h))(i),n=n7(r),t=0;i>t;t++)s=b?T(_[t],t):_[t],r[t]=n?a7(s):+s;return r},XA=zS,o7=Kf,l7=Et,c7=xt("species"),QA=Array,u7=function(e){var t;return XA(e)&&(t=e.constructor,(o7(t)&&(t===QA||XA(t.prototype))||l7(t)&&(t=t[c7])===null)&&(t=void 0)),t===void 0?QA:t},d7=Qn,h7=we,p7=pr,m7=Lr,f7=function(e,t){return new(u7(e))(t===0?0:t)},ZA=X([].push),_7=function(e){var t=e===1,i=e===2,r=e===3,n=e===4,s=e===6,o=e===7,l=e===5||s;return function(c,h,_,f){for(var T,b,C=p7(c),x=h7(C),B=m7(x),Y=d7(h,_),G=0,he=f||f7,H=t?he(c,B):i||o?he(c,0):void 0;B>G;G++)if((l||G in x)&&(b=Y(T=x[G],G,C),e))if(t)H[G]=b;else if(b)switch(e){case 3:return!0;case 5:return T;case 6:return G;case 2:ZA(H,T)}else switch(e){case 4:return!1;case 7:ZA(H,T)}return s?-1:r||n?n:H}},$A={forEach:_7(0)},g7=Lr,eb=It,tb=y,ib=A,v7=E,E7=KA,Gl=cn,rb=Nd,nb=Ol,y7=F,jl=nn,T7=H8,S7=js,sb=uI,j_=JA,I7=function(e){var t=K8(e);return t<0?0:t>255?255:255&t},ab=Zm,zl=ui,R7=Jn,z_=Et,A7=ja,b7=Ya,C7=Lt,th=qa,k7=dd.f,ob=qA,w7=$A.forEach,D7=Pd,N7=zs,lb=Xi,cb=I,ub=function(e,t,i){for(var r=0,n=arguments.length>2?i:g7(t),s=new e(n);n>r;)s[r]=t[r++];return s},P7=Lf,K_=Mi.get,O7=Mi.set,M7=Mi.enforce,db=lb.f,L7=cb.f,J_=tb.RangeError,hb=rb.ArrayBuffer,x7=hb.prototype,U7=rb.DataView,ih=Gl.NATIVE_ARRAY_BUFFER_VIEWS,pb=Gl.TYPED_ARRAY_TAG,mb=Gl.TypedArray,Kl=Gl.TypedArrayPrototype,Y_=Gl.isTypedArray,rh="BYTES_PER_ELEMENT",q_="Wrong length",nh=function(e,t){N7(e,t,{configurable:!0,get:function(){return K_(this)[t]}})},fb=function(e){var t;return C7(x7,e)||(t=R7(e))==="ArrayBuffer"||t==="SharedArrayBuffer"},_b=function(e,t){return Y_(e)&&!A7(t)&&t in e&&T7(+t)&&t>=0},gb=function(e,t){return t=ab(t),_b(e,t)?y7(2,e[t]):L7(e,t)},vb=function(e,t,i){return t=ab(t),!(_b(e,t)&&z_(i)&&zl(i,"value"))||zl(i,"get")||zl(i,"set")||i.configurable||zl(i,"writable")&&!i.writable||zl(i,"enumerable")&&!i.enumerable?db(e,t,i):(e[t]=i.value,e)};v7?(ih||(cb.f=gb,lb.f=vb,nh(Kl,"buffer"),nh(Kl,"byteOffset"),nh(Kl,"byteLength"),nh(Kl,"length")),eb({target:"Object",stat:!0,forced:!ih},{getOwnPropertyDescriptor:gb,defineProperty:vb}),x_.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,n=e+(i?"Clamped":"")+"Array",s="get"+e,o="set"+e,l=tb[n],c=l,h=c&&c.prototype,_={},f=function(b,C){db(b,C,{get:function(){return(function(x,B){var Y=K_(x);return Y.view[s](B*r+Y.byteOffset,!0)})(this,C)},set:function(x){return(function(B,Y,G){var he=K_(B);he.view[o](Y*r+he.byteOffset,i?I7(G):G,!0)})(this,C,x)},enumerable:!0})};ih?E7&&(c=t(function(b,C,x,B){return nb(b,h),P7(z_(C)?fb(C)?B!==void 0?new l(C,j_(x,r),B):x!==void 0?new l(C,j_(x,r)):new l(C):Y_(C)?ub(c,C):ib(ob,c,C):new l(sb(C)),b,c)}),th&&th(c,mb),w7(k7(l),function(b){b in c||jl(c,b,l[b])}),c.prototype=h):(c=t(function(b,C,x,B){nb(b,h);var Y,G,he,H=0,Z=0;if(z_(C)){if(!fb(C))return Y_(C)?ub(c,C):ib(ob,c,C);Y=C,Z=j_(x,r);var de=C.byteLength;if(B===void 0){if(de%r)throw new J_(q_);if((G=de-Z)<0)throw new J_(q_)}else if((G=S7(B)*r)+Z>de)throw new J_(q_);he=G/r}else he=sb(C),Y=new hb(G=he*r);for(O7(b,{buffer:Y,byteOffset:Z,byteLength:G,length:he,view:new U7(Y)});H<he;)f(b,H++)}),th&&th(c,mb),h=c.prototype=b7(Kl)),h.constructor!==c&&jl(h,"constructor",c),M7(h).TypedArrayConstructor=c,pb&&jl(h,pb,n);var T=c!==l;_[n]=c,eb({global:!0,constructor:!0,forced:T,sham:!ih},_),rh in c||jl(c,rh,r),rh in h||jl(h,rh,r),D7(n)}):x_.exports=function(){};var Eb=x_.exports;Eb("Float32",function(e){return function(t,i,r){return e(this,t,i,r)}}),Eb("Uint8",function(e){return function(t,i,r){return e(this,t,i,r)}});var V7=pI,F7=YA,B7=Jn,H7=A,W7=S,G7=cn.aTypedArray,j7=cn.exportTypedArrayMethod,z7=X("".slice);j7("fill",function(e){var t=arguments.length;G7(this);var i=z7(B7(this),0,3)==="Big"?F7(e):+e;return H7(V7,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)},W7(function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),e!==1})),(0,cn.exportTypedArrayStaticMethod)("from",qA,KA);var yb=y,Tb=A,X_=cn,K7=Lr,J7=JA,Y7=pr,Sb=S,q7=yb.RangeError,Q_=yb.Int8Array,Ib=Q_&&Q_.prototype,Rb=Ib&&Ib.set,X7=X_.aTypedArray,Q7=X_.exportTypedArrayMethod,Z_=!Sb(function(){var e=new Uint8ClampedArray(2);return Tb(Rb,e,{length:1,0:3},1),e[1]!==3}),Z7=Z_&&X_.NATIVE_ARRAY_BUFFER_VIEWS&&Sb(function(){var e=new Q_(2);return e.set(1),e.set("2",1),e[0]!==0||e[1]!==2});Q7("set",function(e){X7(this);var t=J7(arguments.length>1?arguments[1]:void 0,1),i=Y7(e);if(Z_)return Tb(Rb,this,i,t);var r=this.length,n=K7(i),s=0;if(n+t>r)throw new q7("Wrong length");for(;s<n;)this[t+s]=i[s++]},!Z_||Z7);var $7=Od,$_=S,eF=Oi,tF=Of,Ab=XS,iF=QS,bb=Ei,Cb=$S,rF=cn.aTypedArray,nF=cn.exportTypedArrayMethod,Jl=y.Uint16Array,po=Jl&&$7(Jl.prototype.sort),sF=!(!po||$_(function(){po(new Jl(2),null)})&&$_(function(){po(new Jl(2),{})})),kb=!!po&&!$_(function(){if(bb)return bb<74;if(Ab)return Ab<67;if(iF)return!0;if(Cb)return Cb<602;var e,t,i=new Jl(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(po(i,function(n,s){return(n/4|0)-(s/4|0)}),e=0;e<516;e++)if(i[e]!==r[e])return!0});nF("sort",function(e){return e!==void 0&&eF(e),kb?po(this,e):tF(rF(this),(function(t){return function(i,r){return t!==void 0?+t(i,r)||0:r!=r?-1:i!=i?1:i===0&&r===0?1/i>0&&1/r<0?1:-1:i>r}})(e))},!kb||sF);var aF=It,oF=A,eg=X,wb=se,lF=$e,cF=Et,uF=ZR,Yl=Bi,dF=zn,hF=v_,pF=bA,mF=xt("replace"),fF=TypeError,tg=eg("".indexOf);eg("".replace);var Db=eg("".slice),_F=Math.max;aF({target:"String",proto:!0},{replaceAll:function(e,t){var i,r,n,s,o,l,c,h,_,f=wb(this),T=0,b="";if(cF(e)){if(uF(e)&&(i=Yl(wb(hF(e))),!~tg(i,"g")))throw new fF("`.replaceAll` does not allow non-global regexes");if(r=dF(e,mF))return oF(r,e,f,t)}for(n=Yl(f),s=Yl(e),(o=lF(t))||(t=Yl(t)),l=s.length,c=_F(1,l),h=tg(n,s);h!==-1;)_=o?Yl(t(s,h,n)):pF(s,n,h,[],void 0,t),b+=Db(n,T,h)+_,T=h+l,h=h+c>n.length?-1:tg(n,s,h+c);return T<n.length&&(b+=Db(n,T)),b}});var Nb={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},ig=sd("span").classList,Pb=ig&&ig.constructor&&ig.constructor.prototype,Ob=Pb===Object.prototype?void 0:Pb,gF=$A.forEach,vF=Sd("forEach")?[].forEach:function(e){return gF(this,e,arguments.length>1?arguments[1]:void 0)},Mb=y,Lb=Nb,EF=Ob,rg=vF,yF=nn,xb=function(e){if(e&&e.forEach!==rg)try{yF(e,"forEach",rg)}catch{e.forEach=rg}};for(var ng in Lb)Lb[ng]&&xb(Mb[ng]&&Mb[ng].prototype);xb(EF);var Ub=y,Vb=Nb,TF=Ob,ql=Yx,Fb=nn,SF=Ys,sg=xt("iterator"),ag=ql.values,Bb=function(e,t){if(e){if(e[sg]!==ag)try{Fb(e,sg,ag)}catch{e[sg]=ag}if(SF(e,t,!0),Vb[t]){for(var i in ql)if(e[i]!==ql[i])try{Fb(e,i,ql[i])}catch{e[i]=ql[i]}}}};for(var og in Vb)Bb(Ub[og]&&Ub[og].prototype,og);Bb(TF,"DOMTokenList");var Hb=Ld.clear;It({global:!0,bind:!0,enumerable:!0,forced:y.clearImmediate!==Hb},{clearImmediate:Hb});var Wb=y,IF=Jf,RF=$e,AF=Nf,bF=ae,CF=Pl,kF=Md,wF=Wb.Function,DF=/MSIE .\./.test(bF)||AF==="BUN"&&(function(){var e=Wb.Bun.version.split(".");return e.length<3||e[0]==="0"&&(e[1]<3||e[1]==="3"&&e[2]==="0")})(),NF=It,Gb=y,jb=Ld.set,PF=function(e,t){var i=1;return DF?function(r,n){var s=kF(arguments.length,1)>i,o=RF(r)?r:wF(r),l=s?CF(arguments,i):[],c=s?function(){IF(o,this,l)}:o;return e(c)}:e},zb=Gb.setImmediate?PF(jb):jb;NF({global:!0,bind:!0,enumerable:!0,forced:Gb.setImmediate!==zb},{setImmediate:zb});var OF=w_.charAt,MF=Bi,Kb=Mi,LF=xS,Jb=wf,Yb="String Iterator",xF=Kb.set,UF=Kb.getterFor(Yb);LF(String,"String",function(e){xF(this,{type:Yb,string:MF(e),index:0})},function(){var e,t=UF(this),i=t.string,r=t.index;return r>=i.length?Jb(void 0,!0):(e=OF(i,r),t.index+=e.length,Jb(e,!1))});var VF=S,FF=E,BF=xt("iterator"),qb=!VF(function(){var e=new URL("b?a=1&b=2&c=3","https://a"),t=e.searchParams,i=new URLSearchParams("a=1&a=2&b=3"),r="";return e.pathname="c%20d",t.forEach(function(n,s){t.delete("b"),r+=s+n}),i.delete("a",2),i.delete("b",void 0),!t.size&&!FF||!t.sort||e.href!=="https://a/c%20d?a=1&c=3"||t.get("c")!=="3"||String(new URLSearchParams("?a=1"))!=="a=1"||!t[BF]||new URL("https://a@b").username!=="a"||new URLSearchParams(new URLSearchParams("a=b")).get("a")!=="b"||new URL("https://тест").host!=="xn--e1aybc"||new URL("https://a#б").hash!=="#%D0%B1"||r!=="a1c3"||new URL("https://x",void 0).host!=="x"}),Xb=E,HF=X,WF=A,GF=S,lg=gS,jF=gf,zF=O,KF=pr,JF=we,mo=Object.assign,Qb=Object.defineProperty,YF=HF([].concat),qF=!mo||GF(function(){if(Xb&&mo({b:1},mo(Qb({},"a",{enumerable:!0,get:function(){Qb(this,"b",{value:3,enumerable:!1})}}),{b:2})).b!==1)return!0;var e={},t={},i=Symbol("assign detection"),r="abcdefghijklmnopqrst";return e[i]=7,r.split("").forEach(function(n){t[n]=n}),mo({},e)[i]!==7||lg(mo({},t)).join("")!==r})?function(e,t){for(var i=KF(e),r=arguments.length,n=1,s=jF.f,o=zF.f;r>n;)for(var l,c=JF(arguments[n++]),h=s?YF(lg(c),s(c)):lg(c),_=h.length,f=0;_>f;)l=h[f++],Xb&&!WF(o,c,l)||(i[l]=c[l]);return i}:mo,XF=yi,QF=LR,ZF=E,$F=Xi,eB=F,tB=Qn,iB=A,rB=pr,nB=function(e,t,i,r){try{return r?t(XF(i)[0],i[1]):t(i)}catch(n){QF(e,"throw",n)}},sB=f_,aB=Kf,oB=Lr,Zb=function(e,t,i){ZF?$F.f(e,t,eB(0,i)):e[t]=i},lB=jd,cB=Bl,$b=Array,ta=X,cg=2147483647,uB=/[^\0-\u007E]/,eC=/[.\u3002\uFF0E\uFF61]/g,tC="Overflow: input needs wider integers to process",iC=RangeError,dB=ta(eC.exec),fo=Math.floor,ug=String.fromCharCode,rC=ta("".charCodeAt),nC=ta([].join),ts=ta([].push),hB=ta("".replace),pB=ta("".split),mB=ta("".toLowerCase),sC=function(e){return e+22+75*(e<26)},fB=function(e,t,i){var r=0;for(e=i?fo(e/700):e>>1,e+=fo(e/t);e>455;)e=fo(e/35),r+=36;return fo(r+36*e/(e+38))},_B=function(e){var t=[];e=(function(Y){for(var G=[],he=0,H=Y.length;he<H;){var Z=rC(Y,he++);if(Z>=55296&&Z<=56319&&he<H){var de=rC(Y,he++);(64512&de)==56320?ts(G,((1023&Z)<<10)+(1023&de)+65536):(ts(G,Z),he--)}else ts(G,Z)}return G})(e);var i,r,n=e.length,s=128,o=0,l=72;for(i=0;i<e.length;i++)(r=e[i])<128&&ts(t,ug(r));var c=t.length,h=c;for(c&&ts(t,"-");h<n;){var _=cg;for(i=0;i<e.length;i++)(r=e[i])>=s&&r<_&&(_=r);var f=h+1;if(_-s>fo((cg-o)/f))throw new iC(tC);for(o+=(_-s)*f,s=_,i=0;i<e.length;i++){if((r=e[i])<s&&++o>cg)throw new iC(tC);if(r===s){for(var T=o,b=36;;){var C=b<=l?1:b>=l+26?26:b-l;if(T<C)break;var x=T-C,B=36-C;ts(t,ug(sC(C+x%B))),T=fo(x/B),b+=36}ts(t,ug(sC(T))),l=fB(o,f,h===c),o=0,h++}}o++,s++}return nC(t,"")},gB=It,vB=X,EB=hd,yB=RangeError,aC=String.fromCharCode,oC=String.fromCodePoint,TB=vB([].join);gB({target:"String",stat:!0,arity:1,forced:!!oC&&oC.length!==1},{fromCodePoint:function(e){for(var t,i=[],r=arguments.length,n=0;r>n;){if(t=+arguments[n++],EB(t,1114111)!==t)throw new yB(t+" is not a valid code point");i[n]=t<65536?aC(t):aC(55296+((t-=65536)>>10),t%1024+56320)}return TB(i,"")}});var dg=It,lC=y,hg=sR,SB=Mt,sh=A,gr=X,Xl=E,cC=qb,uC=Qi,IB=zs,RB=cI,AB=Ys,bB=DS,pg=Mi,dC=Ol,mg=$e,CB=ui,kB=Qn,wB=Jn,DB=yi,hC=Et,Si=Bi,NB=Ya,pC=F,mC=jd,PB=Bl,ah=wf,_o=Md,OB=Of,MB=xt("iterator"),go="URLSearchParams",fC=go+"Iterator",_C=pg.set,Zi=pg.getterFor(go),LB=pg.getterFor(fC),gC=hg("fetch"),oh=hg("Request"),Ql=hg("Headers"),fg=oh&&oh.prototype,vC=Ql&&Ql.prototype,xB=lC.TypeError,UB=lC.encodeURIComponent,VB=String.fromCharCode,FB=SB("String","fromCodePoint"),BB=parseInt,lh=gr("".charAt),EC=gr([].join),is=gr([].push),yC=gr("".replace),HB=gr([].shift),TC=gr([].splice),SC=gr("".split),IC=gr("".slice),WB=gr(/./.exec),GB=/\+/g,jB=/^[0-9a-f]+$/i,RC=function(e,t){var i=IC(e,t,t+2);return WB(jB,i)?BB(i,16):NaN},zB=function(e){for(var t=0,i=128;i>0&&(e&i)!==0;i>>=1)t++;return t},KB=function(e){var t=null;switch(e.length){case 1:t=e[0];break;case 2:t=(31&e[0])<<6|63&e[1];break;case 3:t=(15&e[0])<<12|(63&e[1])<<6|63&e[2];break;case 4:t=(7&e[0])<<18|(63&e[1])<<12|(63&e[2])<<6|63&e[3]}return t>1114111?null:t},AC=function(e){for(var t=(e=yC(e,GB," ")).length,i="",r=0;r<t;){var n=lh(e,r);if(n==="%"){if(lh(e,r+1)==="%"||r+3>t){i+="%",r++;continue}var s=RC(e,r+1);if(s!=s){i+=n,r++;continue}r+=2;var o=zB(s);if(o===0)n=VB(s);else{if(o===1||o>4){i+="�",r++;continue}for(var l=[s],c=1;c<o&&!(++r+3>t||lh(e,r)!=="%");){var h=RC(e,r+1);if(h!=h){r+=3;break}if(h>191||h<128)break;is(l,h),r+=2,c++}if(l.length!==o){i+="�";continue}var _=KB(l);_===null?i+="�":n=FB(_)}}i+=n,r++}return i},JB=/[!'()~]|%20/g,YB={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},qB=function(e){return YB[e]},bC=function(e){return yC(UB(e),JB,qB)},_g=bB(function(e,t){_C(this,{type:fC,target:Zi(e).entries,index:0,kind:t})},go,function(){var e=LB(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,ah(void 0,!0);var r=t[i];switch(e.kind){case"keys":return ah(r.key,!1);case"values":return ah(r.value,!1)}return ah([r.key,r.value],!1)},!0),CC=function(e){this.entries=[],this.url=null,e!==void 0&&(hC(e)?this.parseObject(e):this.parseQuery(typeof e=="string"?lh(e,0)==="?"?IC(e,1):e:Si(e)))};CC.prototype={type:go,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,n,s,o,l,c=this.entries,h=PB(e);if(h)for(i=(t=mC(e,h)).next;!(r=sh(i,t)).done;){if(s=(n=mC(DB(r.value))).next,(o=sh(s,n)).done||(l=sh(s,n)).done||!sh(s,n).done)throw new xB("Expected sequence with length 2");is(c,{key:Si(o.value),value:Si(l.value)})}else for(var _ in e)CB(e,_)&&is(c,{key:_,value:Si(e[_])})},parseQuery:function(e){if(e)for(var t,i,r=this.entries,n=SC(e,"&"),s=0;s<n.length;)(t=n[s++]).length&&(i=SC(t,"="),is(r,{key:AC(HB(i)),value:AC(EC(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],is(i,bC(e.key)+"="+bC(e.value));return EC(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var ch=function(){dC(this,vo);var e=_C(this,new CC(arguments.length>0?arguments[0]:void 0));Xl||(this.size=e.entries.length)},vo=ch.prototype;if(RB(vo,{append:function(e,t){var i=Zi(this);_o(arguments.length,2),is(i.entries,{key:Si(e),value:Si(t)}),Xl||this.size++,i.updateURL()},delete:function(e){for(var t=Zi(this),i=_o(arguments.length,1),r=t.entries,n=Si(e),s=i<2?void 0:arguments[1],o=s===void 0?s:Si(s),l=0;l<r.length;){var c=r[l];if(c.key!==n||o!==void 0&&c.value!==o)l++;else if(TC(r,l,1),o!==void 0)break}Xl||(this.size=r.length),t.updateURL()},get:function(e){var t=Zi(this).entries;_o(arguments.length,1);for(var i=Si(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){var t=Zi(this).entries;_o(arguments.length,1);for(var i=Si(e),r=[],n=0;n<t.length;n++)t[n].key===i&&is(r,t[n].value);return r},has:function(e){for(var t=Zi(this).entries,i=_o(arguments.length,1),r=Si(e),n=i<2?void 0:arguments[1],s=n===void 0?n:Si(n),o=0;o<t.length;){var l=t[o++];if(l.key===r&&(s===void 0||l.value===s))return!0}return!1},set:function(e,t){var i=Zi(this);_o(arguments.length,1);for(var r,n=i.entries,s=!1,o=Si(e),l=Si(t),c=0;c<n.length;c++)(r=n[c]).key===o&&(s?TC(n,c--,1):(s=!0,r.value=l));s||is(n,{key:o,value:l}),Xl||(this.size=n.length),i.updateURL()},sort:function(){var e=Zi(this);OB(e.entries,function(t,i){return t.key>i.key?1:-1}),e.updateURL()},forEach:function(e){for(var t,i=Zi(this).entries,r=kB(e,arguments.length>1?arguments[1]:void 0),n=0;n<i.length;)r((t=i[n++]).value,t.key,this)},keys:function(){return new _g(this,"keys")},values:function(){return new _g(this,"values")},entries:function(){return new _g(this,"entries")}},{enumerable:!0}),uC(vo,MB,vo.entries,{name:"entries"}),uC(vo,"toString",function(){return Zi(this).serialize()},{enumerable:!0}),Xl&&IB(vo,"size",{get:function(){return Zi(this).entries.length},configurable:!0,enumerable:!0}),AB(ch,go),dg({global:!0,constructor:!0,forced:!cC},{URLSearchParams:ch}),!cC&&mg(Ql)){var XB=gr(vC.has),QB=gr(vC.set),kC=function(e){if(hC(e)){var t,i=e.body;if(wB(i)===go)return t=e.headers?new Ql(e.headers):new Ql,XB(t,"content-type")||QB(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),NB(e,{body:pC(0,Si(i)),headers:pC(0,t)})}return e};if(mg(gC)&&dg({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return gC(e,arguments.length>1?kC(arguments[1]):{})}}),mg(oh)){var gg=function(e){return dC(this,fg),new oh(e,arguments.length>1?kC(arguments[1]):{})};fg.constructor=gg,gg.prototype=fg,dg({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:gg})}}var $i,ZB=It,vg=E,$B=qb,Eg=y,wC=Qn,er=X,uh=Qi,tr=zs,e9=Ol,yg=ui,Tg=qF,Eo=function(e){var t=rB(e),i=aB(this),r=arguments.length,n=r>1?arguments[1]:void 0,s=n!==void 0;s&&(n=tB(n,r>2?arguments[2]:void 0));var o,l,c,h,_,f,T=cB(t),b=0;if(!T||this===$b&&sB(T))for(o=oB(t),l=i?new this(o):$b(o);o>b;b++)f=s?n(t[b],b):t[b],Zb(l,b,f);else for(l=i?new this:[],_=(h=lB(t,T)).next;!(c=iB(_,h)).done;b++)f=s?nB(h,n,[c.value,b],!0):c.value,Zb(l,b,f);return l.length=b,l},vr=Pl,t9=w_.codeAt,i9=function(e){var t,i,r=[],n=pB(hB(mB(e),eC,"."),".");for(t=0;t<n.length;t++)i=n[t],ts(r,dB(uB,i)?"xn--"+_B(i):i);return nC(r,".")},un=Bi,r9=Ys,n9=Md,DC={URLSearchParams:ch,getState:Zi},NC=Mi,s9=NC.set,dh=NC.getterFor("URL"),a9=DC.URLSearchParams,o9=DC.getState,Zl=Eg.URL,Sg=Eg.TypeError,hh=Eg.parseInt,l9=Math.floor,PC=Math.pow,ir=er("".charAt),Er=er(/./.exec),$l=er([].join),c9=er(1.1.toString),u9=er([].pop),yo=er([].push),Ig=er("".replace),d9=er([].shift),h9=er("".split),ec=er("".slice),ph=er("".toLowerCase),p9=er([].unshift),Rg="Invalid scheme",ia="Invalid host",OC="Invalid port",MC=/[a-z]/i,m9=/[\d+-.a-z]/i,Ag=/\d/,f9=/^0x/i,_9=/^[0-7]+$/,g9=/^\d+$/,LC=/^[\da-f]+$/i,v9=/[\0\t\n\r #%/:<>?@[\\\]^|]/,E9=/[\0\t\n\r #/:<>?@[\\\]^|]/,y9=/^[\u0000-\u0020]+/,T9=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,S9=/[\t\n\r]/g,tc=function(e){var t,i,r,n;if(typeof e=="number"){for(t=[],i=0;i<4;i++)p9(t,e%256),e=l9(e/256);return $l(t,".")}if(typeof e=="object"){for(t="",r=(function(s){for(var o=null,l=1,c=null,h=0,_=0;_<8;_++)s[_]!==0?(h>l&&(o=c,l=h),c=null,h=0):(c===null&&(c=_),++h);return h>l?c:o})(e),i=0;i<8;i++)n&&e[i]===0||(n&&(n=!1),r===i?(t+=i?":":"::",n=!0):(t+=c9(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},mh={},xC=Tg({},mh,{" ":1,'"':1,"<":1,">":1,"`":1}),UC=Tg({},xC,{"#":1,"?":1,"{":1,"}":1}),bg=Tg({},UC,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),rs=function(e,t){var i=t9(e,0);return i>32&&i<127&&!yg(t,e)?e:encodeURIComponent(e)},fh={ftp:21,file:null,http:80,https:443,ws:80,wss:443},ic=function(e,t){var i;return e.length===2&&Er(MC,ir(e,0))&&((i=ir(e,1))===":"||!t&&i==="|")},VC=function(e){var t;return e.length>1&&ic(ec(e,0,2))&&(e.length===2||(t=ir(e,2))==="/"||t==="\\"||t==="?"||t==="#")},I9=function(e){return e==="."||ph(e)==="%2e"},R9=function(e){return(e=ph(e))===".."||e==="%2e."||e===".%2e"||e==="%2e%2e"},Cg={},FC={},kg={},BC={},HC={},wg={},WC={},GC={},_h={},gh={},Dg={},Ng={},Pg={},Og={},jC={},Mg={},To={},Ur={},zC={},ra={},dn={},Lg=function(e,t,i){var r,n,s,o=un(e);if(t){if(n=this.parse(o))throw new Sg(n);this.searchParams=null}else{if(i!==void 0&&(r=new Lg(i,!0)),n=this.parse(o,null,r))throw new Sg(n);(s=o9(new a9)).bindURL(this),this.searchParams=s}};Lg.prototype={type:"URL",parse:function(e,t,i){var r,n,s,o,l=this,c=t||Cg,h=0,_="",f=!1,T=!1,b=!1;for(e=un(e),t||(l.scheme="",l.username="",l.password="",l.host=null,l.port=null,l.path=[],l.query=null,l.fragment=null,l.cannotBeABaseURL=!1,e=Ig(e,y9,""),e=Ig(e,T9,"$1")),e=Ig(e,S9,""),r=Eo(e);h<=r.length;){switch(n=r[h],c){case Cg:if(!n||!Er(MC,n)){if(t)return Rg;c=kg;continue}_+=ph(n),c=FC;break;case FC:if(n&&(Er(m9,n)||n==="+"||n==="-"||n==="."))_+=ph(n);else{if(n!==":"){if(t)return Rg;_="",c=kg,h=0;continue}if(t&&(l.isSpecial()!==yg(fh,_)||_==="file"&&(l.includesCredentials()||l.port!==null)||l.scheme==="file"&&!l.host))return;if(l.scheme=_,t)return void(l.isSpecial()&&fh[l.scheme]===l.port&&(l.port=null));_="",l.scheme==="file"?c=Og:l.isSpecial()&&i&&i.scheme===l.scheme?c=BC:l.isSpecial()?c=GC:r[h+1]==="/"?(c=HC,h++):(l.cannotBeABaseURL=!0,yo(l.path,""),c=zC)}break;case kg:if(!i||i.cannotBeABaseURL&&n!=="#")return Rg;if(i.cannotBeABaseURL&&n==="#"){l.scheme=i.scheme,l.path=vr(i.path),l.query=i.query,l.fragment="",l.cannotBeABaseURL=!0,c=dn;break}c=i.scheme==="file"?Og:wg;continue;case BC:if(n!=="/"||r[h+1]!=="/"){c=wg;continue}c=_h,h++;break;case HC:if(n==="/"){c=gh;break}c=Ur;continue;case wg:if(l.scheme=i.scheme,n===$i)l.username=i.username,l.password=i.password,l.host=i.host,l.port=i.port,l.path=vr(i.path),l.query=i.query;else if(n==="/"||n==="\\"&&l.isSpecial())c=WC;else if(n==="?")l.username=i.username,l.password=i.password,l.host=i.host,l.port=i.port,l.path=vr(i.path),l.query="",c=ra;else{if(n!=="#"){l.username=i.username,l.password=i.password,l.host=i.host,l.port=i.port,l.path=vr(i.path),l.path.length--,c=Ur;continue}l.username=i.username,l.password=i.password,l.host=i.host,l.port=i.port,l.path=vr(i.path),l.query=i.query,l.fragment="",c=dn}break;case WC:if(!l.isSpecial()||n!=="/"&&n!=="\\"){if(n!=="/"){l.username=i.username,l.password=i.password,l.host=i.host,l.port=i.port,c=Ur;continue}c=gh}else c=_h;break;case GC:if(c=_h,n!=="/"||ir(_,h+1)!=="/")continue;h++;break;case _h:if(n!=="/"&&n!=="\\"){c=gh;continue}break;case gh:if(n==="@"){f&&(_="%40"+_),f=!0,s=Eo(_);for(var C=0;C<s.length;C++){var x=s[C];if(x!==":"||b){var B=rs(x,bg);b?l.password+=B:l.username+=B}else b=!0}_=""}else if(n===$i||n==="/"||n==="?"||n==="#"||n==="\\"&&l.isSpecial()){if(f&&_==="")return"Invalid authority";h-=Eo(_).length+1,_="",c=Dg}else _+=n;break;case Dg:case Ng:if(t&&l.scheme==="file"){c=Mg;continue}if(n!==":"||T){if(n===$i||n==="/"||n==="?"||n==="#"||n==="\\"&&l.isSpecial()){if(l.isSpecial()&&_==="")return ia;if(t&&_===""&&(l.includesCredentials()||l.port!==null))return;if(o=l.parseHost(_))return o;if(_="",c=To,t)return;continue}n==="["?T=!0:n==="]"&&(T=!1),_+=n}else{if(_==="")return ia;if(o=l.parseHost(_))return o;if(_="",c=Pg,t===Ng)return}break;case Pg:if(!Er(Ag,n)){if(n===$i||n==="/"||n==="?"||n==="#"||n==="\\"&&l.isSpecial()||t){if(_!==""){var Y=hh(_,10);if(Y>65535)return OC;l.port=l.isSpecial()&&Y===fh[l.scheme]?null:Y,_=""}if(t)return;c=To;continue}return OC}_+=n;break;case Og:if(l.scheme="file",n==="/"||n==="\\")c=jC;else{if(!i||i.scheme!=="file"){c=Ur;continue}switch(n){case $i:l.host=i.host,l.path=vr(i.path),l.query=i.query;break;case"?":l.host=i.host,l.path=vr(i.path),l.query="",c=ra;break;case"#":l.host=i.host,l.path=vr(i.path),l.query=i.query,l.fragment="",c=dn;break;default:VC($l(vr(r,h),""))||(l.host=i.host,l.path=vr(i.path),l.shortenPath()),c=Ur;continue}}break;case jC:if(n==="/"||n==="\\"){c=Mg;break}i&&i.scheme==="file"&&!VC($l(vr(r,h),""))&&(ic(i.path[0],!0)?yo(l.path,i.path[0]):l.host=i.host),c=Ur;continue;case Mg:if(n===$i||n==="/"||n==="\\"||n==="?"||n==="#"){if(!t&&ic(_))c=Ur;else if(_===""){if(l.host="",t)return;c=To}else{if(o=l.parseHost(_))return o;if(l.host==="localhost"&&(l.host=""),t)return;_="",c=To}continue}_+=n;break;case To:if(l.isSpecial()){if(c=Ur,n!=="/"&&n!=="\\")continue}else if(t||n!=="?")if(t||n!=="#"){if(n!==$i&&(c=Ur,n!=="/"))continue}else l.fragment="",c=dn;else l.query="",c=ra;break;case Ur:if(n===$i||n==="/"||n==="\\"&&l.isSpecial()||!t&&(n==="?"||n==="#")){if(R9(_)?(l.shortenPath(),n==="/"||n==="\\"&&l.isSpecial()||yo(l.path,"")):I9(_)?n==="/"||n==="\\"&&l.isSpecial()||yo(l.path,""):(l.scheme==="file"&&!l.path.length&&ic(_)&&(l.host&&(l.host=""),_=ir(_,0)+":"),yo(l.path,_)),_="",l.scheme==="file"&&(n===$i||n==="?"||n==="#"))for(;l.path.length>1&&l.path[0]==="";)d9(l.path);n==="?"?(l.query="",c=ra):n==="#"&&(l.fragment="",c=dn)}else _+=rs(n,UC);break;case zC:n==="?"?(l.query="",c=ra):n==="#"?(l.fragment="",c=dn):n!==$i&&(l.path[0]+=rs(n,mh));break;case ra:t||n!=="#"?n!==$i&&(n==="'"&&l.isSpecial()?l.query+="%27":l.query+=n==="#"?"%23":rs(n,mh)):(l.fragment="",c=dn);break;case dn:n!==$i&&(l.fragment+=rs(n,xC))}h++}},parseHost:function(e){var t,i,r;if(ir(e,0)==="["){if(ir(e,e.length-1)!=="]"||(t=(function(n){var s,o,l,c,h,_,f,T=[0,0,0,0,0,0,0,0],b=0,C=null,x=0,B=function(){return ir(n,x)};if(B()===":"){if(ir(n,1)!==":")return;x+=2,C=++b}for(;B();){if(b===8)return;if(B()!==":"){for(s=o=0;o<4&&Er(LC,B());)s=16*s+hh(B(),16),x++,o++;if(B()==="."){if(o===0||(x-=o,b>6))return;for(l=0;B();){if(c=null,l>0){if(!(B()==="."&&l<4))return;x++}if(!Er(Ag,B()))return;for(;Er(Ag,B());){if(h=hh(B(),10),c===null)c=h;else{if(c===0)return;c=10*c+h}if(c>255)return;x++}T[b]=256*T[b]+c,++l!==2&&l!==4||b++}if(l!==4)return;break}if(B()===":"){if(x++,!B())return}else if(B())return;T[b++]=s}else{if(C!==null)return;x++,C=++b}}if(C!==null)for(_=b-C,b=7;b!==0&&_>0;)f=T[b],T[b--]=T[C+_-1],T[C+--_]=f;else if(b!==8)return;return T})(ec(e,1,-1)),!t))return ia;this.host=t}else if(this.isSpecial()){if(e=i9(e),Er(v9,e)||(t=(function(n){var s,o,l,c,h,_,f,T=h9(n,".");if(T.length&&T[T.length-1]===""&&T.length--,(s=T.length)>4)return n;for(o=[],l=0;l<s;l++){if((c=T[l])==="")return n;if(h=10,c.length>1&&ir(c,0)==="0"&&(h=Er(f9,c)?16:8,c=ec(c,h===8?1:2)),c==="")_=0;else{if(!Er(h===10?g9:h===8?_9:LC,c))return n;_=hh(c,h)}yo(o,_)}for(l=0;l<s;l++)if(_=o[l],l===s-1){if(_>=PC(256,5-s))return null}else if(_>255)return null;for(f=u9(o),l=0;l<o.length;l++)f+=o[l]*PC(256,3-l);return f})(e),t===null))return ia;this.host=t}else{if(Er(E9,e))return ia;for(t="",i=Eo(e),r=0;r<i.length;r++)t+=rs(i[r],mh);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||this.scheme==="file"},includesCredentials:function(){return this.username!==""||this.password!==""},isSpecial:function(){return yg(fh,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||this.scheme==="file"&&t===1&&ic(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,i=e.username,r=e.password,n=e.host,s=e.port,o=e.path,l=e.query,c=e.fragment,h=t+":";return n!==null?(h+="//",e.includesCredentials()&&(h+=i+(r?":"+r:"")+"@"),h+=tc(n),s!==null&&(h+=":"+s)):t==="file"&&(h+="//"),h+=e.cannotBeABaseURL?o[0]:o.length?"/"+$l(o,"/"):"",l!==null&&(h+="?"+l),c!==null&&(h+="#"+c),h},setHref:function(e){var t=this.parse(e);if(t)throw new Sg(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if(e==="blob")try{return new So(e.path[0]).origin}catch{return"null"}return e!=="file"&&this.isSpecial()?e+"://"+tc(this.host)+(t!==null?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(un(e)+":",Cg)},getUsername:function(){return this.username},setUsername:function(e){var t=Eo(un(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=rs(t[i],bg)}},getPassword:function(){return this.password},setPassword:function(e){var t=Eo(un(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=rs(t[i],bg)}},getHost:function(){var e=this.host,t=this.port;return e===null?"":t===null?tc(e):tc(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,Dg)},getHostname:function(){var e=this.host;return e===null?"":tc(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,Ng)},getPort:function(){var e=this.port;return e===null?"":un(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||((e=un(e))===""?this.port=null:this.parse(e,Pg))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+$l(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,To))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){(e=un(e))===""?this.query=null:(ir(e,0)==="?"&&(e=ec(e,1)),this.query="",this.parse(e,ra)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){(e=un(e))!==""?(ir(e,0)==="#"&&(e=ec(e,1)),this.fragment="",this.parse(e,dn)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var So=function(e){var t=e9(this,Ii),i=n9(arguments.length,1)>1?arguments[1]:void 0,r=s9(t,new Lg(e,!1,i));vg||(t.href=r.serialize(),t.origin=r.getOrigin(),t.protocol=r.getProtocol(),t.username=r.getUsername(),t.password=r.getPassword(),t.host=r.getHost(),t.hostname=r.getHostname(),t.port=r.getPort(),t.pathname=r.getPathname(),t.search=r.getSearch(),t.searchParams=r.getSearchParams(),t.hash=r.getHash())},Ii=So.prototype,rr=function(e,t){return{get:function(){return dh(this)[e]()},set:t&&function(i){return dh(this)[t](i)},configurable:!0,enumerable:!0}};if(vg&&(tr(Ii,"href",rr("serialize","setHref")),tr(Ii,"origin",rr("getOrigin")),tr(Ii,"protocol",rr("getProtocol","setProtocol")),tr(Ii,"username",rr("getUsername","setUsername")),tr(Ii,"password",rr("getPassword","setPassword")),tr(Ii,"host",rr("getHost","setHost")),tr(Ii,"hostname",rr("getHostname","setHostname")),tr(Ii,"port",rr("getPort","setPort")),tr(Ii,"pathname",rr("getPathname","setPathname")),tr(Ii,"search",rr("getSearch","setSearch")),tr(Ii,"searchParams",rr("getSearchParams")),tr(Ii,"hash",rr("getHash","setHash"))),uh(Ii,"toJSON",function(){return dh(this).serialize()},{enumerable:!0}),uh(Ii,"toString",function(){return dh(this).serialize()},{enumerable:!0}),Zl){var KC=Zl.createObjectURL,JC=Zl.revokeObjectURL;KC&&uh(So,"createObjectURL",wC(KC,Zl)),JC&&uh(So,"revokeObjectURL",wC(JC,Zl))}r9(So,"URL"),ZB({global:!0,constructor:!0,forced:!$B,sham:!vg},{URL:So});var A9=A;It({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return A9(URL.prototype.toString,this)}});let YC=!0,qC=!0;function rc(e,t,i){const r=e.match(t);return r&&r.length>=i&&parseFloat(r[i],10)}function na(e,t,i){if(!e.RTCPeerConnection)return;const r=e.RTCPeerConnection.prototype,n=r.addEventListener;r.addEventListener=function(o,l){if(o!==t)return n.apply(this,arguments);const c=h=>{const _=i(h);_&&(l.handleEvent?l.handleEvent(_):l(_))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(l,c),n.apply(this,[o,c])};const s=r.removeEventListener;r.removeEventListener=function(o,l){if(o!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(l))return s.apply(this,arguments);const c=this._eventMap[t].get(l);return this._eventMap[t].delete(l),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[o,c])},Object.defineProperty(r,"on"+t,{get(){return this["_on"+t]},set(o){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),o&&this.addEventListener(t,this["_on"+t]=o)},enumerable:!0,configurable:!0})}function b9(e){return typeof e!="boolean"?new Error("Argument type: "+typeof e+". Please use a boolean."):(YC=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function C9(e){return typeof e!="boolean"?new Error("Argument type: "+typeof e+". Please use a boolean."):(qC=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function XC(){if(typeof window=="object"){if(YC)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function xg(e,t){qC&&console.warn(e+" is deprecated, please use "+t+" instead.")}function QC(e){return Object.prototype.toString.call(e)==="[object Object]"}function ZC(e){return QC(e)?Object.keys(e).reduce(function(t,i){const r=QC(e[i]),n=r?ZC(e[i]):e[i],s=r&&!Object.keys(n).length;return n===void 0||s?t:Object.assign(t,{[i]:n})},{}):e}function Ug(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach(r=>{r.endsWith("Id")?Ug(e,e.get(t[r]),i):r.endsWith("Ids")&&t[r].forEach(n=>{Ug(e,e.get(n),i)})}))}function $C(e,t,i){const r=i?"outbound-rtp":"inbound-rtp",n=new Map;if(t===null)return n;const s=[];return e.forEach(o=>{o.type==="track"&&o.trackIdentifier===t.id&&s.push(o)}),s.forEach(o=>{e.forEach(l=>{l.type===r&&l.trackId===o.id&&Ug(e,l,n)})}),n}const e1=XC;function t1(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const r=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const l={};return Object.keys(o).forEach(c=>{if(c==="require"||c==="advanced"||c==="mediaSource")return;const h=typeof o[c]=="object"?o[c]:{ideal:o[c]};h.exact!==void 0&&typeof h.exact=="number"&&(h.min=h.max=h.exact);const _=function(f,T){return f?f+T.charAt(0).toUpperCase()+T.slice(1):T==="deviceId"?"sourceId":T};if(h.ideal!==void 0){l.optional=l.optional||[];let f={};typeof h.ideal=="number"?(f[_("min",c)]=h.ideal,l.optional.push(f),f={},f[_("max",c)]=h.ideal,l.optional.push(f)):(f[_("",c)]=h.ideal,l.optional.push(f))}h.exact!==void 0&&typeof h.exact!="number"?(l.mandatory=l.mandatory||{},l.mandatory[_("",c)]=h.exact):["min","max"].forEach(f=>{h[f]!==void 0&&(l.mandatory=l.mandatory||{},l.mandatory[_(f,c)]=h[f])})}),o.advanced&&(l.optional=(l.optional||[]).concat(o.advanced)),l},n=function(o,l){if(t.version>=61)return l(o);if((o=JSON.parse(JSON.stringify(o)))&&typeof o.audio=="object"){const c=function(h,_,f){_ in h&&!(f in h)&&(h[f]=h[_],delete h[_])};c((o=JSON.parse(JSON.stringify(o))).audio,"autoGainControl","googAutoGainControl"),c(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=r(o.audio)}if(o&&typeof o.video=="object"){let c=o.video.facingMode;c=c&&(typeof c=="object"?c:{ideal:c});const h=t.version<66;if(c&&(c.exact==="user"||c.exact==="environment"||c.ideal==="user"||c.ideal==="environment")&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||h)){let _;if(delete o.video.facingMode,c.exact==="environment"||c.ideal==="environment"?_=["back","rear"]:c.exact!=="user"&&c.ideal!=="user"||(_=["front"]),_)return i.mediaDevices.enumerateDevices().then(f=>{f=f.filter(b=>b.kind==="videoinput");let T=f.find(b=>_.some(C=>b.label.toLowerCase().includes(C)));return!T&&f.length&&_.includes("back")&&(T=f[f.length-1]),T&&(o.video.deviceId=c.exact?{exact:T.deviceId}:{ideal:T.deviceId}),o.video=r(o.video),e1("chrome: "+JSON.stringify(o)),l(o)})}o.video=r(o.video)}return e1("chrome: "+JSON.stringify(o)),l(o)},s=function(o){return t.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=(function(o,l,c){n(o,h=>{i.webkitGetUserMedia(h,l,_=>{c&&c(s(_))})})}).bind(i),i.mediaDevices.getUserMedia){const o=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(l){return n(l,c=>o(c).then(h=>{if(c.audio&&!h.getAudioTracks().length||c.video&&!h.getVideoTracks().length)throw h.getTracks().forEach(_=>{_.stop()}),new DOMException("","NotFoundError");return h},h=>Promise.reject(s(h))))}}}function i1(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function r1(e){if(typeof e=="object"&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(i){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=i)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",r=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(o=>o.track&&o.track.id===r.track.id):{track:r.track};const s=new Event("track");s.track=r.track,s.receiver=n,s.transceiver={receiver:n},s.streams=[i.stream],this.dispatchEvent(s)}),i.stream.getTracks().forEach(r=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(o=>o.track&&o.track.id===r.id):{track:r};const s=new Event("track");s.track=r,s.receiver=n,s.transceiver={receiver:n},s.streams=[i.stream],this.dispatchEvent(s)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else na(e,"track",t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t))}function n1(e){if(typeof e=="object"&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(n,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=n.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:n}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(o,l){let c=n.apply(this,arguments);return c||(c=t(this,o),this._senders.push(c)),c};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(o){s.apply(this,arguments);const l=this._senders.indexOf(o);l!==-1&&this._senders.splice(l,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(n){this._senders=this._senders||[],i.apply(this,[n]),n.getTracks().forEach(s=>{this._senders.push(t(this,s))})};const r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(n){this._senders=this._senders||[],r.apply(this,[n]),n.getTracks().forEach(s=>{const o=this._senders.find(l=>l.track===s);o&&this._senders.splice(this._senders.indexOf(o),1)})}}else if(typeof e=="object"&&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 i=t.apply(this,[]);return i.forEach(r=>r._pc=this),i},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function s1(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[i,r,n]=arguments;if(arguments.length>0&&typeof i=="function")return t.apply(this,arguments);if(t.length===0&&(arguments.length===0||typeof i!="function"))return t.apply(this,[]);const s=function(l){const c={};return l.result().forEach(h=>{const _={id:h.id,timestamp:h.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[h.type]||h.type};h.names().forEach(f=>{_[f]=h.stat(f)}),c[_.id]=_}),c},o=function(l){return new Map(Object.keys(l).map(c=>[c,l[c]]))};if(arguments.length>=2){const l=function(c){r(o(s(c)))};return t.apply(this,[l,i])}return new Promise((l,c)=>{t.apply(this,[function(h){l(o(s(h)))},c])}).then(r,n)}}function a1(e){if(!(typeof e=="object"&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const i=e.RTCPeerConnection.prototype.getSenders;i&&(e.RTCPeerConnection.prototype.getSenders=function(){const n=i.apply(this,[]);return n.forEach(s=>s._pc=this),n});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const n=r.apply(this,arguments);return n._pc=this,n}),e.RTCRtpSender.prototype.getStats=function(){const n=this;return this._pc.getStats().then(s=>$C(s,n.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const i=e.RTCPeerConnection.prototype.getReceivers;i&&(e.RTCPeerConnection.prototype.getReceivers=function(){const r=i.apply(this,[]);return r.forEach(n=>n._pc=this),r}),na(e,"track",r=>(r.receiver._pc=r.srcElement,r)),e.RTCRtpReceiver.prototype.getStats=function(){const r=this;return this._pc.getStats().then(n=>$C(n,r.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 i=arguments[0];let r,n,s;return this.getSenders().forEach(o=>{o.track===i&&(r?s=!0:r=o)}),this.getReceivers().forEach(o=>(o.track===i&&(n?s=!0:n=o),o.track===i)),s||r&&n?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):r?r.getStats():n?n.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function o1(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(s=>this._shimmedLocalStreams[s][0])};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(s,o){if(!o)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const l=t.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(l)===-1&&this._shimmedLocalStreams[o.id].push(l):this._shimmedLocalStreams[o.id]=[o,l],l};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(s){this._shimmedLocalStreams=this._shimmedLocalStreams||{},s.getTracks().forEach(c=>{if(this.getSenders().find(h=>h.track===c))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();i.apply(this,arguments);const l=this.getSenders().filter(c=>o.indexOf(c)===-1);this._shimmedLocalStreams[s.id]=[s].concat(l)};const r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(s){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[s.id],r.apply(this,arguments)};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(s){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},s&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const l=this._shimmedLocalStreams[o].indexOf(s);l!==-1&&this._shimmedLocalStreams[o].splice(l,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),n.apply(this,arguments)}}function l1(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return o1(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const c=i.apply(this);return this._reverseStreams=this._reverseStreams||{},c.map(h=>this._reverseStreams[h.id])};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(c){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},c.getTracks().forEach(h=>{if(this.getSenders().find(_=>_.track===h))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[c.id]){const h=new e.MediaStream(c.getTracks());this._streams[c.id]=h,this._reverseStreams[h.id]=c,c=h}r.apply(this,[c])};const n=e.RTCPeerConnection.prototype.removeStream;function s(c,h){let _=h.sdp;return Object.keys(c._reverseStreams||[]).forEach(f=>{const T=c._reverseStreams[f],b=c._streams[T.id];_=_.replace(new RegExp(b.id,"g"),T.id)}),new RTCSessionDescription({type:h.type,sdp:_})}e.RTCPeerConnection.prototype.removeStream=function(c){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[c.id]||c]),delete this._reverseStreams[this._streams[c.id]?this._streams[c.id].id:c.id],delete this._streams[c.id]},e.RTCPeerConnection.prototype.addTrack=function(c,h){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const _=[].slice.call(arguments,1);if(_.length!==1||!_[0].getTracks().find(T=>T===c))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(T=>T.track===c))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const f=this._streams[h.id];if(f)f.addTrack(c),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const T=new e.MediaStream([c]);this._streams[h.id]=T,this._reverseStreams[T.id]=h,this.addStream(T)}return this.getSenders().find(T=>T.track===c)},["createOffer","createAnswer"].forEach(function(c){const h=e.RTCPeerConnection.prototype[c],_={[c](){const f=arguments;return arguments.length&&typeof arguments[0]=="function"?h.apply(this,[T=>{const b=s(this,T);f[0].apply(null,[b])},T=>{f[1]&&f[1].apply(null,T)},arguments[2]]):h.apply(this,arguments).then(T=>s(this,T))}};e.RTCPeerConnection.prototype[c]=_[c]});const o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=(function(c,h){let _=h.sdp;return Object.keys(c._reverseStreams||[]).forEach(f=>{const T=c._reverseStreams[f],b=c._streams[T.id];_=_.replace(new RegExp(T.id,"g"),b.id)}),new RTCSessionDescription({type:h.type,sdp:_})})(this,arguments[0]),o.apply(this,arguments)):o.apply(this,arguments)};const l=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const c=l.get.apply(this);return c.type===""?c:s(this,c)}}),e.RTCPeerConnection.prototype.removeTrack=function(c){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!c._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(c._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let h;this._streams=this._streams||{},Object.keys(this._streams).forEach(_=>{this._streams[_].getTracks().find(f=>c.track===f)&&(h=this._streams[_])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(c.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Vg(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(i){const r=e.RTCPeerConnection.prototype[i],n={[i](){return arguments[0]=new(i==="addIceCandidate"?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[i]=n[i]})}function c1(e,t){na(e,"negotiationneeded",i=>{const r=i.target;if(!(t.version<72||r.getConfiguration&&r.getConfiguration().sdpSemantics==="plan-b")||r.signalingState==="stable")return i})}var u1=Object.freeze({__proto__:null,shimMediaStream:i1,shimOnTrack:r1,shimGetSendersWithDtmf:n1,shimGetStats:s1,shimSenderReceiverGetStats:a1,shimAddTrackRemoveTrackWithNative:o1,shimAddTrackRemoveTrack:l1,shimPeerConnection:Vg,fixNegotiationNeeded:c1,shimGetUserMedia:t1,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(typeof t=="function"?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then(r=>{const n=i.video&&i.video.width,s=i.video&&i.video.height,o=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:r,maxFrameRate:o||3}},n&&(i.video.mandatory.maxWidth=n),s&&(i.video.mandatory.maxHeight=s),e.navigator.mediaDevices.getUserMedia(i)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function d1(e,t){const i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(n,s,o){xg("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(n).then(s,o)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const n=function(o,l,c){l in o&&!(c in o)&&(o[c]=o[l],delete o[l])},s=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),n(o.audio,"autoGainControl","mozAutoGainControl"),n(o.audio,"noiseSuppression","mozNoiseSuppression")),s(o)},r&&r.prototype.getSettings){const o=r.prototype.getSettings;r.prototype.getSettings=function(){const l=o.apply(this,arguments);return n(l,"mozAutoGainControl","autoGainControl"),n(l,"mozNoiseSuppression","noiseSuppression"),l}}if(r&&r.prototype.applyConstraints){const o=r.prototype.applyConstraints;r.prototype.applyConstraints=function(l){return this.kind==="audio"&&typeof l=="object"&&(l=JSON.parse(JSON.stringify(l)),n(l,"autoGainControl","mozAutoGainControl"),n(l,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[l])}}}}function h1(e){typeof e=="object"&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Fg(e,t){if(typeof e!="object"||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(n){const s=e.RTCPeerConnection.prototype[n],o={[n](){return arguments[0]=new(n==="addIceCandidate"?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};e.RTCPeerConnection.prototype[n]=o[n]});const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[n,s,o]=arguments;return r.apply(this,[n||null]).then(l=>{if(t.version<53&&!s)try{l.forEach(c=>{c.type=i[c.type]||c.type})}catch(c){if(c.name!=="TypeError")throw c;l.forEach((h,_)=>{l.set(_,Object.assign({},h,{type:i[h.type]||h.type}))})}return l}).then(s,o)}}function p1(e){if(typeof e!="object"||!e.RTCPeerConnection||!e.RTCRtpSender||e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const r=t.apply(this,[]);return r.forEach(n=>n._pc=this),r});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const r=i.apply(this,arguments);return r._pc=this,r}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function m1(e){if(typeof e!="object"||!e.RTCPeerConnection||!e.RTCRtpSender||e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const i=t.apply(this,[]);return i.forEach(r=>r._pc=this),i}),na(e,"track",i=>(i.receiver._pc=i.srcElement,i)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function f1(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(t){xg("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function _1(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function g1(e){if(typeof e!="object"||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const r=i.length>0;r&&i.forEach(s=>{if("rid"in s&&!/^[a-z0-9]{0,16}$/i.test(s.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in s&&!(parseFloat(s.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in s&&!(parseFloat(s.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const n=t.apply(this,arguments);if(r){const{sender:s}=n,o=s.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=i,s.sendEncodings=i,this.setParametersPromises.push(s.setParameters(o).then(()=>{delete s.sendEncodings}).catch(()=>{delete s.sendEncodings})))}return n})}function v1(e){if(typeof e!="object"||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const i=t.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function E1(e){if(typeof e!="object"||!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 y1(e){if(typeof e!="object"||!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 T1=Object.freeze({__proto__:null,shimOnTrack:h1,shimPeerConnection:Fg,shimSenderGetStats:p1,shimReceiverGetStats:m1,shimRemoveStream:f1,shimRTCDataChannel:_1,shimAddTransceiver:g1,shimGetParameters:v1,shimCreateOffer:E1,shimCreateAnswer:y1,shimGetUserMedia:d1,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 r=new DOMException("getDisplayMedia without video constraints is undefined");return r.name="NotFoundError",r.code=8,Promise.reject(r)}return i.video===!0?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})}});function S1(e){if(typeof e=="object"&&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(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(r=>t.call(this,r,i)),i.getVideoTracks().forEach(r=>t.call(this,r,i))},e.RTCPeerConnection.prototype.addTrack=function(i,...r){return r&&r.forEach(n=>{this._localStreams?this._localStreams.includes(n)||this._localStreams.push(n):this._localStreams=[n]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(t);if(i===-1)return;this._localStreams.splice(i,1);const r=t.getTracks();this.getSenders().forEach(n=>{r.includes(n.track)&&this.removeTrack(n)})})}}function I1(e){if(typeof e=="object"&&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(i){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=i),this.addEventListener("track",this._onaddstreampoly=r=>{r.streams.forEach(n=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(n))return;this._remoteStreams.push(n);const s=new Event("addstream");s.stream=n,this.dispatchEvent(s)})})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(r){r.streams.forEach(n=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(n)>=0)return;i._remoteStreams.push(n);const s=new Event("addstream");s.stream=n,i.dispatchEvent(s)})}),t.apply(i,arguments)}}}function R1(e){if(typeof e!="object"||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,r=t.createAnswer,n=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(c,h){const _=arguments.length>=2?arguments[2]:arguments[0],f=i.apply(this,[_]);return h?(f.then(c,h),Promise.resolve()):f},t.createAnswer=function(c,h){const _=arguments.length>=2?arguments[2]:arguments[0],f=r.apply(this,[_]);return h?(f.then(c,h),Promise.resolve()):f};let l=function(c,h,_){const f=n.apply(this,[c]);return _?(f.then(h,_),Promise.resolve()):f};t.setLocalDescription=l,l=function(c,h,_){const f=s.apply(this,[c]);return _?(f.then(h,_),Promise.resolve()):f},t.setRemoteDescription=l,l=function(c,h,_){const f=o.apply(this,[c]);return _?(f.then(h,_),Promise.resolve()):f},t.addIceCandidate=l}function A1(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const i=t.mediaDevices,r=i.getUserMedia.bind(i);t.mediaDevices.getUserMedia=n=>r(b1(n))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=(function(i,r,n){t.mediaDevices.getUserMedia(i).then(r,n)}).bind(t))}function b1(e){return e&&e.video!==void 0?Object.assign({},e,{video:ZC(e.video)}):e}function C1(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(i,r){if(i&&i.iceServers){const n=[];for(let s=0;s<i.iceServers.length;s++){let o=i.iceServers[s];o.urls===void 0&&o.url?(xg("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,n.push(o)):n.push(i.iceServers[s])}i.iceServers=n}return new t(i,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function k1(e){typeof e=="object"&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function w1(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(i){if(i){i.offerToReceiveAudio!==void 0&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const r=this.getTransceivers().find(s=>s.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):i.offerToReceiveAudio!==!0||r||this.addTransceiver("audio",{direction:"recvonly"}),i.offerToReceiveVideo!==void 0&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const n=this.getTransceivers().find(s=>s.receiver.track.kind==="video");i.offerToReceiveVideo===!1&&n?n.direction==="sendrecv"?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":n.direction==="recvonly"&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):i.offerToReceiveVideo!==!0||n||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function D1(e){typeof e!="object"||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var N1=Object.freeze({__proto__:null,shimLocalStreamsAPI:S1,shimRemoteStreamsAPI:I1,shimCallbacksAPI:R1,shimGetUserMedia:A1,shimConstraints:b1,shimRTCIceServerUrls:C1,shimTrackEventTransceiver:k1,shimCreateOfferLegacy:w1,shimAudioContext:D1}),P1={exports:{}};(function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(i){return i.trim().split(`
5
+ `).map(r=>r.trim())},t.splitSections=function(i){return i.split(`
6
+ m=`).map((r,n)=>(n>0?"m="+r:r).trim()+`\r
7
+ `)},t.getDescription=function(i){const r=t.splitSections(i);return r&&r[0]},t.getMediaSections=function(i){const r=t.splitSections(i);return r.shift(),r},t.matchPrefix=function(i,r){return t.splitLines(i).filter(n=>n.indexOf(r)===0)},t.parseCandidate=function(i){let r;r=i.indexOf("a=candidate:")===0?i.substring(12).split(" "):i.substring(10).split(" ");const n={foundation:r[0],component:{1:"rtp",2:"rtcp"}[r[1]]||r[1],protocol:r[2].toLowerCase(),priority:parseInt(r[3],10),ip:r[4],address:r[4],port:parseInt(r[5],10),type:r[7]};for(let s=8;s<r.length;s+=2)switch(r[s]){case"raddr":n.relatedAddress=r[s+1];break;case"rport":n.relatedPort=parseInt(r[s+1],10);break;case"tcptype":n.tcpType=r[s+1];break;case"ufrag":n.ufrag=r[s+1],n.usernameFragment=r[s+1];break;default:n[r[s]]===void 0&&(n[r[s]]=r[s+1])}return n},t.writeCandidate=function(i){const r=[];r.push(i.foundation);const n=i.component;n==="rtp"?r.push(1):n==="rtcp"?r.push(2):r.push(n),r.push(i.protocol.toUpperCase()),r.push(i.priority),r.push(i.address||i.ip),r.push(i.port);const s=i.type;return r.push("typ"),r.push(s),s!=="host"&&i.relatedAddress&&i.relatedPort&&(r.push("raddr"),r.push(i.relatedAddress),r.push("rport"),r.push(i.relatedPort)),i.tcpType&&i.protocol.toLowerCase()==="tcp"&&(r.push("tcptype"),r.push(i.tcpType)),(i.usernameFragment||i.ufrag)&&(r.push("ufrag"),r.push(i.usernameFragment||i.ufrag)),"candidate:"+r.join(" ")},t.parseIceOptions=function(i){return i.substring(14).split(" ")},t.parseRtpMap=function(i){let r=i.substring(9).split(" ");const n={payloadType:parseInt(r.shift(),10)};return r=r[0].split("/"),n.name=r[0],n.clockRate=parseInt(r[1],10),n.channels=r.length===3?parseInt(r[2],10):1,n.numChannels=n.channels,n},t.writeRtpMap=function(i){let r=i.payloadType;i.preferredPayloadType!==void 0&&(r=i.preferredPayloadType);const n=i.channels||i.numChannels||1;return"a=rtpmap:"+r+" "+i.name+"/"+i.clockRate+(n!==1?"/"+n:"")+`\r
8
+ `},t.parseExtmap=function(i){const r=i.substring(9).split(" ");return{id:parseInt(r[0],10),direction:r[0].indexOf("/")>0?r[0].split("/")[1]:"sendrecv",uri:r[1],attributes:r.slice(2).join(" ")}},t.writeExtmap=function(i){return"a=extmap:"+(i.id||i.preferredId)+(i.direction&&i.direction!=="sendrecv"?"/"+i.direction:"")+" "+i.uri+(i.attributes?" "+i.attributes:"")+`\r
9
+ `},t.parseFmtp=function(i){const r={};let n;const s=i.substring(i.indexOf(" ")+1).split(";");for(let o=0;o<s.length;o++)n=s[o].trim().split("="),r[n[0].trim()]=n[1];return r},t.writeFmtp=function(i){let r="",n=i.payloadType;if(i.preferredPayloadType!==void 0&&(n=i.preferredPayloadType),i.parameters&&Object.keys(i.parameters).length){const s=[];Object.keys(i.parameters).forEach(o=>{i.parameters[o]!==void 0?s.push(o+"="+i.parameters[o]):s.push(o)}),r+="a=fmtp:"+n+" "+s.join(";")+`\r
10
+ `}return r},t.parseRtcpFb=function(i){const r=i.substring(i.indexOf(" ")+1).split(" ");return{type:r.shift(),parameter:r.join(" ")}},t.writeRtcpFb=function(i){let r="",n=i.payloadType;return i.preferredPayloadType!==void 0&&(n=i.preferredPayloadType),i.rtcpFeedback&&i.rtcpFeedback.length&&i.rtcpFeedback.forEach(s=>{r+="a=rtcp-fb:"+n+" "+s.type+(s.parameter&&s.parameter.length?" "+s.parameter:"")+`\r
11
+ `}),r},t.parseSsrcMedia=function(i){const r=i.indexOf(" "),n={ssrc:parseInt(i.substring(7,r),10)},s=i.indexOf(":",r);return s>-1?(n.attribute=i.substring(r+1,s),n.value=i.substring(s+1)):n.attribute=i.substring(r+1),n},t.parseSsrcGroup=function(i){const r=i.substring(13).split(" ");return{semantics:r.shift(),ssrcs:r.map(n=>parseInt(n,10))}},t.getMid=function(i){const r=t.matchPrefix(i,"a=mid:")[0];if(r)return r.substring(6)},t.parseFingerprint=function(i){const r=i.substring(14).split(" ");return{algorithm:r[0].toLowerCase(),value:r[1].toUpperCase()}},t.getDtlsParameters=function(i,r){return{role:"auto",fingerprints:t.matchPrefix(i+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(i,r){let n="a=setup:"+r+`\r
12
+ `;return i.fingerprints.forEach(s=>{n+="a=fingerprint:"+s.algorithm+" "+s.value+`\r
13
+ `}),n},t.parseCryptoLine=function(i){const r=i.substring(9).split(" ");return{tag:parseInt(r[0],10),cryptoSuite:r[1],keyParams:r[2],sessionParams:r.slice(3)}},t.writeCryptoLine=function(i){return"a=crypto:"+i.tag+" "+i.cryptoSuite+" "+(typeof i.keyParams=="object"?t.writeCryptoKeyParams(i.keyParams):i.keyParams)+(i.sessionParams?" "+i.sessionParams.join(" "):"")+`\r
14
+ `},t.parseCryptoKeyParams=function(i){if(i.indexOf("inline:")!==0)return null;const r=i.substring(7).split("|");return{keyMethod:"inline",keySalt:r[0],lifeTime:r[1],mkiValue:r[2]?r[2].split(":")[0]:void 0,mkiLength:r[2]?r[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(i){return i.keyMethod+":"+i.keySalt+(i.lifeTime?"|"+i.lifeTime:"")+(i.mkiValue&&i.mkiLength?"|"+i.mkiValue+":"+i.mkiLength:"")},t.getCryptoParameters=function(i,r){return t.matchPrefix(i+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(i,r){const n=t.matchPrefix(i+r,"a=ice-ufrag:")[0],s=t.matchPrefix(i+r,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.substring(12),password:s.substring(10)}:null},t.writeIceParameters=function(i){let r="a=ice-ufrag:"+i.usernameFragment+`\r
15
+ a=ice-pwd:`+i.password+`\r
16
+ `;return i.iceLite&&(r+=`a=ice-lite\r
17
+ `),r},t.parseRtpParameters=function(i){const r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(i)[0].split(" ");r.profile=n[2];for(let o=3;o<n.length;o++){const l=n[o],c=t.matchPrefix(i,"a=rtpmap:"+l+" ")[0];if(c){const h=t.parseRtpMap(c),_=t.matchPrefix(i,"a=fmtp:"+l+" ");switch(h.parameters=_.length?t.parseFmtp(_[0]):{},h.rtcpFeedback=t.matchPrefix(i,"a=rtcp-fb:"+l+" ").map(t.parseRtcpFb),r.codecs.push(h),h.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(h.name.toUpperCase())}}}t.matchPrefix(i,"a=extmap:").forEach(o=>{r.headerExtensions.push(t.parseExtmap(o))});const s=t.matchPrefix(i,"a=rtcp-fb:* ").map(t.parseRtcpFb);return r.codecs.forEach(o=>{s.forEach(l=>{o.rtcpFeedback.find(c=>c.type===l.type&&c.parameter===l.parameter)||o.rtcpFeedback.push(l)})}),r},t.writeRtpDescription=function(i,r){let n="";n+="m="+i+" ",n+=r.codecs.length>0?"9":"0",n+=" "+(r.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=r.codecs.map(o=>o.preferredPayloadType!==void 0?o.preferredPayloadType:o.payloadType).join(" ")+`\r
18
+ `,n+=`c=IN IP4 0.0.0.0\r
19
+ `,n+=`a=rtcp:9 IN IP4 0.0.0.0\r
20
+ `,r.codecs.forEach(o=>{n+=t.writeRtpMap(o),n+=t.writeFmtp(o),n+=t.writeRtcpFb(o)});let s=0;return r.codecs.forEach(o=>{o.maxptime>s&&(s=o.maxptime)}),s>0&&(n+="a=maxptime:"+s+`\r
21
+ `),r.headerExtensions&&r.headerExtensions.forEach(o=>{n+=t.writeExtmap(o)}),n},t.parseRtpEncodingParameters=function(i){const r=[],n=t.parseRtpParameters(i),s=n.fecMechanisms.indexOf("RED")!==-1,o=n.fecMechanisms.indexOf("ULPFEC")!==-1,l=t.matchPrefix(i,"a=ssrc:").map(T=>t.parseSsrcMedia(T)).filter(T=>T.attribute==="cname"),c=l.length>0&&l[0].ssrc;let h;const _=t.matchPrefix(i,"a=ssrc-group:FID").map(T=>T.substring(17).split(" ").map(b=>parseInt(b,10)));_.length>0&&_[0].length>1&&_[0][0]===c&&(h=_[0][1]),n.codecs.forEach(T=>{if(T.name.toUpperCase()==="RTX"&&T.parameters.apt){let b={ssrc:c,codecPayloadType:parseInt(T.parameters.apt,10)};c&&h&&(b.rtx={ssrc:h}),r.push(b),s&&(b=JSON.parse(JSON.stringify(b)),b.fec={ssrc:c,mechanism:o?"red+ulpfec":"red"},r.push(b))}}),r.length===0&&c&&r.push({ssrc:c});let f=t.matchPrefix(i,"b=");return f.length&&(f=f[0].indexOf("b=TIAS:")===0?parseInt(f[0].substring(7),10):f[0].indexOf("b=AS:")===0?1e3*parseInt(f[0].substring(5),10)*.95-16e3:void 0,r.forEach(T=>{T.maxBitrate=f})),r},t.parseRtcpParameters=function(i){const r={},n=t.matchPrefix(i,"a=ssrc:").map(l=>t.parseSsrcMedia(l)).filter(l=>l.attribute==="cname")[0];n&&(r.cname=n.value,r.ssrc=n.ssrc);const s=t.matchPrefix(i,"a=rtcp-rsize");r.reducedSize=s.length>0,r.compound=s.length===0;const o=t.matchPrefix(i,"a=rtcp-mux");return r.mux=o.length>0,r},t.writeRtcpParameters=function(i){let r="";return i.reducedSize&&(r+=`a=rtcp-rsize\r
22
+ `),i.mux&&(r+=`a=rtcp-mux\r
23
+ `),i.ssrc!==void 0&&i.cname&&(r+="a=ssrc:"+i.ssrc+" cname:"+i.cname+`\r
24
+ `),r},t.parseMsid=function(i){let r;const n=t.matchPrefix(i,"a=msid:");if(n.length===1)return r=n[0].substring(7).split(" "),{stream:r[0],track:r[1]};const s=t.matchPrefix(i,"a=ssrc:").map(o=>t.parseSsrcMedia(o)).filter(o=>o.attribute==="msid");return s.length>0?(r=s[0].value.split(" "),{stream:r[0],track:r[1]}):void 0},t.parseSctpDescription=function(i){const r=t.parseMLine(i),n=t.matchPrefix(i,"a=max-message-size:");let s;n.length>0&&(s=parseInt(n[0].substring(19),10)),isNaN(s)&&(s=65536);const o=t.matchPrefix(i,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:r.fmt,maxMessageSize:s};const l=t.matchPrefix(i,"a=sctpmap:");if(l.length>0){const c=l[0].substring(10).split(" ");return{port:parseInt(c[0],10),protocol:c[1],maxMessageSize:s}}},t.writeSctpDescription=function(i,r){let n=[];return n=i.protocol!=="DTLS/SCTP"?["m="+i.kind+" 9 "+i.protocol+" "+r.protocol+`\r
25
+ `,`c=IN IP4 0.0.0.0\r
26
+ `,"a=sctp-port:"+r.port+`\r
27
+ `]:["m="+i.kind+" 9 "+i.protocol+" "+r.port+`\r
28
+ `,`c=IN IP4 0.0.0.0\r
29
+ `,"a=sctpmap:"+r.port+" "+r.protocol+` 65535\r
30
+ `],r.maxMessageSize!==void 0&&n.push("a=max-message-size:"+r.maxMessageSize+`\r
31
+ `),n.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(i,r,n){let s;const o=r!==void 0?r:2;return s=i||t.generateSessionId(),`v=0\r
32
+ o=`+(n||"thisisadapterortc")+" "+s+" "+o+` IN IP4 127.0.0.1\r
33
+ s=-\r
34
+ t=0 0\r
35
+ `},t.getDirection=function(i,r){const n=t.splitLines(i);for(let s=0;s<n.length;s++)switch(n[s]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[s].substring(2)}return r?t.getDirection(r):"sendrecv"},t.getKind=function(i){return t.splitLines(i)[0].split(" ")[0].substring(2)},t.isRejected=function(i){return i.split(" ",2)[1]==="0"},t.parseMLine=function(i){const r=t.splitLines(i)[0].substring(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(i){const r=t.matchPrefix(i,"o=")[0].substring(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(i){if(typeof i!="string"||i.length===0)return!1;const r=t.splitLines(i);for(let n=0;n<r.length;n++)if(r[n].length<2||r[n].charAt(1)!=="=")return!1;return!0},e.exports=t})(P1);var O1=P1.exports,Io=v(O1),k9=d({__proto__:null,default:Io},[O1]);function vh(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(i){if(typeof i=="object"&&i.candidate&&i.candidate.indexOf("a=")===0&&((i=JSON.parse(JSON.stringify(i))).candidate=i.candidate.substring(2)),i.candidate&&i.candidate.length){const r=new t(i),n=Io.parseCandidate(i.candidate);for(const s in n)s in r||Object.defineProperty(r,s,{value:n[s]});return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new t(i)},e.RTCIceCandidate.prototype=t.prototype,na(e,"icecandidate",i=>(i.candidate&&Object.defineProperty(i,"candidate",{value:new e.RTCIceCandidate(i.candidate),writable:"false"}),i))}function Bg(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||na(e,"icecandidate",t=>{if(t.candidate){const i=Io.parseCandidate(t.candidate.candidate);i.type==="relay"&&(t.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[i.priority>>24])}return t})}function Eh(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return this._sctp===void 0?null:this._sctp}});const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,t.browser==="chrome"&&t.version>=76){const{sdpSemantics:r}=this.getConfiguration();r==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if((function(r){if(!r||!r.sdp)return!1;const n=Io.splitSections(r.sdp);return n.shift(),n.some(s=>{const o=Io.parseMLine(s);return o&&o.kind==="application"&&o.protocol.indexOf("SCTP")!==-1})})(arguments[0])){const r=(function(c){const h=c.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(h===null||h.length<2)return-1;const _=parseInt(h[1],10);return _!=_?-1:_})(arguments[0]),n=(function(c){let h=65536;return t.browser==="firefox"&&(h=t.version<57?c===-1?16384:2147483637:t.version<60?t.version===57?65535:65536:2147483637),h})(r),s=(function(c,h){let _=65536;t.browser==="firefox"&&t.version===57&&(_=65535);const f=Io.matchPrefix(c.sdp,"a=max-message-size:");return f.length>0?_=parseInt(f[0].substring(19),10):t.browser==="firefox"&&h!==-1&&(_=2147483637),_})(arguments[0],r);let o;o=n===0&&s===0?Number.POSITIVE_INFINITY:n===0||s===0?Math.max(n,s):Math.min(n,s);const l={};Object.defineProperty(l,"maxMessageSize",{get:()=>o}),this._sctp=l}return i.apply(this,arguments)}}function yh(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(r,n){const s=r.send;r.send=function(){const o=arguments[0],l=o.length||o.size||o.byteLength;if(r.readyState==="open"&&n.sctp&&l>n.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+n.sctp.maxMessageSize+" bytes)");return s.apply(r,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const r=i.apply(this,arguments);return t(r,this),r},na(e,"datachannel",r=>(t(r.channel,r.target),r))}function Hg(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(i){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),i&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=i)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(i=>{const r=t[i];t[i]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=n=>{const s=n.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;const o=new Event("connectionstatechange",n);s.dispatchEvent(o)}return n},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}})}function Wg(e,t){if(!e.RTCPeerConnection||t.browser==="chrome"&&t.version>=71||t.browser==="safari"&&t._safariVersion>=13.1)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(r){if(r&&r.sdp&&r.sdp.indexOf(`
36
+ a=extmap-allow-mixed`)!==-1){const n=r.sdp.split(`
37
+ `).filter(s=>s.trim()!=="a=extmap-allow-mixed").join(`
38
+ `);e.RTCSessionDescription&&r instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:r.type,sdp:n}):r.sdp=n}return i.apply(this,arguments)}}function Th(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&i.length!==0&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(t.browser==="chrome"&&t.version<78||t.browser==="firefox"&&t.version<68||t.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Sh(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&i.length!==0&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let r=arguments[0]||{};if(typeof r!="object"||r.type&&r.sdp)return i.apply(this,arguments);if(r={type:r.type,sdp:r.sdp},!r.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":r.type="offer";break;default:r.type="answer"}return r.sdp||r.type!=="offer"&&r.type!=="answer"?i.apply(this,[r]):(r.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(n=>i.apply(this,[n]))})}var w9=Object.freeze({__proto__:null,shimRTCIceCandidate:vh,shimRTCIceCandidateRelayProtocol:Bg,shimMaxMessageSize:Eh,shimSendThrowTypeError:yh,shimConnectionState:Hg,removeExtmapAllowMixed:Wg,shimAddIceCandidateNullOrEmpty:Th,shimParameterlessSetLocalDescription:Sh});(function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=XC,r=(function(s){const o={browser:null,version:null};if(s===void 0||!s.navigator||!s.navigator.userAgent)return o.browser="Not a browser.",o;const{navigator:l}=s;if(l.mozGetUserMedia)o.browser="firefox",o.version=parseInt(rc(l.userAgent,/Firefox\/(\d+)\./,1));else if(l.webkitGetUserMedia||s.isSecureContext===!1&&s.webkitRTCPeerConnection)o.browser="chrome",o.version=parseInt(rc(l.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!s.RTCPeerConnection||!l.userAgent.match(/AppleWebKit\/(\d+)\./))return o.browser="Not a supported browser.",o;o.browser="safari",o.version=parseInt(rc(l.userAgent,/AppleWebKit\/(\d+)\./,1)),o.supportsUnifiedPlan=s.RTCRtpTransceiver&&"currentDirection"in s.RTCRtpTransceiver.prototype,o._safariVersion=rc(l.userAgent,/Version\/(\d+(\.?\d+))/,1)}return o})(e),n={browserDetails:r,commonShim:w9,extractVersion:rc,disableLog:b9,disableWarnings:C9,sdp:k9};switch(r.browser){case"chrome":if(!u1||!Vg||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),n;if(r.version===null)return i("Chrome shim can not determine version, not shimming."),n;i("adapter.js shimming chrome."),n.browserShim=u1,Th(e,r),Sh(e),t1(e,r),i1(e),Vg(e,r),r1(e),l1(e,r),n1(e),s1(e),a1(e),c1(e,r),vh(e),Bg(e),Hg(e),Eh(e,r),yh(e),Wg(e,r);break;case"firefox":if(!T1||!Fg||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),n;i("adapter.js shimming firefox."),n.browserShim=T1,Th(e,r),Sh(e),d1(e,r),Fg(e,r),h1(e),f1(e),p1(e),m1(e),_1(e),g1(e),v1(e),E1(e),y1(e),vh(e),Hg(e),Eh(e,r),yh(e);break;case"safari":if(!N1||!t.shimSafari)return i("Safari shim is not included in this adapter release."),n;i("adapter.js shimming safari."),n.browserShim=N1,Th(e,r),Sh(e),C1(e),w1(e),R1(e),S1(e),I1(e),k1(e),A1(e),D1(e),vh(e),Bg(e),Eh(e,r),yh(e),Wg(e,r);break;default:i("Unsupported browser!")}})({window:typeof window>"u"?void 0:window});var Ae,D9=Object.create,nc=Object.defineProperty,N9=Object.defineProperties,M1=Object.getOwnPropertyDescriptor,P9=Object.getOwnPropertyDescriptors,O9=Object.getOwnPropertyNames,Ih=Object.getOwnPropertySymbols,L1=Object.getPrototypeOf,Gg=Object.prototype.hasOwnProperty,x1=Object.prototype.propertyIsEnumerable,M9=Reflect.get,sc=Math.pow,jg=(e,t,i)=>t in e?nc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,ve=(e,t)=>{for(var i in t||(t={}))Gg.call(t,i)&&jg(e,i,t[i]);if(Ih)for(var i of Ih(t))x1.call(t,i)&&jg(e,i,t[i]);return e},xe=(e,t)=>N9(e,P9(t)),U1=(e,t)=>{var i={};for(var r in e)Gg.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(e!=null&&Ih)for(var r of Ih(e))t.indexOf(r)<0&&x1.call(e,r)&&(i[r]=e[r]);return i},hn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),pn=(e,t)=>{for(var i in t)nc(e,i,{get:t[i],enumerable:!0})},ti=(e,t,i)=>(i=e!=null?D9(L1(e)):{},((r,n,s,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let l of O9(n))!Gg.call(r,l)&&l!==s&&nc(r,l,{get:()=>n[l],enumerable:!(o=M1(n,l))||o.enumerable});return r})(!t&&e&&e.__esModule?i:nc(i,"default",{value:e,enumerable:!0}),e)),_e=(e,t,i,r)=>{for(var n,s=M1(t,i),o=e.length-1;o>=0;o--)(n=e[o])&&(s=n(t,i,s)||s);return s&&nc(t,i,s),s},m=(e,t,i)=>jg(e,typeof t!="symbol"?t+"":t,i),xi=(e,t,i)=>M9(L1(e),i,t),P=(e,t,i)=>new Promise((r,n)=>{var s=c=>{try{l(i.next(c))}catch(h){n(h)}},o=c=>{try{l(i.throw(c))}catch(h){n(h)}},l=c=>c.done?r(c.value):Promise.resolve(c.value).then(s,o);l((i=i.apply(e,t)).next())}),Ri=hn((e,t)=>{var i=Object.prototype.hasOwnProperty,r="~";function n(){}function s(h,_,f){this.fn=h,this.context=_,this.once=f||!1}function o(h,_,f,T,b){if(typeof f!="function")throw new TypeError("The listener must be a function");var C=new s(f,T||h,b),x=r?r+_:_;return h._events[x]?h._events[x].fn?h._events[x]=[h._events[x],C]:h._events[x].push(C):(h._events[x]=C,h._eventsCount++),h}function l(h,_){--h._eventsCount===0?h._events=new n:delete h._events[_]}function c(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(r=!1)),c.prototype.eventNames=function(){var h,_,f=[];if(this._eventsCount===0)return f;for(_ in h=this._events)i.call(h,_)&&f.push(r?_.slice(1):_);return Object.getOwnPropertySymbols?f.concat(Object.getOwnPropertySymbols(h)):f},c.prototype.listeners=function(h){var _=r?r+h:h,f=this._events[_];if(!f)return[];if(f.fn)return[f.fn];for(var T=0,b=f.length,C=new Array(b);T<b;T++)C[T]=f[T].fn;return C},c.prototype.listenerCount=function(h){var _=r?r+h:h,f=this._events[_];return f?f.fn?1:f.length:0},c.prototype.emit=function(h,_,f,T,b,C){var x=r?r+h:h;if(!this._events[x])return!1;var B,Y,G=this._events[x],he=arguments.length;if(G.fn){switch(G.once&&this.removeListener(h,G.fn,void 0,!0),he){case 1:return G.fn.call(G.context),!0;case 2:return G.fn.call(G.context,_),!0;case 3:return G.fn.call(G.context,_,f),!0;case 4:return G.fn.call(G.context,_,f,T),!0;case 5:return G.fn.call(G.context,_,f,T,b),!0;case 6:return G.fn.call(G.context,_,f,T,b,C),!0}for(Y=1,B=new Array(he-1);Y<he;Y++)B[Y-1]=arguments[Y];G.fn.apply(G.context,B)}else{var H,Z=G.length;for(Y=0;Y<Z;Y++)switch(G[Y].once&&this.removeListener(h,G[Y].fn,void 0,!0),he){case 1:G[Y].fn.call(G[Y].context);break;case 2:G[Y].fn.call(G[Y].context,_);break;case 3:G[Y].fn.call(G[Y].context,_,f);break;case 4:G[Y].fn.call(G[Y].context,_,f,T);break;default:if(!B)for(H=1,B=new Array(he-1);H<he;H++)B[H-1]=arguments[H];G[Y].fn.apply(G[Y].context,B)}}return!0},c.prototype.on=function(h,_,f){return o(this,h,_,f,!1)},c.prototype.once=function(h,_,f){return o(this,h,_,f,!0)},c.prototype.removeListener=function(h,_,f,T){var b=r?r+h:h;if(!this._events[b])return this;if(!_)return l(this,b),this;var C=this._events[b];if(C.fn)C.fn===_&&(!T||C.once)&&(!f||C.context===f)&&l(this,b);else{for(var x=0,B=[],Y=C.length;x<Y;x++)(C[x].fn!==_||T&&!C[x].once||f&&C[x].context!==f)&&B.push(C[x]);B.length?this._events[b]=B.length===1?B[0]:B:l(this,b)}return this},c.prototype.removeAllListeners=function(h){var _;return h?(_=r?r+h:h,this._events[_]&&l(this,_)):(this._events=new n,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=r,c.EventEmitter=c,t!==void 0&&(t.exports=c)}),zg=hn((e,t)=>{var i=t.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(r){return r.encoding?"rtpmap:%d %s/%s/%s":r.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(r){return r.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(r){return r.subtype!=null?"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(r){return"extmap:%d"+(r.direction?"/%s":"%v")+(r["encrypt-uri"]?" %s":"%v")+" %s"+(r.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(r){return r.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(r){var n="candidate:%s %d %s %d %s %d typ %s";return n+=r.raddr!=null?" raddr %s rport %d":"%v%v",n+=r.tcptype!=null?" tcptype %s":"%v",r.generation!=null&&(n+=" generation %d"),n+=r["network-id"]!=null?" network-id %d":"%v",n+=r["network-cost"]!=null?" 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(r){var n="ssrc:%d";return r.attribute!=null&&(n+=" %s",r.value!=null&&(n+=":%s")),n}},{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(r){return r.maxMessageSize!=null?"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(r){return r.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(r){return"imageattr:%s %s %s"+(r.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(r){return"simulcast:%s %s"+(r.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(r){return"ts-refclk:%s"+(r.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(r){var n="mediaclk:";return n+=r.id!=null?"id=%s %s":"%v%s",n+=r.mediaClockValue!=null?"=%s":"",n+=r.rateNumerator!=null?" rate=%s":"",n+=r.rateDenominator!=null?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(i).forEach(function(r){i[r].forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})})}),L9=hn(e=>{var t=function(o){return String(Number(o))===o?Number(o):o},i=function(o,l,c){var h=o.name&&o.names;o.push&&!l[o.push]?l[o.push]=[]:h&&!l[o.name]&&(l[o.name]={});var _=o.push?{}:h?l[o.name]:l;(function(f,T,b,C){if(C&&!b)T[C]=t(f[1]);else for(var x=0;x<b.length;x+=1)f[x+1]!=null&&(T[b[x]]=t(f[x+1]))})(c.match(o.reg),_,o.names,o.name),o.push&&l[o.push].push(_)},r=zg(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(o){var l={},c=[],h=l;return o.split(/(\r\n|\r|\n)/).filter(n).forEach(function(_){var f=_[0],T=_.slice(2);f==="m"&&(c.push({rtp:[],fmtp:[]}),h=c[c.length-1]);for(var b=0;b<(r[f]||[]).length;b+=1){var C=r[f][b];if(C.reg.test(T))return i(C,h,T)}}),l.media=c,l};var s=function(o,l){var c=l.split(/=(.+)/,2);return c.length===2?o[c[0]]=t(c[1]):c.length===1&&l.length>1&&(o[c[0]]=void 0),o};e.parseParams=function(o){return o.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(o){return o.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(o){for(var l=[],c=o.split(" ").map(t),h=0;h<c.length;h+=3)l.push({component:c[h],ip:c[h+1],port:c[h+2]});return l},e.parseImageAttributes=function(o){return o.split(" ").map(function(l){return l.substring(1,l.length-1).split(",").reduce(s,{})})},e.parseSimulcastStreamList=function(o){return o.split(";").map(function(l){return l.split(",").map(function(c){var h,_=!1;return c[0]!=="~"?h=t(c):(h=t(c.substring(1,c.length)),_=!0),{scid:h,paused:_}})})}}),x9=hn((e,t)=>{var i=zg(),r=/%[sdv%]/g,n=function(c){var h=1,_=arguments,f=_.length;return c.replace(r,function(T){if(h>=f)return T;var b=_[h];switch(h+=1,T){case"%%":return"%";case"%s":return String(b);case"%d":return Number(b);case"%v":return""}})},s=function(c,h,_){var f=[c+"="+(h.format instanceof Function?h.format(h.push?_:_[h.name]):h.format)];if(h.names)for(var T=0;T<h.names.length;T+=1){var b=h.names[T];h.name?f.push(_[h.name][b]):f.push(_[h.names[T]])}else f.push(_[h.name]);return n.apply(null,f)},o=["v","o","s","i","u","e","p","c","b","t","r","z","a"],l=["i","c","b","a"];t.exports=function(c,h){h=h||{},c.version==null&&(c.version=0),c.name==null&&(c.name=" "),c.media.forEach(function(b){b.payloads==null&&(b.payloads="")});var _=h.outerOrder||o,f=h.innerOrder||l,T=[];return _.forEach(function(b){i[b].forEach(function(C){C.name in c&&c[C.name]!=null?T.push(s(b,C,c)):C.push in c&&c[C.push]!=null&&c[C.push].forEach(function(x){T.push(s(b,C,x))})})}),c.media.forEach(function(b){T.push(s("m",i.m[0],b)),f.forEach(function(C){i[C].forEach(function(x){x.name in b&&b[x.name]!=null?T.push(s(C,x,b)):x.push in b&&b[x.push]!=null&&b[x.push].forEach(function(B){T.push(s(C,x,B))})})})}),T.join(`\r
39
+ `)+`\r
40
+ `}}),U9=hn(e=>{var t=L9(),i=x9(),r=zg();e.grammar=r,e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList}),V1=hn((e,t)=>{var i=t.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(r){return r.encoding?"rtpmap:%d %s/%s/%s":r.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(r){return r.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(r){return r.subtype!=null?"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(r){return"extmap:%d"+(r.direction?"/%s":"%v")+(r["encrypt-uri"]?" %s":"%v")+" %s"+(r.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(r){return r.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(r){var n="candidate:%s %d %s %d %s %d typ %s";return n+=r.raddr!=null?" raddr %s rport %d":"%v%v",n+=r.tcptype!=null?" tcptype %s":"%v",r.generation!=null&&(n+=" generation %d"),n+=r["network-id"]!=null?" network-id %d":"%v",n+=r["network-cost"]!=null?" 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(r){var n="ssrc:%d";return r.attribute!=null&&(n+=" %s",r.value!=null&&(n+=":%s")),n}},{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(r){return r.maxMessageSize!=null?"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(r){return r.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(r){return"imageattr:%s %s %s"+(r.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(r){return"simulcast:%s %s"+(r.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(r){return"ts-refclk:%s"+(r.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(r){var n="mediaclk:";return n+=r.id!=null?"id=%s %s":"%v%s",n+=r.mediaClockValue!=null?"=%s":"",n+=r.rateNumerator!=null?" rate=%s":"",n+=r.rateDenominator!=null?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(i).forEach(function(r){i[r].forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})})}),V9=hn(e=>{var t=function(o){return String(Number(o))===o?Number(o):o},i=function(o,l,c){var h=o.name&&o.names;o.push&&!l[o.push]?l[o.push]=[]:h&&!l[o.name]&&(l[o.name]={});var _=o.push?{}:h?l[o.name]:l;(function(f,T,b,C){if(C&&!b)T[C]=t(f[1]);else for(var x=0;x<b.length;x+=1)f[x+1]!=null&&(T[b[x]]=t(f[x+1]))})(c.match(o.reg),_,o.names,o.name),o.push&&l[o.push].push(_)},r=V1(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(o){var l={},c=[],h=l;return o.split(/(\r\n|\r|\n)/).filter(n).forEach(function(_){var f=_[0],T=_.slice(2);f==="m"&&(c.push({rtp:[],fmtp:[]}),h=c[c.length-1]);for(var b=0;b<(r[f]||[]).length;b+=1){var C=r[f][b];if(C.reg.test(T))return i(C,h,T)}}),l.media=c,l};var s=function(o,l){var c=l.split(/=(.+)/,2);return c.length===2?o[c[0]]=t(c[1]):c.length===1&&l.length>1&&(o[c[0]]=void 0),o};e.parseParams=function(o){return o.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(o){return o.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(o){for(var l=[],c=o.split(" ").map(t),h=0;h<c.length;h+=3)l.push({component:c[h],ip:c[h+1],port:c[h+2]});return l},e.parseImageAttributes=function(o){return o.split(" ").map(function(l){return l.substring(1,l.length-1).split(",").reduce(s,{})})},e.parseSimulcastStreamList=function(o){return o.split(";").map(function(l){return l.split(",").map(function(c){var h,_=!1;return c[0]!=="~"?h=t(c):(h=t(c.substring(1,c.length)),_=!0),{scid:h,paused:_}})})}}),F9=hn((e,t)=>{var i=V1(),r=/%[sdv%]/g,n=function(c){var h=1,_=arguments,f=_.length;return c.replace(r,function(T){if(h>=f)return T;var b=_[h];switch(h+=1,T){case"%%":return"%";case"%s":return String(b);case"%d":return Number(b);case"%v":return""}})},s=function(c,h,_){var f=[c+"="+(h.format instanceof Function?h.format(h.push?_:_[h.name]):h.format)];if(h.names)for(var T=0;T<h.names.length;T+=1){var b=h.names[T];h.name?f.push(_[h.name][b]):f.push(_[h.names[T]])}else f.push(_[h.name]);return n.apply(null,f)},o=["v","o","s","i","u","e","p","c","b","t","r","z","a"],l=["i","c","b","a"];t.exports=function(c,h){h=h||{},c.version==null&&(c.version=0),c.name==null&&(c.name=" "),c.media.forEach(function(b){b.payloads==null&&(b.payloads="")});var _=h.outerOrder||o,f=h.innerOrder||l,T=[];return _.forEach(function(b){i[b].forEach(function(C){C.name in c&&c[C.name]!=null?T.push(s(b,C,c)):C.push in c&&c[C.push]!=null&&c[C.push].forEach(function(x){T.push(s(b,C,x))})})}),c.media.forEach(function(b){T.push(s("m",i.m[0],b)),f.forEach(function(C){i[C].forEach(function(x){x.name in b&&b[x.name]!=null?T.push(s(C,x,b)):x.push in b&&b[x.push]!=null&&b[x.push].forEach(function(B){T.push(s(C,x,B))})})})}),T.join(`\r
41
+ `)+`\r
42
+ `}}),F1=hn(e=>{var t=V9(),i=F9();e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList}),B9=ti(Ri()),B1=((Ae=B1||{})[Ae.INVALID_PARAMETER=4096]="INVALID_PARAMETER",Ae[Ae.INVALID_OPERATION=4097]="INVALID_OPERATION",Ae[Ae.NOT_SUPPORTED=4098]="NOT_SUPPORTED",Ae[Ae.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",Ae[Ae.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",Ae[Ae.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",Ae[Ae.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",Ae[Ae.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",Ae[Ae.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",Ae[Ae.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",Ae[Ae.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",Ae[Ae.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",Ae[Ae.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",Ae[Ae.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",Ae[Ae.CLIENT_BANNED=16448]="CLIENT_BANNED",Ae[Ae.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",Ae[Ae.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",Ae[Ae.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",Ae[Ae.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",Ae[Ae.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",Ae[Ae.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",Ae[Ae.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",Ae[Ae.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",Ae[Ae.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",Ae[Ae.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",Ae[Ae.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",Ae[Ae.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",Ae[Ae.API_CALL_ABORTED=16461]="API_CALL_ABORTED",Ae[Ae.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",Ae[Ae.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",Ae[Ae.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",Ae[Ae.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",Ae[Ae.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",Ae[Ae.UNKNOWN=65535]="UNKNOWN",Ae),te=B1,H1=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=te.UNKNOWN,extraCode:n=0,constraint:s}=e,o="<".concat((function(c){for(let h in te)if(te[h]===c)return h;return"UNKNOWN"})(r)," 0x").concat(r.toString(16),">"),l="".concat(i).concat(s?" constraint: ".concat(s):"").concat(i!=null&&i.includes(o)?"":" ".concat(o));super(l),m(this,"code"),m(this,"extraCode"),m(this,"message"),m(this,"originMessage"),m(this,"name"),m(this,"constraint"),this.code=r,this.extraCode=n,this.name=t,this.message=l,this.constraint=s,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},me=H1,Kg=0,W1=!0,G1=function(e){Kg=e;let t=new Date;t.setTime(t.getTime()+e),fe[W1?"info":"debug"]("baseTime from server: ".concat(t," offset: ").concat(e)),W1=!1},H9=function(){return Kg},ac=function(){return Date.now()+Kg},j1=function(){let e=new Date;return e.setTime(ac()),e.toLocaleString()},Jg=function(e){let t=String(e.getMilliseconds());return"padStart"in String.prototype&&(t=t.toString().padStart(3,"0")),"".concat(e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(t)},Vr={};pn(Vr,{REPORT_TYPE:()=>C0,buildSSOPackage:()=>wo,bytes2ms:()=>T2,calculateScaleResolutionDownNumber:()=>Vh,concatArrayBuffers:()=>k0,convertObjectNumberToInt:()=>Uh,copyProperties:()=>y2,deepClone:()=>ko,deepCloneBasic:()=>Fh,deepMerge:()=>gn,delay:()=>Br,fibonacci:()=>Co,formatedTime:()=>P2,getConstructorName:()=>Oh,getContainerFromElement:()=>N2,getEnv:()=>f2,getFirst16Bits:()=>M2,getInternalVersion:()=>w2,getLast16Bits:()=>w0,getLoggerUrl:()=>bo,getMediaStreamTrackInfo:()=>b0,getMuteStateFromFlag:()=>ca,getNetworkType:()=>Ph,getNumNetworkType:()=>Ec,getReconnectionTimeout:()=>la,getStringByteLength:()=>xh,getTestSignalDomain:()=>_2,getTurnServer:()=>D2,getUint32Version:()=>I0,getValueType:()=>ii,getViewListFromView:()=>Rc,glog:()=>I2,ipv4ToUint32:()=>Ic,isArray:()=>Jt,isAudioWorkletSupported:()=>b2,isBoolean:()=>Rt,isConstructor:()=>Tc,isEmpty:()=>Mh,isFunction:()=>Ut,isLangChinese:()=>_n,isMediaStreamTrack:()=>R2,isNumber:()=>nt,isObject:()=>Fr,isOverseaSdkAppId:()=>os,isPlainObject:()=>nr,isPortrait:()=>S0,isPromise:()=>yc,isRemoteTrack:()=>A2,isRotate90Or270:()=>ls,isSetSinkIdSupported:()=>C2,isString:()=>pt,isUndefined:()=>j,loadImage:()=>Ac,loadVideo:()=>O2,ms2bytes:()=>S2,ms2samples:()=>T0,normalizeUrl:()=>A0,performanceNow:()=>Ue,promiseAny:()=>Sc,samples2ms:()=>y0,setNetworkTypeFromWebRTC:()=>E0,stringify:()=>Tr,stringifyIncludeValue:()=>Lh,throttlePromise:()=>R0});var z1={};pn(z1,{ASR_ROBOT_FROM_TYPE:()=>Nh,AUDIO_MUTE_BIT:()=>s0,AUDIO_STAT_BIT:()=>dc,AUX_STAT_BIT:()=>Ah,AUX_STREAM_MSID:()=>i2,BACKEND_ENV:()=>r0,BASE_DOC_URL:()=>mn,BASE_HOST:()=>J1,CAPABILITIES_KEYS:()=>c0,CLASS_NAME:()=>cH,CLOUD_CONSOLE_URL:()=>z9,CROSS_ROOM_BIT:()=>e2,DATA_CHANNEL_FROM_TYPE_BIT:()=>t2,DATA_FREEZE_TIMING:()=>o0,DOC_BILLING_CN:()=>Zg,DOC_BILLING_OVERSEA:()=>$g,DOC_URL:()=>K9,DTLS_STATE_UNKNOWN:()=>ss,ENV_NAME:()=>sa,EXCHANGE_SDP_TIMEOUT:()=>l2,IS_WORKER:()=>Rh,IS_WORKLET:()=>Xg,KIBANA_EVENT:()=>di,LOCAL_STREAM_PUBLISH_STATE:()=>c2,LOGGER_CMD_TYPE:()=>lc,LOGGER_DOMAIN:()=>Y1,LOGGER_DOMAIN_OVERSEA:()=>q1,LOG_LEVEL:()=>ns,LOG_LEVEL_NAME:()=>dH,MAIN_STREAM_MSID:()=>bh,MAX_RTT:()=>Dh,MICROPHONE_COMMUNICATIONS:()=>uH,MICROPHONE_DEFAULT:()=>pc,MUTE_ALL_BIT:()=>q9,NAME:()=>D,NETWORK_TYPE:()=>e0,NOT_SUPPORTED_H264:()=>kh,PAUSED_RETRY_COUNT:()=>oa,PEERCONNECTION_CONNECTING_TIMEOUT:()=>l0,PEER_CONNECTION_STATE:()=>Kt,PEER_LEAVE_REASON:()=>u2,RECOVER_CAPTURE_INTERVAL:()=>fc,REMOTE_STREAM_TYPE_AUX:()=>n2,REMOTE_STREAM_TYPE_MAIN:()=>r2,RENDER_FREEZE_TIMING:()=>sH,SCHEDULE_DOMAIN:()=>as,SCHEDULE_TIMEOUT:()=>lH,SDP_SEMANTICS_PLAN_B:()=>Ch,SDP_SEMANTICS_UNIFIED_PLAN:()=>hc,SECOND_HOST:()=>G9,SIGNAL_PING_PONG_INTERVAL:()=>Y9,SIGNAL_PING_TIMEOUT:()=>J9,SIGNAL_RECONNECTION_COUNT:()=>rH,SMALL_STAT_BIT:()=>n0,SPEAKER_DEFAULT:()=>wh,STORAGE_EXPIRES_TIME:()=>Q1,STREAM_TYPE_BIG:()=>aH,STREAM_TYPE_SMALL:()=>oH,SUBSCRIBE_SMALL_RETRY_COUNT:()=>mc,SYNC_USER_LIST_INTERVAL:()=>nH,Scene:()=>$1,THIRD_HOST:()=>j9,TRANSPORT_DIRECTION:()=>rt,TRTC_ERROR_ASSISTANCE:()=>X1,TRTC_QUALITY_BAD:()=>eH,TRTC_QUALITY_DISCONNECTED:()=>iH,TRTC_QUALITY_EXCELLENT:()=>Q9,TRTC_QUALITY_GOOD:()=>Z9,TRTC_QUALITY_POOR:()=>$9,TRTC_QUALITY_UNKNOWN:()=>X9,TRTC_QUALITY_VERY_BAD:()=>tH,UPDATE_OFFER_TIMEOUT:()=>o2,VIDEO_MUTE_BIT:()=>a0,VIDEO_STAT_BIT:()=>uc,WEBGL_ATTRIBUTES:()=>d2,audioProfileMap:()=>t0,defaultBigVideoProfile:()=>cc,defaultSmallVideoProfile:()=>Z1,getRetryCount:()=>Ro,getScriptDir:()=>W9,innerVersion:()=>Yg,loggerProxy:()=>Qg,screenProfileMap:()=>i0,setLoggerProxy:()=>oc,setRetryCount:()=>a2,setVersion:()=>K1,version:()=>yr,videoProfileMap:()=>fn});var Yg="4.15.00.1600",yr="5.0.0";function K1(e){yr=e;let[t,i,r]=e.split(".").map(n=>parseInt(n,10));Yg="".concat(t,".").concat(Math.min(15,i),".").concat(Math.min(15,r),".").concat(i.toString().padStart(2,"0")).concat(r.toString().padStart(2,"0"))}var qg,Wi,Rh=typeof importScripts<"u",Xg=typeof registerProcessor<"u",W9=()=>{let e=Rh?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},Qg="",oc=e=>Qg=e,J1="web.sdk.qcloud.com",G9="web.sdk.tencent.cn",j9="web.sdk.cloud.tencent.cn",z9="https://console.cloud.tencent.com/trtc",mn="https://".concat(J1,"/trtc/webrtc/doc"),K9="".concat(mn,"/zh-cn/"),Zg="https://cloud.tencent.com/document/product/647/85386",$g="https://trtc.io/document/56025",Y1="https://yun.tim.qq.com",q1="https://apisgp.my-imcloud.com",X1="trtc_error_assistance",lc={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},sa={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},ns=((Wi=ns||{})[Wi.TRACE=0]="TRACE",Wi[Wi.DEBUG=1]="DEBUG",Wi[Wi.INFO=2]="INFO",Wi[Wi.WARN=3]="WARN",Wi[Wi.ERROR=4]="ERROR",Wi[Wi.NONE=5]="NONE",Wi),J9=18e3,Y9=2e3,e0={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},Q1=6048e5,t0={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:128},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},fn={"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}},cc=fn["480p_2"],Z1=fn["120p_2"],i0={"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}},D={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADSTART:"loadstart",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture",FULLSCREEN_CHANGE:"fullscreenchange",RESIZE:"resize",TIME_UPDATE:"timeupdate"},rt={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},r0={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},$1=((qg=$1||{}).LIVE="live",qg.RTC="rtc",qg),uc=1,n0=2,Ah=4,dc=8,s0=64,a0=16,q9=112,e2=128,t2=256,bh="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",i2="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",r2=D.MAIN,n2=D.AUXILIARY,X9=0,Q9=1,Z9=2,$9=3,eH=4,tH=5,iH=6,ss="unknown",Kt={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},s2=1/0;function a2(e){s2=e}function Ro(){return s2}var aa,rH=30,di={JOIN:"join",DELTA_JOIN:"delta-join",REJOIN:"rejoin",LEAVE:"leave",DELTA_LEAVE:"delta-leave",PUBLISH:"publish",DELTA_PUBLISH:"delta-publish",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",UPLINK_CONNECTION:"uplink-connection",UPLINK_RECONNECTION:"uplink-reconnection",DOWNLINK_CONNECTION:"downlink-connection",DOWNLINK_RECONNECTION:"downlink-reconnection",ON_TRACK:"ontrack",ICE_CONNECTION_STATE:"iceConnectionState",LOCAL_STREAM_INITIALIZE:"stream-initialize",SIGNAL_CONNECTION:"websocketConnectionState",SIGNAL_RECONNECTION:"websocketReconnectionState",UPDATE_STREAM:"update-stream",RECOVER_LOCAL_AUDIO_TRACK:"recover-local-audio-track",RECOVER_LOCAL_VIDEO_TRACK:"recover-local-video-track",RECOVER_SUBSCRIPTION:"recover-subscription",START_MIX_TRANSCODE:"start-mix-transcode",STOP_MIX_TRANSCODE:"stop-mix-transcode",PLAYER_ERROR:"player-error",SCHEDULE:"schedule",LOAD_WORKLET:"load-worklet",VIDEO_FROZEN_COUNT:"videoFrozenCount",GET_USER_MEDIA_RETRY:"getUserMedia-retry",VIDEO_ENCODE_FAILED_DURING_CALL:"video-encode-failed-during-call",VIDEO_ENCODE_RESUME_DURING_CALL:"video-encode-resume-during-call",AUDIO_ENCODE_FAILED_DURING_CALL:"audio-encode-failed-during-call",AUDIO_ENCODE_RESUME_DURING_CALL:"audio-encode-resume-during-call",VIDEO_DECODE_FAILED_DURING_CALL:"video-decode-failed-during-call",VIDEO_DECODE_RESUME_DURING_CALL:"video-decode-resume-during-call",AUDIO_DECODE_FAILED_DURING_CALL:"audio-decode-failed-during-call",AUDIO_DECODE_RESUME_DURING_CALL:"audio-decode-resume-during-call",VIDEO_HARDWARE_DECODE_FAILED:"video-hardware-decode-failed",VIDEO_HARDWARE_DECODE_RESUME:"video-hardware-decode-resume"},nH=1e4,o2=1e4,l2=1e4,hc="unified-plan",Ch="plan-b",kh=1028,c2=((aa=c2||{})[aa.UNPUBLISH=-1]="UNPUBLISH",aa[aa.PUBLISHING=0]="PUBLISHING",aa[aa.PUBLISHED=1]="PUBLISHED",aa),o0=500,sH=1e3,aH=D.BIG,oH=D.SMALL,l0=1e4,as={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},lH=2e3,cH={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},oa=5,pc="default",wh=pc,uH="communications",dH=Object.keys(ns),u2=["normal leave","timeout leave","kick","role change"],mc=10,fc=2e3,c0=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],Dh=1e4,Nh=14,d2={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},hH=function(e,t,i,r){return new(i||(i=Promise))(function(n,s){function o(h){try{c(r.next(h))}catch(_){s(_)}}function l(h){try{c(r.throw(h))}catch(_){s(_)}}function c(h){h.done?n(h.value):(function(_){return _ instanceof i?_:new i(function(f){f(_)})})(h.value).then(o,l)}c((r=r.apply(e,[])).next())})},u0=Symbol(32),d0=Symbol(16),h0=Symbol(8),Ao=class{constructor(e){this.g=e,this.consumed=0,e&&(this.need=e.next().value)}setG(e){this.g=e,this.demand(e.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(e,t){return t&&this.consume(),this.need=e,this.flush()}read(e){return hH(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((t,i)=>{var r;this.reject=i,this.resolve=n=>{delete this.lastReadPromise,delete this.resolve,delete this.need,t(n)},this.demand(e,!0)||(r=this.pull)===null||r===void 0||r.call(this,e)})})}readU32(){return this.read(u0)}readU16(){return this.read(d0)}readU8(){return this.read(h0)}close(){var e;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(e=this.reject)===null||e===void 0||e.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let e=null,t=this.buffer.subarray(this.consumed),i=0,r=n=>t.length<(i=n);if(typeof this.need=="number"){if(r(this.need))return;e=t.subarray(0,i)}else if(this.need===u0){if(r(4))return;e=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===d0){if(r(2))return;e=t[0]<<8|t[1]}else if(this.need===h0){if(r(1))return;e=t[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(r(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(t.subarray(0,i)),e=this.need}else if(this.g)return void this.g.throw(new Error("Unsupported type"))}else{if(r(this.need.byteLength))return;new Uint8Array(this.need).set(t.subarray(0,i)),e=this.need}return this.consumed+=i,this.g?this.demand(this.g.next(e).value,!0):this.resolve&&this.resolve(e),e}write(e){if(e instanceof Uint8Array?this.malloc(e.length).set(e):"buffer"in e?this.malloc(e.byteLength).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):this.malloc(e.byteLength).set(new Uint8Array(e)),!this.g&&!this.resolve)return new Promise(t=>this.pull=t);this.flush()}writeU32(e){this.malloc(4).set([e>>24&255,e>>16&255,e>>8&255,255&e]),this.flush()}writeU16(e){this.malloc(2).set([e>>8&255,255&e]),this.flush()}writeU8(e){this.malloc(1)[0]=e,this.flush()}malloc(e){if(this.buffer){let t=this.buffer.length,i=t+e;if(i<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,i);else{let r=new Uint8Array(i);r.set(this.buffer),this.buffer=r}return this.buffer.subarray(t,i)}return this.buffer=new Uint8Array(e),this.buffer}};Ao.U32=u0,Ao.U16=d0,Ao.U8=h0;var pH=128;function p0(e){let t=new Ao;for(;e>=128;)t.malloc(1)[0]=255&e|pH,e>>>=7;return t.malloc(1)[0]=255&e,t.buffer||new Uint8Array(0)}function m0(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=new Ao,r=t<<3;switch(typeof e){case"boolean":let n=i.malloc(2);n[0]=r,n[1]=e?1:0;break;case"number":i.malloc(1)[0]=r,i.write(p0(e));break;case"string":i.malloc(1)[0]=2|r;let s=new TextEncoder().encode(e);i.write(p0(s.length));let o=i.malloc(s.length);for(let c=0;c<s.length;c++)o[c]=s[c];break;case"object":let l=new Ao;if(Array.isArray(e))for(let c=0;c<e.length;c++){let h=m0(e[c],c+1);h&&l.write(h)}else{let c=1;for(let h in e){let _=m0(e[h],c++);_&&l.write(_)}}t===0?l.buffer&&i.write(l.buffer):(i.malloc(1)[0]=2|r,l.buffer&&(i.write(p0(l.buffer.length)),i.write(l.buffer)))}return i.buffer||new Uint8Array(0)}var h2=class{constructor(){m(this,"buffer"),this.buffer=[]}get data(){return this.buffer}get length(){return this.buffer.length}writeInt32(e){this.buffer.push(e>>>24&255),this.buffer.push(e>>>16&255),this.buffer.push(e>>>8&255),this.buffer.push(255&e)}writeInt16(e){this.buffer.push(e>>>8&255),this.buffer.push(255&e)}writeByte(e){this.buffer.push(255&e)}writeBytes(e){for(let t=0;t<e.length;t++)this.buffer.push(e[t])}};function p2(e,t,i){e[i]=t>>>24&255,e[i+1]=t>>>16&255,e[i+2]=t>>>8&255,e[i+3]=255&t}function Ui(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function m2(e,t){return e[t]}function _c(e,t,i){return new TextDecoder().decode((function(r,n,s){return r.slice(n,n+s)})(e,t,i))}var f0=0,_0=2654435769,g0=16,gc=2,vc=7;function mH(e,t){let i=new h2,r=(function(G,he,H){let Z=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"AVQualityReportSvc.C2S";return{version:arguments.length>4&&arguments[4]!==void 0?arguments[4]:2e3,encryption:arguments.length>5&&arguments[5]!==void 0?arguments[5]:2,d2:"",d2Len:0,uinType:arguments.length>6&&arguments[6]!==void 0?arguments[6]:30,uin:"",uinLen:0,reqHead:{seqNumber:H,appId:G,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:Z,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:he}})(t,e,f0);f0=f0+1&2147483647,i.writeInt32(0),i.writeInt32(r.version),i.writeByte(r.encryption);let n=new TextEncoder().encode(r.d2);i.writeInt32(n.length+4),n&&i.writeBytes(n),i.writeByte(r.uinType);let s=new TextEncoder().encode(r.uin);i.writeInt32(s.length+4),s.length&&i.writeBytes(s);let o=new h2;o.writeInt32(0),o.writeInt32(r.reqHead.seqNumber),o.writeInt32(r.reqHead.appId),o.writeByte(r.reqHead.appId>>>24&255),o.writeByte(r.reqHead.appId>>>16&255),o.writeByte(r.reqHead.appId>>>8&255),o.writeByte(255&r.reqHead.appId);for(let G=4;G<16;G++)o.writeByte(0);let l=new TextEncoder().encode(r.reqHead.a2);o.writeInt32(l.length+4),l.length&&o.writeBytes(l);let c=new TextEncoder().encode(r.reqHead.serviceCmd);o.writeInt32(c.length+4),c.length&&o.writeBytes(c);let h=new TextEncoder().encode(r.reqHead.cookie);o.writeInt32(h.length+4),h.length&&o.writeBytes(h);let _=new TextEncoder().encode(r.reqHead.imei);o.writeInt32(_.length+4),_.length&&o.writeBytes(_);let f=new TextEncoder().encode(r.reqHead.ksid);o.writeInt32(f.length+4),f.length&&o.writeBytes(f);let T=new TextEncoder().encode(r.reqHead.clientVersionInfo);o.writeInt16(T.length+2),T.length&&o.writeBytes(T);let b=o.length;o.data[0]=b>>>24&255,o.data[1]=b>>>16&255,o.data[2]=b>>>8&255,o.data[3]=255&b,pt(e)&&(e=new TextEncoder().encode(e)),o.writeInt32(e.length+4),e.length&&o.writeBytes(e);let C=new Uint8Array(o.data),x=null;r.encryption===1?x=new TextEncoder().encode(r.uin):r.encryption===2&&(x=new Uint8Array(16)),x&&(C=(function(G,he){let H=G.length,Z=(H+1+gc+vc)%8;Z&&(Z=8-Z);let de=H+1+gc+vc+Z,pe=new Uint8Array(de),Pe=0,be=new Uint8Array(8),je=new Uint8Array(8),Oe=new Uint8Array(8),Be=0;be[0]=248&Math.floor(256*Math.random())|Z,Be=1;for(let yt=0;yt<Z;yt++)be[Be]=255&Math.floor(256*Math.random()),Be+=1;for(let yt=0;yt<gc;)if(Be<8&&(be[Be]=255&Math.floor(256*Math.random()),Be+=1,yt+=1),Be===8){v0(be,he,je,Oe,pe,Pe),Pe+=8,Be=0;for(let gt=0;gt<8;gt++)Oe[gt]=pe[Pe-8+gt]}let at=0;for(;at<H;)if(Be<8&&(be[Be]=G[at],Be+=1,at+=1),Be===8){v0(be,he,je,Oe,pe,Pe),Pe+=8,Be=0;for(let yt=0;yt<8;yt++)Oe[yt]=pe[Pe-8+yt]}for(let yt=0;yt<vc;)if(Be<8&&(be[Be]=0,Be+=1,yt+=1),Be===8){v0(be,he,je,Oe,pe,Pe),Pe+=8,Be=0;for(let gt=0;gt<8;gt++)Oe[gt]=pe[Pe-8+gt]}return pe})(C,x)),i.writeBytes(C);let B=new Uint8Array(i.data),Y=B.length;return B[0]=Y>>>24&255,B[1]=Y>>>16&255,B[2]=Y>>>8&255,B[3]=255&Y,B}function v0(e,t,i,r,n,s){for(let o=0;o<8;o++)e[o]^=r[o];(function(o,l,c,h){let _=Ui(o,0),f=Ui(o,4),T=[];for(let C=0;C<4;C++)T[C]=Ui(l,4*C);let b=0;for(let C=0;C<g0;C++)b+=_0,b>>>=0,_+=(f<<4)+T[0]^f+b^(f>>>5)+T[1],_>>>=0,f+=(_<<4)+T[2]^_+b^(_>>>5)+T[3],f>>>=0;p2(c,_,h),p2(c,f,h+4)})(e,t,n,s);for(let o=0;o<8;o++)n[s+o]^=i[o];for(let o=0;o<8;o++)i[o]=e[o]}var f2=function(){return new URLSearchParams(location.search).get("trtc_env")||""},_2=function(e){return e.includes(".")?e:"".concat(e).concat(".rtc.qq.com")},os=e=>Number(e)<14e8,bo=function(e,t){let i;i=Qg||(os(e)?q1:Y1);let r=Math.floor(Math.random()*sc(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},g2="unknown";function Ph(){(function(){var s;v2||(v2=!0,(s=navigator.connection)==null||s.addEventListener("typechange",fH))})();let{userAgent:e,connection:t}=navigator,i=(e.match(/NetType\/\S+/)||[])[0]||"";i=i.toLowerCase().replace("nettype/",""),i==="3gnet"&&(i="3g");let r=t&&t.type&&t.type.toLowerCase(),n=t&&t.effectiveType&&t.effectiveType.toLowerCase();return n==="slow-2"&&(n="2g"),r?E2(r,n):g2}function fH(){fe.warn("netType changed",Ph())}var v2=!1;function E2(e,t){if(e0[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function E0(e){g2=E2(e)}function Ec(){return e0[Ph()]}function y2(e,t){for(let i of Reflect.ownKeys(t))if(i!=="constructor"&&i!=="prototype"&&i!=="name"){let r=Object.getOwnPropertyDescriptor(t,i)||"";Object.defineProperty(e,i,r)}return e}function T2(e){return y0(e/4,arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function y0(e){return 1e3*e/(arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function S2(e){return 4*T0(e,arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function T0(e){return e*(arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)/1e3}var I2=typeof window<"u"&&typeof window.glog=="function"?window.glog:()=>{},_n=()=>{let e=navigator.language;return e=e.substring(0,2),e==="zh"},nr=function(e){if(!e||typeof e!="object"||Object.prototype.toString.call(e)!="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let i=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof i=="function"&&i instanceof i&&Function.prototype.toString.call(i)===Function.prototype.toString.call(Object)};function Co(e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;return e<=1?t:Co(e-1,t,(arguments.length>1&&arguments[1]!==void 0?arguments[1]:1)+t)}function la(e){return e>8?3e4:1e3*Co(e)}function ii(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var Ut=e=>typeof e=="function",j=e=>e===void 0,pt=e=>typeof e=="string",nt=e=>typeof e=="number",Rt=e=>typeof e=="boolean",Fr=e=>ii(e)==="object",Jt=e=>ii(e)==="array",R2=e=>ii(e)==="MediaStreamTrack".toLowerCase(),A2=e=>e.isRemote,yc=e=>ii(e)==="promise",Tc=e=>Ut(e)&&e.prototype.constructor===e,Oh=e=>Tc(e)?e.prototype.constructor.name:"",b2=typeof AudioWorkletNode<"u",C2=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype;function Sc(e){return new Promise((t,i)=>{let r=[];e.forEach(n=>{n.then(t).catch(s=>{r.push(s),r.length===e.length&&i(r)})})})}function Ue(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var k2=e=>+e<10?"0".concat(e):e,w2=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=k2(i[1])+k2(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},_H=Object.prototype.hasOwnProperty;function Mh(e){if(e==null)return!0;if(typeof e=="boolean")return!1;if(typeof e=="number")return e===0;if(typeof e=="string"||typeof e=="function"||Array.isArray(e))return e.length===0;if(e instanceof Error)return e.message==="";if(nr(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return e.size===0;case"[object Object]":for(let t in e)if(_H.call(e,t))return!1;return!0}return!1}function ca(e,t){return{userId:t,hasAudio:!!(e&dc),hasVideo:!!(e&uc),hasAuxiliary:!!(e&Ah),hasSmall:!!(e&n0),audioMuted:!!(e&s0),videoMuted:!!(e&a0),audioAvailable:!(!(e&dc)||e&s0),videoAvailable:!(!(e&uc)||e&a0),hasDatachannel:!!(e&t2)}}function D2(e){let t={urls:e.url.startsWith("turn:")||e.url.startsWith("turns:")?e.url:"turn:".concat(e.url)};return!j(e.username)&&!j(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",j(e.credentialType)||(t.credentialType=e.credentialType)),t}function Ic(e){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];if(!pt(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 gn=function(e,t,i,r){if(!Fr(e)||!Fr(t))return 0;let n,s=0,o=Object.keys(t);for(let l=0,c=o.length;l<c;l++)if(n=o[l],!(j(t[n])||i&&i.includes(n)))if(Fr(e[n])&&Fr(t[n]))s+=gn(e[n],t[n],i,r);else{if(r&&r.includes(t[n]))continue;e[n]!==t[n]&&(e[n]=ko(t[n]),s+=1)}return s};function ko(e){if(Jt(e)){let t=[];return e.forEach((i,r)=>{t[r]=ko(i)}),t}if(Fr(e)){let t={};return Object.keys(e).forEach(i=>{t[i]=ko(e[i])}),t}return e}var Rc=e=>{let t=[];if(Jt(e))t=[...e];else if(pt(e)){let i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},N2=e=>pt(e)?document.getElementById(e):e,P2=()=>(e=>{let t=c=>c<10?"0".concat(c):"".concat(c),i=e.getFullYear(),r=e.getMonth()+1,n=e.getDate(),s=t(e.getHours()),o=t(e.getMinutes()),l=t(e.getSeconds());return"".concat(i,"/").concat(r,"/").concat(n," ").concat(s,":").concat(o,":").concat(l)})(new Date);function Tr(e,t){let{keysToInclude:i,keysToExclude:r}=t;try{if(Jt(e))return"[".concat(e.map(l=>Tr(l,{keysToInclude:i,keysToExclude:r})).join(","),"]");if(!nr(e)||!Jt(i)&&!Jt(r))return JSON.stringify(e);let n={},s=new Set(i),o=new Set(r);return Object.keys(e).forEach(l=>{(o.size===0&&s.has(l)||s.size===0&&!o.has(l))&&(n[l]=nr(e[l])||Jt(e[l])?JSON.parse(Tr(e[l],{keysToExclude:r,keysToInclude:i})):e[l])}),JSON.stringify(n)}catch{return"{}"}}function Lh(e){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1],i=[];return Object.keys(e).forEach(r=>{t===e[r]&&i.push(r)}),Tr(e,{keysToInclude:i})}function xh(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var S0=()=>{var e,t,i,r;return(e=window.screen)!=null&&e.orientation?!((r=(i=(t=window.screen)==null?void 0:t.orientation)==null?void 0:i.type)==null||!r.includes("portrait")):window.orientation===0||window.orientation===180},Ac=e=>P(null,null,function*(){return new Promise((t,i)=>{let r;if(pt(e))r=new Image,r.crossOrigin="anonymous",r.src=e;else if(r=e,r.complete)return void t(r);r.onload=()=>t(r),r.onerror=()=>{i(new me({code:te.INVALID_PARAMETER,message:"load image failed, url: ".concat(e)}))}})}),I0=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},Uh=e=>(Object.keys(e).forEach(t=>{nt(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(nr(e[t])||Jt(e[t]))&&Uh(e[t])}),e);function Br(e,t){return new Promise(i=>{let r=setTimeout(i,e);t&&t(r)})}function R0(e,t){let i=null;return function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];return i||(i=e.apply(t||this,n),i.finally(()=>i=null),i)}}function A0(e){return e.replace(/(^|[^:])\/{2,}/g,"$1/")}function b0(e){var t;try{let{width:i,height:r,frameRate:n,sampleRate:s,sampleSize:o,channelCount:l}=(t=e.getSettings)==null?void 0:t.call(e),c=e.kind===D.AUDIO?"".concat(s,"x").concat(o,"@").concat(l):"".concat(i,"x").concat(r,"@").concat(n),h=e.stats?" stats: ".concat(JSON.stringify(e.stats).replaceAll('"',"")):"";return"".concat(e.id," ").concat(e.readyState," muted:").concat(e.muted," ").concat(e.kind," ").concat(e.label," ").concat(c).concat(h)}catch{return""}}function Vh(e,t){return e.width*e.height===t.width*t.height?1:S0()&&t.width>t.height&&e.height>t.width?Math.max(e.width/t.height,e.height/t.width,1):Math.max(e.width/t.width,e.height/t.height,1)}function ls(e){return e===90||e===270}function O2(e){return P(this,null,function*(){return new Promise((t,i)=>{let r=document.createElement("video");r.crossOrigin="anonymous",r.src=e,r.muted=!0,r.loop=!0,r.playsInline=!0,r.play().then(()=>t(r)),r.onerror=()=>{i(r.error)}})})}function Fh(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:new WeakMap;if(typeof e!="object"||e===null)return e;if(t.has(e))return t.get(e);if(Array.isArray(e)){let i=[];return t.set(e,i),e.forEach((r,n)=>{i[n]=Fh(r,t)}),i}if(Object.prototype.toString.call(e)==="[object Object]"){let i={};return t.set(e,i),Reflect.ownKeys(e).forEach(r=>{i[r]=Fh(e[r],t)}),i}return e}var C0=(e=>(e[e.END_REPORT=2001]="END_REPORT",e[e.LOG=2002]="LOG",e[e.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",e))(C0||{});function wo(e,t,i,r){try{let n=(function(s,o,l,c){let h={data:s,random:Math.floor(2147483648*Math.random()),sdkAppId:l};return j(c)||(h=xe(ve({},h),{gzip:+c})),{uint32_sdkappid:0,uint64_from_uin:0,uint32_timestamp:0,uint32_seq:0,msg_common_info:{msg_device_info:{enum_device_type:0,str_device_brand:"",str_device_model:"",str_device_board:"",str_device_cpu_abi:""},msg_system_info:{enum_os_type:0,str_os_version:"",msg_network_info:0},msg_network_info:{enum_network_type:0}},msg_report_content:{uint32_type:o,bytes_report_data:JSON.stringify(h)}}})(e,t,i,r);return mH(m0(n),i)}catch{return JSON.stringify(e)}}function k0(e,t){let i=new Uint8Array(e.byteLength+t.byteLength);return i.set(new Uint8Array(e),0),i.set(new Uint8Array(t),e.byteLength),i.buffer}function w0(e){return(65535&e)>>>0}function M2(e){return(4294901760&e)>>>0}function gH(e){let t=(function(i){try{let r={},n=0;r.totalLength=Ui(i,n),n+=4,r.version=Ui(i,n),n+=4,r.encryption=m2(i,n),n+=1,r.uinType=m2(i,n),n+=1,r.uinLength=Ui(i,n),n+=4,r.uin=r.uinLength>4?_c(i,n,r.uinLength-4):"",n+=r.uinLength-4;let s=i.slice(n);return r.encryption===2?(i=(function(o,l){let c=0,h=new Uint8Array(8).fill(0),_=new Uint8Array(o.slice(0,8)),f=L2(_,l),T=7&f[0],b=o.length-1-T-gc-vc,C=new Uint8Array(b),x=0,B=h,Y=o.slice(0,8);c=8;let G=1;G+=T;for(let H=1;H<=gc;)if(G<8)G++,H++;else if(G===8){let Z=D0(o,c,B,Y,f,l);B=Z.ivPreCrypt,Y=Z.ivCurCrypt,f=Z.debiBuf,c=Z.bufPos,G=0}let he=b;for(;he>0;)if(G<8)C[x++]=f[G]^B[G],G++,he--;else if(G===8){let H=D0(o,c,B,Y,f,l);B=H.ivPreCrypt,Y=H.ivCurCrypt,f=H.debiBuf,c=H.bufPos,G=0}for(let H=1;H<=vc;)if(G<8)f[G],B[G],G++,H++;else if(G===8){if(c>=o.length)break;let Z=D0(o,c,B,Y,f,l);if(!Z.success)break;B=Z.ivPreCrypt,Y=Z.ivCurCrypt,f=Z.debiBuf,c=Z.bufPos,G=0}return C})(s,new Uint8Array(16).fill(0)),r.decrypted=!0,n=0):(i=s,n=0),r.rspHeadLength=Ui(i,n),n+=4,r.seqNo=Ui(i,n),n+=4,r.retCode=Ui(i,n),n+=4,r.retStrLength=Ui(i,n),n+=4,r.retStr=r.retStrLength?_c(i,n,r.retStrLength-4):"",n+=r.retStrLength-4,r.serviceCmdLength=Ui(i,n),n+=4,r.serviceCmd=r.serviceCmdLength?_c(i,n,r.serviceCmdLength-4):"",n+=r.serviceCmdLength-4,r.cookieLength=Ui(i,n),n+=4,r.cookie=r.cookieLength?_c(i,n,r.cookieLength-4):"",n+=r.cookieLength-4,r.flag=Ui(i,n),n+=4,r.busiBuffLength=Ui(i,n),n+=4,r.busiBuff=r.busiBuffLength?_c(i,n,r.busiBuffLength-4):"",n+=r.busiBuffLength-4,r}catch{}})(e);return t?.busiBuff}function L2(e,t){let i=e[0]<<24|e[1]<<16|e[2]<<8|e[3],r=e[4]<<24|e[5]<<16|e[6]<<8|e[7];i>>>=0,r>>>=0;let n=_0*g0>>>0;for(let s=0;s<g0;s++)r-=(i<<4)+t[2]^i+n^(i>>>5)+t[3],r>>>=0,i-=(r<<4)+t[0]^r+n^(r>>>5)+t[1],i>>>=0,n-=_0,n>>>=0;return new Uint8Array([i>>>24&255,i>>>16&255,i>>>8&255,255&i,r>>>24&255,r>>>16&255,r>>>8&255,255&r])}function D0(e,t,i,r,n,s){if(t+8>e.length)return{success:!1};let o=new Uint8Array(r),l=e.slice(t,t+8),c=new Uint8Array(8);for(let h=0;h<8;h++)c[h]=n[h]^l[h];return{success:!0,ivPreCrypt:o,ivCurCrypt:l,debiBuf:L2(c,s),bufPos:t+8}}var x2=typeof TextDecoder<"u"?new TextDecoder:void 0;function bc(e){let{url:t,body:i,method:r="POST",timeout:n,priority:s}=e;return new Promise((o,l)=>{if("fetch"in window)return fetch(t,{method:r,body:i,priority:s}).then(h=>h.clone().json().then(_=>({data:_}),()=>h.arrayBuffer().then(_=>({data:gH(new Uint8Array(_))||(x2?x2.decode(_):_)})))).then(o,l);let c=new XMLHttpRequest;c.onreadystatechange=()=>{if(c.readyState===4)if(c.status>=200&&c.status<300)try{let h=JSON.parse(c.response);o({data:h})}catch{o({data:c.response})}else l({status:c.status,statusText:c.statusText||"request failed!"})},c.timeout=n||5e3,c.open(r,t,!0),c.send(i)})}function U2(e){return P(this,null,function*(){let t=Ue(),i=JSON.stringify(e);try{if(!CompressionStream||i.length<=2800)return i;let r=new Blob([i],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),n=yield(yield(yield new Response(r)).blob()).arrayBuffer();return fe.debug("compressJSON ".concat(i.length," -> ").concat(n.byteLength," ").concat(Ue()-t,"ms")),n}catch{return i}})}var vH=Object.prototype.hasOwnProperty,ua=e=>typeof e=="function",sr=e=>e===void 0,N0=e=>typeof e=="string",V2=e=>typeof e=="boolean",P0=e=>e.isRemote,F2=function(e){if(!e||typeof e!="object"||Object.prototype.toString.call(e)!="[object Object]")return!1;let t=Object.getPrototypeOf(e);if(t===null)return!0;let i=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof i=="function"&&i instanceof i&&Function.prototype.toString.call(i)===Function.prototype.toString.call(Object)},Cc=function(e){let{retryFunction:t,settings:i,onError:r,onRetrying:n,onRetryFailed:s,onRetrySuccess:o,context:l}=e;return function(){for(var c=arguments.length,h=new Array(c),_=0;_<c;_++)h[_]=arguments[_];let{retries:f=5,timeout:T=1e3}=i,b=0,C=-1,x=0,B=(Y,G)=>P(this,null,function*(){let he=l||this;try{let H=yield t.apply(he,h);b>0&&o&&o.call(this,b),b=0,Y(H)}catch(H){let Z=()=>{clearTimeout(C),b=0,x=2,G(H)},de=()=>{x!==2&&b<(ua(f)?f():f)?(b++,x=1,ua(n)&&n.call(this,b,Z),C=window.setTimeout(()=>{C=-1,B(Y,G)},ua(T)?T(b):T)):(Z(),ua(s)&&s.call(this,H))};ua(r)?r.call(this,{error:H,retry:de,reject:G,retryFuncArgs:h,retriedCount:b}):de()}});return new Promise(B)}},O0=class $N{constructor(t){m(this,"_parentPath"),m(this,"userId"),m(this,"remoteUserId"),m(this,"id"),m(this,"sdkAppId"),m(this,"type"),m(this,"isLocal"),this.id=t.id,this.userId=t.userId,this.sdkAppId=t.sdkAppId,this.remoteUserId=t.remoteUserId,this.isLocal=!V2(t.isLocal)||t.isLocal,this.type=this.isLocal?"":t.type}getFullId(){return this._parentPath&&this.id?"".concat(this._parentPath,"-").concat(this.id):this._parentPath?this._parentPath:this.id}createChild(t){let i=new $N({id:t.id,userId:sr(t.userId)?this.userId:t.userId,sdkAppId:sr(t.sdkAppId)?this.sdkAppId:t.sdkAppId,type:sr(t.type)?this.type:t.type,isLocal:sr(t.isLocal)?this.isLocal:t.isLocal,remoteUserId:sr(t.remoteUserId)?this.remoteUserId:t.remoteUserId});return i.bindParent(this),i}bindParent(t){let i=t.getFullId();this._parentPath!==i&&(this.debug("bind logger parent: ".concat(t.id)),this._parentPath=i,this.userId=t.userId||this.userId,this.sdkAppId=t.sdkAppId||this.sdkAppId)}setUserId(t){this.userId=t}setSdkAppId(t){this.sdkAppId=t}log(t,i){let r=this.isLocal?this.userId:this.remoteUserId,n=this.getFullId();i.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&this.type!=="main"?"*":"").concat(n).concat(r?"|".concat(r):"","]")),fe.log(t,i,sr(this.userId)||(function(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(F2(s))switch(Object.prototype.toString.call(s)){case"[object File]":case"[object Map]":case"[object Set]":return s.size===0;case"[object Object]":for(let o in s)if(vH.call(s,o))return!1;return!0}return!1})(this.userId),this.userId,this.sdkAppId)}info(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];this.log(2,i)}debug(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];this.log(1,i)}warn(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];this.log(3,i)}error(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];this.log(4,i)}},B2={};pn(B2,{ANDROID_VERSION:()=>Hh,CHROME_MAJOR_VERSION:()=>lr,CHROME_VERSION:()=>$0,EDGE_VERSION:()=>x0,EDG_MAJOR_VERSION:()=>G2,EDG_VERSION:()=>U0,ELECTRON_MAJOR_VERSION:()=>Y2,FIREFOX_MAJOR_VERSION:()=>Wh,FIREFOX_VERSION:()=>L0,HUAWEI_VERSION:()=>q0,IE_VERSION:()=>IH,IOS_MAIN_VERSION:()=>Sr,IOS_VERSION:()=>cr,IPADQQB_VERSION:()=>z0,IS_ANDROID:()=>Vt,IS_ANDROID_WEBVIEW:()=>CH,IS_ANY_SAFARI:()=>pa,IS_CHROME:()=>$h,IS_CHROME_OS:()=>K0,IS_CHROMIUM_128_TO_143:()=>Oo,IS_CHROMIUM_BASE:()=>or,IS_DESKTOP_IOS_CHROME:()=>Q2,IS_EDG:()=>wc,IS_EDGE:()=>No,IS_ELECTRON:()=>AH,IS_FIREFOX:()=>ut,IS_HEADLESS_CHROME:()=>J2,IS_HONOR:()=>K2,IS_HUAWEI:()=>Y0,IS_HUAWEIBROWSER:()=>qh,IS_IE:()=>j2,IS_IE8:()=>SH,IS_IOS:()=>Gt,IS_IOS_13_OR_14:()=>X2,IS_IOS_15_1:()=>q2,IS_IOS_CHROME:()=>xc,IS_IPAD:()=>Do,IS_IPADQQB:()=>Jh,IS_IPAD_PRO:()=>M0,IS_IPHONE:()=>da,IS_IPOD:()=>W2,IS_LINUX:()=>Oc,IS_LOCAL:()=>fa,IS_MAC:()=>us,IS_MACQQB:()=>Kh,IS_MIBROWSER:()=>Yh,IS_MQQB:()=>Nc,IS_NATIVE_ANDROID:()=>TH,IS_OLD_ANDROID:()=>yH,IS_OPENHARMONY:()=>Lc,IS_OPPOBROWSER:()=>Mc,IS_SAFARI:()=>ri,IS_SAFARI_15_1:()=>kH,IS_SAMSUNGBROWSER:()=>Xh,IS_SOGOU:()=>jh,IS_SOGOUM:()=>Gh,IS_TBS:()=>Hr,IS_UCBROWSER:()=>z2,IS_VIVOBROWSER:()=>Qh,IS_WECHAT:()=>ha,IS_WIN:()=>Po,IS_WQQB:()=>zh,IS_WX:()=>RH,IS_X5MQQB:()=>Dc,IS_XWEB:()=>cs,MACQQB_VERSION:()=>j0,MI_VERSION:()=>J0,MQQB_VERSION:()=>Pc,OPENHARMONY_VERSION:()=>bH,OPPO_VERSION:()=>Q0,SAFARI_VERSION:()=>ma,SAMSUNG_VERSION:()=>X0,SOGOUM_VERSION:()=>V0,SOGOU_VERSION:()=>F0,TBS_VERSION:()=>B0,UA_DATA_STRING:()=>vn,USER_AGENT:()=>ar,VIVO_VERSION:()=>Z0,WECHAT_VERSION:()=>W0,WQQB_VERSION:()=>G0,XWEB_VERSION:()=>H0,browserInfo:()=>ds,getBrowserCoreNumber:()=>tk,getBrowserInfo:()=>Z2,getChromeMajorVersion:()=>Zh,getDeviceModel:()=>Lo,getDeviceModelFromUA:()=>nv,getGPUInfo:()=>Mo,getOSName:()=>sv,getOSNumber:()=>tp,getOSString:()=>xo,getOSType:()=>NH,getTerminalType:()=>ik,getUserAgentData:()=>ep,isAMDGPU:()=>$2,isAppleSiliconGPU:()=>DH,isLocalStorageEnabled:()=>_a,isMobile:()=>iv,isNvidiaGPU:()=>wH,isRealIOS:()=>kc,isVersionLargerThan:()=>tv,isVersionSmallerThan:()=>ev});var ar=typeof navigator>"u"?"":navigator.userAgent,Ye=e=>new RegExp(e,"i").test(ar),Wt=e=>{if(Ye(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=ar.match(t);if(i&&i[1])return i[1]}return""},Bh=e=>{if(Ye(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=ar.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},H2=/AppleWebKit\/([\d.]+)/i.exec(ar),EH=H2?parseFloat(H2[1]):NaN,Do=Ye("iPad"),M0=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Ye("Macintosh"),da=Ye("iPhone")&&!Do,W2=Ye("iPod"),Gt=da||Do||W2||M0,kc=()=>{try{return Gt&&navigator.maxTouchPoints>1&&navigator.vendor.includes("Apple")}catch{return Gt}},Vt=Ye("Android"),Hh=(function(){if(Vt){let e=ar.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})(),yH=Vt&&Ye("webkit")&&Hh<2.3,TH=Vt&&Hh<5&&EH<537,ut=Ye("Firefox"),L0=Wt("Firefox"),Wh=Bh("Firefox"),No=Ye("Edge"),x0=Wt("Edge"),wc=Ye("Edg"),U0=Wt("Edg"),G2=Bh("Edg"),Gh=Ye("SogouMobileBrowser"),V0=Wt("SogouMobileBrowser"),jh=Ye("MetaSr\\s"),F0=Wt("MetaSr\\s"),Hr=Ye("TBS"),B0=Wt("TBS"),cs=Ye("XWEB"),H0=Wt("XWEB"),SH=Ye("MSIE\\s8\\.0"),j2=Ye("MSIE\\/\\d+"),IH=(function(){if(j2){let e=/MSIE\s(\d+)\.\d/.exec(ar),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(ar)&&/rv:11.0/.test(ar)&&(t=11),t}return NaN})(),ha=Ye("(micromessenger|webbrowser)"),W0=Wt("MicroMessenger"),Dc=!Hr&&Ye("MQQBrowser")&&Ye("COVC"),Nc=!Hr&&Ye("MQQBrowser")&&!Ye("COVC"),Pc=Nc||Dc?Wt("MQQBrowser"):"",zh=!Hr&&Ye(" QQBrowser"),G0=Wt(" QQBrowser"),Kh=!Hr&&Ye("QQBrowserLite"),j0=Wt("QQBrowserLite"),Jh=!Hr&&Ye("MQBHD"),z0=Wt("MQBHD"),Po=Ye("Windows"),us=!Gt&&Ye("MAC OS X"),Oc=!Vt&&Ye("Linux"),K0=Ye("CrOS"),RH=Ye("MicroMessenger"),z2=Ye("UCBrowser"),AH=Ye("Electron"),Yh=Ye("MiuiBrowser"),J0=Wt("MiuiBrowser"),qh=Ye("HuaweiBrowser"),Y0=Ye("Huawei")||Ye("HUAWEI"),K2=Ye("Honor")||Ye("HONOR"),q0=Wt("HuaweiBrowser"),Xh=Ye("SamsungBrowser"),X0=Wt("SamsungBrowser"),Mc=Ye("HeyTapBrowser"),Q0=Wt("HeyTapBrowser"),Qh=Ye("VivoBrowser"),Z0=Wt("VivoBrowser"),Lc=Ye("OpenHarmony"),bH=Wt("OpenHarmony"),Zh=()=>Bh("Chrome"),xc=Ye("CriOS"),or=Ye("Chrome"),$h=!No&&!jh&&!Gh&&!Hr&&!cs&&!wc&&!zh&&!Yh&&!qh&&!Xh&&!Mc&&!Qh&&or,J2=Ye("HeadlessChrome"),lr=Zh(),Oo=or&&lr>=128&&lr<=143,$0=Wt("Chrome"),Y2=Bh("Electron"),ri=!or&&!Nc&&!Dc&&!Kh&&!Jh&&Ye("Safari"),pa=ri||Gt,ma=Wt("Version"),CH=/Android.*(wv|.0.0.0)/.test(ar),cr=(()=>{if(M0)return ma;if(Gt){let e=ar.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})();function ev(e,t){let i=e.split(".").map(n=>Number(n)),r=t.split(".").map(n=>Number(n));for(let n=0;n<Math.max(i.length,r.length);n++){let s=i[n]||0,o=r[n]||0;if(s<o)return!0;if(s>o)return!1}return!1}function tv(e,t){let i=arguments.length>2&&arguments[2]!==void 0&&arguments[2],r=e.split(".").map(s=>Number(s)),n=t.split(".").map(s=>Number(s));for(let s=0;s<Math.max(r.length,n.length);s++){let o=r[s]||0,l=n[s]||0;if(o>l)return!0;if(o<l)return!1}return i}var Sr=Number(cr.split(".")[0]),kH=ma==="15.1",q2=cr==="15.1",X2=(()=>{let e=Number(cr.split(".")[0]);return e===14||e===13})(),Q2=xc&&ma==="11.1.1",fa=typeof location<"u"&&(location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"),_a=(()=>{let e;return()=>{if(e===void 0)try{e=!!window.localStorage}catch{e=!1}return e}})(),ds=Z2();function Z2(){let e=new Map([[ut,["Firefox",L0]],[wc,["Edg",U0]],[$h,["Chrome",$0]],[xc,["ChiOS",Wt("CriOS")]],[ri&&!xc,["Safari",ma]],[Hr,["TBS",B0]],[cs,["XWEB",H0]],[ha&&da,["WeChat",W0]],[zh,["QQ(Win)",G0]],[Nc,["QQ(Mobile)",Pc]],[Dc,["QQ(Mobile X5)",Pc]],[Kh,["QQ(Mac)",j0]],[Jh,["QQ(iPad)",z0]],[Yh,["MI",J0]],[qh,["HW",q0]],[Xh,["Samsung",X0]],[Mc,["OPPO",Q0]],[Qh,["VIVO",Z0]],[No,["EDGE",x0]],[Gh,["SogouMobile",V0]],[jh,["Sogou",F0]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var Tt=null;function iv(){return Tt&&typeof Tt.mobile=="boolean"?Tt.mobile:Vt||Gt||da||Do||Lc}var vn="";function ep(){return P(this,null,function*(){if(Tt)return Tt;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return(Tt=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!vn&&(vn="UAData: ".concat(Tt.platform,"/").concat(Tt.platformVersion),Tt.architecture&&Tt.bitness&&(vn+=" ".concat(Tt.architecture,"/").concat(Tt.bitness)),Tt.mobile&&(vn+=" mobile"),Tt.model&&(vn+=" model: ".concat(Tt.model.replace(/\s+/g,"/"))),Tt.fullVersionList&&(vn+=" ".concat(Tt.fullVersionList.filter(e=>e.brand!=="Not/A)Brand").map(e=>"".concat(e.brand,"/").concat(e.version)).join(",")))),Tt}catch{return null}})}var rv="";function Mo(){try{if(rv)return rv;let e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return"";let i=t.getExtension("WEBGL_debug_renderer_info");if(i){let r=t.getParameter(i.UNMASKED_VENDOR_WEBGL),n=t.getParameter(i.UNMASKED_RENDERER_WEBGL);return rv="".concat(r," ").concat(n)}return""}catch{return""}}function $2(){try{let e=Mo();return e.includes("AMD")||e.includes("ATI")}catch{return!1}}function wH(){try{let e=Mo();return e.includes("NVIDIA")||e.includes("GeForce")}catch{return!1}}function DH(){try{return Mo().includes("Apple M")}catch{return!1}}function Lo(){return Tt?.model||nv()||""}function nv(){let e=ar.match(/;\s*([^;)]+)\s+Build\//);return e!=null&&e[1]?e[1].trim():null}var ek=new Map([[Vt,"Android"],[Gt,"iOS"],[Po,"Windows"],[us,"MacOS"],[Oc,"Linux"],[K0,"ChromeOS"]]),sv=function(){return ek.get(!0)?ek.get(!0):Tt?Tt.platform:"unknown"};function tp(){return Po?1:Vt?2:us?3:Gt?4:Oc?5:K0?6:Lc?7:0}function tk(){return ha||cs?4:or?1:ri?2:ut?3:0}var xo=()=>{let e=sv();return Tt!=null&&Tt.platformVersion?e+="/".concat(Tt.platformVersion):Gt?e+="/".concat(cr):Vt&&(e+="/".concat(Hh)),e+="/".concat(ds.name,"/").concat(ri&&!xc?ds.version:ds.version.split(".")[0]),Tt!=null&&Tt.architecture&&(e+="/".concat(Tt.architecture)),e};function ik(){return Vt?4:da?2:Do?3:us?12:Po?5:Oc?13:Lc?22:1}function NH(){return Vt?"Android":da?"iPhone":Do?"iPad":us?"Mac":Po?"Windows":Oc?"Linux":"unknown"}var Ce,$=new(ti(Ri(),1)).default,rk=((Ce=rk||{}).ROOM_DESTROY="1",Ce.JOIN_START="21",Ce.JOIN_SCHEDULE_SUCCESS="22",Ce.JOIN_SIGNAL_CONNECTION_START="23",Ce.JOIN_SIGNAL_CONNECTION_END="24",Ce.JOIN_SEND_CMD="25",Ce.JOIN_RECEIVED_CMD_RES="26",Ce.JOIN_SUCCESS="27",Ce.JOIN_FAILED="28",Ce.LEAVE_START="51",Ce.LEAVE_SEND_CMD="52",Ce.LEAVE_SUCCESS="53",Ce.PUBLISH_START="61",Ce.SEND_FIRST_VIDEO_FRAME="62",Ce.PUBLISH_FAILED="63",Ce.SUBSCRIBE_START="81",Ce.SUBSCRIBE_SUCCESS="82",Ce.SUBSCRIBE_FAILED="84",Ce.UNSUBSCRIBE_SUCCESS="83",Ce.LOCAL_TRACK_CAPTURE_START="101",Ce.LOCAL_TRACK_CAPTURE_SUCCESS="102",Ce.LOCAL_TRACK_CAPTURE_FAILED="103",Ce.LOCAL_TRACK_PUBLISHED="104",Ce.LOCAL_TRACK_UNPUBLISHED="105",Ce.LOCAL_TRACK_REPLACED="106",Ce.SWITCH_DEVICE_SUCCESS="107",Ce.TRACK_MUTED="108",Ce.TRACK_UNMUTED="109",Ce.REMOTE_TRACK_SUBSCRIBED="110",Ce.REMOTE_TRACK_UNSUBSCRIBED="111",Ce.LOCAL_TRACK_RECAPTURE="112",Ce.LOCAL_AUDIO_STARTED="113",Ce.LOCAL_AUDIO_STOPPED="114",Ce.REMOTE_AUDIO_STARTED="115",Ce.REMOTE_AUDIO_STOPPED="116",Ce.PLAY_TRACK_START="151",Ce.PLAYER_STATE_CHANGED="152",Ce.VIDEO_LOADED_DATA="153",Ce.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",Ce.AUDIO_CONTEXT_LONG_SUSPENDED="155",Ce.REMOTE_VIDEO_PLAY_START="156",Ce.REMOTE_VIDEO_PLAY_FINISH="157",Ce.SIGNAL_CONNECTION_STATE_CHANGED="201",Ce.PEER_CONNECTION_STATE_CHANGED="202",Ce.SINGLE_CONNECTION_STAT="203",Ce.SPC_RECONNECTED="204",Ce.HEARTBEAT_REPORT="251",Ce.RECEIVED_PUBLISHED_USER_LIST="252",Ce.REMOTE_PUBLISH_STATE_CHANGED="253",Ce.AUDIO_LEVEL_INTERVAL="260",Ce.NETWORK_QUALITY="261",Ce.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",Ce.QUALITY_LIMITATION_CHANGED="263",Ce.LOG="264",Ce.AUDIO_PROCESSOR_DEBUG="265",Ce.SSO_SWITCH="266",Ce.SEI_MESSAGE="267",Ce.USER_PAUSE_IN_PIP="268",Ce.USER_RESUME_IN_PIP="269",Ce.ENTER_PICTURE_IN_PICTURE="270",Ce.LEAVE_PICTURE_IN_PICTURE="271",Ce.SWITCH_ROOM_START="401",Ce.SWITCH_ROOM_SUCCESS="407",Ce.SWITCH_ROOM_FAILED="408",Ce),ie=rk,Uc=new class{constructor(){m(this,"enable",!1),m(this,"ssoFailCount",0),$.on("22",e=>{let{schedule:t}=e;var i;(i=t?.config)!=null&&i.sso&&$.emit("266",{enable:!0})}),$.on("266",e=>{let{enable:t}=e;this.enable=t})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&$.emit("266",{enable:!1})}},nk=class eP{constructor(){m(this,"_isEnableUploadLog",!0),m(this,"_localJoinedUser",new Map),m(this,"_queue",[]),m(this,"_timeoutId",-1),m(this,"_logLevel",1),m(this,"_logLevelToUpload",2),!Rh&&!Xg&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){$.on(ie.JOIN_SCHEDULE_SUCCESS,t=>{let{schedule:i}=t;var r;(r=i?.config)!=null&&r.logLevelToUpload&&ns[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),$.on(ie.JOIN_START,t=>{let{params:i}=t;this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),$.on(ie.LEAVE_SUCCESS,t=>{let{room:i}=t;this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(t){this._localJoinedUser.set(t.userId,t),this.startUpload()}deleteJoinedUser(t){this._localJoinedUser.delete(t)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let t={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return t;let i=0;for(;i<this._queue.length&&i!==50;i++){let r=this._queue[i];if(r.forAllJoinedClients)this._localJoinedUser.forEach(n=>{let{userId:s,sdkAppId:o}=n;t.map.has(s)?t.map.get(s).logs.push(r):t.map.set(s,{userId:s,sdkAppId:o,logs:[r]})});else if(pt(r.userId)&&nt(r.sdkAppId)){let{userId:n,sdkAppId:s}=r;t.map.has(n)?t.map.get(n).logs.push(r):t.map.set(n,{userId:n,sdkAppId:s,logs:[r]})}}return t.map.size>0&&(t.splicedQueue=this._queue.splice(0,i)),t}upload(){return P(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:t,splicedQueue:i}=this.getLogsToUpload();if(t.size===0)return;try{let n=[...t.values()];for(let s=0;s<n.length;s++){let{userId:o,sdkAppId:l,logs:c}=n[s],h={timestamp:j1(),sdkAppId:String(l),userId:o,version:yr,log:c.map(T=>T.log).join(`
43
+ `)},_=JSON.stringify(h),f=Uc.enable?wo(h,2002,l):_;yield this.uploadLogWithRetry(f,l,f instanceof Uint8Array,_),c.forEach(T=>T.uploaded=!0)}}catch{}let r=i.filter(n=>!n.uploaded);r.length>0&&(this._queue=r.concat(this._queue))})}uploadLogWithRetry(t,i,r,n){return Cc({retryFunction:()=>bc({url:bo(i,lc.LOG),body:t,timeout:5e3,priority:"low"}).then(s=>{r&&s.data!=="ok"&&(Uc.handleUploadFailed(),this.uploadLogWithRetry(n,i,!1,n))}),settings:{retries:3,timeout:2e3},onError:s=>{let{retry:o}=s;o()}})()}getPrefix(t){let i=new Date;return i.setTime(ac()),"[".concat(Jg(i),"] <").concat(ns[t],">")}getLogLevel(){return this._logLevel}setLogLevel(t){j(ns[t])||(this._logLevel!==t&&this.info("setLogLevel",t),this._logLevel=t)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(t){if(pt(t))return t;try{return t instanceof Error?t.toString():JSON.stringify(t)}catch{return""}}addLogToQueue(t,i){let r=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2],n=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0,o={log:i.reduce((l,c)=>"".concat(l," ").concat(this.logChunkToString(c)).trim(),""),level:t,userId:n,sdkAppId:s,forAllJoinedClients:r};$.emit(ie.LOG,{log:o}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(o)}log(t,i){let r=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2],n=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;var o;if(i.unshift(this.getPrefix(t)),this.addLogToQueue(t,i,r,n,s),t<this._logLevel)return;let l=((o=ns[t])==null?void 0:o.toLowerCase())||"info";eP.PRINT_LOG_TAG?console[l]("%cTRTC%c%s","padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;","display: inline",...i):console[l](...i)}debug(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];this.log(1,i)}info(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];this.log(2,i)}warn(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];this.log(3,i)}error(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];this.log(4,i)}createLogger(t){if(t.parent instanceof O0){let i=t,{parent:r}=i,n=U1(i,["parent"]),s=new O0(n);return s.bindParent(r),s}return new O0(t)}checkURLParam(){let t=new URLSearchParams(location.search).get("logLevelToUpload"),i=t?Number(t):-1;ns[i]&&(this._logLevelToUpload=i)}getQueue(){return this._queue}};m(nk,"PRINT_LOG_TAG",!(Gt||Vt||J2));var fe=new nk,sk=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return(e=="x"?t:3&t|8).toString(16)})},av=new class{constructor(){m(this,"_prefix","TRTC"),m(this,"_queue",new Map)}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){_a()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(e=>{if(e.startsWith(this._prefix))try{let t=localStorage.getItem(e);if(!t)return!1;let i=JSON.parse(t);if(i&&i.expiresIn<Date.now())return!0}catch{return!1}return!1}).forEach(e=>localStorage.removeItem(e)))}doFlush(){if(_a())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(e){fe.warn(e)}}getItem(e){if(!_a())return null;try{let t=localStorage.getItem(this.getRealKey(e));if(!t)return null;let i=JSON.parse(t);return i&&i.expiresIn>=Date.now()?i.value:null}catch(t){fe.warn(t)}}setItem(e,t){if(_a())try{let i={expiresIn:Date.now()+Q1,value:t};this._queue.set(this.getRealKey(e),i)}catch(i){fe.warn(i)}}deleteItem(e){if(!_a())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(t){return fe.warn(t),!1}}clear(){if(_a())try{localStorage.clear()}catch(e){fe.warn(e)}}},Vc={};pn(Vc,{HTTPS_API:()=>HH,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>mw,IS_GET_CAPABILITIES_SUPPORTED:()=>pw,IS_GET_SETTINGS_SUPPORTED:()=>Fo,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>hw,IS_INSERTABLE_STREAM_SUPPORTED:()=>va,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>ap,IS_RTC_RTP_SENDER_SUPPORTED:()=>jc,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>sp,IS_SEI_SUPPORTED:()=>Tv,IS_SPC_SUPPORTED:()=>Gc,basis:()=>jH,capabilityCheck:()=>yw,checkSystemRequirementsInternal:()=>fv,decodeSupportStatus:()=>mv,detectVideoCodecCapabilities:()=>Iw,detectVideoDecoderCapabilities:()=>Aw,detectVideoEncoderCapabilities:()=>Rw,encodeSupportStatus:()=>pv,getBrowserInfo:()=>UH,getDisplayResolution:()=>aw,getH264ProfileLevelIds:()=>bw,isAddTransceiverSupported:()=>Rr,isBrowserSupported:()=>uv,isCanvasCaptureStreamAPISupported:()=>cw,isCanvasSmallStreamSupported:()=>vv,isGetReceiversSupported:()=>np,isGetSendersSupported:()=>Wc,isGetTransceiversSupported:()=>Vo,isGetUserMediaSupported:()=>ow,isMediaDevicesSupported:()=>dv,isMediaSessionSupported:()=>fw,isMediaStreamTrackGeneratorSupported:()=>VH,isMediaStreamTrackProcessorSupported:()=>hv,isReplaceTrackSupported:()=>dw,isRequestVideoFrameCallbackSupported:()=>zc,isSIMDSupported:()=>gw,isScaleResolutionDownBySupported:()=>uw,isScreenCaptureApiAvailable:()=>rp,isSelectedCandidatePair:()=>Hc,isSetParametersSupported:()=>yv,isSetSinkIdSupported:()=>BH,isSmallStreamSupported:()=>Ev,isStopTransceiverSupported:()=>GH,isTRTCSupported:()=>FH,isUnifiedPlanDefault:()=>WH,isUsedInHttpProtocol:()=>ga,isWebAudioSupported:()=>lw,isWebCodecSupported:()=>Iv,isWebCodecsSupported:()=>ip,isWebRTCSupported:()=>Sv,isWebTransportSupported:()=>_w});var ak={};pn(ak,{AUDIO_LEVEL_SCALE:()=>Wr,AlphaStitchingType:()=>cv,AudioCodecPipelineType:()=>Gk,AudioDecoderDowngradeState:()=>Sk,AudioPlayerMode:()=>Uk,AudioType:()=>Ck,BASIC_TYPE:()=>Hk,BannedReason:()=>Vk,CONNECTION_CLOSED_REASON:()=>ck,CheckPermissionType:()=>qk,ClientEvent:()=>uk,CodecType:()=>jk,ConnectionEvent:()=>lk,ConnectionState:()=>Tk,DECODE_FAILED_ERROR_CODE:()=>zk,DenoiserMode:()=>Bk,DeviceType:()=>Xk,FacingMode:()=>Lk,FrameWorkType:()=>ok,LeaveReason:()=>Fk,LocalTrackEvent:()=>hk,MULTI_VIDEO_DATA_TYPE:()=>Nk,MediaType:()=>bk,MediaTypeLabel:()=>PH,MonitorEventId:()=>Pk,MutedFlag:()=>gk,NetworkQualityValue:()=>Ok,PlayerState:()=>pk,ReceiveMode:()=>Mk,RemoteStreamType:()=>Dk,RemoteTrackEvent:()=>_k,RoomEvent:()=>mk,SMALL_MODE:()=>Yk,SceneNumber:()=>vk,StreamEvent:()=>dk,StreamType:()=>wk,SubscribeMediaType:()=>OH,TIMER_TYPE:()=>Jk,TRACK_ACTION:()=>Ak,TRACK_KIND:()=>Rk,TrackEvent:()=>fk,UserRole:()=>yk,UserRoleNumber:()=>Ek,VideoCodec:()=>lv,VideoCodecPipelineType:()=>Wk,VideoContentHint:()=>Kk,VideoDecoderDowngradeState:()=>Ik,VideoPlayerMode:()=>xk,VideoType:()=>kk});var wt,qt,Ee,ov,Fc,Ai,Ct,En,Uo,hi,fi,ok=(e=>(e[e.WEBRTC=30]="WEBRTC",e[e.WASM=37]="WASM",e))(ok||{}),lk=((fi=lk||{}).TRACK_ADDED="track-added",fi.TRACK_UPDATED="track-updated",fi.TRACK_SUBSCRIBED="track-subscribed",fi.STREAM_ADDED="stream-added",fi.STREAM_REMOVED="stream-removed",fi.STREAM_UPDATED="stream-updated",fi.STREAM_PUBLISHED="stream-published",fi.STREAM_SUBSCRIBED="stream-subscribed",fi.STREAM_UNSUBSCRIBED="stream-unsubscribed",fi.STATE_CHANGED="state-changed",fi.ERROR="error",fi.CONNECTION_STATE_CHANGED="connection-state-changed",fi.FIREWALL_RESTRICTION="firewall-restriction",fi.SEI_MESSAGE="sei-message",fi.CLOSED="closed",fi),ck=(e=>(e.REMOTE_LEAVE="remote user exitRoom",e.REMOTE_UNPUBLISH="remote user unpublished",e.LOCAL_LEAVE="you exitRoom",e.LOCAL_UNPUBLISH="you unpublished",e.LOCAL_UNSUBSCRIBE="you unsubscribed",e.SWITCH_ROLE="you switch role to audience",e))(ck||{}),uk=((hi=uk||{}).STREAM_ADDED="stream-added",hi.STREAM_REMOVED="stream-removed",hi.STREAM_UPDATED="stream-updated",hi.STREAM_SUBSCRIBED="stream-subscribed",hi.CONNECTION_STATE_CHANGED="connection-state-changed",hi.PEER_JOIN="peer-join",hi.PEER_LEAVE="peer-leave",hi.MUTE_AUDIO="mute-audio",hi.MUTE_VIDEO="mute-video",hi.UNMUTE_AUDIO="unmute-audio",hi.UNMUTE_VIDEO="unmute-video",hi.CLIENT_BANNED="client-banned",hi.NETWORK_QUALITY="network-quality",hi.AUDIO_VOLUME="audio-volume",hi.SEI_MESSAGE="sei-message",hi.ERROR="error",hi),dk=((Uo=dk||{}).PLAYER_STATE_CHANGED="player-state-changed",Uo.SCREEN_SHARING_STOPPED="screen-sharing-stopped",Uo.CONNECTION_STATE_CHANGED="connection-state-changed",Uo.DEVICE_AUTO_RECOVERED="device-auto-recovered",Uo.ERROR="error",Uo),hk=((En=hk||{}).DEVICE_AUTO_RECOVERED="1",En.DEVICE_RECOVER_FAILED="5",En.DEVICE_CHANGED="2",En.ERROR="3",En.PUBLISH_STATE_CHANGED="4",En.ENCODE_FAILED="6",En.TRACK_ENDED="7",En.RENDER="render",En),pk=(e=>(e.PAUSED="PAUSED",e.PLAYING="PLAYING",e.STOPPED="STOPPED",e))(pk||{}),mk=((Ct=mk||{}).PEER_JOIN="peer-join",Ct.PEER_LEAVE="peer-leave",Ct.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",Ct.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",Ct.BANNED="banned",Ct.NETWORK_QUALITY="network-quality",Ct.AUDIO_VOLUME="audio-volume",Ct.SEI_MESSAGE="sei-message",Ct.ERROR="error",Ct.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",Ct.REMOTE_PUBLISHED="remote-published",Ct.REMOTE_UNPUBLISHED="remote-unpublished",Ct.FIREWALL_RESTRICTION="firewall-restriction",Ct.HEARTBEAT_REPORT="heartbeat-report",Ct.CUSTOM_MESSAGE="custom-message",Ct.LAYER_DATA="layerData",Ct.FIRST_VIDEO_FRAME="first-video-frame",Ct.DUMP="dump",Ct.AUDIO_FRAME="audio-frame",Ct.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",Ct.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",Ct.NTP_TIME_UPDATED="ntp-time-updated",Ct.DATA_CHANNEL_MESSAGE="data-channel-message",Ct.ASR_ROBOT_PEER_JOIN="asr-robot-peer-join",Ct.ASR_ROBOT_PEER_LEAVE="asr-robot-peer-leave",Ct),fk=(e=>(e.PLAYER_STATE_CHANGED="player-state-changed",e.MUTE="mute",e.UNMUTE="unmute",e.ERROR="error",e.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",e.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",e.FIRST_VIDEO_FRAME="first-video-frame",e.VIDEO_SIZE_CHANGED="video-size-changed",e))(fk||{}),_k=(e=>(e.DECODE_FAILED="decode-failed",e.DECODE_FAILED_DURING_CALL="decode-failed-during-call",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e.REMOTE_PUBLISH_CHANGED="remote-publish-changed",e.AUDIO_FRAME_WITH_NTP="audio-frame-with-ntp",e))(_k||{}),gk=((Ai=gk||{})[Ai.VIDEO=1]="VIDEO",Ai[Ai.SMALL=2]="SMALL",Ai[Ai.AUX=4]="AUX",Ai[Ai.AUDIO=8]="AUDIO",Ai[Ai.VIDEO_MUTE=16]="VIDEO_MUTE",Ai[Ai.AUX_MUTE=32]="AUX_MUTE",Ai[Ai.AUDIO_MUTE=64]="AUDIO_MUTE",Ai),vk=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(vk||{}),Ek=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(Ek||{}),yk=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(yk||{}),Tk=(e=>(e.CONNECTED="CONNECTED",e.DISCONNECTED="DISCONNECTED",e.CONNECTING="CONNECTING",e.RECONNECTED="RECONNECTED",e.RECONNECTING="RECONNECTING",e))(Tk||{}),Sk=((Fc=Sk||{}).INITIALIZED="INITIALIZED",Fc.STARTING="STARTING",Fc.STARTED="STARTED",Fc.FAILED="FAILED",Fc),Ik=(e=>(e.INITIALIZED="INITIALIZED",e.STARTING="STARTING",e.STARTED="STARTED",e.FAILED="FAILED",e))(Ik||{}),Rk=(e=>(e.AUDIO="audio",e.VIDEO="video",e.AUXILIARY="auxVideo",e))(Rk||{}),Ak=(e=>(e.ADD="add",e.REMOVE="remove",e))(Ak||{}),bk=(e=>(e[e.NULL=0]="NULL",e[e.AUDIO=1]="AUDIO",e[e.AUX_VIDEO=2]="AUX_VIDEO",e[e.BIG_VIDEO=4]="BIG_VIDEO",e[e.SMALL_VIDEO=8]="SMALL_VIDEO",e))(bk||{}),PH={1:"audio",2:"auxVideo",4:"video"},Ck=((ov=Ck||{})[ov.opus=111]="opus",ov),kk=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(kk||{}),wk=(e=>(e.Big="big",e.Small="small",e))(wk||{}),Dk=(e=>(e.Main="main",e.Aux="auxiliary",e))(Dk||{}),Nk=(e=>(e[e.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",e[e.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",e[e.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",e[e.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",e[e.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",e))(Nk||{}),Pk=((Ee=Pk||{})[Ee.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",Ee[Ee.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",Ee[Ee.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",Ee[Ee.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",Ee[Ee.MUTE_AUDIO=32772]="MUTE_AUDIO",Ee[Ee.MUTE_VIDEO=32773]="MUTE_VIDEO",Ee[Ee.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",Ee[Ee.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",Ee[Ee.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",Ee[Ee.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",Ee[Ee.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",Ee[Ee.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",Ee[Ee.SWITCH_CAMERA=32780]="SWITCH_CAMERA",Ee[Ee.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",Ee[Ee.REPLACE_VIDEO=32782]="REPLACE_VIDEO",Ee[Ee.REPLACE_AUDIO=32783]="REPLACE_AUDIO",Ee[Ee.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",Ee[Ee.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",Ee[Ee.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",Ee[Ee.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",Ee[Ee.JOIN=32788]="JOIN",Ee[Ee.LEAVE=32789]="LEAVE",Ee[Ee.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",Ee[Ee.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",Ee[Ee.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",Ee[Ee.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",Ee[Ee.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",Ee[Ee.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",Ee[Ee.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",Ee[Ee.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",Ee[Ee.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",Ee[Ee.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",Ee[Ee.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",Ee[Ee.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",Ee[Ee.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",Ee[Ee.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",Ee[Ee.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",Ee[Ee.PUBLISH_AUX=32805]="PUBLISH_AUX",Ee[Ee.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",Ee[Ee.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",Ee[Ee.VIDEO_ENCODER=4004]="VIDEO_ENCODER",Ee[Ee.VIDEO_DECODER=4005]="VIDEO_DECODER",Ee),Ok=(e=>(e[e.UNKNOWN=0]="UNKNOWN",e[e.EXCELLENT=1]="EXCELLENT",e[e.GOOD=2]="GOOD",e[e.POOR=3]="POOR",e[e.BAD=4]="BAD",e[e.VERY_BAD=5]="VERY_BAD",e[e.DISCONNECTED=6]="DISCONNECTED",e))(Ok||{}),Mk=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTO_AUDIO=1]="AUTO_AUDIO",e[e.AUTO_VIDEO=2]="AUTO_VIDEO",e[e.AUTO_ALL=3]="AUTO_ALL",e))(Mk||{}),Lk=(e=>(e.user="user",e.environment="environment",e))(Lk||{}),xk=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CANVAS_FROM_ELEMENT=1]="CANVAS_FROM_ELEMENT",e[e.CANVAS_WITHOUT_ELEMENT=2]="CANVAS_WITHOUT_ELEMENT",e))(xk||{}),Uk=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(Uk||{}),Vk=(e=>(e.BANNED="banned",e.KICK="kick",e.USER_TIME_OUT="user_time_out",e.ROOM_DISBAND="room_disband",e))(Vk||{}),Fk=((qt=Fk||{})[qt.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",qt[qt.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",qt[qt.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",qt[qt.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",qt[qt.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",qt[qt.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",qt[qt.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",qt[qt.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",qt[qt.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",qt),Wr=1e8,Bk=(e=>(e[e.NORMAL=0]="NORMAL",e[e.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",e))(Bk||{}),OH=class{constructor(){m(this,"mediaType",0)}set audio(e){e?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(1&this.mediaType)}set video(e){e?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(4&this.mediaType)}set auxiliary(e){e?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(2&this.mediaType)}set smallVideo(e){e?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(8&this.mediaType)}},Hk=(e=>(e.String="string",e.Number="number",e.Boolean="boolean",e.Array="array",e.Object="object",e))(Hk||{}),lv=(e=>(e.H264="h264",e.H265="h265",e.VP8="vp8",e.VP9="vp9",e.AV1="av1",e))(lv||{}),Wk=(e=>(e[e.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",e[e.DUMP=1]="DUMP",e[e.SEI=2]="SEI",e[e.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",e))(Wk||{}),Gk=(e=>(e[e.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",e[e.NTP_TO_AUDIO_FRAME=1]="NTP_TO_AUDIO_FRAME",e[e.DUMP=2]="DUMP",e[e.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",e))(Gk||{}),jk=(e=>(e.WebRTC="webrtc",e.WebCodecs="webcodecs",e.WebAssembly="webassembly",e))(jk||{}),zk=((wt=zk||{})[wt.SUCCESS=0]="SUCCESS",wt[wt.FAILED=1]="FAILED",wt[wt.WEBCODEC_INIT=2]="WEBCODEC_INIT",wt[wt.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",wt[wt.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",wt[wt.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",wt[wt.WASM_INIT=6]="WASM_INIT",wt[wt.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",wt[wt.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",wt[wt.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",wt[wt.TEST=10]="TEST",wt[wt.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",wt),Kk=(e=>(e.NONE="",e.DETAIL="detail",e.MOTION="motion",e.TEXT="text",e))(Kk||{}),Jk=(e=>(e.INTERVAL="interval",e.TIMEOUT="timeout",e.RAF="raf",e.RIC="ric",e.INTERVAL_IN_WORKER="intervalInWorker",e))(Jk||{}),Yk=(e=>(e.CANVAS="canvas",e.API="api",e))(Yk||{}),qk=(e=>(e[e.NONE=0]="NONE",e[e.MICROPHONE=1]="MICROPHONE",e[e.CAMERA=2]="CAMERA",e[e.BOTH=3]="BOTH",e))(qk||{}),Xk=(e=>(e.CAMERA="camera",e.MICROPHONE="microphone",e))(Xk||{}),cv=(e=>(e[e.none=0]="none",e[e.horizontal=1]="horizontal",e[e.vertical=2]="vertical",e))(cv||{}),Fe={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},Ir={AVOID_REPEATED_CALL:e=>"previous ".concat(e.name,"() is ongoing, please avoid repeated calls."),INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:n}=e,s="".concat(t||i.name),o="";return o=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(s,"' must be type of ").concat(o," when calling ").concat(r,"(), received type: ").concat(ii(n),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' cannot be '").concat(n,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:n}=e,s="".concat(t||i.name),o="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(s,"' must be instanceof ").concat(o," when calling ").concat(r,"(), received type: ").concat(ii(n),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,fnName:r,value:n}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(n,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,fnName:r,value:n}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(n,".")},API_CALL_TIMEOUT:e=>"".concat(e.commandDesc||e.command," timeout observed."),SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:e=>"SignalChannel setup failure: (errorCode: ".concat(e.errorCode,", errorMsg: ").concat(e.errorMsg," })."),ERROR_MESSAGE(e){let t="".concat(e.type," failed");return e.message&&(t="".concat(t,": ").concat(e.message,".")),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:e=>"exchange sdp failed ".concat(e.errMsg,"."),UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:e=>"'".concat(e,"' must be validate string when useStringRoomId is true."),INVALID_ROOMID_INTEGER:e=>"'".concat(e,"' must be an integer between [1, 4294967294] when useStringRoomId is false."),INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED(e){let{error:t,code:i}=e;return"Failed to join room - ".concat(t," code: ").concat(i)},REJOIN_ROOM_FAILED:e=>"reJoin room: ".concat(e.roomId," failed, please check your network."),INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:'no permission to publish() under live/audience, please call switchRole("anchor") firstly before publish().',INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:e=>"duplicate ".concat(e," stream publishing, please unpublish your prev ").concat(e," stream and then re-publish."),INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED(e){let{message:t,userId:i,streamType:r}=e;return"failed to subscribe ".concat(i," ").concat(r," stream, reason: ").concat(t,".")},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as anchor or audience.",INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:e=>"switchRole failed, errCode: ".concat(e.code," errMsg: ").concat(e.message,"."),CLIENT_BANNED:e=>"client was banned because of ".concat(e.message,"."),INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:e=>"startPublishCDNStream failed, errMsg: ".concat(e.message,"."),STOP_PUBLISH_CDN_FAILED:e=>"stopPublishCDNStream failed, errMsg: ".concat(e.message,"."),INVALID_STREAM_ID:e=>"'".concat(e,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores."),START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK:e=>"cannot replace ".concat(e.kind," track because stream has not ").concat(e.kind," track"),NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED:e=>"startMixTranscode failed, errMsg: ".concat(e.message,"."),STOP_MIX_TRANSCODE_FAILED:e=>"stopMixTranscode failed, errMsg: ".concat(e.message,"."),MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' cannot be less than 0 when calling ").concat(r,"().")},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER:e=>"'".concat(e,"' is required and must be between 1 and 15."),MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:e=>{let{key:t,fnName:i}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(i,"().")},INVALID_ELEMENT_ID_TYPE:e=>{let{key:t,fnName:i,type:r}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(i,"(), received: ").concat(r,".")},PLAY_FAILED:e=>"".concat(e.media," play failed, browser exception: ").concat(e.error.toString()),INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK:e=>"".concat(e,"Track is not supported on your browser."),NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED:e=>"".concat(e.signalResponse," failed, response code is ").concat(e.code," , errMsg: ").concat(e.message,"."),CATCH_HANDLER_ERROR(e){let{name:t,event:i}=e;return"an error was caught in ".concat(t,".on('").concat(i,"', handler), please check your code in 'handler'.")},API_NOT_EXIST(e){let{name:t}=e;return"experimental api ".concat(t," does not exist.")},REPEAT_JOIN:e=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED(e){let{funName:t}=e;return"failed to call ".concat(t,"() because client was destroyed.")},SEI_NOT_SUPPORT:e=>"not support to sendSEIMessage".concat(e===!1?" without using h264 codec":""),SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:e=>{let{isSize:t,name:i,timesInSecond:r,maxSizeInSecond:n}=e;return"api ".concat(i," call ").concat(t?"size":"times"," is over ").concat(t?"".concat(n," bytes"):r," in a second.")},CONNECTION_ABORTED:e=>"connection aborted due to: ".concat(e),API_CALL_ABORTED(e){let t;return t=e.message.includes("REMOTE_STREAM_NOT_EXIST")?"Subscribe ".concat(e.userId," ").concat(e.streamType," stream aborted, reason: remote user ").concat(e.userId," unpublished stream."):"API aborted, reason: ".concat(e.message),t},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:e=>"'streamType' is required when 'userId' is not '*', calling ".concat(e,"()")},Qk=(e,t)=>t?"".concat(mn,"/").concat(e,"/").concat(t):"".concat(mn,"/").concat(e,"/index.html"),MH=()=>{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==null?void 0:localStorage.getItem(X1);if(e){e=JSON.parse(e);let t=document.createElement("script");t.type="text/javascript",t.text=e.message,document.body.appendChild(t);let i=window.TRTC_ERROR_INFO,r=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:i,TRTC_ERROR_LINK:r}}return{}};function He(e){let{key:t,data:i,link:r,addDocLink:n=!0}=e,s="",o="",l="";Ut(Ir[t])?s=Ir[t](i):pt(Ir[t])&&(s=Ir[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:h}=MH();r?l="".concat(r.className,".html#").concat(r.fnName):h&&h[t]&&(Ut(h[t])?l=h[t](i):pt(h[t])&&(l=h[t]));let _=s;return _n()&&(c&&c[t]&&(Ut(c[t])?o=c[t](i):pt(c[t])&&(o=c[t])),o&&(_=n?"".concat(o,`
44
+ 请查看文档: `).concat(Qk("zh-cn",l),`
45
+
46
+ `):"".concat(o,`
47
+
48
+ `),_+=s)),n&&(_+=`
49
+ Refer to: `.concat(Qk("en",l),`
50
+ `)),_}var Je,it,Zk=ti(U9(),1),$k=class{constructor(){let e=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];m(this,"countMap",new Map),m(this,"distributionMap",new Map),m(this,"version"),m(this,"log",fe.createLogger({id:"kv"})),e&&($.on("102",t=>{let{track:i,cost:r}=t;this.addSuccessEvent({key:i.kind===D.AUDIO?501700:511700,cost:r})}),$.on("103",t=>{let{track:i,error:r}=t;this.addFailedEvent({key:i.kind===D.AUDIO?501700:511700,error:r})}),$.on("266",t=>{let{enable:i}=t;this.log.info("".concat(i?"enable":"disable"," sso")),i?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})}))}getReportData(e,t){let i={msg_sdk_basic_info:{uint32_sdk_version:I0(this.version||yr),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(r=>{let[n,s]=r;return{uint32_key:n,uint32_count:s}}),stats_distribution:[...this.distributionMap.entries()].map(r=>{let[n,s]=r;return{uint32_key:n,distribution_items:[...s.entries()].map(o=>{let[l,c]=o;return{uint32_item_key:l,uint32_item_value:c}})}}),str_user_sig:e,bytes_report_token:t};return this.countMap.clear(),this.distributionMap.clear(),i}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(e){let t=+String(e).slice(-3);return t>=700&&t<799}isErrorCodeKey(e){let t=+String(e).slice(-3);return t>=600&&t<699}isCountKey(e){let t=+String(e).slice(-3);return t>=0&&t<599}isNumberKey(e){let t=+String(e).slice(-3);return t>=800&&t<899}addCount(e){let{key:t,useUV:i=!1}=e;this.isCountKey(t)?i&&this.countMap.has(t)||this.countMap.set(t,(this.countMap.get(t)||0)+1):this.log.debug("".concat(t," is not count key, last 3 number should be 0~599"))}addEnum(e){let{key:t,value:i,useUV:r=!0}=e;var n;if(!this.isEnumKey(t))return this.log.debug("".concat(t," is not enum key, last 3 number should be 700~799"));if(r&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let s=((n=this.distributionMap)==null?void 0:n.get(t))||new Map;s.set(i,(s.get(i)||0)+1),this.distributionMap.set(t,s)}addNumber(e){let{key:t,value:i,split:r=100,useUV:n=!1,max:s=5e3}=e;var o;if(!this.isNumberKey(t))return this.log.debug("".concat(t," is not number key, last 3 number should be 800~899"));if(n&&this.countMap.has(t))return;i>s&&(i=s),this.countMap.set(t,(this.countMap.get(t)||0)+1);let l=((o=this.distributionMap)==null?void 0:o.get(t))||new Map,c=0;if(nt(r))c=Math.floor(i/r);else for(let h=r.length-1;h>0;h--)if(i>r[h]){c=h;break}l.set(c,(l.get(c)||0)+1),this.distributionMap.set(t,l)}addSuccessEvent(e){let{key:t,cost:i,timeKey:r,split:n}=e;if(t&&(this.addEnum({key:t,value:1,useUV:!1}),i)){let s=+String(t).slice(-3);s<800&&s>=700?this.addNumber({key:r||t+100,value:i,split:n}):r||this.log.debug("time stat ignored, ".concat(t))}}addFailedEvent(e){let{key:t,error:i}=e;if(!t)return;let r=te.UNKNOWN;i&&(nt(i)?r=i:(!j(i.extraCode)||!j(i.code))&&(r=i.extraCode||i.code)),this.addEnum({key:t,value:0,useUV:!1}),this.addEnum({key:t,value:Math.abs(r),useUV:!1})}},ew=((Je=ew||{})[Je.enterRoom=500700]="enterRoom",Je[Je.exitRoom=500701]="exitRoom",Je[Je.switchRole=500702]="switchRole",Je[Je.destroy=500703]="destroy",Je[Je.startLocalAudio=500704]="startLocalAudio",Je[Je.updateLocalAudio=500705]="updateLocalAudio",Je[Je.stopLocalAudio=500706]="stopLocalAudio",Je[Je.startLocalVideo=500707]="startLocalVideo",Je[Je.updateLocalVideo=500708]="updateLocalVideo",Je[Je.stopLocalVideo=500709]="stopLocalVideo",Je[Je.startScreenShare=500710]="startScreenShare",Je[Je.updateScreenShare=500711]="updateScreenShare",Je[Je.stopScreenShare=500712]="stopScreenShare",Je[Je.startRemoteVideo=500713]="startRemoteVideo",Je[Je.updateRemoteVideo=500714]="updateRemoteVideo",Je[Je.stopRemoteVideo=500715]="stopRemoteVideo",Je[Je.muteRemoteAudio=500716]="muteRemoteAudio",Je[Je.setRemoteAudioVolume=500717]="setRemoteAudioVolume",Je[Je.use=500718]="use",Je[Je.switchRoom=500719]="switchRoom",Je[Je.getPermissions=500720]="getPermissions",Je[Je.sendSEIMessage=5e5]="sendSEIMessage",Je[Je.sendCustomMessage=500001]="sendCustomMessage",Je),tw=(e=>(e[e.AudioMixer=550700]="AudioMixer",e[e.AIDenoiser=551700]="AIDenoiser",e[e.VirtualBackground=570700]="VirtualBackground",e[e.Beauty=571700]="Beauty",e[e.Watermark=572700]="Watermark",e[e.BasicBeauty=574700]="BasicBeauty",e[e.FaceDetector=575700]="FaceDetector",e[e.CDNStreaming=590700]="CDNStreaming",e[e.DeviceDetector=591700]="DeviceDetector",e[e.Debug=592700]="Debug",e[e.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",e[e.VideoMixer=594700]="VideoMixer",e[e.AudioProcessor=595700]="AudioProcessor",e[e.LEBPlayer=596700]="LEBPlayer",e[e.RealtimeTranscriber=597700]="RealtimeTranscriber",e))(tw||{}),iw=(e=>(e[e.AudioMixer=550701]="AudioMixer",e[e.AIDenoiser=551701]="AIDenoiser",e[e.VirtualBackground=570701]="VirtualBackground",e[e.Beauty=571701]="Beauty",e[e.Watermark=572701]="Watermark",e[e.BasicBeauty=574701]="BasicBeauty",e[e.FaceDetector=575701]="FaceDetector",e[e.CDNStreaming=590701]="CDNStreaming",e[e.DeviceDetector=591701]="DeviceDetector",e[e.Debug=592701]="Debug",e[e.SmallStreamAutoSwitcher=593701]="SmallStreamAutoSwitcher",e[e.VideoMixer=594701]="VideoMixer",e[e.AudioProcessor=595701]="AudioProcessor",e[e.LEBPlayer=596701]="LEBPlayer",e[e.RealtimeTranscriber=597701]="RealtimeTranscriber",e))(iw||{}),rw=(e=>(e[e.AudioMixer=550702]="AudioMixer",e[e.AIDenoiser=551702]="AIDenoiser",e[e.VirtualBackground=570702]="VirtualBackground",e[e.Beauty=571702]="Beauty",e[e.Watermark=572702]="Watermark",e[e.BasicBeauty=574702]="BasicBeauty",e[e.FaceDetector=575702]="FaceDetector",e[e.CDNStreaming=590702]="CDNStreaming",e[e.DeviceDetector=591702]="DeviceDetector",e[e.Debug=592702]="Debug",e[e.SmallStreamAutoSwitcher=593702]="SmallStreamAutoSwitcher",e[e.VideoMixer=594702]="VideoMixer",e[e.AudioProcessor=595702]="AudioProcessor",e[e.LEBPlayer=596702]="LEBPlayer",e[e.RealtimeTranscriber=597702]="RealtimeTranscriber",e))(rw||{}),nw=((it=nw||{})[it.DECODER_TYPE=514700]="DECODER_TYPE",it[it.DECODER_HW_SW=514701]="DECODER_HW_SW",it[it.DECODE_RESULT=514702]="DECODE_RESULT",it[it.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",it[it.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",it[it.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",it[it.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",it[it.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",it[it.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",it[it.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",it[it.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",it[it.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",it[it.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",it[it.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",it[it.H264_PROFILE_LEVEL_ID_HIGH=514714]="H264_PROFILE_LEVEL_ID_HIGH",it[it.H264_PROFILE_LEVEL_ID_MAIN=514715]="H264_PROFILE_LEVEL_ID_MAIN",it[it.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",it[it.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",it[it.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",it),LH=new $k(!0),Bc=new $k(!1),ce=LH,Ze={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}},xH=new Map([[ut,["Firefox",L0]],[wc,["Edg",U0]],[$h,["Chrome",$0]],[ri,["Safari",ma]],[Hr,["TBS",B0]],[cs,["XWEB",H0]],[ha&&da,["WeChat",W0]],[zh,["QQ(Win)",G0]],[Nc,["QQ(Mobile)",Pc]],[Dc,["QQ(Mobile X5)",Pc]],[Kh,["QQ(Mac)",j0]],[Jh,["QQ(iPad)",z0]],[Yh,["MI",J0]],[qh,["HW",q0]],[Xh,["Samsung",X0]],[Mc,["OPPO",Q0]],[Qh,["VIVO",Z0]],[No,["EDGE",x0]],[Gh,["SogouMobile",V0]],[jh,["Sogou",F0]]]);function UH(){let e=xH.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var uv=function(){return!(z2||No||wc&&G2<80||ut&&Wh<56)},ip=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(e=>e in window)},dv=function(){if(!navigator.mediaDevices)return ga()||fe.error(Ir.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter(t=>t in navigator.mediaDevices).length===e.length},sw=!1;function ga(){return location.protocol==="http:"&&!fa&&(sw||fe.error(He({key:Fe.NOT_SUPPORTED_HTTP})),sw=!0,!0)}var hv=function(){return window?.OffscreenCanvas&&window?.MediaStreamTrackProcessor&&window?.MediaStreamTrackGenerator},VH=function(){return!(window==null||!window.MediaStreamTrackGenerator)},pv=function(){return P(this,null,function*(){var e,t,i;if(Ze.detail.isH264EncodeSupported&&Ze.detail.isVp8EncodeSupported)return{isH264EncodeSupported:Ze.detail.isH264EncodeSupported,isVp8EncodeSupported:Ze.detail.isVp8EncodeSupported,isH265EncodeSupported:Ze.detail.isH265EncodeSupported};let r,n=!1,s=!1,o=!1;try{let l=new RTCPeerConnection,c=document.createElement(D.CANVAS);c.getContext("2d");let h=c.captureStream(0);return l.addTrack(h.getVideoTracks()[0],h),r=yield l.createOffer(),n=((e=r.sdp)==null?void 0:e.toLowerCase().indexOf("h264"))!==-1,s=((t=r.sdp)==null?void 0:t.toLowerCase().indexOf("vp8"))!==-1,o=((i=r.sdp)==null?void 0:i.toLowerCase().indexOf("h265"))!==-1,l.close(),{isH264EncodeSupported:n,isVp8EncodeSupported:s,isH265EncodeSupported:o}}catch{return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}})},mv=function(){return P(this,null,function*(){var e;if(Ze.detail.isH264DecodeSupported&&Ze.detail.isVp8DecodeSupported)return{isH264DecodeSupported:Ze.detail.isH264DecodeSupported,isVp8DecodeSupported:Ze.detail.isVp8DecodeSupported,isH265DecodeSupported:Ze.detail.isH265DecodeSupported};let t,i=!1,r=!1;try{let n=new RTCPeerConnection;Rr()?(n.addTransceiver(D.VIDEO,{direction:"recvonly"}),t=yield n.createOffer()):t=yield n.createOffer({offerToReceiveVideo:!0}),t.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),t.sdp.toLowerCase().indexOf("vp8")!==-1&&(r=!0);let s=((e=t.sdp)==null?void 0:e.toLowerCase().indexOf("h265"))!==-1;return n.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:r,isH265DecodeSupported:s}}catch{return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}})},fv=R0(e=>P(null,null,function*(){let t=Date.now(),i=Sv(),r=dv(),n=ip();if(Ze.detail.isWebRTCSupported=i,Ze.detail.isMediaDevicesSupported=r,Ze.detail.isWebCodecsSupported=n,Ze.detail.isScreenShareSupported=rp(),Ze.detail.isSmallStreamSupported=Ev(),e===37)return Object.assign(Ze.detail,yield(function(){return P(this,null,function*(){return gv||(gv=new Promise(C=>P(null,null,function*(){let x={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!ip())return void C(x);let B=null,Y=null,G=null,he=()=>{G&&clearTimeout(G),B=null,Y=null};try{B=document.createElement("canvas"),Y=B.getContext("2d"),B.width=320,B.height=240;let H=0,Z=()=>{!Y||!B||(Y.fillStyle="hsl(".concat(H%360,", 50%, 50%)"),Y.fillRect(0,0,B.width,B.height),Y.fillStyle="white",Y.font="20px Arial",Y.fillText("Frame ".concat(H),10,30),H++)};G=setTimeout(()=>{he(),C(x)},5e3);let de=[{type:"h264",encodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"},width:320,height:240,bitrate:1e6},decodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"}}},{type:"vp8",encodeConfig:{codec:"vp8",width:320,height:240,bitrate:1e6},decodeConfig:{codec:"vp8"}}];(yield Promise.all(de.map(pe=>P(null,null,function*(){let Pe,be={type:pe.type,encodeSupported:!1,decodeSupported:!1};try{Pe=yield new Promise((je,Oe)=>P(null,null,function*(){try{let Be=new VideoEncoder({output:yt=>{je(yt),be.encodeSupported=!0},error:Oe});Be.configure(pe.encodeConfig),Z();let at=new VideoFrame(B,{timestamp:0});Be.encode(at,{keyFrame:!0}),at.close(),yield Be.flush(),Be.close()}catch(Be){Oe(Be)}}))}catch(je){return fe.warn("".concat(pe.type," encoder error:"),je),be}try{yield new Promise((je,Oe)=>P(null,null,function*(){try{let Be=new VideoDecoder({output:at=>{be.decodeSupported=!0,je(0),at.close()},error:Oe});Be.configure(pe.decodeConfig),Be.decode(Pe),yield Be.flush(),Be.close()}catch(Be){Oe(Be)}}))}catch(je){fe.warn("".concat(pe.type," decoder error:"),je)}return be})))).forEach(pe=>{pe.type==="h264"?(x.isH264EncodeSupported=pe.encodeSupported,x.isH264DecodeSupported=pe.decodeSupported):pe.type==="vp8"&&(x.isVp8EncodeSupported=pe.encodeSupported,x.isVp8DecodeSupported=pe.decodeSupported)}),he(),C(x)}catch(H){he(),fe.warn("detectWebCodecsSupported failed:",H),C(x)}})),gv)})})()),Ze.detail.isBrowserSupported=n,Ze.result=r&&n,Ze.result||fe.error("".concat(navigator.userAgent," ").concat(Lh(Ze.detail,!1))),Ew(e),ce.addNumber({key:523800,value:Date.now()-t}),Ze;if(Ze.result&&Ze.detail.isH264EncodeSupported&&Ze.detail.isVp8EncodeSupported&&Ze.detail.isH265EncodeSupported&&Ze.detail.isH264DecodeSupported&&Ze.detail.isVp8DecodeSupported&&Ze.detail.isH265DecodeSupported)return Ze;let s=uv(),{encode:o,decode:l}=yield(function(){return P(this,null,function*(){let[C,x]=yield Promise.all([pv(),mv()]);return{encode:{h264:C.isH264EncodeSupported,vp8:C.isVp8EncodeSupported,h265:C.isH265EncodeSupported},decode:{h264:x.isH264DecodeSupported,vp8:x.isVp8DecodeSupported,h265:x.isH265DecodeSupported}}})})(),{h264:c,vp8:h}=o,{h264:_}=l,{h265:f}=o,{vp8:T,h265:b}=l;if(!c||!h){let C=yield pv();fe.warn("detect encode again h264:".concat(c," vp8:").concat(h," result: ").concat(JSON.stringify(C))),c=C.isH264EncodeSupported,h=C.isVp8EncodeSupported}if(c&&_&&Vt&&or&&!cs&&!Hr&&(!Mc||lr!==115)){let{encode:C,decode:x}=yield(function(){return P(this,null,function*(){return _v||(_v=new Promise(B=>P(null,null,function*(){let Y={encode:!1,decode:!1},G=()=>{};try{let he=document.createElement("canvas"),H=he.getContext("2d");he.width=640,he.height=480;let Z=setInterval(()=>{H.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))},66),de=-1,pe=-1;G=()=>{clearInterval(de),clearInterval(Z),clearTimeout(pe),be.close(),je.close(),Pe.getTracks().forEach(gt=>gt.stop())},pe=setTimeout(()=>{G(),B(Y)},2e3);let Pe=he.captureStream(),be=new RTCPeerConnection({}),je=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});be.addEventListener("icecandidate",gt=>je.addIceCandidate(gt.candidate)),je.addEventListener("icecandidate",gt=>be.addIceCandidate(gt.candidate)),be.addTrack(Pe.getVideoTracks()[0],Pe);let Oe=yield be.createOffer();yield be.setLocalDescription(Oe),yield je.setRemoteDescription(Oe);let Be=yield je.createAnswer(),at=Zk.default.parse(Be.sdp),yt=at.media[0].rtp.findIndex(gt=>gt.codec==="H264");at.media[0].rtp=[at.media[0].rtp[yt]],at.media[0].fmtp=at.media[0].fmtp.filter(gt=>gt.payload===at.media[0].rtp[0].payload),at.media[0].rtcpFb&&(at.media[0].rtcpFb=at.media[0].rtcpFb.filter(gt=>gt.payload===at.media[0].rtp[0].payload)),Be.sdp=Zk.default.write(at),yield je.setLocalDescription(Be),yield be.setRemoteDescription(Be),de=setInterval(()=>P(null,null,function*(){Y.encode&&Y.decode&&(G(),B(Y));let[gt,Ma]=yield Promise.all([be.getSenders()[0].getStats(),je.getReceivers()[0].getStats()]);Y.encode||gt.forEach(Vi=>{Vi.type==="outbound-rtp"&&Vi.mediaType===D.VIDEO&&Vi.bytesSent>0&&(Y.encode=!0)}),Y.decode||Ma.forEach(Vi=>{Vi.type==="inbound-rtp"&&Vi.mediaType===D.VIDEO&&Vi.bytesReceived>0&&(Y.decode=!0)})}),100)}catch(he){G(),fe.warn("detectH264Supported failed",he),B({encode:!0,decode:!0})}})).then(B=>(B.encode||(B.decode=!0),(!B.encode||!B.decode)&&fe.warn("detectH264Supported encode: ".concat(B.encode," decode: ").concat(B.decode," ").concat(vn)),B)),_v)})})();c=C,_=x}return Ze.result=s&&i&&r&&(c||h)&&(_||T),Ze.detail.isBrowserSupported=s,Ze.detail.isWebRTCSupported=i,Ze.detail.isH264EncodeSupported=c,Ze.detail.isVp8EncodeSupported=h,Ze.detail.isH265EncodeSupported=f,Ze.detail.isH264DecodeSupported=_,Ze.detail.isVp8DecodeSupported=T,Ze.detail.isH265DecodeSupported=b,Ze.result||fe.error("".concat(navigator.userAgent," ").concat(Lh(Ze.detail,!1))),Ew(),ce.addNumber({key:523800,value:Date.now()-t}),Ze})),FH=function(){return Ze.result},rp=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},BH=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype,_v=null,gv=null,HH=(e,t,i)=>{location.protocol==="http:"&&!fa&&(e[t]=()=>{throw new me({code:te.INVALID_OPERATION,message:Ir.NOT_SUPPORTED_HTTP})})},Hc=function(e){return!(e.type!=="candidate-pair"||!e.nominated||e.state!=="in-progress"&&e.state!=="succeeded")&&!(Rt(e.selected)&&!e.selected)};function aw(){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 ow(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function lw(){let e={isSupported:!1},t=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let i=0;i<t.length;i++)if(t[i]in window){e.isSupported=!0;break}return e.isSupported}function cw(){return"captureStream"in HTMLCanvasElement.prototype}function vv(){return!(ha||Gt||lr&&lr<63)&&!(!uv()||!cw())}function uw(){return!(lr<74||No||Sr<11||Wh<46)}function Ev(){return vv()||uw()}var WH=function(){if(j(window.RTCRtpTransceiver)||!Rr()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:hc}),e.addTransceiver(D.AUDIO),t=!0}catch{}return e?.close(),t};function np(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Wc(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function Vo(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function Rr(){return!(Sr===11&&!Q2)&&"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var Gc=!(!Rr()||or&&lr<86);function GH(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var jc="RTCRtpSender"in window;function dw(){return jc&&"replaceTrack"in window.RTCRtpSender.prototype}function yv(){return jc&&"setParameters"in window.RTCRtpSender.prototype&&Wc()}var hw="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,Fo=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,pw=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,mw=typeof InputDeviceInfo<"u"&&"getCapabilities"in InputDeviceInfo.prototype,va=jc&&"createEncodedStreams"in window.RTCRtpSender.prototype&&Zh()>=86,sp="RTCRtpScriptTransform"in window,Tv=jc&&(va||sp),Sv=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(e=>e in window).length>0};function Iv(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return j(window.AudioDecoder)||(e.AudioDecoder=!0),j(window.AudioEncoder)||(e.AudioEncoder=!0),j(window.VideoDecoder)||(e.VideoDecoder=!0),j(window.VideoEncoder)||(e.VideoEncoder=!0),j(window.ImageDecoder)||(e.ImageDecoder=!0),e}function fw(){return"mediaSession"in navigator&&!j(navigator.mediaSession.setActionHandler)}function _w(){return!j(window.WebTransport)}function gw(){return typeof WebAssembly<"u"&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}function jH(){let e={browser:"".concat(ds.name,"/").concat(ds.version),os:sv(),displayResolution:aw(),isScreenShareSupported:rp(),isWebRTCSupported:Sv(),isGetUserMediaSupported:ow(),isWebAudioSupported:lw(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Iv(),isMediaSessionSupported:fw(),isWebTransportSupported:_w()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var vw="checkResult";function Ew(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:30;av.setItem(vw+e,{ua:navigator.userAgent,checkResult:Ze})}function yw(e){ga();let t=av.getItem(vw+e);t&&t.ua===navigator.userAgent&&t.checkResult&&(function(i,r){return!!Fr(i)&&Object.keys(r).every(n=>n in i)})(t.checkResult.detail,Ze.detail)&&(Ze=t.checkResult),fv(e)}function zc(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var ap="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function Tw(e){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[e]}var Sw=!1;function Iw(){return P(this,null,function*(){var e;try{if(Sw||(e=navigator?.mediaCapabilities)==null||!e.encodingInfo)return;let t=tp(),i=tk();if(t===0||i===0)return;Sw=!0;let r=["H264","VP8","VP9","AV1","H265"],[n,s]=yield Promise.all([Rw(r),Aw(r)]);n&&Object.keys(n).forEach(c=>{let h=Tw(c.toLowerCase());ce.addEnum({key:513707,value:+"".concat(h).concat(+n[c].supported).concat(+n[c].powerEfficient).concat(t).concat(i),useUV:!1})}),s&&Object.keys(s).forEach(c=>{let h=Tw(c.toLowerCase());ce.addEnum({key:514713,value:+"".concat(h).concat(+s[c].supported).concat(+s[c].powerEfficient).concat(t).concat(i),useUV:!1})});let{sender:o,receiver:l}=bw();ce.addEnum({key:513708,value:+"".concat(t).concat(i).concat(+o.high),useUV:!1}),ce.addEnum({key:513709,value:+"".concat(t).concat(i).concat(+o.main),useUV:!1}),ce.addEnum({key:514714,value:+"".concat(t).concat(i).concat(+l.high),useUV:!1}),ce.addEnum({key:514715,value:+"".concat(t).concat(i).concat(+l.main),useUV:!1})}catch(t){fe.info("detectVideoCodecCapabilities failed",t)}})}function Rw(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1920,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1080,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:30,n=arguments.length>4&&arguments[4]!==void 0?arguments[4]:3e3;return P(this,null,function*(){let s={};try{for(let o of e){let l=yield navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:"video/".concat(o),width:t,height:i,bitrate:n,framerate:r}});s[o]=l}}catch{}return s})}function Aw(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1920,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1080,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:30,n=arguments.length>4&&arguments[4]!==void 0?arguments[4]:3e3;return P(this,null,function*(){let s={};try{for(let o of e){let l=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:"video/".concat(o),width:t,height:i,bitrate:n,framerate:r}});s[o]=l}}catch{}return s})}function bw(){let e={sender:{base:!1,main:!1,high:!1},receiver:{base:!1,main:!1,high:!1}};try{if(RTCRtpSender&&typeof RTCRtpSender.getCapabilities=="function"){let t=RTCRtpSender.getCapabilities("video");t&&t.codecs&&t.codecs.filter(i=>i.mimeType.toLowerCase()==="video/h264").forEach(i=>{if(i.sdpFmtpLine){let r=i.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(r&&r[1])switch(r[1].slice(0,2)){case"42":e.sender.base=!0;break;case"4d":e.sender.main=!0;break;case"64":e.sender.high=!0}}})}if(RTCRtpReceiver&&typeof RTCRtpReceiver.getCapabilities=="function"){let t=RTCRtpReceiver.getCapabilities("video");t&&t.codecs&&t.codecs.filter(i=>i.mimeType.toLowerCase()==="video/h264").forEach(i=>{if(i.sdpFmtpLine){let r=i.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(r&&r[1])switch(r[1].slice(0,2)){case"42":e.receiver.base=!0;break;case"4d":e.receiver.main=!0;break;case"64":e.receiver.high=!0}}})}}catch(t){fe.warn("get H264 profile levelId failed",t)}return e}var zH=ti(Ri(),1),Cw=Symbol("instance"),op=Symbol("cacheResult"),Rv=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,Jc.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},Av=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}},Kc=new Map;function ni(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(r,n,s)=>{let o=i.action||n;if(!i.context){let c=Kc.get(r)||[];Kc.has(r)||Kc.set(r,c),c.push({from:e,to:t,action:o})}let l=s.value;s.value=function(){let c=this;for(var h=arguments.length,_=new Array(h),f=0;f<h;f++)_[f]=arguments[f];if(i.context&&(c=et.get(typeof i.context=="function"?i.context.call(this,..._):i.context)),c.state===t)return i.sync?c[op]:Promise.resolve(c[op]);c.state instanceof Rv&&c.state.action==i.abortAction&&c.state.abort(c);let T=null;Array.isArray(e)?e.length==0?c.state instanceof Rv&&c.state.abort(c):(typeof c.state!="string"||!e.includes(c.state))&&(T=new Av(c._state,"".concat(c.name," ").concat(o," to ").concat(t," failed: current state ").concat(c._state," not from ").concat(e.join("|")))):e!==c.state&&(T=new Av(c._state,"".concat(c.name," ").concat(o," to ").concat(t," failed: current state ").concat(c._state," not from ").concat(e)));let b=G=>{if(i.fail&&i.fail.call(this,G),i.sync){if(i.ignoreError)return G;throw G}return i.ignoreError?Promise.resolve(G):Promise.reject(G)};if(T)return b(T);let C=c.state,x=new Rv(C,t,o);Jc.call(c,x);let B=G=>{var he;return c[op]=G,x.aborted||(Jc.call(c,t),(he=i.success)===null||he===void 0||he.call(this,c[op])),G},Y=G=>(Jc.call(c,C,G),b(G));try{let G=l.apply(this,_);return(function(he){return typeof he=="object"&&he&&"then"in he})(G)?G.then(B).catch(Y):i.sync?B(G):Promise.resolve(B(G))}catch(G){return Y(new Av(c._state,"".concat(c.name," ").concat(o," from ").concat(e," to ").concat(t," failed: ").concat(G),G instanceof Error?G:new Error(String(G))))}}}}var KH=typeof window<"u"&&window.__AFSM__?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:typeof importScripts<"u"?(e,t)=>{postMessage({type:e,payload:t})}:()=>{};function Jc(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(et.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var et=class dr extends zH.default{constructor(t,i,r){super(),this.name=t,this.groupName=i,this._state=dr.INIT,t||(t=Date.now().toString(36)),r?Object.setPrototypeOf(this,r):r=Object.getPrototypeOf(this),i||(this.groupName=this.constructor.name);let n=r[Cw];n?this.name=n.name+"-"+n.count++:r[Cw]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let t=Object.getPrototypeOf(this),i=Kc.get(t)||[],r=new Set,n=[],s=[],o=new Set,l=Object.getPrototypeOf(t);Kc.has(l)&&(l.stateDiagram.forEach(h=>r.add(h)),l.allStates.forEach(h=>o.add(h))),i.forEach(h=>{let{from:_,to:f,action:T}=h;typeof _=="string"?n.push({from:_,to:f,action:T}):_.length?_.forEach(b=>{n.push({from:b,to:f,action:T})}):s.push({to:f,action:T})}),n.forEach(h=>{let{from:_,to:f,action:T}=h;o.add(_),o.add(f),o.add(T+"ing"),r.add("".concat(_," --> ").concat(T,"ing : ").concat(T)),r.add("".concat(T,"ing --> ").concat(f," : ").concat(T," 🟢")),r.add("".concat(T,"ing --> ").concat(_," : ").concat(T," 🔴"))}),s.forEach(h=>{let{to:_,action:f}=h;r.add("".concat(f,"ing --> ").concat(_," : ").concat(f," 🟢")),o.forEach(T=>{T!==_&&r.add("".concat(T," --> ").concat(f,"ing : ").concat(f))})});let c=[...r];return Object.defineProperties(t,{stateDiagram:{value:c},allStates:{value:o}}),c}static get(t){let i;return typeof t=="string"?(i=dr.instances.get(t),i||dr.instances.set(t,i=new dr(t,void 0,Object.create(dr.prototype)))):(i=dr.instances2.get(t),i||dr.instances2.set(t,i=new dr(t.constructor.name,void 0,Object.create(dr.prototype)))),i}static getState(t){var i;return(i=dr.get(t))===null||i===void 0?void 0:i.state}updateDevTools(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};KH(dr.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(t){Jc.call(this,t)}};et.STATECHANGED="stateChanged",et.UPDATEAFSM="updateAFSM",et.INIT="[*]",et.ON="on",et.OFF="off",et.instances=new Map,et.instances2=new WeakMap;var bv=typeof window<"u",kw=bv&&window.requestIdleCallback||function(e){let t=Date.now();return setTimeout(()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})},1e3)},JH=bv&&window.cancelIdleCallback||function(e){clearTimeout(e)},ww=bv&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),Yc=class ki{static generateTaskID(){return this.currentTaskID++}static run(t,i,r){r!=null&&r.fps&&(r.delay=r.delay||Number((1e3/r.fps).toFixed(2))),r=ve(t==="interval"?{delay:2e3,count:0,backgroundTask:!0}:t==="ric"?{delay:1e4,count:0}:t==="raf"?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},r);let n=xe(ve({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:t,callback:i},r),{delay:r.delay});return this.taskMap.set(n.taskID,n),this[t](n),n.taskID}static interval(t){return t.intervalID=setInterval(()=>{t.callback(),t.loopCount+=1,ki.isBreakLoop(t)},t.delay)}static intervalInWorker(t){ki.sharedWorker||(ki.sharedWorker=new Worker(URL.createObjectURL(new Blob([`
51
+ const timers = new Map();
52
+ self.onmessage = function(e) {
53
+ const { taskId, delay, type } = e.data;
54
+ if (type === 'start') {
55
+ timers.set(taskId, setInterval(() => {
56
+ self.postMessage({ type: 'tick', taskId });
57
+ }, delay));
58
+ } else if (type === 'stop') {
59
+ clearInterval(timers.get(taskId));
60
+ timers.delete(taskId);
61
+ }
62
+ };
63
+ `],{type:"application/javascript"}))),ki.sharedWorker.onmessage=i=>{var r;if(i.data.type==="tick"){let n=ki.workerTasks.get(i.data.taskId);n&&(ki.isBreakLoop(n)?((r=ki.sharedWorker)==null||r.postMessage({type:"stop",taskId:n.taskID}),ki.workerTasks.delete(n.taskID)):(n.callback(),n.loopCount+=1))}}),ki.workerTasks.set(t.taskID,t),ki.sharedWorker.postMessage({taskId:t.taskID,delay:t.delay,type:"start"})}static timeout(t){let i=()=>{if(t.callback(),t.loopCount+=1,!ki.isBreakLoop(t))return t.timeoutID=setTimeout(i,t.delay)};return t.timeoutID=setTimeout(i,t.delay)}static ric(t){let i,r=Ue(),n=()=>{if(i=Ue()-r,i>=t.delay&&(r=Ue()-Math.floor(i%t.delay),t.callback(),t.loopCount+=1),!ki.isBreakLoop(t))return t.ricID=kw(n,{timeout:t.delay})};return t.ricID=kw(n,{timeout:t.delay})}static raf(t){let i,r=Ue(),n=()=>document.hidden&&t.backgroundTask?(i=Ue()-r,r=Ue(),t.callback(),t.loopCount+=1,ki.isBreakLoop(t)?void 0:t.timeoutID=setTimeout(n,t.delay-Math.floor(i%t.delay))):(i=Ue()-r,i>=t.delay&&(r=Ue()-Math.floor(i%t.delay),t.callback(),t.loopCount+=1),ki.isBreakLoop(t)?void 0:t.rafID=requestAnimationFrame(n));if(t.rafID=requestAnimationFrame(n),t.backgroundTask){let s=()=>{if(document.hidden){let o=Ue()-r;o>=t.delay?n():t.timeoutID=setTimeout(n,t.delay-o)}};document.addEventListener("visibilitychange",s),t.onVisibilitychange=s,document.hidden&&s()}return t.taskID}static hasTask(t){return this.taskMap.has(t)}static clearTask(t){if(!this.taskMap.has(t))return!0;let{intervalID:i,timeoutID:r,rafID:n,ricID:s,onVisibilitychange:o}=this.taskMap.get(t);return i&&clearInterval(i),r&&clearTimeout(r),n&&ww&&ww(n),s&&JH(s),o&&document.removeEventListener("visibilitychange",o),this.taskMap.delete(t),!0}static isBreakLoop(t){return!this.hasTask(t.taskID)||t.count!==0&&t.loopCount>=t.count&&(this.clearTask(t.taskID),!0)}};m(Yc,"taskMap",new Map),m(Yc,"currentTaskID",1),m(Yc,"sharedWorker",null),m(Yc,"workerTasks",new Map);var ft=Yc,Me={LOAD_START:D.LOADSTART,LOADED_DATA:D.LOADEDDATA,LOADED_META_DATA:D.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",RESIZE:D.RESIZE,TIME_UPDATE:"time-update",LEAVE_PICTURE_IN_PICTURE:D.LEAVE_PICTURE_IN_PICTURE,ENTER_PICTURE_IN_PICTURE:D.ENTER_PICTURE_IN_PICTURE,USER_RESUME_IN_PIP_OR_FULL_SCREEN:"user-resume-in-pip-or-full-screen",USER_PAUSE_IN_PIP_OR_FULL_SCREEN:"user-pause-in-pip-or-full-screen",ENTER_FULL_SCREEN:"enter-full-screen",LEAVE_FULL_SCREEN:"leave-full-screen",VOLUME_CHANGE:"volume-change"},Cv={};pn(Cv,{create:()=>Ar,remove:()=>bi});var qc=new WeakMap;function Ar(e,t){qc.has(e)||qc.set(e,[]);let i=qc.get(e),r={add:(n,s)=>("addEventListener"in t?(i.push(t.removeEventListener.bind(t,n,s)),t.addEventListener(n,s)):(i.push(t.off.bind(t,n,s)),t.on(n,s)),r)};return r}function bi(e){let t=qc.get(e);t&&(t.forEach(i=>i()),qc.delete(e))}var dt=new class{constructor(){m(this,"_roomIdMap",new Map),m(this,"_configs"),typeof registerProcessor>"u"&&(this._configs={sdkAppId:"",userId:"",version:yr,env:sa.QCLOUD,browserVersion:ds.name+ds.version,ua:navigator.userAgent})}setConfig(e){let{sdkAppId:t,env:i,userId:r,roomId:n}=e;t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=i,this._configs.userId=r,this._roomIdMap.set(r,String(n))}logSuccessEvent(e){fa||!fe.isAbleToUpload||this._configs.env===sa.QCLOUD&&this.uploadEventToKibana(xe(ve({},e),{result:"success"}))}logFailedEvent(e){if(fa||!fe.isAbleToUpload)return;let{eventType:t,code:i,error:r,userId:n}=e,s={roomId:this._roomIdMap.get(n||this._configs.userId),userId:n,eventType:t,result:"failed",code:i||r?.extraCode||r?.code||te.UNKNOWN};this._configs.env===sa.QCLOUD&&this.uploadEventToKibana(xe(ve({},s),{error:r}))}uploadEventToKibana(e){let t="stat-".concat(e.eventType,"-").concat(e.result);(e.eventType==="delta-join"||e.eventType==="delta-leave"||e.eventType==="delta-publish")&&(t="".concat(e.eventType,":").concat(e.delta)),this.uploadEvent({log:t,userId:e.userId}),e.result==="failed"&&(t="stat-".concat(e.eventType,"-").concat(e.result,"-").concat(e.code),this.uploadEvent({log:t,userId:e.userId,error:e.error}))}uploadEvent(e){let{log:t,userId:i,error:r}=e,n={timestamp:j1(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:yr,log:t};r&&(n.errorInfo=r.message,r.stack&&(n.errorInfo+=`
64
+ `.concat(r.stack)));let s=Uc.enable?wo(n,2002,Number(this._configs.sdkAppId)):JSON.stringify(n);this.sendRequest(bo(this._configs.sdkAppId,lc.LOG),s)}sendRequest(e,t){setTimeout(()=>bc({url:e,body:t,priority:"low"}).catch(()=>{}),2e3)}},Gr=new WeakMap;function hs(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:n}=e;return function(s,o,l){let c=Cc({retryFunction:l.value,settings:t,onError(h){let{error:_,retry:f,reject:T,retryFuncArgs:b}=h;var C;i?i.call(this,_,()=>{var x;(x=Gr.get(s))!=null&&x.has(o)?f():T(_)},T,b):(C=Gr.get(s))!=null&&C.has(o)?f():T(_)},onRetrying(h,_){var f;ua(r)&&r.call(this,h,_),(f=Gr.get(s))!=null&&f.has(o)&&(Gr.get(s).get(o).stopRetry=_)},onRetryFailed:n});return l.value=function(){let h=Gr.get(s);for(var _=arguments.length,f=new Array(_),T=0;T<_;T++)f[T]=arguments[T];return h?h.set(o,{args:f}):Gr.set(s,new Map([[o,{args:f}]])),c.apply(this,f).finally(()=>{var b;return(b=Gr.get(s))==null?void 0:b.delete(o)})},l}}function lp(e){let{fnName:t,callback:i,validateArgs:r=!0}=e;return function(n,s,o){let l=o.value;return o.value=function(){for(var c,h,_=arguments.length,f=new Array(_),T=0;T<_;T++)f[T]=arguments[T];if((c=Gr.get(n))!=null&&c.has(t)){let{stopRetry:b,args:C}=Gr.get(n).get(t),x=!0;if(r){for(let B of C)if(!f.find(Y=>Y===B)){x=!1;break}}x&&(i&&i.apply(this,f),b&&b(),(h=Gr.get(n))==null||h.delete(t))}return l.apply(this,f)},o}}var Ea=class extends et{constructor(e,t){super(e.id,"".concat(t,"-player")),this.options=e,this.kind=t,m(this,"id"),m(this,"element",null),m(this,"track"),m(this,"url"),m(this,"attr"),m(this,"mode"),m(this,"muted"),m(this,"_log"),m(this,"isPausedByUserCall",!1),m(this,"_pausedRetryCount"),m(this,"_isElementPlayingFired",!1),m(this,"_interval"),m(this,"_delayDestroyTimeoutId",0),m(this,"_playSuccessResolve"),m(this,"_isReplayByRecreateMediaStreamCalled",!1),m(this,"isPlayCalled",!1),m(this,"isInAutoPlayFailedState",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=oa,this._state="STOPPED",this.bindTrackEvents(),this._log.info("create ".concat(t,"-player ").concat(this.id))}get isPlaying(){var e;return this._state==="PLAYING"&&((e=this.element)==null?void 0:e.paused)===!1}get isPaused(){var e;return this._state==="PAUSED"||((e=this.element)==null?void 0:e.paused)===!0}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return P(this,null,function*(){if(!this.isPlaying)try{this.isPlayCalled=!0,this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise((e,t)=>{this._playSuccessResolve=e,this.element.play().then(e,t)})}catch(e){let t=He({key:Fe.PLAY_FAILED,data:{media:this.kind,error:e}});if(this._log.warn(e),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new me({code:te.PLAY_NOT_ALLOWED,message:t})}})}stop(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;var t;this.isPlayCalled=!1,this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!pa?this._delayDestroyTimeoutId||((t=this.element)==null||t.remove(),this._log.info("destroy element after 3 * ".concat(e)),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(D.ENDED),this._interval>0&&ft.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.src="",this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){this._log.info("pause"),this.isPausedByUserCall=!0,this.doPause()}doPause(){var e;(e=this.element)==null||e.pause()}resume(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this.isPausedByUserCall=!1,this.doResume(e)}doResume(){return this._log.info("resume"),this.isPausedByUserCall||this.isPlaying?Promise.resolve():q2?this.replay():this.play().catch(()=>{})}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return Ar(this.element,this.element).add(D.PLAYING,e).add(D.ENDED,e).add(D.PAUSE,e).add(D.ERROR,e).add(D.LOADSTART,e).add(D.LOADEDDATA,e).add(D.LOADEDMETADATA,e)}}bindTrackEvents(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.track;if(e){let t=this.handleTrackEvent.bind(this);Cv?.create(e,e).add(D.ENDED,t).add(D.MUTE,t).add(D.UNMUTE,t),e.readyState===D.ENDED&&this.handleTrackEvent({type:D.ENDED}),e.muted&&this.handleTrackEvent({type:D.MUTE})}}bindAutoPlayEvent(){$.listeners(ie.AUTOPLAY_DIALOG_CLICK_CONFIRM).includes(this.resume)||$.on(ie.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.track;e&&bi(e)}unbindEvents(){this.element&&bi(this.element),this.unbindTrackEvents(),$.off(ie.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case D.PLAYING:Qc()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(D.PLAYING),this._interval&&(ft.clearTask(this._interval),this._interval=-1);break;case D.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(D.ENDED);break;case D.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(D.PAUSE);break;case D.ERROR:if(this.element&&this.element.error){this.handlePaused(D.ERROR);let{code:t,message:i}=this.element.error;this._log.error("".concat(this.kind," ").concat(this._log.isLocal?"local":"remote"," MediaError code: ").concat(t," message: ").concat(i," userAgent: ").concat(navigator.userAgent)),dt.uploadEvent({log:"stat-".concat(this.kind,"-").concat(di.PLAYER_ERROR,"-").concat(t,"-").concat(navigator.userAgent),error:this.element.error}),K2||Y0?this.emit(Me.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case D.LOADEDDATA:this.kind===D.VIDEO&&this.emit(Me.LOADED_DATA);break;case D.LOADEDMETADATA:this.kind===D.VIDEO&&this.emit(Me.LOADED_META_DATA);break;case D.LOADSTART:this.emit(Me.LOAD_START)}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),dt.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),ce.addSuccessEvent({key:this.kind===D.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),dt.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),ce.addFailedEvent({key:this.kind===D.AUDIO?506700:516700,error:(t=this.element)==null?void 0:t.error}),this.emit(Me.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn("delay ".concat(e,"ms to recreate mediaStream")),new Promise((t,i)=>{Br(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var r,n,s;this._log.warn("element onerror ".concat((n=(r=this.element)==null?void 0:r.error)==null?void 0:n.code," fired after recreated mediaStream")),i((s=this.element)==null?void 0:s.error)}),Br(5e3).then(()=>{var r,n;(!this.isPlaying||(r=this.element)!=null&&r.error)&&i((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){return P(this,null,function*(){let t=e.type;switch(this.options.enableLogTrackState&&this._log[t===D.UNMUTE?"info":"warn"]("track ".concat(t)),t){case D.ENDED:this.handleStopped(D.ENDED);break;case D.MUTE:this.handlePaused(D.MUTE);break;case D.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&!this.isPausedByUserCall&&(this._log.warn("track unmuted and element is paused, resume"),yield this.doResume()),this.element&&!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(D.UNMUTE))}})}handlePlaying(e){var t;return this._log.debug("handlePlaying",e),(t=this._playSuccessResolve)==null||t.call(this,e),e}handlePaused(e){return this._log.debug("handlePaused",e),e}handleStopped(e){return this._log.debug("handleStopped",e),e}getElement(){return this.element}};m(Ea,"PlayerEvent",Me),_e([hs({settings:{retries:2,timeout:0},onError(e,t,i,r){r[0]=(r[0]||1e3)+1e3,t()}})],Ea.prototype,"doReplayByRecreateMediaStream"),_e([ni([],"PLAYING",{sync:!0,success(e){this.emit(Me.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}})],Ea.prototype,"handlePlaying"),_e([ni("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(e){this.emit(Me.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}})],Ea.prototype,"handlePaused"),_e([ni([],"STOPPED",{sync:!0,success(e){this.emit(Me.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}})],Ea.prototype,"handleStopped");var yn="trtc_autoplay",kv="".concat(yn,"_mask"),Xc="".concat(yn,"_wrapper"),Dw="".concat(yn,"_header"),wv="".concat(yn,"_content"),cp="".concat(yn,"_action_wrapper"),Dv="".concat(yn,"_question"),Nv="".concat(yn,"_collapse"),up="".concat(yn,"_action_confirm"),Nw="".concat(yn,"_detail"),Pw="#2473E8",Pv="dialog",YH="".concat(Pv,"-show"),qH="".concat(Pv,"-1"),XH="".concat(Pv,"-2"),Ow=!1,Ov=!1,Qc=()=>Ov,Mw="".concat(mn,"/").concat(_n()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),Lw="<br><a href='".concat(Mw,"' target='_blank'>").concat(_n()?"其他方案?":"Any other solution?","</a>"),QH="".concat(_n()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(Lw):"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(Lw)),ZH=class{constructor(){if(m(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),m(this,"_dialogNode",null),m(this,"_bodyPosition",""),m(this,"_showDetail",!1),m(this,"_isCollapseClicked",!1),m(this,"_isQuestionClicked",!1),_n()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Ow){let e=document.createElement("style");e.innerHTML=".".concat(kv,"{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(kv," div:not(.").concat(cp,"){display:block !important;}.").concat(Xc,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(Xc," a{color:").concat(Pw,";}.").concat(Dw,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(wv,"{margin:8px 0;}.").concat(cp,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(Nv,"{margin-right:auto;cursor:pointer}.").concat(Dv,"{height:100%;line-height:16px;cursor:pointer;}.").concat(up,"{margin-left:8px;color:#fff;background:").concat(Pw,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(up,":hover{opacity:0.9;}.").concat(Nv,",.").concat(up,",.").concat(wv,",.").concat(Dv,"{font-size:14px;}@media screen and (max-width:750px){.").concat(Xc,"{width:80vw;}}"),document.head.appendChild(e),Ow=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(kv,`"><div class='`).concat(Xc,"'><div class='").concat(Dw,"'>").concat(location.host,"</div><div class='").concat(wv,"'>").concat(this.content,"</div><div class='").concat(Nw,`' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">`).concat(QH,"</div><div class='").concat(cp,"'></div></div></div>").trim();let t=document.createElement("button");t.className=up,t.innerText=_n()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=Dv,i.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
65
+ <svg class="icon" width="18" height="18" p-id="2030" t="1639646523624" version="1.1" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
66
+ <path d="m464 784.35c0 26.51 21.49 48 48 48s48-21.49 48-48-21.49-48-48-48-48 21.49-48 48z" p-id="2031"/>
67
+ <path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>
68
+ <path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>
69
+ </svg>
70
+ `,i.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=Nv,r.innerText="".concat(_n()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let n=e.content.firstChild,s=n.querySelector(".".concat(cp));return s.appendChild(r),s.appendChild(i),s.appendChild(t),n}addDiaLog(){Qc()||(Ov=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(Xc)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",fe.info("show autoplay dialog"),dt.uploadEvent({log:YH}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,Ov=!1),Zc=null}onConfirm(){fe.warn("confirm clicked, try resume stream"),$.emit(ie.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat(Nw));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||dt.uploadEvent({log:qH}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Mw,"_blank"),this._isQuestionClicked||dt.uploadEvent({log:XH}),this._isQuestionClicked=!0}},Zc=null;function Mv(){Zc||(Zc=new ZH)}var $c,jr=class tP extends Ea{constructor(t){super(t,D.VIDEO),m(this,"stat",{}),m(this,"_calculateTimeout",-1),m(this,"viewMirror",!1),m(this,"objectFit","cover"),m(this,"container"),m(this,"canvas"),m(this,"shouldRenderAlpha",!1),m(this,"_preSize",{width:0,height:0}),m(this,"posterImg"),m(this,"pipWindow"),m(this,"enterPIPPromise"),m(this,"_originContainerPosition"),m(this,"_isResettingSrcObject",!1),this.mode=t.canvas?1:0,this.container=t.container,this.canvas=t.canvas,j(t.viewMirror)||(this.viewMirror=t.viewMirror),j(t.objectFit)||(this.objectFit=t.objectFit),this.initializeElement()}get isPlaying(){var t;return!(this._state!=="PLAYING"||this.element&&this.element.paused)&&((t=this.track)==null?void 0:t.readyState)==="live"&&!this.track.muted}initializeElement(){var t;let i=document.createElement(D.VIDEO);this.track&&this.mode!==2&&(i.srcObject=new MediaStream([this.track])),i.muted=!0,i.setAttribute("id","video_".concat(this.id)),i.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),i.setAttribute("autoplay","autoplay"),i.setAttribute("playsinline","playsinline"),this.element=i,Vt&&(i.poster="data:,"),(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let t="width:100%;height:100%;object-fit:".concat(this.objectFit,";").concat(this.shouldRenderAlpha?"":"background-color:black",";");return this.viewMirror&&(t+="transform:scaleX(-1);"),t}setContainer(t){var i;this.container=t,this._pausedRetryCount=oa,this.track&&this.elementToRender&&((i=this.container)==null||i.appendChild(this.elementToRender))}bindElementEvents(){let t=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),this.handleFullscreenChange=this.handleFullscreenChange.bind(this),this.handleVolumeChange=this.handleVolumeChange.bind(this),t&&t.add(D.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(D.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(D.RESIZE,this.handleElementEvent),this.element&&(this.element.addEventListener(D.FULLSCREEN_CHANGE,this.handleFullscreenChange),this.element.addEventListener("webkitbeginfullscreen",this.handleFullscreenChange),this.element.addEventListener("webkitendfullscreen",this.handleFullscreenChange),this.element.addEventListener("volumechange",this.handleVolumeChange))}handleTrackEvent(t){var i;return t.type===D.MUTE&&((i=this.stat)!=null&&i.fps&&(this.stat.fps=0),this.isFullscreen()&&this.resetSrcObjectToReplay()),super.handleTrackEvent(t)}handleFullscreenChange(){this.isFullscreen()?(this._log.info("enter fullscreen"),this.emit(Me.ENTER_FULL_SCREEN)):(this._log.info("leave fullscreen"),this.emit(Me.LEAVE_FULL_SCREEN))}handleVolumeChange(){var t;(this.isPictureInPicture()||this.isFullscreen())&&this.emit(Me.VOLUME_CHANGE,{muted:(t=this.element)==null?void 0:t.muted})}handleElementEvent(t){var i,r,n,s,o,l;if(this.mode===2)return;super.handleElementEvent(t);let c=t.type,h=this.isPictureInPicture(),_=this.isFullscreen(),f=t.isTrusted&&(h&&ri||_);if(c===D.PLAYING&&f&&!this._isResettingSrcObject&&(this._log.warn("user resume in ".concat(_?"fullscreen":"pip")),this.emit(Me.USER_RESUME_IN_PIP_OR_FULL_SCREEN)),c===D.PAUSE&&(f&&(this._log.warn("user pause in ".concat(_?"fullscreen":"pip")),this.emit(Me.USER_PAUSE_IN_PIP_OR_FULL_SCREEN)),this.container&&!this.container.isConnected&&(this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(this.container.id)),Br(500).then(()=>{var T;(T=this.container)!=null&&T.isConnected&&(this._pausedRetryCount=oa,this._log.info("view container ".concat(this.container.id," is in dom, reset pausedRetryCount")))})),this._pausedRetryCount>0&&!Qc()&&!this.isPausedByUserCall&&!f&&(this._log.info("[".concat(oa-this._pausedRetryCount+1,"/").concat(oa,"] ").concat(this.kind," player auto resume when paused")),this.doResume(),this._pausedRetryCount--),Gt&&!f&&(this._interval=ft.run("timeout",()=>{this.element&&this._state==="PAUSED"&&!this.isPausedByUserCall&&this.doResume()},{delay:3e3})),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let T=this.element.style.transform;c===D.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=T.replace("scaleX(-1)",""):c===D.LEAVE_PICTURE_IN_PICTURE&&!T.includes("scaleX")&&(this.element.style.transform="".concat(T," scaleX(-1)"))}c===D.RESIZE&&(this._preSize.height!==((i=this.element)==null?void 0:i.videoHeight)||this._preSize.width!==((r=this.element)==null?void 0:r.videoWidth))&&(this._log.info("video size changed to ".concat((n=this.element)==null?void 0:n.videoWidth,"x").concat((s=this.element)==null?void 0:s.videoHeight)),this._preSize.height=((o=this.element)==null?void 0:o.videoHeight)||0,this._preSize.width=((l=this.element)==null?void 0:l.videoWidth)||0,this.emit(Me.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height})),c===D.LEAVE_PICTURE_IN_PICTURE&&(this._log.warn("exit pip"),this.isPaused&&!this.isPausedByUserCall&&(this._log.warn("resume after exit pip"),this.doResume()),this.resetSrcObjectToReplay(),this.emit(Me.LEAVE_PICTURE_IN_PICTURE)),c===D.ENTER_PICTURE_IN_PICTURE&&this.emit(Me.ENTER_PICTURE_IN_PICTURE)}resetSrcObjectToReplay(){Vt&&Oo&&this.isPlayCalled&&this.element&&this.track&&!this.isPausedByUserCall&&(this._log.warn("reset srcObject to replay for android chromium"),this._isResettingSrcObject=!0,this.element.srcObject=new MediaStream([this.track]),this.element.play().catch(t=>{this._log.warn("play failed after reset srcObject",t)}).finally(()=>{this._isResettingSrcObject=!1}))}setCanvas(t){let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1;var r,n,s,o;this.canvas!==t&&((r=this.canvas)==null||r.remove(),t?.setAttribute("style",this.styleAttribute),this.canvas=t,this.mode=t?i:0,this.mode===2&&this.setTrack(t.captureStream().getVideoTracks()[0]),t?((n=this.element)==null||n.remove(),(s=this.container)==null||s.appendChild(t)):this.element&&((o=this.container)==null||o.appendChild(this.element)))}setAttr(t){let i=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},t);i.style=Object.assign({width:"100%",height:"100%"},i.style),super.setAttr(i)}get mirror(){return this.viewMirror}setRect(t,i){this.elementToRender&&(this.elementToRender.style.width="".concat(t,"px"),this.elementToRender.style.height="".concat(i,"px"))}setViewMirror(t){this.elementToRender&&(this.elementToRender.style.transform=t?"scaleX(-1)":""),this.viewMirror=t}setObjectFit(t){this.elementToRender&&(this.elementToRender.style.objectFit="".concat(t)),this.objectFit=t}setPoster(t){let i=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return new Promise(r=>{if(!this.element||(this._log.info("setPoster",t.slice(0,10)),t===""?this.element.removeAttribute("poster"):this.element.poster=t,!i||!ri&&!ut))return r();if(t==="")return this.removePosterImg(),r();if(this.posterImg)return r();let n=document.createElement("img");n.src=t;let s=window.getComputedStyle(this.element).objectFit||this.objectFit;n.style="position:absolute;top:0;left:0;width:100%;height:100%;object-fit:".concat(s,";"),n.onload=()=>P(this,null,function*(){var o;try{n.decode&&(yield n.decode()),this.container&&window.getComputedStyle(this.container).position==="static"&&(this._originContainerPosition=this.container.style.position,this.container.style.position="relative"),this.posterImg=n,(o=this.container)==null||o.appendChild(n),kc()&&Sr<=17&&this.elementToRender&&(this.elementToRender.style.visibility="hidden")}catch(l){this._log.warn("decode poster image error",l)}return r()}),n.onerror=()=>(this._log.warn("load poster image error"),r())})}removePosterImg(){this.posterImg&&(kc()&&Sr<=17&&this.elementToRender&&(this.elementToRender.style.visibility=""),this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),this.container&&!j(this._originContainerPosition)&&this.container.style.position==="relative"&&(this.container.style.position=this._originContainerPosition),delete this.posterImg)}get hasPoster(){var t;return!!this.posterImg||!((t=this.element)==null||!t.getAttribute("poster"))}pause(){let t=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return P(this,null,function*(){xi(tP.prototype,this,"pause").call(this),!this.isPictureInPicture()&&!this.hasPoster&&(Oo||t&&(ut||ri))&&(yield this.setPoster(this.getVideoFrame(),!0))})}resume(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return super.resume(t).then(()=>{var i;(this.posterImg||(i=this.element)!=null&&i.poster)&&this.setPoster("",!0)})}doResume(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this.isPaused&&t&&this.element&&this.track&&Oo&&this.track.kind==="video"&&(this.element.srcObject=new MediaStream([this.track])),super.doResume()}stop(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;var i;this.isPictureInPicture()&&this.exitPictureInPicture().catch(r=>{}),this.isFullscreen()&&this.exitFullscreen().catch(r=>{}),this.element&&(this.element.removeEventListener(D.FULLSCREEN_CHANGE,this.handleFullscreenChange),this.element.removeEventListener("webkitbeginfullscreen",this.handleFullscreenChange),this.element.removeEventListener("webkitendfullscreen",this.handleFullscreenChange),this.element.removeEventListener("volumechange",this.handleVolumeChange)),super.stop(t),(i=this.canvas)==null||i.remove(),this.removePosterImg()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(t){t!==this.track&&(this.unbindTrackEvents(),this.track=t,this.emit(Me.MEDIA_TRACK_CHANGED,t),t!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([t]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let t=document.createElement("canvas");return t.width=this.element.videoWidth,t.height=this.element.videoHeight,t.getContext("2d").drawImage(this.element,0,0),t.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(zc()&&this.element&&this._calculateTimeout<0){let t=0,i=null,r=(n,s)=>{this.stat.width=s.width,this.stat.height=s.height,i&&(this.stat.fps=Math.round((s.presentedFrames-i.presentedFrames)/(n-t)*1e3)),t=n,i=s,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var o;return(o=this.element)==null?void 0:o.requestVideoFrameCallback(r)},2e3))};this.element.requestVideoFrameCallback(r)}}catch(t){this._log.warn("init stat failed",t)}}enterFullscreen(){return P(this,null,function*(){let t=this.elementToRender;if(!t)throw this._log.warn("no element to render, cannot enter fullscreen"),new Error("No element available for fullscreen");if(Gt&&this.isPictureInPicture()){this._log.info("exit pip before entering fullscreen");try{yield this.exitPictureInPicture()}catch(i){this._log.warn("exit pip failed before fullscreen:",i)}}try{if(t.requestFullscreen)yield t.requestFullscreen();else if(t.webkitRequestFullscreen)yield t.webkitRequestFullscreen();else if(t.webkitEnterFullscreen)yield t.webkitEnterFullscreen();else if(t.mozRequestFullScreen)yield t.mozRequestFullScreen();else{if(!t.msRequestFullscreen)throw new Error("Fullscreen API not supported");yield t.msRequestFullscreen()}this._log.info("entered fullscreen mode")}catch(i){throw this._log.error("failed to enter fullscreen:",i),i}})}exitFullscreen(){return P(this,null,function*(){try{if(document.exitFullscreen)yield document.exitFullscreen();else if(document.webkitExitFullscreen)yield document.webkitExitFullscreen();else if(document.mozCancelFullScreen)yield document.mozCancelFullScreen();else{if(!document.msExitFullscreen)throw new Error("Exit fullscreen API not supported");yield document.msExitFullscreen()}this._log.info("exited fullscreen mode")}catch(t){throw this._log.error("failed to exit fullscreen:",t),t}})}isFullscreen(){let t=this.elementToRender;return!!t&&(this.element&&this.element.webkitDisplayingFullscreen?!this.isPictureInPicture():(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)===t)}toggleFullscreen(){return P(this,null,function*(){this.isFullscreen()?yield this.exitFullscreen():yield this.enterFullscreen()})}enterPictureInPicture(){return P(this,null,function*(){this.enterPIPPromise=this._enterPictureInPicture();try{return yield this.enterPIPPromise}finally{delete this.enterPIPPromise}})}_enterPictureInPicture(){return P(this,null,function*(){var t;try{if(!this.element)throw new Error("No video element available for pip");if(this.canvas&&this.mode!==1)throw new Error("pip is not supported for canvas-only mode");let{element:i}=this;if(i.requestPictureInPicture){this._log.info("requestPictureInPicture");let r=yield i.requestPictureInPicture();return this.pipWindow=r,this._log.info("entered pip mode"),this.elementToRender===this.canvas&&(this.canvas.remove(),(t=this.container)==null||t.appendChild(this.element)),r}if(i.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),yield i.webkitSetPresentationMode("picture-in-picture"),this._log.info("entered pip mode (webkit)"),{};throw new Error("pip API not supported")}catch(i){throw this._log.error("failed to enter pip:",i.name,i.message),i}})}exitPictureInPicture(){return P(this,null,function*(){var t,i;try{if(!this.isPictureInPicture())return;if(delete this.pipWindow,document.pictureInPictureElement&&document.exitPictureInPicture)yield document.exitPictureInPicture(),this.elementToRender===this.canvas&&((t=this.element)==null||t.remove(),this._pausedRetryCount=oa,(i=this.container)==null||i.appendChild(this.canvas)),this._log.info("exited pip mode");else{if(!this.element||!this.element.webkitSetPresentationMode)throw new Error("Exit pip API not supported or not in PiP mode");yield this.element.webkitSetPresentationMode("inline"),this._log.info("exited pip mode (webkit)")}}catch(r){throw this._log.error("failed to exit pip:",r),r}})}isPictureInPicture(){if(!this.element)return!1;let{element:t}=this;return document.pictureInPictureElement?document.pictureInPictureElement===t:!!t.webkitPresentationMode&&t.webkitPresentationMode==="picture-in-picture"}togglePictureInPicture(){return P(this,null,function*(){this.isPictureInPicture()?yield this.exitPictureInPicture():yield this.enterPictureInPicture()})}};function dp(e,t){return P(this,null,function*(){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield e.audioWorklet.addModule(t),fe.info("worklet addModule success")}catch(i){throw fe.info("worklet addModule catch error. ".concat(i.message)),i}})}typeof AudioContext<"u"?$c=AudioContext:typeof webkitAudioContext<"u"?$c=webkitAudioContext:typeof mozAudioContext<"u"&&($c=mozAudioContext);var _i,$H=1500,xw=-1,hp=0,eu=-1,Lv=!1,Uw=0,Vw=-1,Fw=-1;(function e(){try{if(_i)return;(_i=new $c({sampleRate:48e3})).onstatechange=()=>{fe.info("context state: ".concat(_i.state).concat(_i.state!=="running"?" visibilityState: ".concat(document.visibilityState):"")),Bo()},clearTimeout(xw)}catch(t){fe.error("initAudioContext failed: ".concat(t," typeof AudioContextClass: ").concat(typeof $c)),xw=setTimeout(e,1e3)}})();var Bo=()=>{_i.state==="suspended"?(hp=Ue(),eu===-1&&(eu=setTimeout(()=>{_i.state==="suspended"&&(Lv=!0,$.emit("155",{isSuspended:!0}))},$H)),tu(),document.addEventListener("click",Bo)):_i.state==="interrupted"?tu():(hp&&(ce.addNumber({key:507800,value:Ue()-hp,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),hp=0),eu!==-1&&(clearTimeout(eu),eu=-1,Lv&&(Lv=!1,$.emit("155",{isSuspended:!1}))),document.removeEventListener("visibilitychange",Bo),document.removeEventListener("click",Bo))},xv=0,Uv=-1;function tu(){return new Promise((e,t)=>{if(_i.state==="running")return e();Date.now()-xv<1e3?(clearTimeout(Uv),Uv=setTimeout(()=>{xv=Date.now(),_i.resume().then(e,t)},1e3)):(clearTimeout(Uv),xv=Date.now(),_i.resume().then(e,t))}).catch(e=>{fe.warn("context resume failed: ".concat(e)),document.addEventListener("visibilitychange",Bo)})}document.addEventListener("click",Bo);var pi=e=>_i,gi=class{constructor(e){this.name=e,m(this,"node"),m(this,"node2"),m(this,"pre",new Set),m(this,"next",new Set),m(this,"context"),m(this,"connectedNodes",new Set),m(this,"nextInputChannelMap",new Map),m(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(e){this._channelCount=e,this.setChannelCount(this.node,e),this.setChannelCount(this.node2,e),this.next.forEach(t=>t.channelCount=e)}setChannelCount(e,t){!e||e instanceof ScriptProcessorNode||(e.channelCountMode="explicit",e.channelCount=t||this.channelCount||1)}setContext(e){this.context=e,this.node&&e.addMixWeight()}removeContext(){var e;this.node&&((e=this.context)==null||e.reduceMixWeight()),delete this.context}replaceNode(e){var t;if(e!==this.node)try{this.node?this._disconnect():(t=this.context)==null||t.addMixWeight(),this.node=e,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(i){fe.error(i)}}setNode(e,t){var i;if(!this.node)try{(i=this.context)==null||i.addMixWeight(),this.node=e,this.setChannelCount(this.node),t&&(this.node2=t,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),ce.addSuccessEvent({key:502701})}catch(r){fe.error(r),ce.addFailedEvent({key:502701,error:r})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(e=this.context)==null||e.reduceMixWeight(),this.preNodeReconnect(),ce.addSuccessEvent({key:502702})}catch(t){fe.error(t),ce.addFailedEvent({key:502702,error:t})}}preNodeReconnect(){this.pre.forEach(e=>{e.node?e.reconnect():e.preNodeReconnect()})}connectNext(e){this.next.forEach(t=>{let i=this.nextInputChannelMap.get(t);e._connect(t.node,i)||t.connectNext(e)})}_connect(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return!(!this.node||!e)&&((this.node2||this.node).connect(e,0,t),this.connectedNodes.add(e),!0)}_disconnect(){this.connectedNodes.forEach(e=>{var t;return(t=this.node2||this.node)==null?void 0:t.disconnect(e)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return this.next.add(e),e.pre.add(this),this.nextInputChannelMap.set(e,t),e}},eW=class extends gi{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:256;super(),this.fftSize=e,m(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=0,i=0,r="M".concat(t,",").concat(i);for(let n=0;n<e.length;n++)i=e[n]/128*100/2,r+="L".concat(t,",").concat(i),t+=1;return r}},Bw=class{constructor(){m(this,"source",new gi),m(this,"gain",new gi),m(this,"destination",new gi)}get volume(){var e;return((e=this.gain.node)==null?void 0:e.gain.value)||1}setVolume(e){e!==1?(this.gain.node||this.gain.setNode(pi().createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){let t=Vv(e);t&&this.source.replaceNode(t)}get track(){var e;return(e=this.stream)==null?void 0:e.getAudioTracks()[0]}get stream(){var e;return(e=this.destination.node)==null?void 0:e.stream}},Hw=class extends Bw{constructor(e){super(),this.context=e,m(this,"aec",new gi("aec")),m(this,"mixNode",new gi("mixNode")),m(this,"silentNode",new gi("silentNode")),m(this,"denoiser",new gi("denoiser")),m(this,"voiceChanger",new gi("voiceChanger")),this.source.pipeTo(this.aec).pipeTo(this.denoiser).pipeTo(this.voiceChanger).pipeTo(this.gain).pipeTo(this.destination),this.silentNode.pipeTo(this.mixNode).pipeTo(this.aec,1)}get isProcessEnabled(){return this.aec.node||this.denoiser.node||this.voiceChanger.node||this.gain.node}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.aec.setContext(this.context),this.silentNode.setContext(this.context),this.mixNode.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.aec.removeContext(),this.silentNode.removeContext(),this.mixNode.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.aec.deleteNode(),this.silentNode.deleteNode(),this.mixNode.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){e!==1?(this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}},tW=class{constructor(){m(this,"audioContext",pi()),m(this,"destination",this.audioContext.createMediaStreamDestination()),m(this,"inputs",new Set),m(this,"mixWeight",0),this.destination.channelCount=1}addMixWeight(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.mixWeight+=e,this.mixWeight-1==e+1>>1&&this.mixOnChange()}reduceMixWeight(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.addMixWeight(-e)}close(){this.inputs.forEach(e=>e.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},Ww=new WeakMap;function Vv(e){try{let t=Ww.get(e);if(t)return t;let i=pi();if(e instanceof HTMLAudioElement)t=i.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=i.createMediaStreamSource(new MediaStream([e]))}return Ww.set(e,t),t}catch(t){if(!(ut&&t instanceof Error&&t.name==="NotSupportedError"))throw t;fe.warn(t)}}var pp=class Cn{constructor(t){m(this,"_volume",0),m(this,"_volumeDb",0),m(this,"_log"),m(this,"_scriptProcessorNode",null),m(this,"_audioWorkletNode",null),m(this,"_interval",200),m(this,"ready",this.preload());let{log:i}=t;this._log=i,$.on(ie.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-Cn.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!Cn.workletReady){let t='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';Cn.workletReady=dp(Cn.audioContext,URL.createObjectURL(new Blob([t],{type:"application/javascript"})))}return Cn.workletReady.then(()=>this.initAudioWorklet()).catch(t=>(this._log.error("volumeMeter preload error: ".concat(t)),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Cn.audioContext,"volume-meter");let t=!1;this._audioWorkletNode.port.onmessage=i=>{Cn.lastMessageTime=Date.now(),this._volume=i.data.volume||0,this._volumeDb=i.data.volumeDb||0,!t&&i.data.cacheLen&&i.data.outputLen&&(this._log.warn("worklet play success"),t=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(t){this._log.error("volumeMeter init audio worklet error: ".concat(t)),dt.logFailedEvent({userId:this._log.userId,eventType:di.LOAD_WORKLET,error:t}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=pi().createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=t=>{Cn.lastMessageTime=Date.now();let i=t.inputBuffer.getChannelData(0),r=0;for(let n=0;n<i.length;++n)r+=i[n]*i[n];this._volume=Math.sqrt(r/i.length)||0}}catch(t){this._log.error("volumeMeter init script processor error: ".concat(t))}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,$.off(ie.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(100*this._volumeDb)}handleAudioLevelInterval(t){var i;let{interval:r}=t;this._interval=r,(i=this._audioWorkletNode)==null||i.port.postMessage({name:"setIntervalTime",intervalTime:r})}};m(pp,"lastMessageTime",0),m(pp,"audioContext",pi()),m(pp,"workletReady");var Gw=pp,jw=class extends gi{constructor(e){super(),m(this,"_volumeMeter"),this._volumeMeter=new Gw(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return P(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),i=new Float32Array(t>>2);e.copyTo(i,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:i},[i.buffer]),e.close()}}},mp=Gw,iW=ti(Ri(),1),zw=e=>t=>t.deviceId===e,Fv=class{constructor(e,t){m(this,"kind"),m(this,"type"),m(this,"devices",[]),this.kind=e,this.type=t}update(e,t){let i=e.filter(r=>r.kind==="".concat(this.kind).concat(this.type.toLocaleLowerCase()));this.devices.length===1&&iu(this.devices[0])||t&&(i.forEach(r=>{if(r.deviceId&&!this.devices.find(zw(r.deviceId))){let n="".concat(this.kind).concat(this.type,"Added");fe.warn("".concat(n,": ").concat(JSON.stringify(r))),t.emit(n,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!i.find(zw(r.deviceId))){let n="".concat(this.kind).concat(this.type,"Removed");fe.warn("".concat(n,": ").concat(JSON.stringify(r))),t.emit(n,r)}})),this.devices=i}hasDevice(e){return!!this.devices.find(t=>t.deviceId===e)}},rW=class extends iW.EventEmitter{constructor(){super(),m(this,"audioInputs",new Fv(D.AUDIO,"Input")),m(this,"videoInputs",new Fv(D.VIDEO,"Input")),m(this,"audioOutputs",new Fv(D.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||ft.run("interval",()=>{this.update()},{delay:1e4}))}init(){fp().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return P(this,arguments,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return(function*(){let i=yield fp(t);return e.audioInputs.update(i,e),e.videoInputs.update(i,e),e.audioOutputs.update(i,e),e})()})}hasBlueTooth(){var e;if(1e3*((e=pi())==null?void 0:e.outputLatency)>150)return!0;let t=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(i=>t.some(r=>i.label.toLowerCase().includes(r)))||this.audioInputs.devices.some(i=>t.some(r=>i.label.toLowerCase().includes(r)))}},Xt=Xg||Rh?null:new rW;function iu(e){return e.deviceId===e.groupId&&e.groupId===""}function fp(){return P(this,arguments,function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return(function*(){if(ga()||!dv())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(e!==0){let i={audio:!1,video:!1};if(t.forEach(r=>{iu(r)&&(r.kind===D.AUDIO_INPUT?i.audio=!0:r.kind===D.VIDEO_INPUT&&(i.video=!0))}),e===2&&(i.audio=!1),e===1&&(i.video=!1),i.audio||i.video){let r;try{r=yield navigator.mediaDevices.getUserMedia(i),i.audio&&tu()}catch(n){fe.debug("capture before getDevices failed: ",n)}t=yield navigator.mediaDevices.enumerateDevices(),r?.getTracks().forEach(n=>n.stop())}}return t.map((i,r)=>{let n={kind:i.kind,deviceId:i.deviceId,groupId:i.groupId,label:i.label||"".concat(i.kind,"_").concat(r)};return i.deviceId.length>0&&Bv.add("".concat(i.deviceId,"_").concat(i.kind)),i.getCapabilities&&(n.getCapabilities=()=>i.getCapabilities()),n})})()})}function Tn(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return Xt.update(e?1:0).then(t=>t.audioInputs.devices)}function Sn(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return Xt.update(e?2:0).then(t=>t.videoInputs.devices)}var Kw=!1;function ya(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return P(this,null,function*(){return(Gt||ri)&&(e=!1),Xt.update(e?1:0).then(t=>t.audioOutputs.devices)})}var Bv=new Set;function Jw(e,t){return P(this,null,function*(){let i=(yield Tn()).find(r=>r.deviceId===pc);return!t&&i?.groupId===e||i?.groupId===e&&i.label===t})}var _p,nW=class extends Bw{constructor(e){super(),this.log=e,m(this,"volumeMeter"),m(this,"volumeMeterAfter3A"),m(this,"volumeDestination"),m(this,"analyser",new eW),this.volumeMeter=new jw({log:this.log}),this.volumeMeterAfter3A=new jw({log:this.log}),this.volumeDestination=new gi,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},Hv=class iP extends Ea{constructor(t){super(t,D.AUDIO),m(this,"_outputDeviceId"),m(this,"_floatVolume",1),m(this,"_destination"),m(this,"pipeline"),m(this,"volumeMeterMode","worklet"),m(this,"enableVolumeControlInIOS"),this.enableVolumeControlInIOS=t.enableVolumeControlInIOS,this.mode=0,t.url&&(this.url=t.url),this.pipeline=new nW(this._log)}setTrack(t){}get duration(){var t;return Math.floor(1e3*(((t=this.element)==null?void 0:t.duration)||0))}get currentTime(){var t;return Math.floor(1e3*(((t=this.element)==null?void 0:t.currentTime)||0))}set currentTime(t){this.element&&(this.element.currentTime=t/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(t){if((cr==="15.2"||cr==="15.3"||cr==="15.4")&&this.muted)return void this._log.info("audioElement is muted.");let i=_p||new Audio;i.setAttribute("autoplay","autoplay"),i.srcObject=this.getMediaStream(),i.muted=this.muted,this.url&&(i.crossOrigin="anonymous",i.src=this.url),this.element=i,this.setVolume(nt(t)?t/100:this._floatVolume),i===_p&&(_p=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(Me.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(t){return P(this,null,function*(){if(this.track||this.url){try{!this.pipeline.source.node&&this.track&&this.pipeline.replaceSource(this.track),this.element||this.initializeElement(t?.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(pi().createAnalyser()),(function(){P(this,null,function*(){try{Kw||(Kw=!0,fe.info("speakers:".concat((yield ya()).map(i=>" ".concat(i.deviceId.slice(0,8),": ").concat(i.label)))))}catch{}})})()}catch(i){throw this._log.warn("audio play error: ".concat(i)),(cs||ha)&&tv(cr,"18.7",!0)&&this.bindAutoPlayEvent(),i}return xi(iP.prototype,this,"play").call(this)}})}stop(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.pipeline.destroy(),super.stop(t)}setVolume(t){this._floatVolume=t,this.element&&(this.element.volume=t)}setSinkId(t){return P(this,null,function*(){var i,r;this._outputDeviceId!==t&&(this._outputDeviceId=t),this.element&&this.element.sinkId!==t&&(yield(r=(i=this.element).setSinkId)==null?void 0:r.call(i,t))})}get useDestination(){return!!this.pipeline.stream}setLoop(t){this.element&&(this.element.loop=t)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},sW=class extends Hv{setTrack(e){this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(Me.MEDIA_TRACK_CHANGED,e),e&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]))))}},Yw=class extends Hv{constructor(e){super(e),m(this,"_sourceElement"),m(this,"_output",new gi),this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(pi().destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,i,r;((i=(t=this.element)==null?void 0:t.error)==null?void 0:i.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(Me.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((r=e.getSettings())==null?void 0:r.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){var t;let i=e<=1&&!kc();if(this._floatVolume!==e||!(i&&((t=this.element)==null?void 0:t.volume)===e||!i&&this.pipeline.volume===e))if(this._floatVolume=e,this.useDestination)this.pipeline.setVolume(e),this._log.info("set pipeline volume: ".concat(e));else if(i)this.element?(this._log.info("set element volume: ".concat(e)),this.element.volume=e):this._log.info("set element volume: no element");else{if(kc()){if(!this.enableVolumeControlInIOS)return;(function(){if(!Gt||Fw!==-1)return;let r=()=>{Ue()-Uw<500||(_i&&_i.state==="running"&&_i.currentTime===Vw&&(fe.warn("context is fake running, auto resume"),_i.suspend().catch(n=>{fe.warn("context suspend failed: ".concat(n))})),Vw=_i.currentTime,Uw=Ue())};Fw=setInterval(()=>{r()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&r()})})()}if(ut&&!this.pipeline.source.node)return void this._log.warn("set pipeline volume failed: no source node");this._log.info("start set pipeline volume: ".concat(e)),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this._destination||(this._destination=pi().createMediaStreamDestination()),this.pipeline.destination.setNode(this._destination),bi(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play().catch(r=>{this.emit(Me.AUTOPLAY_FAILED,r)}))}}stop(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.pipeline.destroy();let t=this._sourceElement||this.element;t&&pa&&(_p=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},Wv=class extends et{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:n,PlayerClass:s=r===1?Yw:jr}=e;var o;super(),m(this,"id",sk()),m(this,"userId",""),m(this,"isRemote"),m(this,"mediaType"),m(this,"room"),m(this,"user"),m(this,"_log"),m(this,"_inputTrack"),m(this,"_outputTrack"),m(this,"isPlayCalled"),m(this,"container",null),m(this,"player"),m(this,"subVideoPlayerMap"),m(this,"muted",!1),m(this,"abortCtrl"),m(this,"objectFit","cover"),m(this,"mirror"),m(this,"rotation"),m(this,"isScreen",!1),m(this,"manager"),m(this,"trackSettings"),m(this,"isFirstVideoFrameEmitted",!1),this.userId=t||"",this.mediaType=r,this._log=fe.createLogger({parent:n?.getLogger(),id:"".concat(this.kind[0],"t"),userId:(o=n||this.room)==null?void 0:o.userId,remoteUserId:this instanceof cu?void 0:this.userId,sdkAppId:i,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof cu}),this.player=new s({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:n?.enableVolumeControlInIOS}),this.player.on(Me.PLAYER_STATE_CHANGED,l=>{if($.emit(ie.PLAYER_STATE_CHANGED,ve({track:this},l)),this.emit("player-state-changed",l),l.state==="PLAYING"&&this.room){let c=!0;for(let{remoteAudioTrack:h,remoteVideoTrack:_,remoteAuxiliaryTrack:f}of[...this.room.remotePublishedUserMap.values()])if(h.isAvailable&&!h.player.isPlaying||_.isAvailable&&!_.player.isPlaying||f.isAvailable&&!f.player.isPlaying){c=!1;break}c&&Qc()&&Zc&&Zc.deleteDialog()}}),this.kind===D.VIDEO&&(this.player.on(Me.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(Me.LOADED_DATA),$.emit(ie.VIDEO_LOADED_DATA,{track:this})}),this.player.on(Me.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(Me.LOADED_META_DATA)}),this.player.on(Me.MEDIA_TRACK_CHANGED,l=>{var c;(c=this.subVideoPlayerMap)==null||c.forEach(h=>h.setTrack(l))}),this.player.on(Me.RESIZE,l=>{this.emitFirstVideoFrameEvent(Me.RESIZE),this.emit("video-size-changed",ve({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},l))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(Me.ERROR,this.onPlayerError.bind(this)),this.player.on(Me.AUTOPLAY_FAILED,this.handleAutoPlayFailed,this)}get log(){return this._log||fe}get kind(){return this.mediaType===1?D.AUDIO:D.VIDEO}get isAudio(){return this.kind===D.AUDIO}get strMediaType(){return this.mediaType===4?D.VIDEO:this.mediaType===2?D.SCREEN:D.AUDIO}get streamType(){return 2&this.mediaType?"auxiliary":"main"}get isMediaTrackActive(){return!!this.mediaTrack&&!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}play(e,t){return P(this,null,function*(){let i=Jt(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!j(t.muted)&&this.setPlayerMute(t.muted),t&&!j(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof jr&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),Jt(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!j(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===D.VIDEO)&&this.setPlayerMute(!0),t&&!j(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof jr&&(this.player.setObjectFit(this.objectFit),t&&!j(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof jr&&this.player.setContainer(i)),$.emit(ie.PLAY_TRACK_START,{track:this}),this._outputTrack){this._log.info("play with options: ".concat(JSON.stringify(t)));try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(t),Jt(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(r){throw this.handleAutoPlayFailed(r),r}}else this.log.info("play has not mediaTrack, abort")})}setMirror(e,t){if(this.isScreen||this.kind!==D.VIDEO||j(e)||e===this.mirror)return;this.mirror=e;let i=this.player;t&&(i=t);let r=this.manager;if(Rt(this.mirror))return i.setViewMirror(this.mirror),void(!this.isRemote&&r&&(r.mirror=!1));switch(this.mirror){case"view":r&&(r.mirror=!1),i.setViewMirror(!0);break;case"publish":r&&(r.mirror=!0),i.setViewMirror(!0);break;case"both":r&&(r.mirror=!0),i.setViewMirror(!1)}}playSubContainer(e,t){return P(this,null,function*(){if(!this._outputTrack||this.kind===D.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((r,n)=>{var s;e.find(o=>n===o)||(r.stop(),(s=this.subVideoPlayerMap)==null||s.delete(n))});for(let[r,n]of e.entries()){let s=this.subVideoPlayerMap.get(n);s?t&&(j(t.objectFit)||s.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new jr({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:"vp-sub".concat(r+1)})}))}let i=[...this.subVideoPlayerMap.values()];for(let r of i)r.setViewMirror(this.player.mirror),yield r.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];this.isPlayCalled&&(this.isPlayCalled=!1,this.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(P0(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(t=>{t.stop()}),this.container=null)}resume(){return P(this,null,function*(){var e;this.isPlayCalled&&(yield(e=this.player)==null?void 0:e.resume())})}close(){this._toInitState(),this.log.info("close"),this.isPlayCalled&&this.stop(!0)}_toInitState(){}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),$.emit(e?ie.TRACK_MUTED:ie.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){Ar(e,e).add(D.MUTE,this.onTrackMuted).add(D.UNMUTE,this.onTrackUnmuted).add(D.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===D.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){bi(e)}setInputMediaStreamTrack(e){var t;let i=this._inputTrack;if(e!==i)return this._inputTrack=e,this.trackSettings=(t=e.getSettings)==null?void 0:t.call(e),e.enabled=!this.muted,i&&this.uninstallTrackEvent(i),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,i||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;e!==this._outputTrack&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(t=e.getSettings)==null?void 0:t.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){var t,i;if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch(r=>this.handleAutoPlayFailed(r)),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return P0(this)&&this.isAudio&&(t=this.user)!=null&&t.muteState.hasAudio&&(i=this.user)!=null&&i.muteState.audioMuted?void 0:(this.player.stop(P0(this)?this.jitterBufferDelay:0),void this.log.info("playing state updated, stop ".concat(this.kind)))}this.log.debug("updatePlayingState abort ".concat(this.isPlayCalled," ").concat(e," ").concat(this.player.isStopped))}handleAutoPlayFailed(e){return P(this,null,function*(){var t;this.log.warn("handleAutoPlayFailed",e);let i=()=>{this.resume().then(()=>{document.removeEventListener("click",i,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((cs||ha)&&(yield Br(100),(t=this.player)!=null&&t.isPlaying))return;Mv()}else document.addEventListener("click",i,!0);$.once(ie.LOCAL_TRACK_CAPTURE_SUCCESS,r=>{let{track:n}=r;n.kind==="audio"&&Qc()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&i()}),this.emit("error",e)})}getVideoFrame(){return this.player instanceof jr?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var t,i,r;if(this.isFirstVideoFrameEmitted)return;let n=(t=this.mediaTrack)==null?void 0:t.getSettings(),s=n?.width||((i=this.player.element)==null?void 0:i.videoWidth)||0,o=n?.height||((r=this.player.element)==null?void 0:r.videoHeight)||0;e===Me.RESIZE&&!s&&!o||e===Me.LOADED_META_DATA&&!s&&!o||(e===Me.LOADED_DATA&&!s&&!o&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,ls(this.rotation)&&([s,o]=[o,s]),this.emit("first-video-frame",{width:s,height:o,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn("".concat(this.kind," track is unable to provide media output"))}onTrackUnmuted(){this._log.info("".concat(this.kind," track is able to provide media output"))}onTrackEnded(){this._log.warn("".concat(this.kind," track ended"))}};_e([ni([],et.INIT,{sync:!0})],Wv.prototype,"_toInitState");var aW=Object.prototype.hasOwnProperty,In=function(e){if(e==null)return!0;if(typeof e=="boolean")return!1;if(typeof e=="number")return e===0;if(typeof e=="string"||typeof e=="function"||Array.isArray(e))return e.length===0;if(e instanceof Error)return e.message==="";if(nr(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return e.size===0;case"[object Object]":for(let t in e)if(aW.call(e,t))return!1;return!0}return!1},oW=Cc({retryFunction:function(e){return P(this,null,function*(){let t=(function(s){return{audio:lW(s),video:cW(s)}})(e);fe.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],r=[],n=["label","deviceId","groupId"];if(t.audio&&(i=yield Tn(),fe.info("microphones: ".concat(Tr(i.map(s=>xe(ve({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:n})))),t.video&&(r=yield Sn(),fe.info("cameras: ".concat(Tr(r,{keysToInclude:n}))),!Rt(t.video)&&t.video.facingMode==="user"&&!t.video.deviceId)){let s=r.filter(o=>!o.label.includes("infrared")).find(o=>o.label.includes("facing front"));s&&(t.video.deviceId=s.deviceId,fe.info("exclude infrared camera: ".concat(JSON.stringify(t))))}try{let s=yield navigator.mediaDevices.getUserMedia(t);return pw&&s.getTracks().forEach(o=>{var l;let c=o.getCapabilities();fe.info("".concat(o.kind," capabilities: ").concat(Tr(c,{keysToInclude:c0}))),!j(e.echoCancellation)&&((l=c.echoCancellation)==null?void 0:l.indexOf(e.echoCancellation))===-1&&fe.warn("Invalid argument for 'echoCancellation'. Expected one of [".concat(JSON.stringify(c.echoCancellation),"], but received '").concat(e.echoCancellation,"'"))}),t.audio&&tu(),s}catch(s){let{message:o}=s;throw s.name==="NotFoundError"&&(e.video&&r&&r.length===0&&(o=He({key:Fe.CAMERA_NOT_FOUND})),e.audio&&i&&i.length===0&&(o=He({key:Fe.MICROPHONE_NOT_FOUND}))),new me({code:te.INITIALIZE_FAILED,name:s.name,message:o,constraint:s.constraint})}})},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:i,reject:r,retryFuncArgs:n,retriedCount:s}=e,o=s+1;t.name==="NotReadableError"||t.name==="OverconstrainedError"||t.name==="AbortError"?(o===1?(n[0].video&&(n[0].maxResolution=!1,(!ri||n[0].width*n[0].height<=2073600)&&n[0].frameRate&&(n[0].frameRate=n[0].frameRate>10?10:5)),n[0].retryWhenExactFailed&&n[0].useExactDeviceId&&(n[0].useExactDeviceId=!1)):o===2?n[0].useDeviceIdOnly=!0:o===3&&!n[0].useExactDeviceId&&(n[0].useTrueAsConstraint=!0),i()):r(t),n[0].microphoneId&&qw(n[0].microphoneId,!1),n[0].cameraId&&qw(n[0].cameraId,!0)},onRetrying:e=>{fe.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{dt.logFailedEvent({eventType:di.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{dt.logSuccessEvent({eventType:di.GET_USER_MEDIA_RETRY}),dt.uploadEvent({log:"stat-".concat(di.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function qw(e,t){return P(this,null,function*(){let i=(t?yield Sn():yield Tn()).find(r=>r.deviceId===e);i&&Ut(i.getCapabilities)&&fe.warn(Tr(i.getCapabilities(),{keysToInclude:c0}))})}function lW(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!In(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(nt(e.channelCount)&&(t.channelCount=e.channelCount),(Rt(e.echoCancellation)||e.echoCancellation==="remote-only"||e.echoCancellation==="all")&&(t.echoCancellation=e.echoCancellation),Rt(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),Rt(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!In(t)||t)}function cW(e){if(!e.video)return!1;if(e.useTrueAsConstraint)return!0;let{maxResolution:t=!0}=e,i={};return e.cameraId?i.deviceId=e.useExactDeviceId?{exact:e.cameraId}:e.cameraId:e.facingMode&&(i.facingMode=e.facingMode),e.useDeviceIdOnly&&!In(i)?i:(e.width&&(i.width={ideal:e.width},t&&!ut&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!ut&&(i.height.max=e.height)),ut&&us&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!In(i)||i)}var uW=oW;function Xw(e){return _t((t,i)=>function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];return P(this,null,function*(){return yield e.apply(this,n),t.apply(this,n)})})}function Ta(e){return _t((t,i)=>function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];return P(this,null,function*(){let o=yield t.apply(this,n);return yield e.call(this,...n),o})})}function Qw(e){return _t((t,i)=>function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];return P(this,null,function*(){try{return yield t.apply(this,n)}catch(o){e.call(this,o)}})})}function _t(e){return function(t,i,r){return r.value=e(r.value,i),r}}var dW=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&fe.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",()=>{fe.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState}),e=!0)}})(),hW=0,Zw=class{constructor(e){m(this,"log"),m(this,"isRunning",!1),m(this,"queue",[]);let t="fq".concat(++hW);e&&(t+="|".concat(e)),this.log=fe.createLogger({id:t})}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(e){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];var i,r;let n=ve({},e),s=new Promise((o,l)=>{n.resolve=o,n.reject=l});return n.promise=s,t?this.length<=1?this.queue.push(n):(r=(i=this.lastQueueItem)==null?void 0:i.promise)==null||r.then(n.resolve,n.reject):this.queue.push(n),this.log.debug("push ".concat(this.length),e.funcName,e.args),this.isRunning||this.callNext(),s}shift(){let e=this.queue.shift();return this.log.debug("shift ".concat(this.length),e?.funcName,e?.args),e}callNext(){if(this.isRunning||this.length===0)return;let{fn:e,args:t,context:i,resolve:r,reject:n,funcName:s}=this.queue[0];this.log.debug("callNext",this.length,s,t),this.isRunning=!0,e.apply(i,t).then(r,n).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},gp=new WeakMap,vp=new WeakMap;function ru(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return function(t,i,r){let n=r.value;return r.value=function(){let s=gp.get(this)||new Zw;for(var o=arguments.length,l=new Array(o),c=0;c<o;c++)l[c]=arguments[c];return gp.set(this,s),s.push({fn:n,args:l,context:this,funcName:i},e)},r}}function $w(e){return function(t,i,r){let n=r.value;return r.value=function(){var s,o,l;let c=[];for(var h=arguments.length,_=new Array(h),f=0;f<h;f++)_[f]=arguments[f];return(o=(s=gp.get(this))==null?void 0:s.queue)==null||o.forEach(T=>c.push(T)),(l=vp.get(this))==null||l.forEach(T=>T?.queue.forEach(b=>c.push(b))),c.forEach(T=>{T.reject(new me({code:te.API_CALL_ABORTED,message:e}))}),gp.delete(this),vp.delete(this),n.apply(this,_)},r}}function ps(e,t){return function(i,r,n){let s=n.value,o=l=>e(...l);return n.value=function(){for(var l=arguments.length,c=new Array(l),h=0;h<l;h++)c[h]=arguments[h];let _=vp.get(this)||new Map,f=_.get(o(c))||new Zw(t?.(...c));return _.set(o(c),f),vp.set(this,_),f.push({fn:s,args:c,context:this,funcName:r})},n}}function ms(e,t){return _t((i,r)=>function(){let n=e;try{for(var s=arguments.length,o=new Array(s),l=0;l<s;l++)o[l]=arguments[l];let c=i.apply(this,o),h=Ue();return yc(c)?c.then(_=>(t?ce.addSuccessEvent({key:n,cost:Ue()-h}):ce.addSuccessEvent({key:n}),_)).catch(_=>{throw ce.addFailedEvent({key:n,error:_}),_}):(ce.addSuccessEvent({key:n}),c)}catch(c){throw ce.addFailedEvent({key:n,error:c}),c}})}var eD={};function Pt(){}pn(eD,{Events:()=>jt,Inspect:()=>fs,LastSink:()=>Ep,Sink:()=>qe,Subscribe:()=>yp,TimeoutError:()=>rD,audit:()=>QW,bindCallback:()=>MW,bindNodeCallback:()=>LW,buffer:()=>SW,bufferCount:()=>TW,bufferTime:()=>yG,call:()=>tD,catchError:()=>SD,combineLatest:()=>aD,concat:()=>_W,concatMap:()=>uG,concatMapTo:()=>dG,count:()=>VW,create:()=>st,debounce:()=>$W,debounceTime:()=>eG,defer:()=>oD,delay:()=>TG,deliver:()=>Xe,dispose:()=>Gv,elementAt:()=>tG,empty:()=>Yv,every:()=>aG,exhaustMap:()=>_G,exhaustMapTo:()=>gG,expand:()=>IG,filter:()=>Sa,find:()=>iG,findIndex:()=>rG,first:()=>nG,fromAnimationFrame:()=>PW,fromArray:()=>bW,fromEvent:()=>St,fromEventPattern:()=>CW,fromFetch:()=>kW,fromIterable:()=>wW,fromPromise:()=>dD,fromReadableStream:()=>NW,fromReader:()=>DW,groupBy:()=>vG,identity:()=>pW,ignoreElements:()=>WW,iif:()=>vW,inspect:()=>iD,interval:()=>uD,last:()=>sG,map:()=>Xv,mapTo:()=>lG,max:()=>FW,merge:()=>jv,mergeMap:()=>pG,mergeMapTo:()=>mG,min:()=>BW,never:()=>xW,nothing:()=>Pt,of:()=>AW,pairwise:()=>oG,pipe:()=>At,race:()=>sD,range:()=>OW,reduce:()=>hD,retry:()=>CG,scan:()=>fD,setAsapScheduler:()=>RW,share:()=>nu,shareReplay:()=>gW,skip:()=>zW,skipUntil:()=>KW,skipWhile:()=>qv,startWith:()=>zv,subject:()=>zr,subscribe:()=>Qt,sum:()=>HW,switchMap:()=>Sp,switchMapTo:()=>Rp,take:()=>Wo,takeLast:()=>jW,takeUntil:()=>Ci,takeWhile:()=>GW,tap:()=>Qv,throttle:()=>qW,throwError:()=>UW,timeInterval:()=>EG,timeout:()=>bG,timer:()=>Jv,toPromise:()=>RG,toReadableStream:()=>AG,withLatestFrom:()=>yW,zip:()=>EW});var tD=e=>e(),pW=e=>e;function Gv(){this.dispose()}var iD=()=>typeof __FASTRX_DEVTOOLS__<"u",mW=1,fs=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new fW(e,this,this.streamId++);return jt.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},Ep=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=Pt,this.error=Pt,this.next=Pt,this.dispose=Pt,this.subscribe=Pt,this.doDefer()}subscribe(e){return e instanceof fs?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(tD),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}},qe=class extends Ep{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)}},yp=class extends Ep{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Pt,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Pt,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:Pt;if(super(),this._next=t,this._error=i,this._complete=r,this.then=Pt,e instanceof fs){let n={toString:()=>"subscribe",id:0,source:e};this.defer(()=>{jt.defer(n,0)}),jt.create(n),jt.pipe(n),this.sourceId=n.id,this.subscribe(e),jt.subscribe({id:n.id,end:!0}),t==Pt?this._next=s=>jt.next(n,0,s):this.next=s=>{jt.next(n,0,s),t(s)},r==Pt?this._complete=()=>jt.complete(n,0):this.complete=()=>{this.dispose(),jt.complete(n,0),r()},i==Pt?this._error=s=>jt.complete(n,0,s):this.error=s=>{this.dispose(),jt.complete(n,0,s),i(s)}}else this.subscribe(e)}next(e){this._next(e)}complete(){this.dispose(),this._complete()}error(e){this.dispose(),this._error(e)}};function At(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return i.reduce((n,s)=>s(n),e)}function st(e,t,i){if(iD()){let r=Object.defineProperties(Object.setPrototypeOf(e,fs.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}});jt.create(r);for(let n=0;n<i.length;n++){let s=i[n];typeof s=="function"&&s instanceof fs&&jt.addSource(r,s)}return r}return e}function Xe(e,t){return function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return s=>{if(s instanceof fs){let o=st(l=>{let c=new e(l,...r);c.sourceId=o.id,c.subscribe(s)},t,arguments);return o.source=s,jt.pipe(o),o}return o=>s(new e(o,...r))}}}function _s(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var fW=class extends qe{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer(()=>{jt.defer(this.source,this.id)})}next(e){jt.next(this.source,this.id,e),this.sink.next(e)}complete(){jt.complete(this.source,this.id),this.sink.complete()}error(e){jt.complete(this.source,this.id,e),this.sink.error(e)}},jt={addSource(e,t){_s("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){_s("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;_s("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){_s("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){_s("defer",{id:e.id,streamId:t})},pipe(e){_s("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){_s("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=mW++),_s("create",{name:e.toString(),id:e.id})}},rD=class extends Error{constructor(e){super("timeout after ".concat(e,"ms")),this.timeout=e}},nD=class extends Ep{constructor(e){super(),this.source=e,this.sinks=new Set}add(e){e.defer(()=>this.remove(e)),this.sinks.add(e).size===1&&(this.reset(),this.subscribe(this.source))}remove(e){this.sinks.delete(e),this.sinks.size===0&&this.dispose()}next(e){this.sinks.forEach(t=>t.next(e))}complete(){this.sinks.forEach(e=>e.complete()),this.sinks.clear()}error(e){this.sinks.forEach(t=>t.error(e)),this.sinks.clear()}};function nu(){return e=>{let t=new nD(e);if(e instanceof fs){let i=st(r=>{t.add(r)},"share",arguments);return t.sourceId=i.id,i.source=e,jt.pipe(i),i}return st(t.add.bind(t),"share",arguments)}}function jv(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return st(r=>{let n=new qe(r),s=t.length;n.complete=()=>{--s===0&&r.complete()},t.forEach(n.bindSubscribe)},"merge",arguments)}function sD(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return st(r=>{let n=new Map;t.forEach(s=>{let o=new qe(r);n.set(s,o),o.complete=()=>{n.delete(s),n.size===0?r.complete():o.dispose()},o.next=l=>{n.delete(s),n.forEach(c=>c.dispose()),o.resetNext(),o.resetComplete(),o.next(l)}}),t.forEach(s=>n.get(s).subscribe(s))},"race",arguments)}function _W(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return st(r=>{let n=0,s=t.length,o=new qe(r);o.complete=()=>{n<s&&!o.disposed?(o.doDefer(),o.subscribe(t[n++])):r.complete()},o.complete()},"concat",arguments)}function gW(e){return t=>{let i=new nD(t),r=[];return i.next=function(n){r.push(n),r.length>e&&r.shift(),this.sinks.forEach(s=>s.next(n))},st(n=>{n.defer(()=>i.remove(n)),r.forEach(s=>n.next(s)),i.add(n)},"shareReplay",arguments)}}function vW(e,t,i){return st(r=>e()?t(r):i(r),"iif",arguments)}function aD(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return st(r=>{let n=t.length,s=n,o=n,l=new Array(n),c=()=>{--o===0&&r.complete()};t.forEach((h,_)=>{let f=new qe(r);f.next=T=>{s--,f.next=b=>{l[_]=b,s===0&&r.next(l)},f.next(T)},f.complete=c,f.subscribe(h)})},"combineLatest",arguments)}function EW(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return st(r=>{let n=t.length,s=n,o=new Array(n),l=()=>{--s===0&&r.complete()};t.forEach((c,h)=>{let _=new qe(r),f=[];o[h]=f,_.next=T=>{f.push(T),o.every(b=>b.length)&&r.next(o.map(b=>b.shift()))},_.complete=l,_.subscribe(c)})},"zip",arguments)}function zv(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return r=>st(function(n){let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:t.length;for(;s<o&&!n.disposed;)n.next(t[s++]);n.disposed||n.subscribe(r)},"startWith",arguments)}var yW=Xe(class extends qe{constructor(e){super(e);let t=new qe(this.sink);for(var i=arguments.length,r=new Array(i>1?i-1:0),n=1;n<i;n++)r[n-1]=arguments[n];t.next=s=>this.buffer=s,t.complete=Pt,t.subscribe(aD(...r))}next(e){this.buffer&&this.sink.next([e,...this.buffer])}},"withLatestFrom"),TW=Xe(class extends qe{constructor(e,t,i){super(e),this.bufferSize=t,this.startBufferEvery=i,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(e){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(t=>{t.push(e)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(e),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(e=>this.sink.next(e)),super.complete()}},"bufferCount"),SW=Xe(class extends qe{constructor(e,t){super(e),this.buffer=[];let i=new qe(e);i.next=r=>{e.next(this.buffer),this.buffer=[]},i.complete=Pt,i.subscribe(t)}next(e){this.buffer.push(e)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},"buffer"),IW=function(e,t,i,r){return new(i||(i=Promise))(function(n,s){function o(h){try{c(r.next(h))}catch(_){s(_)}}function l(h){try{c(r.throw(h))}catch(_){s(_)}}function c(h){h.done?n(h.value):(function(_){return _ instanceof i?_:new i(function(f){f(_)})})(h.value).then(o,l)}c((r=r.apply(e,[])).next())})};function zr(e){let t=arguments,i=nu()(st(r=>{i.next=n=>r.next(n),i.complete=()=>r.complete(),i.error=n=>r.error(n),e&&r.subscribe(e)},"subject",t));return i.next=Pt,i.complete=Pt,i.error=Pt,i}function oD(e){return st(t=>t.subscribe(e()),"defer",arguments)}var Ho={promise:e=>{Promise.resolve().then(e)},setImmediate:typeof setImmediate<"u"?e=>setImmediate(e):null,setTimeout:e=>setTimeout(e,0)},Kv=typeof Promise<"u"?Ho.promise:Ho.setImmediate?Ho.setImmediate:Ho.setTimeout,lD=e=>t=>{Kv(()=>e(t))},RW=e=>{typeof e=="function"?Kv=e:Ho[e]&&(Kv=Ho[e])},cD=e=>lD(t=>{for(let i=0;!t.disposed&&i<e.length;i++)t.next(e[i]);t.complete()});function AW(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return st(cD(t),"of",arguments)}function bW(e){return st(cD(e),"fromArray",arguments)}function uD(e){return st(t=>{let i=0,r=setInterval(()=>t.next(i++),e);return t.defer(()=>{clearInterval(r)}),"interval"},"interval",arguments)}function Jv(e,t){return st(i=>{let r=0,n=setTimeout(()=>{if(i.removeDefer(s),i.next(r++),t){let o=setInterval(()=>i.next(r++),t);i.defer(()=>{clearInterval(o)})}else i.complete()},e),s=()=>clearTimeout(n);i.defer(s)},"timer",arguments)}function Tp(e,t){return i=>{let r=n=>i.next(n);i.defer(()=>t(r)),e(r)}}function CW(e,t){return st(Tp(e,t),"fromEventPattern",arguments)}function St(e,t){if("on"in e&&"off"in e)return st(Tp(i=>e.on(t,i),i=>e.off(t,i)),"fromEvent",arguments);if("addListener"in e&&"removeListener"in e)return st(Tp(i=>e.addListener(t,i),i=>e.removeListener(t,i)),"fromEvent",arguments);if("addEventListener"in e)return st(Tp(i=>e.addEventListener(t,i),i=>e.removeEventListener(t,i)),"fromEvent",arguments);throw"target is not a EventDispachter"}function dD(e){return st(t=>{e.then(i=>{t.next(i),t.complete()},t.error.bind(t))},"fromPromise",arguments)}function kW(e,t){return st(oD(()=>dD(fetch(e,t))),"fromFetch",arguments)}function wW(e){return st(lD(t=>{try{for(let i of e){if(t.disposed)return;t.next(i)}t.complete()}catch(i){t.error(i)}}),"fromIterable",arguments)}function DW(e){let t=i=>IW(this,void 0,void 0,function*(){try{if(i.disposed)return;let{done:r,value:n}=yield e.read();if(r)return void i.complete();i.next(n),t(i)}catch(r){i.error(r)}});return st(i=>{t(i)},"fromReader",arguments)}function NW(e){return st(t=>{let i=new AbortController,r=i.signal;t.defer(()=>i.abort("cancelled")),e.pipeTo(new WritableStream({write(n){t.next(n)},close(){t.complete()},abort(n){t.error(n)}}),{signal:r}).then(()=>t.complete(),n=>t.error(n))},"fromReadableStream",arguments)}function PW(){return st(e=>{let t=requestAnimationFrame(function i(r){e.disposed||(e.next(r),t=requestAnimationFrame(i))});e.defer(()=>cancelAnimationFrame(t))},"fromAnimationFrame",arguments)}function OW(e,t){return st(function(i){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:e,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:t+e;for(;r<n&&!i.disposed;)i.next(r++);return i.complete(),"range"},"range",arguments)}function MW(e,t){for(var i=arguments.length,r=new Array(i>2?i-2:0),n=2;n<i;n++)r[n-2]=arguments[n];return st(s=>{let o=r.concat(l=>(s.next(l),s.complete()));e.apply(t,o)},"bindCallback",arguments)}function LW(e,t){for(var i=arguments.length,r=new Array(i>2?i-2:0),n=2;n<i;n++)r[n-2]=arguments[n];return st(s=>{let o=r.concat((l,c)=>l?s.error(l):(s.next(c),s.complete()));e.apply(t,o)},"bindNodeCallback",arguments)}function xW(){return st(()=>{},"never",arguments)}function UW(e){return st(t=>t.error(e),"throwError",arguments)}function Yv(){return st(e=>e.complete(),"empty",arguments)}var su=class extends qe{constructor(e,t,i){super(e),this.f=t;let r=()=>{this.sink.next(this.acc),this.sink.complete()};i===void 0?this.next=n=>{this.acc=n,this.complete=r,this.resetNext()}:(this.acc=i,this.complete=r)}next(e){this.acc=this.f(this.acc,e)}},hD=Xe(su,"reduce"),VW=e=>Xe(su,"count")((t,i)=>e(i)?t+1:t,0),FW=()=>Xe(su,"max")(Math.max),BW=()=>Xe(su,"min")(Math.min),HW=()=>Xe(su,"sum")((e,t)=>e+t,0),Sa=Xe(class extends qe{constructor(e,t,i){super(e),this.filter=t,this.thisArg=i}next(e){this.filter.call(this.thisArg,e)&&this.sink.next(e)}},"filter"),WW=Xe(class extends qe{next(e){}},"ignoreElements"),Wo=Xe(class extends qe{constructor(e,t){super(e),this.count=t}next(e){this.sink.next(e),--this.count===0&&(this.doDefer(),this.complete())}},"take"),Ci=Xe(class extends qe{constructor(e,t){super(e);let i=new qe(e);i.next=()=>{i.doDefer(),e.complete()},i.complete=Gv,i.subscribe(t)}},"takeUntil"),GW=Xe(class extends qe{constructor(e,t){super(e),this.f=t}next(e){this.f(e)?this.sink.next(e):(this.doDefer(),this.complete())}},"takeWhile"),jW=e=>hD((t,i)=>(t.push(i),t.length>e&&t.shift(),t),[]),zW=Xe(class extends qe{constructor(e,t){super(e),this.count=t}next(e){--this.count===0&&(this.next=super.next)}},"skip"),KW=Xe(class extends qe{constructor(e,t){super(e),e.next=Pt;let i=new qe(e);i.next=()=>{i.doDefer(),e.resetNext()},i.complete=Gv,i.subscribe(t)}},"skipUntil"),qv=Xe(class extends qe{constructor(e,t){super(e),this.f=t}next(e){this.f(e)||(this.next=super.next,this.next(e))}},"skipWhile"),JW={leading:!0,trailing:!1},YW=class extends qe{constructor(e,t,i){super(e),this.durationSelector=t,this.trailing=i}cacheValue(e){this.last=e,this.disposed&&this.throttle(e)}send(e){this.sink.next(e),this.throttle(e)}throttle(e){this.reset(),this.subscribe(this.durationSelector(e))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},pD=class extends qe{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:JW;super(e),this.durationSelector=t,this.config=i,this._throttle=new YW(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(e){this._throttle.disposed&&this.config.leading?this._throttle.send(e):this._throttle.cacheValue(e)}complete(){this._throttle.throttle=Pt,this._throttle.complete(),super.complete()}},qW=Xe(pD,"throttle"),XW={leading:!1,trailing:!0},QW=e=>Xe(pD,"audit")(e,XW),ZW=class extends qe{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},mD=class extends qe{constructor(e,t){super(e),this.durationSelector=t,this._debounce=new ZW(this.sink),this._debounce.dispose()}next(e){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=e,this._debounce.subscribe(this.durationSelector(e))}complete(){this._debounce.complete(),super.complete()}},$W=Xe(mD,"debounce"),eG=e=>Xe(mD,"debounceTime")(t=>Jv(e)),tG=Xe(class extends qe{constructor(e,t,i){super(e),this.count=t,this.defaultValue=i}next(e){this.count--===0&&(this.defaultValue=e,this.doDefer(),this.complete())}complete(){this.defaultValue!==void 0?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("not enough elements in sequence"))}},"elementAt"),iG=e=>t=>Wo(1)(qv(i=>!e(i))(t)),rG=Xe(class extends qe{constructor(e,t){super(e),this.f=t,this.i=0}next(e){this.f(e)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},"findIndex"),nG=Xe(class extends qe{constructor(e,t,i){super(e),this.f=t,this.defaultValue=i,this.index=0}next(e){(!this.f||this.f(e,this.index++))&&(this.defaultValue=e,this.doDefer(),this.complete())}complete(){this.defaultValue!==void 0?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},"first"),sG=Xe(class extends qe{constructor(e,t,i){super(e),this.f=t,this.defaultValue=i,this.index=0}next(e){(!this.f||this.f(e,this.index++))&&(this.defaultValue=e)}complete(){this.defaultValue!==void 0?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},"last"),aG=Xe(class extends qe{constructor(e,t){super(e),this.predicate=t,this.index=0}next(e){this.predicate(e,this.index++)?this.result=!0:(this.result=!1,this.doDefer(),this.complete())}complete(){this.result!==void 0?(this.sink.next(this.result),super.complete()):this.error(new Error("no elements in sequence"))}},"every"),fD=Xe(class extends qe{constructor(e,t,i){super(e),this.f=t,i===void 0?this.next=r=>{this.acc=r,this.resetNext(),this.sink.next(this.acc)}:this.acc=i}next(e){this.sink.next(this.acc=this.f(this.acc,e))}},"scan"),oG=Xe(class extends qe{constructor(){super(...arguments),this.hasLast=!1}next(e){this.hasLast?this.sink.next([this.last,e]):this.hasLast=!0,this.last=e}},"pairwise"),_D=class extends qe{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},Xv=Xe(_D,"map"),lG=e=>Xe(_D,"mapTo")(t=>e),au=class extends qe{constructor(e,t,i){super(e),this.data=t,this.context=i}next(e){let t=this.context.combineResults;t?this.sink.next(t(this.data,e)):this.sink.next(e)}tryComplete(){this.context.resetComplete(),this.dispose()}},ou=class rP extends qe{constructor(t,i,r){super(t),this.makeSource=i,this.combineResults=r,this.index=0}subInner(t,i){let r=this.currentSink=new i(this.sink,t,this);this.complete===rP.prototype.complete&&(this.complete=this.tryComplete),r.complete=r.tryComplete,r.subscribe(this.makeSource(t,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},gD=class extends au{},vD=class extends ou{next(e){this.subInner(e,gD),this.next=t=>{this.currentSink.dispose(),this.subInner(t,gD)}}},Sp=Xe(vD,"switchMap");function Ip(e){return(t,i)=>e(()=>t,i)}var Rp=Ip(Xe(vD,"switchMapTo")),cG=class extends au{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},ED=class extends ou{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(e){this.next2(e),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),cG),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},uG=Xe(ED,"concatMap"),dG=Ip(Xe(ED,"concatMapTo")),hG=class extends au{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},yD=class extends ou{constructor(){super(...arguments),this.inners=new Set}next(e){this.subInner(e,hG),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(e=>e.resetComplete()):this.dispose()}},pG=Xe(yD,"mergeMap"),mG=Ip(Xe(yD,"mergeMapTo")),fG=class extends au{dispose(){this.context.resetNext(),super.dispose()}},TD=class extends ou{next(e){this.next=Pt,this.subInner(e,fG)}},_G=Xe(TD,"exhaustMap"),gG=Ip(Xe(TD,"exhaustMapTo")),vG=Xe(class extends qe{constructor(e,t){super(e),this.f=t,this.groups=new Map}next(e){let t=this.f(e),i=this.groups.get(t);i===void 0&&(i=zr(),i.key=t,this.groups.set(t,i),super.next(i)),i.next(e)}complete(){this.groups.forEach(e=>e.complete()),super.complete()}error(e){this.groups.forEach(t=>t.error(e)),super.error(e)}},"groupBy"),EG=Xe(class extends qe{constructor(){super(...arguments),this.start=new Date}next(e){this.sink.next({value:e,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},"timeInterval"),yG=Xe(class extends qe{constructor(e,t){super(e),this.miniseconds=t,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(e){this.buffer.push(e)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},"bufferTime"),TG=Xe(class extends qe{constructor(e,t){super(e),this.buffer=[],this.delayTime=t}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(e){this.timeoutId=setTimeout(()=>{let t=this.buffer.shift();if(t){let{time:i,data:r}=t;super.next(r),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(i))}},e)}next(e){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:e})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},"delay"),SD=Xe(class extends qe{constructor(e,t){super(e),this.selector=t}error(e){this.dispose(),this.selector(e)(this.sink)}},"catchError"),SG=class extends au{tryComplete(){let e=this.context.inners.delete(this);super.dispose(),e&&this.context.checkComplete()}next(e){this.sink.next(e),this.context.expandValue(e)}},IG=Xe(class extends ou{constructor(e,t){super(e,t),this.project=t,this.inners=new Set,this.sourceCompleted=!1}next(e){this.sink.next(e),this.expandValue(e)}expandValue(e){let t=new SG(this.sink,e,this);this.currentSink=t,this.complete=this.tryComplete,t.complete=t.tryComplete,this.inners.add(t),t.subscribe(this.makeSource(e,this.index++))}complete(){this.sourceCompleted=!0,this.checkComplete()}checkComplete(){this.sourceCompleted&&this.inners.size===0&&(this.resetComplete(),super.complete())}tryComplete(){this.sourceCompleted=!0,this.checkComplete()}},"expand"),RG=()=>e=>new Promise((t,i)=>{let r;new yp(e,n=>r=n,i,()=>t(r))}),AG=()=>e=>{let t;return new ReadableStream({start(i){t=new yp(e,i.enqueue.bind(i),i.error.bind(i),i.close.bind(i))},cancel(){t.dispose()}})},Qt=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Pt,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Pt,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Pt;return r=>new yp(r,e,t,i)},Qv=Xe(class extends qe{constructor(e,t){super(e),t instanceof Function?this.next=i=>{t(i),e.next(i)}:(t.next&&(this.next=i=>{t.next(i),e.next(i)}),t.complete&&(this.complete=()=>{t.complete(),e.complete()}),t.error&&(this.error=i=>{t.error(i),e.error(i)}))}},"tap"),bG=Xe(class extends qe{constructor(e,t){super(e),this.timeout=t,this.id=setTimeout(()=>this.error(new rD(this.timeout)),this.timeout)}next(e){super.next(e),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},"timeout"),CG=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1/0;return t=>{if(t instanceof fs){let i=st(r=>{let n=e,s=new qe(r);s.error=o=>{n-- >0?s.subscribe(t):r.error(o)},s.sourceId=i.id,s.subscribe(t)},"retry",[e]);return i.source=t,jt.pipe(i),i}return i=>{let r=e,n=new qe(i);n.error=s=>{r-- >0?t(n):i.error(s)},t(n)}}},Zv=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(Zv||{}),lu=class nP extends Wv{constructor(t,i){super({mediaType:t,PlayerClass:i}),m(this,"isRemote",!1),m(this,"deviceId"),m(this,"groupId",""),m(this,"label",""),m(this,"sourceTrack"),m(this,"enableAutoSwitchWhenRecapturing",!0),m(this,"_isRecapturing",!1),m(this,"_lastRecaptureTime",0),m(this,"_onMuteTimeoutId",-1),m(this,"_encodeCheckTimeoutId",-1),m(this,"recaptureMode",0),m(this,"profile"),m(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}get isUseCustomSource(){return!(!this.mediaTrack||this.sourceTrack===this.mediaTrack)}encodeFrame(t,i){throw new Error("Method not implemented.")}installTrackEvent(t){t.addEventListener(D.MUTE,this.onTrackMuted),t.addEventListener(D.UNMUTE,this.onTrackUnmuted),t.addEventListener(D.ENDED,this.onTrackEnded),t.muted&&this.onTrackMuted(),t.readyState===D.ENDED&&this.onTrackEnded()}uninstallTrackEvent(t){t.removeEventListener(D.MUTE,this.onTrackMuted),t.removeEventListener(D.UNMUTE,this.onTrackUnmuted),t.removeEventListener(D.ENDED,this.onTrackEnded)}setStateToReady(){}capture(t){let i=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return P(this,null,function*(){var r;let n=this.sourceTrack;try{let s,o=Ue();$.emit(ie.LOCAL_TRACK_CAPTURE_START,{track:this}),t.customSource?(s=new MediaStream,s.addTrack(t.customSource)):(i||(r=this.sourceTrack)==null||r.stop(),s=yield uW(t));let l=s.getTracks()[0];return yield this.setInputMediaStreamTrack(l),t.customSource||(this.sourceTrack=l,this.updateDeviceIdInUse(),this.listenDeviceChange()),$.emit(ie.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Ue()-o}),s}catch(s){throw $.emit(ie.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:s}),this.log.error("getUserMedia error observed ".concat(s)),s}finally{i&&n?.stop()}})}setOutputMediaStreamTrack(t){var i;if(super.setOutputMediaStreamTrack(t),this.setStateToReady(),this.isPublishing||this.isPublished)return(i=this.room)==null?void 0:i.replaceTrack(this)}get hasFlag(){var t,i;let r=ca(((t=this.room)==null?void 0:t.localPublishFlag)||0,((i=this.room)==null?void 0:i.userId)||"");return this.mediaType===4&&r.hasVideo||this.mediaType===1&&r.hasAudio||this.mediaType===2&&r.hasAuxiliary}publish(t,i){return P(this,null,function*(){return this.room=t,this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=t.userId,this._log.bindParent(t.getLogger()),yield i,this._checkPublishFlag(t)})}_checkPublishFlag(t){return new Promise((i,r)=>P(this,null,function*(){var n,s,o,l,c;let h=()=>r(new me({code:te.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?i():((this.state===et.INIT||this.state==="ready")&&h(),At(St(t,"local-publish-flag-changed"),Sa(()=>this.hasFlag),Ci(jv(St(this,et.INIT),St(this,"ready"))),Qt(i,r,h))),(o=(s=(n=this.room)==null?void 0:n.networkQuality)==null?void 0:s.hadRecentBadUplink)!=null&&o.call(s,2))return i();let _=t.heartbeatCount,f=((c=(l=this.mediaTrack)==null?void 0:l.stats)==null?void 0:c.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(()=>P(this,null,function*(){var T,b,C,x,B,Y,G,he;if((C=(b=(T=this.room)==null?void 0:T.networkQuality)==null?void 0:b.hadRecentBadUplink)!=null&&C.call(b,2)||t.heartbeatCount-_<3)return i();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((x=this.mediaTrack)!=null&&x.stats){let de=this.mediaTrack.stats.totalFrames||0;de-f===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",de)}let H=this.kind===D.AUDIO,Z=this.stat.bytesSent>0;if(ce[Z?"addSuccessEvent":"addFailedEvent"]({key:H?503700:513702}),!H){let de={H264:513704,H265:513705,VP8:513706}[((Y=(B=this.room)==null?void 0:B.videoCodec)==null?void 0:Y.toUpperCase())||"H264"];de&&ce[Z?"addSuccessEvent":"addFailedEvent"]({key:de})}if(!Z){if(ce.addEnum({key:H?503701:513703,value:tp()}),dt.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(Lo()||xo()),userId:this.userId}),this.log.warn(H?"encode failed":"".concat((he=(G=this.room)==null?void 0:G.videoCodec)==null?void 0:he.toUpperCase()," encode failed")),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield Br(5e3),this.stat.bytesSent>0||this.hasFlag)))return i();this.emit("6",this),r(new me({message:"".concat(this.strMediaType," encode failed"),code:H?te.AUDIO_ENCODE_FAILED:te.VIDEO_ENCODE_FAILED}))}}}),1e4)}))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),$.emit(ie.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return P(this,null,function*(){if(this.sourceTrack&&Fo){let{deviceId:t,groupId:i}=this.sourceTrack.getSettings(),{label:r}=this.sourceTrack;(yield(function(n){return P(this,arguments,function(s){let{newDeviceId:o,oldDeviceId:l,oldGroupId:c,oldLabel:h,kind:_}=s;return(function*(){return o===l&&(_!==D.AUDIO||o!==pc||(yield Jw(c,h)))})()})})({newDeviceId:t,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=t,this.label=r,i&&(this.groupId=i),fp().then(n=>{let s=n.find(o=>{let l=o.deviceId===t;return i&&(l=l&&o.groupId===i),l});s&&this.emit("2",s)}))}})}setProfile(t){this.log.info("setProfile",t),Object.assign(this.profile,t)}isNeedToRecapture(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return!(!this.deviceId||!this.sourceTrack||this.kind===D.AUDIO&&!(function(i){if(i instanceof CanvasCaptureMediaStreamTrack||!(i instanceof MediaStreamTrack))return!1;let r=i.label.toLocaleLowerCase();if(r.includes("mic")||r.includes("麦克风"))return!0;let n="".concat((i?.getSettings()||{}).deviceId,"_").concat(D.AUDIO_INPUT);return!!Bv.has(n)})(this.sourceTrack)||this.kind===D.VIDEO&&!(function(i){if(i instanceof CanvasCaptureMediaStreamTrack||!(i instanceof MediaStreamTrack))return!1;let r=i.label.toLocaleLowerCase();if(r.includes("camera")||r.includes("webcam"))return!0;let n="".concat((i?.getSettings()||{}).deviceId,"_").concat(D.VIDEO_INPUT);return!!Bv.has(n)})(this.sourceTrack)||this._isRecapturing||t&&us&&ri)}onTrackMuted(){if(super.onTrackMuted(),dW(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<fc)return void setTimeout(()=>this.onTrackMuted(),fc);this._onMuteTimeoutId=setTimeout(()=>P(this,null,function*(){var t;if((t=this.sourceTrack)!=null&&t.muted){if((Gt||Vt)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return P(this,null,function*(){if(xi(nP.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTime<fc)return void setTimeout(()=>this.onTrackEnded(),fc);this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(t){let i=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return P(this,null,function*(){var r;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let n=this.sourceTrack;i||(r=this.sourceTrack)==null||r.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let s={useExactDeviceId:!0};if(t==="user"||t==="environment")s.facingMode=t;else{let o;(this.kind==="audio"?yield Tn():yield Sn()).find(l=>l.deviceId===t)&&(o=t),s.deviceId=o}return this.capture(s,i).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),$.emit(ie.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(o=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(o.message)),this.emit("5",o),$.emit(ie.LOCAL_TRACK_RECAPTURE,{track:this,error:o})}).finally(()=>{i&&n?.stop()})})}getRecoverCaptureDeviceId(){return P(this,null,function*(){let t=this instanceof Rn;if(t&&this.facingMode)return this.facingMode;let{deviceId:i}=this;if(i){let r=(uu.get(i)||0)+1;if(uu.set(i,r),r>=3&&this.enableAutoSwitchWhenRecapturing){let n=t?(yield Sn()).find(s=>!uu.has(s.deviceId)):(yield Tn()).find(s=>!uu.has(s.deviceId));n&&(this.log.warn("".concat(i," capture fail ").concat(r," times, change new ").concat(n.deviceId)),i=n.deviceId)}}return i})}stopCapture(){var t;this.sourceTrack&&(this.sourceTrack.stop(),this.uninstallTrackEvent(this.sourceTrack)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),(t=this.manager)==null||t.removeInput(this)}close(){super.close(),this.stopCapture()}};_e([ni(et.INIT,"ready",{ignoreError:!0,sync:!0})],lu.prototype,"setStateToReady"),_e([ru()],lu.prototype,"capture"),_e([ni("ready","publish",{ignoreError:!0,success(){$.emit(ie.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(e){var t;(t=this.room)==null||t.localTracks.delete(this);let i="error",r=e instanceof me?e:e.cause instanceof me?e.cause:e,n=!1;r instanceof me&&(r.message.includes("timeout")?i="timeout":r.code===te.API_CALL_ABORTED&&(n=!0,i="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:i,error:r}),this.log[n?"info":"error"]("publish failed",r)}}),ms(521714,!1)],lu.prototype,"publish"),_e([_t(e=>function(){return P(this,null,function*(){let t=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),ni([],"ready",{sync:!0})],lu.prototype,"unpublish");var cu=lu,uu=new Map;$.on(ie.SWITCH_DEVICE_SUCCESS,e=>{e.track.deviceId&&uu.delete(e.track.deviceId)});var Ia=class yu extends cu{constructor(t){super(1,sW),m(this,"mediaType",1),m(this,"volume",0),m(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),m(this,"playerMuted",!0),m(this,"pipeline"),m(this,"earMonitorGainNode",new gi),m(this,"_output",new gi),m(this,"codecPipeline",[]),m(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),m(this,"mixedAudioReferenceMap",new Map),m(this,"isAudioContextLongSuspended",!1),m(this,"after3aSilenceStartTime",0),this.manager=t,this.pipeline=new Hw(t),this.pipeline.source.pipeTo(this.player.pipeline.volumeMeter),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeterAfter3A),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this),$.on(ie.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return mp.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let t=(this.volume||super.getAudioLevel())*this.captureVolume;return t>1?1:t}getInternalAudioLevelAfter3A(){if(this.pipeline.isProcessEnabled)return this.player.getInternalAudioLevelAfter3A()}updateAfter3aSilenceStartTime(t){j(t)||(t!==0||this.after3aSilenceStartTime?t>0&&(this.after3aSilenceStartTime=0):this.after3aSilenceStartTime=Ue())}setInputMediaStreamTrack(t){return P(this,null,function*(){let i=this.trackSettings||{};ce.addEnum({key:501701,value:i.channelCount||0,useUV:!1}),ce.addEnum({key:501702,value:i.sampleRate||0,useUV:!1}),ce.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:n}=i;this._log.info("local audio track input ".concat(JSON.stringify({sampleRate:r,channelCount:n}))),this.pipeline.source.channelCount=n||1,this.pipeline.replaceSource(t),yield xi(yu.prototype,this,"setInputMediaStreamTrack").call(this,t),this.updatePlayingState(!!t)})}capture(t){return P(this,arguments,function(i){var r=this;let{deviceId:n,customSource:s,useExactDeviceId:o=!0,retryWhenExactFailed:l}=i,c=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return(function*(){let h=yield xi(yu.prototype,r,"capture").call(r,{video:!1,audio:!0,microphoneId:n,echoCancellation:r.profile.echoCancellation,autoGainControl:r.profile.autoGainControl,noiseSuppression:r.profile.noiseSuppression,sampleRate:r.profile.sampleRate,channelCount:r.profile.channelCount,useExactDeviceId:o,retryWhenExactFailed:l,customSource:s},c);return tu(),h})()})}switchDevice(t){return P(this,null,function*(){if(this.mediaTrack){if(this.deviceId===t&&!this.isUseCustomSource&&(t!==pc||(yield Jw(this.groupId,this.label))))return;try{this.log.info("switchDevice audio to: ".concat(t)),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:t,useExactDeviceId:!0,retryWhenExactFailed:!1}),$.emit(ie.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(i){throw this.log.error("switch microphone failed ".concat(i)),this.deviceId&&this.recapture(this.deviceId),i}}})}listenDeviceChange(){Xt&&!Xt.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&Xt.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(t){return P(this,null,function*(){if(t.deviceId===this.deviceId){let i=this.recaptureMode===1;if(this.log.warn("RecaptureMode: ".concat(Zv[this.recaptureMode],". Current microphone is lost: ").concat(JSON.stringify(t))),this.recaptureMode===0){Ht(this.userId,{eventId:2003,param1:6,streamType:1});let r=yield Tn();r[0]?this.recapture(r[0].deviceId):i=!0}i&&Xt.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(t){this.recaptureMode===1&&t.deviceId!==this.deviceId||(Xt.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn("microphone added: ".concat(JSON.stringify(t))),this.recapture(t.deviceId))}update3A(t){return P(this,arguments,function(i){var r=this;let{echoCancellation:n,noiseSuppression:s,autoGainControl:o}=i;return(function*(){let l=r.sourceTrack||r.mediaTrack;if(!l)return;let c=l.getConstraints(),h=!1;!j(n)&&n!==r.profile.echoCancellation&&(r.profile.echoCancellation=n,c.echoCancellation=n,h=!0),!j(s)&&s!==r.profile.noiseSuppression&&(r.profile.noiseSuppression=s,c.noiseSuppression=s,h=!0),!j(o)&&o!==r.profile.autoGainControl&&(r.profile.autoGainControl=o,c.autoGainControl=o,h=!0),h&&(ut||ri?yield l.applyConstraints(c).catch(_=>r._log.warn("update3A failed: ",_)):r.deviceId&&(yield r.recapture(r.deviceId,!0)))})()})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(t){this.pipeline.setVolume(t/100),this.pipeline.gain.node&&ce.addEnum({key:502700,value:2})}setAudioVolume(t){super.setAudioVolume(0),Gt&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(pi().createGain()),this._output.setNode(pi().destination)),this.earMonitorGainNode.node.gain.value=t}enableTrackANS(t){return this.update3A({noiseSuppression:t})}enableTrackAEC(t){if(this.sourceTrack&&!ri&&!Gt)return this.update3A({echoCancellation:t})}addDenoiser(t){var i;lr<=92&&((i=this.trackSettings)==null?void 0:i.sampleRate)!==48e3?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(ce.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(t),this.enableTrackANS(!1))}mixAudioReference(t,i){if(this.mixedAudioReferenceMap.has(i))return;this.log.info("mixAudioReference() => ".concat(i));let r=Vv(t);if(!r)return;let n=new gi,s=pi().createGain();s.gain.value=1;let o=new gi;n.pipeTo(o).pipeTo(this.pipeline.mixNode),n.setNode(r),o.setNode(s),this.mixedAudioReferenceMap.set(i,[n,o])}unMixAudioReference(t){let[i,r]=this.mixedAudioReferenceMap.get(t)||[];i&&(this.log.info("unMixAudioReference() => ".concat(t)),i.deleteNode(),r?.deleteNode(),this.mixedAudioReferenceMap.delete(t))}setAudioReferenceVolume(t,i){let[r,n]=this.mixedAudioReferenceMap.get(t)||[];n!=null&&n.node&&(n.node.gain.value=i/100,this.log.info("setAudioReferenceVolume() => ".concat(t," ").concat(n.node.gain.value)))}addAudioProcessor(t,i,r){this.pipeline.silentNode.setNode(r),this.pipeline.mixNode.setNode(i),this.pipeline.aec.setNode(t)}removeDenoiser(t){if(this.pipeline.denoiser.node===t)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(t){this.pipeline.aec.node===t&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode())}close(){this.mixedAudioReferenceMap.forEach(t=>{let[i,r]=t;i.deleteNode(),r.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),Xt.off("audioInputAdded",this.handleMicrophoneAdded,this),Xt.off("audioInputRemoved",this.handleMicrophoneRemoved,this),$.off(ie.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(t){let i=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return P(this,null,function*(){try{yield xi(yu.prototype,this,"recapture").call(this,t,i)}catch(r){let n=(yield Tn()).find(s=>s.deviceId!==t);if(!n)throw r;yield xi(yu.prototype,this,"recapture").call(this,n.deviceId)}})}encodeFrame(t){return this.manager?this.manager.encodePipeline.reduceRight((i,r)=>r?r({frame:i,ntp:ac()}):i,t):t}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some(t=>t)}get enableEncryptFrame(){return this.manager&&!!this.manager.encodePipeline[0]}handleAudioContextLongSuspended(t){let{isSuspended:i}=t;if(this.pipeline.isProcessEnabled)if(i){this.isAudioContextLongSuspended=!0,this.log.warn("context has suspended for ".concat(1.5," seconds, change to source audio").concat(pa?"":", non-Safari"));let r=this.sourceTrack||this.mediaTrack;r&&this.setOutputMediaStreamTrack(r)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(t){if(this.isAudioContextLongSuspended){let i=this.sourceTrack||this.mediaTrack;i&&(t=i)}super.setOutputMediaStreamTrack(t)}};function Ap(e,t){return t+4<=e.byteLength&&e.getUint8(t)===0&&e.getUint8(t+1)===0&&e.getUint8(t+2)===0&&e.getUint8(t+3)===1?4:t+3<=e.byteLength&&e.getUint8(t)===0&&e.getUint8(t+1)===0&&e.getUint8(t+2)===1?3:0}function ID(e){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1],i=new DataView(e),r=[],n=0;for(;n<i.byteLength;){let s=Ap(i,n);if(s===0){n+=1;continue}let o=-1;for(let f=n+s;f<i.byteLength;f+=1)if(Ap(i,f)>0){o=f;break}let l=o===-1?i.byteLength:o,c=l-n,h=new ArrayBuffer(c),_=new DataView(h);for(let f=0;f<c;f+=1)_.setUint8(f,i.getUint8(n+f));r.push(new bp(_,t)),n=l}return r}var bp=class{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];this.dataView=e,this.isSEI&&(t?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let{seiPayloadStartIndex:e}=this,t=this.dataView.byteLength-2,i=[],r=0;for(let s=e;s<=t;s++){let o=this.dataView.getInt8(s);switch(o){case 0:case 1:case 2:case 3:r===2&&(i.push(3),r=0),o===0?r+=1:r=0,i.push(o);break;default:r=0,i.push(o)}}i.push(this.dataView.getInt8(this.dataView.byteLength-1));let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=n}removePreventionByte(){let{seiPayloadStartIndex:e}=this,t=this.dataView.byteLength-1,i=[],r=0;for(let s=e;s<=t;s++)switch(this.dataView.getInt8(s)){case 0:r++,i.push(this.dataView.getInt8(s));break;case 3:r!==2&&i.push(this.dataView.getInt8(s)),r=0;break;default:i.push(this.dataView.getInt8(s)),r=0}let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=n}get seiPayloadStartIndex(){let e=6;for(let t=6;t<this.dataView.buffer.byteLength&&(e+=1,this.dataView.getUint8(t)===255);t+=1);return e}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let e=0,t=6;for(let s=6;s<this.dataView.buffer.byteLength;s+=1){let o=this.dataView.getUint8(s);if(t+=1,o!==255){e+=o;break}e+=255}let i=new ArrayBuffer(e),r=new DataView(i),n=t;for(let s=0;s<i.byteLength;s+=1)r.setInt8(s,this.dataView.getInt8(n+s));return r}get naluType(){let e=this.getStartCodeLength();return e>=this.dataView.byteLength?0:31&this.dataView.getUint8(e)}getStartCodeLength(){return this.dataView.byteLength>=4&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===0&&this.dataView.getUint8(3)===1?4:this.dataView.byteLength>=3&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===1?3:0}get isIDR(){return this.naluType===5}get isSPS(){return this.naluType===7}get isPPS(){return this.naluType===8}get isSEI(){return this.naluType===6}},kG=class{constructor(){m(this,"_seiMessageList",[]),m(this,"_smallSeiMessageList",[]),m(this,"_seiPayloadType",243)}encodeSEINalu(e){let t=e.byteLength,i=parseInt(String(t/255),10),r=t%255,n=[];n.push(0,0,0,1,6,this._seiPayloadType);for(let o=0;o<i;o++)n.push(255);n.push(r);let s=new DataView(e);return n.push(...new Uint8Array(s.buffer)),n.push(128),new bp(new DataView(new Uint8Array(n).buffer),!0)}sendSEI(e,t){t!=null&&t.seiPayloadType&&(this._seiPayloadType=t.seiPayloadType),this._seiMessageList.push(e),t!=null&&t.small&&this._smallSeiMessageList.push(e)}isEmpty(){return!this._seiMessageList.length}getNaluCount(e){let t=0,i=0,r=new DataView(e);for(let n=0;n<e.byteLength;n++)switch(r.getUint8(n)){case 0:t++;break;case 1:(t===2||t===3)&&i++,t=0;break;default:t=0}return i}encode(e,t){let i=t?this._smallSeiMessageList:this._seiMessageList;if(i.length>0&&e.data.byteLength>0){let r=9-this.getNaluCount(e.data);if(r<=0)return 0;let n=i.splice(0,r).reverse().map(this.encodeSEINalu.bind(this)),s=n.reduce((_,f)=>_+f.dataView.byteLength,0),o=new ArrayBuffer(s+e.data.byteLength),l=new DataView(o),c=new DataView(e.data),h=0;for(let _=0;_<n.length;_++)for(let f=0;f<n[_].dataView.byteLength;f++)l.setInt8(h++,n[_].dataView.getInt8(f));for(let _=0;_<e.data.byteLength;_++)l.setInt8(h++,c.getInt8(_));return e.data=o,n.length}return 0}},RD=class Qo extends cu{constructor(t){super(arguments.length>1&&arguments[1]!==void 0?arguments[1]:4,jr),m(this,"profile",ve({},cc)),m(this,"avoidCropping",!1),m(this,"_scaleResolutionDownBy"),m(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0}),m(this,"small"),m(this,"isNeedToSetBandwidth"),m(this,"muteImage"),m(this,"manager"),m(this,"_seiCodec",new kG),this.manager=t;let i=()=>{var r;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{let n=os(((r=this.room)==null?void 0:r.sdkAppId)||0)?$g:Zg;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(n)),this.setProfile(xe(ve({},this.profile),{width:1920,height:1080})),this.applyProfile()}};this.on("input-media-track-changed",i),this.on("publish",i),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(Fo&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get contentHint(){var t;return((t=this._inputTrack)==null?void 0:t.contentHint)||""}get isQosClearFirst(){var t;return((t=this._inputTrack)==null?void 0:t.contentHint)==="detail"}get hasSmall(){var t;return!((t=this.manager)==null||!t.hasSmall)}setMute(t){return P(this,null,function*(){var i,r,n;if(pt(t)){if(this.muteImage===t)return;yield(i=this.manager)==null?void 0:i.deleteWatermark("mute"),yield(r=this.manager)==null?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:t,fillVideo:!0}),this.muteImage=t,xi(Qo.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(n=this.manager)==null?void 0:n.deleteWatermark("mute"),this.muteImage=void 0),xi(Qo.prototype,this,"setMute").call(this,t)})}capture(t){return P(this,arguments,function(i){var r=this;let{deviceId:n,facingMode:s,useExactDeviceId:o=!0,customSource:l,retryWhenExactFailed:c=!0}=i;return(function*(){let h={audio:!1,video:!0,facingMode:s||r.facingMode,cameraId:n,width:r.profile.width,height:r.profile.height,frameRate:r.profile.frameRate,useExactDeviceId:o,retryWhenExactFailed:c,customSource:l};if(h.facingMode==="environment"){let _=yield r.getDeviceIdWhenUsingBackCamera();_&&(h.cameraId=_)}return xi(Qo.prototype,r,"capture").call(r,h)})()})}setProfile(t){var i;let r=this.fallbackProfile(t);if(r.bitrate&&(this.isNeedToSetBandwidth=r.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(r);else{let n=os(((i=this.room)==null?void 0:i.sdkAppId)||0)?$g:Zg;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(n)),super.setProfile(xe(ve({},this.profile),{width:1920,height:1080}))}}applyProfile(){return P(this,null,function*(){var t;if(!this.mediaTrack)return;let{width:i=0,height:r=0}=(this.sourceTrack||this.mediaTrack).getSettings(),n=i*r,s=this.settings,o=s.height!==this.profile.height||s.width!==this.profile.width||s.frameRate!==this.profile.frameRate;if(o&&(Sr===16&&this.deviceId?yield this.recapture(this.deviceId):(yield(t=this.sourceTrack||this.mediaTrack)==null?void 0:t.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;let{width:l=0,height:c=0}=(this.sourceTrack||this.mediaTrack).getSettings(),h=l*c;return o&&h&&n&&h===n?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:D.VIDEO,videoType:D.BIG})}})}get settings(){let t={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},i=this.sourceTrack||this.mediaTrack;return Fo&&i&&Object.assign(t,i.getSettings()),t}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:Vh(this.settings,this.profile)}isAllowed2k4k(t){var i;return!(this.room&&this.room.scheduleResult&&!this.isScreen&&!(t.height*t.width<3686400))||((i=this.room.scheduleResult.trtcAutoConf)==null?void 0:i["2k4k"])===1}isNeedToSwitchDevice(t){return!(!this.mediaTrack||this.deviceId===t||this.facingMode===t)}switchDevice(t){return P(this,null,function*(){try{if(!this.isNeedToSwitchDevice(t)&&!this.isUseCustomSource)return;let i={useExactDeviceId:!0,retryWhenExactFailed:!1};t==="user"||t==="environment"?i.facingMode=t:i.deviceId=t,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(i),$.emit(ie.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(i){throw this.log.error("switch camera failed ".concat(i)),this.deviceId&&this.recapture(this.deviceId),i}})}getDeviceIdWhenUsingBackCamera(){return P(this,null,function*(){let t;try{if(Y0&&!Lc&&mw){let i=(yield Sn(!0)).map(n=>{var s;return xe(ve({},n),{capabilities:(s=n.getCapabilities)==null?void 0:s.call(n)})}).filter(n=>{var s,o;return(o=(s=n.capabilities)==null?void 0:s.facingMode)==null?void 0:o.includes("environment")}),r=i[0];i.forEach(n=>{var s,o,l,c;let{capabilities:h}=n;((s=h.width)!=null&&s.max&&(o=h.height)!=null&&o.max?h.width.max*h.height.max:0)>((l=r.capabilities.width)!=null&&l.max&&(c=r.capabilities.height)!=null&&c.max?r.capabilities.width.max*r.capabilities.height.max:0)&&(r=n)}),r!=null&&r.capabilities&&(this._log.info("use max resolution back camera",r),t=r.deviceId)}}catch(i){this._log.warn("get max res camera failed",i)}return t})}updateSmallConfig(t){return P(this,null,function*(){var i,r;this._log.info("update small stream config: ".concat(JSON.stringify(t)));let n=!this.small;this.small=this.fallbackProfile(t,!0),yield(i=this.manager)==null?void 0:i.update(),n&&(yield(r=this.room)==null?void 0:r.enableSmall(!0)),this.log.info("update small stream config success")})}fallbackProfile(t){let i=arguments.length>1&&arguments[1]!==void 0&&arguments[1],r=t.width>t.height,n=ve({},t);return t.width*t.height<=19200&&Vt&&or&&(this.log.warn("".concat(i?"small ":"","resolution is ").concat(t.width,"*").concat(t.height,", fallback to 240*180 for android chrome")),n.width=r?240:180,n.height=r?180:240,n.bitrate=Math.max(t.bitrate,150)),t.width*t.height>921600&&X2&&(n.width=r?1280:720,n.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),ev(cr,"14.3")&&tv(cr,"14.0",!0)&&this.on("7",()=>{let s=this.profile.width>this.profile.height;this.profile.width*this.profile.height>307200?(this.profile.width=s?640:480,this.profile.height=s?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>230400&&(this.profile.width=s?640:360,this.profile.height=s?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!i&&this.avoidCropping&&(or||ut)&&!iv()&&t.width*t.height<=230400&&t.width/t.height===16/9&&(this._scaleResolutionDownBy=1280/t.width,t.width=1280,t.height=720,this.log.warn("capture 720p, scale: ".concat(this._scaleResolutionDownBy))),n}stopSmall(){var t,i;this.small&&(delete this.small,(t=this.manager)==null||t.update(),(i=this.room)==null||i.enableSmall(!1))}listenDeviceChange(){Xt&&!Xt.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&Xt.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(t){return P(this,null,function*(){if(t.deviceId===this.deviceId){let i=this.recaptureMode===1;if(this.log.warn("RecaptureMode: ".concat(Zv[this.recaptureMode],". Current camera is lost: ").concat(JSON.stringify(t))),this.recaptureMode===0){Ht(this.userId,{eventId:2003,param1:7,streamType:2});let r=yield Sn();r[0]?this.recapture(r[0].deviceId):i=!0}i&&Xt.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(t){return P(this,null,function*(){this.recaptureMode===1&&t.deviceId!==this.deviceId||(Xt.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn("camera added: ".concat(JSON.stringify(t))),this.recapture(t.deviceId))})}encodeFrame(t,i){if(!this.manager)return t;let r=i?8:this.mediaType;return this.manager.encodePipeline.reduceRight((n,s)=>s?s({frame:n,mediaType:r}):n,t)}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some(t=>t)}play(t,i){return j(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(t,i)}close(){Xt.off("videoInputAdded",this.handleCameraAdded,this),Xt.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(t){return P(this,null,function*(){try{yield xi(Qo.prototype,this,"recapture").call(this,t)}catch(i){let r=(yield Sn()).find(n=>n.deviceId!==t);if(!r)throw i;yield xi(Qo.prototype,this,"recapture").call(this,r.deviceId)}})}setContentHint(t){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==t&&(this.log.info("setContentHint ".concat(t)),this.mediaTrack.contentHint=t),this.outMediaTrack&&this.outMediaTrack.contentHint!==t&&(this.outMediaTrack.contentHint=t))}setRotation(t){this.manager&&(this.isScreen||j(t)||t!==this.rotation&&(this.rotation=t,this.manager.rotation=t))}};_e([Ta(function(e){this.setContentHint(e.contentHint||"motion")})],RD.prototype,"capture");var Rn=RD,AD={};pn(AD,{REPORT_TYPE:()=>C0,buildSSOPackage:()=>wo,bytes2ms:()=>T2,calculateScaleResolutionDownNumber:()=>Vh,concatArrayBuffers:()=>k0,convertObjectNumberToInt:()=>Uh,copyProperties:()=>y2,deepClone:()=>ko,deepCloneBasic:()=>Fh,deepMerge:()=>gn,delay:()=>Br,fibonacci:()=>Co,formatedTime:()=>P2,getConstructorName:()=>Oh,getContainerFromElement:()=>N2,getEnv:()=>f2,getFirst16Bits:()=>M2,getInternalVersion:()=>w2,getLast16Bits:()=>w0,getLoggerUrl:()=>bo,getMediaStreamTrackInfo:()=>b0,getMuteStateFromFlag:()=>ca,getNetworkType:()=>Ph,getNumNetworkType:()=>Ec,getReconnectionTimeout:()=>la,getStringByteLength:()=>xh,getTestSignalDomain:()=>_2,getTurnServer:()=>D2,getUint32Version:()=>I0,getValueType:()=>ii,getViewListFromView:()=>Rc,glog:()=>I2,ipv4ToUint32:()=>Ic,isArray:()=>Jt,isAudioWorkletSupported:()=>b2,isBoolean:()=>Rt,isConstructor:()=>Tc,isEmpty:()=>Mh,isFunction:()=>Ut,isLangChinese:()=>_n,isMediaStreamTrack:()=>R2,isNumber:()=>nt,isObject:()=>Fr,isOverseaSdkAppId:()=>os,isPlainObject:()=>nr,isPortrait:()=>S0,isPromise:()=>yc,isRemoteTrack:()=>A2,isRotate90Or270:()=>ls,isSetSinkIdSupported:()=>C2,isString:()=>pt,isUndefined:()=>j,loadImage:()=>Ac,loadVideo:()=>O2,ms2bytes:()=>S2,ms2samples:()=>T0,normalizeUrl:()=>A0,performanceNow:()=>Ue,promiseAny:()=>Sc,samples2ms:()=>y0,setNetworkTypeFromWebRTC:()=>E0,stringify:()=>Tr,stringifyIncludeValue:()=>Lh,throttlePromise:()=>R0});var wG=[-1,-1,1,-1,-1,1,1,1],DG=[0,0,1,0,0,1,1,1],du=class OE extends et{constructor(t,i){if(super(),this.context=t,m(this,"name"),m(this,"input"),m(this,"output"),m(this,"texture"),m(this,"ctx2d",null),m(this,"fbo"),m(this,"width",0),m(this,"height",0),m(this,"x",0),m(this,"y",0),m(this,"program"),m(this,"vertexShader"),m(this,"fragmentShader"),m(this,"totalFrames",0),m(this,"dropFrames",0),m(this,"matchInputSize",!0),m(this,"texCoordBuffer"),m(this,"positionBuffer"),m(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),m(this,"cost",0),m(this,"_canvas",null),m(this,"_image"),m(this,"log"),this.context.on("disconnect",this.close,this),this.name=i.name,this.log=i.logger,this.matchInputSize=i.matchInputSize!==!1,this.width=i.width||t.width,this.height=i.height||t.height,this._image=i.image,t instanceof Kr)t.ctx&&i.create2d&&(typeof OffscreenCanvas=="function"&&Sr!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);else try{let r=t.ctx;this.texCoordBuffer=this.createBuffer(DG),this.positionBuffer=this.createBuffer(wG),i.createTexture!==!1&&(this.texture=r.createTexture(),this.useTexture(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.UNPACK_ALIGNMENT,1)),i.useFbo&&(this.fbo=r.createFramebuffer(),this.useBufferFrame(),this.useTexture(),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,this.width,this.height,0,r.RGBA,r.UNSIGNED_BYTE,null),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.texture,0)),i.useDefaultProgram?this.program=t.defaultProgam:(i.vertexShaderSource||i.fragmentShaderSource)&&(this.vertexShader=i.vertexShaderSource?t.createShader(r.VERTEX_SHADER,i.vertexShaderSource):t.defaultVShader,this.fragmentShader=i.fragmentShaderSource?t.createShader(r.FRAGMENT_SHADER,i.fragmentShaderSource):t.defaultFShader,this.program=t.createProgram(this.vertexShader,this.fragmentShader))}catch(r){this.context.destroy(new me({code:te.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(r.message||r)}))}}get image(){return this._image}set image(t){this._image=t}createFramebuffer(t){let i=this.context.ctx,r=i.createFramebuffer();return i.bindFramebuffer(i.FRAMEBUFFER,r),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,t,0),r}connect(t){for(var i=arguments.length,r=new Array(i>1?i-1:0),n=1;n<i;n++)r[n-1]=arguments[n];return t.addInput(this,...r),this.output=t,t}addInput(t){this.input=t,this.matchInputSize&&t.width&&t.height&&this.resize(t.width,t.height)}requestFrame(t){let i=Date.now();return!!(this.context instanceof ur&&this.render(t)||this.context instanceof Kr&&this.render2d(t))&&(this.totalFrames++,this.cost=Date.now()-i,!0)}render2d(t){var i;return!((i=this.input)==null||!i.requestFrame(t))&&this.draw2d(this.input.image,0,0,this.width,this.height)}update(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;var i;(i=this.output)==null||i.update(t)}disconnect(){for(var t,i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];(t=this.output)==null||t.removeInput(this,...r),delete this.output}removeInput(t){delete this.input}close(){var t,i;if(this.context.off("disconnect",this.close,this),(t=this.output)==null||t.removeInput(this),delete this.output,(i=this.input)==null||i.disconnect(),this.context instanceof ur){let r=this.context.ctx;r.deleteBuffer(this.texCoordBuffer),r.deleteBuffer(this.positionBuffer),this.fbo&&r.deleteFramebuffer(this.fbo),this.texture&&r.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&r.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&r.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&r.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var t;this.useTextures((t=this.input)==null?void 0:t.texture)}useTextures(){let t=this.context.ctx;for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];r.forEach((s,o)=>{s&&(t.activeTexture(t.TEXTURE0+o),t.bindTexture(t.TEXTURE_2D,s))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let t=this.context.ctx;t.bindFramebuffer(t.FRAMEBUFFER,this.fbo||null)}createBuffer(t){let i=this.context.ctx,r=i.createBuffer();return i.bindBuffer(i.ARRAY_BUFFER,r),i.bufferData(i.ARRAY_BUFFER,new Float32Array(t),i.STATIC_DRAW),r}setTexBuffer(t){let i=this.context.ctx;i.bindBuffer(i.ARRAY_BUFFER,this.texCoordBuffer),i.bufferData(i.ARRAY_BUFFER,new Float32Array(t),i.STATIC_DRAW)}setPosBuffer(t){let i=this.context.ctx;i.bindBuffer(i.ARRAY_BUFFER,this.positionBuffer),i.bufferData(i.ARRAY_BUFFER,new Float32Array(t),i.STATIC_DRAW)}changeBufferData(t,i){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,t),r.bufferData(r.ARRAY_BUFFER,new Float32Array(i),r.STATIC_DRAW)}setAttributes(){let t=this.context.ctx;for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];r.forEach((s,o)=>{t.enableVertexAttribArray(o),t.bindBuffer(t.ARRAY_BUFFER,s),t.vertexAttribPointer(o,2,t.FLOAT,!1,0,0)})}getVertexPoint(t,i){return[t/this.width*2-1,i/this.height*2-1]}layout2texCoords(t){return[...this.getVertexPoint(t.x,t.y),...this.getVertexPoint(t.x+t.width,t.y),...this.getVertexPoint(t.x,t.y+t.height),...this.getVertexPoint(t.x+t.width,t.y+t.height)]}resize(t,i){if(this.width!==t||this.height!==i){if(this.width=t,this.height=i,this._canvas&&(this._canvas.width=t,this._canvas.height=i),this.texture&&this.fbo){this.useTexture();let r=this.context.ctx;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,t,i,0,r.RGBA,r.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(t,i)}}draw(t,i){this.setAttributes(t||this.positionBuffer,i||this.texCoordBuffer);let r=this.context.ctx;r.drawArrays(r.TRIANGLE_STRIP,0,4)}draw2d(t,i,r,n,s,o,l,c,h){let _=!(j(o)||j(l)||j(c)||j(h));return!(!this.ctx2d||!t)&&(t instanceof ImageData?(_?this.ctx2d.putImageData(t,i,r,o,l,c,h):this.ctx2d.putImageData(t,i,r),this.emit(OE.RENDER,this.ctx2d.canvas)):(_?this.ctx2d.drawImage(t,o,l,c,h,i,r,n,s):this.ctx2d.drawImage(t,i,r,n,s),this.emit(OE.RENDER,t)),typeof VideoFrame<"u"&&t instanceof VideoFrame&&t.close(),!0)}drawBackGround2d(t){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=t,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var t;let{totalFrames:i,x:r,y:n,width:s,height:o,name:l,cost:c}=this,h=Date.now(),_=(i-this.lastInfo.totalFrames)/((h-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:i,x:r,y:n,width:s,height:o,timestamp:h,fps:_,name:l,cost:c},ve({parent:(t=this.input)==null?void 0:t.getInfo()},this.lastInfo)}createTexture(t){let i=this.context.ctx,r=i.createTexture();return this.useTextures(r),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.pixelStorei(i.UNPACK_ALIGNMENT,1),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,i.RGBA,i.UNSIGNED_BYTE,t),r}};m(du,"RENDER","render"),_e([ni(et.INIT,"connected",{sync:!0})],du.prototype,"connect"),_e([ni("connected",et.INIT,{ignoreError:!0,sync:!0})],du.prototype,"disconnect"),_e([ni([],"closed",{sync:!0})],du.prototype,"close");var Gi=du,NG=At(uD(250),Xv(()=>performance.now()),nu()),PG=[0,1,1,1,0,0,1,0],$v=class extends Gi{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),m(this,"_intervalId",0),m(this,"_sequence",0),m(this,"checkGLError",!1),m(this,"checkVisibilityChange"),e instanceof Kr?this.ctx2d=e.ctx||null:e.available&&t!=null&&t.mirrorUpAndDown&&this.setTexBuffer(PG)}start(e){this.log.info("".concat(this.name," start render ").concat(e," fps")),ft.clearTask(this._intervalId),this._intervalId=ft.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(ft.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof ur){let t=this.context.ctx.getError();t&&this.context.destroy(new me({code:te.VIDEO_MANAGER_ERROR,extraCode:5,message:"".concat(this.name," req ").concat(this._sequence," render ").concat(this.totalFrames," faild ").concat(t)}))}},{fps:this.context.frameRate})}render(e){var t;return!((t=this.input)==null||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(Gi.RENDER,this.context._canvas),!0)}addInput(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];super.addInput(e,...i),this.start(this.context.frameRate)}update(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.state!=="closed"&&(this._intervalId&&(ft.clearTask(this._intervalId),this._intervalId=0,e===1&&(this.log.info("".concat(this.name," use requestVideoFrameCallback")),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info("".concat(this.name," use timer")),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++))}removeInput(e){super.removeInput(e),ft.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),ft.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},eE=class extends $v{constructor(e,t){super(e,t),m(this,"_videoTrack"),m(this,"_muteOb"),m(this,"_closedOb",St(this,"closed")),m(this,"_subscription"),m(this,"_canvasContainer"),Number(ma)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=St(this._videoTrack,"mute"),At(St(this._videoTrack,"ended"),Ci(this._closedOb),Qt(()=>{this.context.destroy(new me({code:te.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){var e;this._subscription=At(this._muteOb,Ci(this._closedOb),Rp((e=5e3,t=>{let i=performance.now();At(NG,qv(r=>r-i<e),Wo(1))(t)})),Sa(()=>{var t;return!((t=this._videoTrack)==null||!t.muted||document.hidden)}),Qt(()=>{this.context.destroy(new me({code:te.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info("".concat(this.name," put canvas to body")),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(t=this._canvasContainer)==null||t.remove()}},OG=class extends eE{render(e){var t;let i=!((t=this.input)==null||!t.requestFrame(e));if(this.context._canvas2d){let r=this.context._canvas2d.getContext("2d");r.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),r.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height),this.emit(Gi.RENDER,this.context._canvas2d)}else this.emit(Gi.RENDER,this.context._canvas);return i}},MG=class extends eE{constructor(e,t,i){super(e,{name:"smallDestination",logger:i}),this.resolution=t}resize(e,t){let i,r=e*t,n=this.resolution.width*this.resolution.height;this.log.info("big res: ".concat(e,"*").concat(t," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),r>n?i=r/n:(this.log.warn("Small stream resolution is not smaller than big stream, which is invalid. big: ".concat(e," * ").concat(t," small: ").concat(this.resolution.width," * ").concat(this.resolution.height)),i=r/19200),super.resize(e/Math.sqrt(i),t/Math.sqrt(i))}},bD=class extends Gi{constructor(e,t){super(e,ve({name:"imageSource"},t)),m(this,"_lastImage"),m(this,"_totalFrames",0),m(this,"_autoResize",!1),m(this,"_canvasRendered"),m(this,"videoCallbackId",0),m(this,"waitingFirstFrame",!0),m(this,"shouldUpdate",!0),this._autoResize=t?.autoResize!==!1,Sr===16&&(this._canvasRendered=zr(),At(this._canvasRendered,zv(this._image),Sp(i=>i instanceof HTMLCanvasElement?St(i,"rendered"):Yv()),Ci(St(this,"closed")),Qt(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),zc()&&!document.hidden&&(this.videoCallbackId=e.requestVideoFrameCallback((t,i)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=i.presentedFrames,this.update(1))}))}_render(e,t){var i;let{width:r,height:n}=this,{image:s}=this;if(s instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:r,videoHeight:n}=s,!r||!n)return!1;s.width=r,s.height=n}else if(s instanceof HTMLImageElement||s instanceof ImageData||s instanceof ImageBitmap){if({width:r,height:n}=s,s!==this._lastImage)this._lastImage=s;else if(r===this.width&&n===this.height)return!0}else s instanceof HTMLCanvasElement||s instanceof OffscreenCanvas?({width:r,height:n}=s,this._lastImage=s):typeof VideoFrame<"u"&&s instanceof VideoFrame&&({displayWidth:r,displayHeight:n}=s,(i=this._lastImage)==null||i.close(),this._lastImage=s);if(!this._autoResize)return!0;if(this.width===r&&this.height===n&&this.totalFrames){if(t){this.useTexture();let o=this.context.ctx;o.texSubImage2D(o.TEXTURE_2D,0,0,0,o.RGBA,o.UNSIGNED_BYTE,s)}}else{if(t){this.useTexture();let o=this.context.ctx;o.texImage2D(o.TEXTURE_2D,0,o.RGBA,o.RGBA,o.UNSIGNED_BYTE,s)}this.resize(r,n)}return!0}get image(){return this._image}set image(e){var t;(t=this._canvasRendered)==null||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},CD=class extends bD{constructor(e,t,i){super(e,i),this._player=t,this.name="videoPlayerSource",At(St(this._player,Me.PLAYER_STATE_CHANGED),Ci(St(this,"closed")),Sa(r=>{let{state:n}=r;return n==="PLAYING"}),Qt(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},Go=class extends CD{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(e,t,i){super(e,new jr({id:i.name,track:t,muted:!0,container:null,objectFit:"contain",log:i.logger}),i),this.name="videoTrackSource",this._player.play()}replaceTrack(e){this.waitingFirstFrame=!0,this._player.setTrack(e),this._player.play()}close(){super.close(),this._player.stop()}},LG=class extends Gi{constructor(e,t,i){super(e,xe(ve({name:"textSource"},i),{create2d:!0})),m(this,"hasChange",!0),m(this,"content",""),this.ctx2d.textBaseline="top",this.content=t.content||"",t.font&&(this.font=t.font),t.color&&(this.color=t.color)}set font(e){this.ctx2d&&(this.ctx2d.font=e,this.hasChange=!0)}get font(){var e;return((e=this.ctx2d)==null?void 0:e.font)||""}set color(e){this.ctx2d&&(this.ctx2d.fillStyle=e,this.hasChange=!0)}get color(){var e;return((e=this.ctx2d)==null?void 0:e.fillStyle)||""}render2d(e){return!(!this.ctx2d||!this.hasChange)&&(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0)}render(e){return!1}resize(e,t){if(!this.ctx2d)return;let{color:i,font:r}=this;super.resize(e,t),this.color=i,this.font=r}drawMultilineText(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1.2;if(!this.ctx2d)return;let r=this.ctx2d.measureText(this.content);t+=r.fontBoundingBoxAscent||r.actualBoundingBoxAscent||0;let n=this.font.match(/(\d+)px/),s=(n?parseInt(n[1],10):16)*i,o=this.content.split(`
71
+ `);for(let l=0;l<o.length;l++)this.ctx2d.fillText(o[l],e,t+l*s)}},hu=class extends et{constructor(e){super(),m(this,"frameRate"),m(this,"_canvas"),m(this,"log"),m(this,"hasAlpha",!1),m(this,"name"),m(this,"error"),this.name=e.name,this.log=e.logger.createChild({id:"vc-".concat(this.name)}),this.frameRate=e.frameRate}get canvas(){return this._canvas}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new Go(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new eE(this,e)}createVideoImageSource(e,t){return new bD(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new CD(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new LG(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};m(hu,"_ids",0);var pu=class extends hu{constructor(){super(...arguments),m(this,"defaultProgam"),m(this,"defaultVShader"),m(this,"defaultFShader"),m(this,"ctx"),m(this,"_canvas2d")}get canvas(){return this._canvas2d||this._canvas}create(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(hu._ids++)),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",d2),!this.ctx)throw new me({code:te.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,`
72
+ // 顶点着色器
73
+ attribute vec4 a_position;
74
+ attribute vec2 a_texCoord;
75
+ varying vec2 v_texCoord;
76
+
77
+ void main() {
78
+ gl_Position = a_position;
79
+ v_texCoord = a_texCoord;
80
+ }
81
+ `),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,`
82
+ // 片元着色器
83
+ precision mediump float;
84
+ varying vec2 v_texCoord;
85
+ uniform sampler2D u_texture;
86
+
87
+ void main() {
88
+ gl_FragColor = texture2D(u_texture, v_texCoord);
89
+ } `),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new me({code:te.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,ce.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info("video context destroy".concat(t)?": ".concat(t):""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e,this._canvas2d&&(this._canvas2d.width=e)}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e,this._canvas2d&&(this._canvas2d.height=e)}setSize(e,t){var i;(i=this.ctx)==null||i.viewport(0,0,e,t),super.setSize(e,t),this._canvas2d&&(this._canvas2d.width=e,this._canvas2d.height=t)}createShader(e,t){let i=this.ctx,r=i.createShader(e);return i.shaderSource(r,t),i.compileShader(r),r}createProgram(e,t){let i=this.ctx,r=i.createProgram();return i.attachShader(r,e),i.attachShader(r,t),i.linkProgram(r),i.getProgramParameter(r,i.LINK_STATUS)||this.log.error(i.getProgramInfoLog(r)),r}};m(pu,"UNAVAILABLE","unavailable"),_e([ni(et.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),ce.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),ce.addSuccessEvent({key:512700})}})],pu.prototype,"create"),_e([ni("created",et.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(pu.UNAVAILABLE,e),this.removeAllListeners()}})],pu.prototype,"destroy");var ur=pu,Kr=class extends hu{constructor(){super(...arguments),m(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(hu._ids++),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha,willReadFrequently:e.willReadFrequently}),!this.ctx)throw new me({code:te.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(e){let t="";e&&(t=e.message,this.error=e,ce.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info("video context destroy ".concat(t?": ".concat(t):"")),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),ce.addSuccessEvent({key:512703})}};function xG(e,t,i,r,n){arguments.length>5&&arguments[5]!==void 0&&arguments[5]&&([i,r]=[r,i]);let s={sWidth:e,sHeight:t,dWidth:i,dHeight:r,sx:0,sy:0,dx:0,dy:0};if(e===0||t===0)return s;switch(n){case void 0:case"fill":break;case"contain":{let o=Math.min(i/e,r/t);s.dWidth=e*o,s.dHeight=t*o,s.dx=(i-s.dWidth)/2,s.dy=(r-s.dHeight)/2;break}case"cover":{let o=Math.max(i/e,r/t),l=i/o,c=r/o;s.sx=(e-l)/2,s.sy=(t-c)/2,s.sWidth=l,s.sHeight=c;break}}return s}_e([ni(et.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),ce.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),ce.addSuccessEvent({key:512701})}})],Kr.prototype,"create"),_e([ni("created",et.INIT,{ignoreError:!0,sync:!0})],Kr.prototype,"destroy");var UG=class{constructor(e,t){this.node=e,this.layout=t,m(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},kD=class extends Gi{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t}),m(this,"inputs",[]),m(this,"backgroundColor","black")}addInput(e,t){let i=0,r=this.inputs.length;for(;i<r;){let s=Math.floor((i+r)/2);if(this.inputs[s].layout.zIndex<t.zIndex)i=s+1;else{if(!(this.inputs[s].layout.zIndex>t.zIndex))throw new Error("input already exists at zIndex ".concat(t.zIndex));r=s}}let n=new UG(e,t);this.inputs.splice(i,0,n)}changeInputLayout(e,t){let i=this.inputs.findIndex(T=>T.node===e);if(i<0)return;let{x:r,y:n,width:s,height:o,zIndex:l,fillMode:c,rotation:h,hidden:_}=t;if(!j(l)&&this.inputs.some(T=>T.layout.zIndex===l&&T.node!==e))throw new Error("input already exists at zIndex ".concat(t.zIndex));let f=this.inputs[i];j(r)||(f.layout.x=r),j(n)||(f.layout.y=n),j(s)||(f.layout.width=s),j(o)||(f.layout.height=o),j(h)||(f.layout.rotation=h),j(_)||(f.layout.hidden=_),c&&(f.layout.fillMode=c),!j(l)&&l!==f.layout.zIndex&&(f.layout.zIndex=l,this.inputs.sort((T,b)=>T.layout.zIndex-b.layout.zIndex))}hasInput(e){return this.inputs.some(t=>t.node===e)}hasNoInput(){return this.inputs.length===0}resize(e,t){if(!this.matchInputSize)return void super.resize(e,t);let i=this.inputs.reduce((r,n)=>n?Object.assign(r,{width:Math.max(r.width,n.right),height:Math.max(r.height,n.bottom)}):r,{width:0,height:0});super.resize(i.width,i.height),this.context instanceof ur&&this.inputs.forEach(r=>{if(r){let n=this.layout2texCoords(r);r.positionBuffer?this.changeBufferData(r.positionBuffer,n):r.positionBuffer=this.createBuffer(n)}})}connect(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return super.connect(e,...i),this.drawBackGround2d(this.backgroundColor),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs=this.inputs.filter(t=>t.node!==e),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce((i,r)=>r.node.requestFrame(e)||i,!1)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let i=0;i<this.inputs.length;i++){let r=this.inputs[i];r&&(r.node.useTexture(),this.draw(r.positionBuffer))}return!0}return!1}render2d(e){if(this.inputs.forEach(t=>t.node.requestFrame(e)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let t=0;t<this.inputs.length;t++){let i=this.inputs[t];if(i.hidden)continue;let r=xG(i.node.width,i.node.height,i.width,i.height,i.fillMode,ls(i.rotation));this.draw2d(i.node.image,i.x+r.dx,i.y+r.dy,r.dWidth,r.dHeight,r.sx,r.sy,r.sWidth,r.sHeight)}return!0}return!1}debugLayout(e,t,i,r){let n=arguments.length>4&&arguments[4]!==void 0&&arguments[4];this.ctx2d&&(n&&([i,r]=[r,i]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(e,t,i,r),this.ctx2d.restore())}getInfo(){let{totalFrames:e,x:t,y:i,width:r,height:n,name:s}=this,o=Date.now(),l=(e-this.lastInfo.totalFrames)/((o-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:e,x:t,y:i,width:r,height:n,timestamp:o,fps:l,name:s},ve({parent:this.inputs.filter(c=>c).map(c=>c.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(e=>{var t;if(e.node.disconnect(),e.positionBuffer&&this.context instanceof ur)try{(t=this.context.ctx)==null||t.deleteBuffer(e.positionBuffer)}catch{}})}close(){super.close(),this.removeAllInputs()}},VG=[1,0,0,0,1,1,0,1],gs=class extends Gi{constructor(e,t,i,r){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t}),m(this,"mirror",!1),m(this,"rotation",0),i&&(this.mirror=i),r&&(this.rotation=r),e instanceof ur)try{this.setTexBuffer(VG)}catch(n){e.destroy(new me({code:te.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(n.message||n)}))}}draw2d(e,t,i,r,n){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(r,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/r,r/n)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,n),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(n/r,r/n));let s=super.draw2d(e,t,i,r,n);return this.ctx2d.restore(),s}return!1}render(e){var t;return!((t=this.input)==null||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}resize(e,t){ls(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}},tE=class extends cu{constructor(e){super(arguments.length>1&&arguments[1]!==void 0?arguments[1]:4,jr),m(this,"inputLocalVideoTracks",new Map),m(this,"inputLocalScreenTracks",new Map),m(this,"cameraNodeMap",new Map),m(this,"screenNodeMap",new Map),m(this,"textNodeMap",new Map),m(this,"imageNodeMap",new Map),m(this,"videoNodeMap",new Map),m(this,"endedIds",new Set),m(this,"videoContext"),m(this,"mixNode"),m(this,"destination"),m(this,"manager"),m(this,"stat"),m(this,"_checkId",0),m(this,"autoSetFps",!0),this.manager=e,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(Gi.RENDER,t=>{this.emit("render",t)}),this.mixNode=new kD(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3;this._checkId=ft.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new Kr({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(e){this.autoSetFps=!1,this.videoContext.frameRate=e;for(let t of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])t.shouldUpdate=!1;setTimeout(()=>{var t;return(t=this.destination)==null?void 0:t.start(this.videoContext.frameRate)},500)}setFpsAuto(){var e;if(!this.autoSetFps)return;for(let n of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])n.shouldUpdate=!1;let t=null,i=0,r=!0;for(let[n,s]of this.inputLocalVideoTracks)if(s.profile.frameRate>i){if(this.endedIds.has(n)){let o=this.cameraNodeMap.get(n);o&&o.image.cancelVideoFrameCallback(o.videoCallbackId);continue}i=s.profile.frameRate,t=n}for(let[n,s]of this.inputLocalScreenTracks)if(s.profile.frameRate>i){if(this.endedIds.has(n)){let o=this.screenNodeMap.get(n);o&&o.image.cancelVideoFrameCallback(o.videoCallbackId);continue}i=s.profile.frameRate,t=n,r=!1}if(t!==null){let n=r?this.cameraNodeMap.get(t):this.screenNodeMap.get(t);n&&(n.shouldUpdate=!0,n.tryVideoFrameCallback()),this.log.info("set mix fps: ",i)}else(e=this.destination)==null||e.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(e){this.mixNode&&(this.mixNode.backgroundColor=e)}resizeMixCanvas(e,t){var i;(i=this.mixNode)==null||i.resize(e,t)}startMix(){return P(this,null,function*(){var e;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),pa&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(e=this.manager)==null||e.changeInput(this)})}addCameraSource(e,t,i){if(this.inputLocalVideoTracks.has(e)||this.cameraNodeMap.has(e))throw new Error("There is already a cameraSource with the same ID: ".concat(e));let r,{mediaTrack:n}=t;if(!n)throw new Error("no mediaTrack, add cameraSource failed");t.recaptureMode=1,Ar(this,Xt).add("videoInputRemoved",s=>{s.deviceId===t.deviceId&&(this.endedIds.add(e),this.setFpsAuto())}),t.on("output-media-track-changed",()=>{this.endedIds.delete(e),this.updateCameraSource(e,i,t.mediaTrack)}),r=Sr===16&&n instanceof CanvasCaptureMediaStreamTrack?this.videoContext.createVideoImageSource(n.canvas,{name:"cameraCanvasSource",logger:this.log}):this.videoContext.createVideoTrackSource(n,"cameraNodeSource"),r.resize(t.settings.width,t.settings.height),r.shouldUpdate=!1,this._connectMix(r,i,"cover"),this.inputLocalVideoTracks.set(e,t),this.cameraNodeMap.set(e,r),this.setFpsAuto()}addScreenSource(e,t,i){if(this.inputLocalScreenTracks.has(e)||this.screenNodeMap.has(e))throw new Error("There is already a screenSource with the same ID: ".concat(e));let{mediaTrack:r}=t;if(!r)throw new Error("no mediaTrack, add cameraSource failed");let n=this.videoContext.createVideoTrackSource(r,"screenNodeSource");n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,i),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,n),this.setFpsAuto()}addTextSource(e){let{id:t,content:i="",font:r,color:n,layout:s}=e;if(this.textNodeMap.has(t))throw new Error("There is already a textSource with the same ID: ".concat(t));let o=this.videoContext.createTextSource({content:i,font:r,color:n});o.resize(s.width,s.height),this._connectMix(o,s),this.textNodeMap.set(t,o)}addImageSource(e,t,i){if(this.imageNodeMap.has(e))throw new Error("There is already a imageSource with the same ID: ".concat(e));let r=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});r.resize(t.width,t.height),this._connectMix(r,i),this.imageNodeMap.set(e,r)}addVideoSource(e,t,i){if(this.videoNodeMap.has(e))throw new Error("There is already a videoSource with the same ID: ".concat(e));let r=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});r.resize(t.videoWidth,t.videoHeight),r.shouldUpdate=!1,this._connectMix(r,i),this.videoNodeMap.set(e,r)}updateCameraSource(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,r=arguments.length>3?arguments[3]:void 0,n=this.cameraNodeMap.get(e);if(n){if(i){if(Sr===16&&i instanceof CanvasCaptureMediaStreamTrack)if(n instanceof Go){let l=n.output;n.close(),n=this.videoContext.createVideoImageSource(i.canvas,{name:"cameraCanvasSource",logger:this.log}),n.connect(l),this.cameraNodeMap.set(e,n)}else n.image=i.canvas;else if(n instanceof Go)n.replaceTrack(i);else{let l=n.output;n.close(),n=this.videoContext.createVideoTrackSource(i,"cameraNodeSource"),n.connect(l),this.cameraNodeMap.set(e,n)}let{width:s,height:o}=i.getSettings();s&&o&&n.resize(s,o)}r&&n.resize(r.width,r.height),(r||i)&&this.setFpsAuto(),this._changeMixLayout(n,t)}}updateScreenSource(e,t){let i=this.screenNodeMap.get(e);i&&this._changeMixLayout(i,t)}updateTextSource(e){let{id:t,content:i,font:r,color:n,layout:s}=e,o=this.textNodeMap.get(t);o&&(j(i)||(o.content=i),j(r)||(o.font=r),j(n)||(o.color=n),o.resize(s.width,s.height),this._changeMixLayout(o,s))}updateImageSource(e,t,i){let r=this.imageNodeMap.get(e);r&&(i&&(r.image=i,r.resize(i.width,i.height)),this._changeMixLayout(r,t))}updateVideoSource(e,t,i){let r=this.videoNodeMap.get(e);if(r){if(i){let n=r.image;n instanceof HTMLVideoElement&&this.stopVideoElement(n),r.image=i,r.resize(i.videoWidth,i.videoHeight)}this._changeMixLayout(r,t)}}_connectMix(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"contain";if(!this.mixNode)return;let{mirror:r,rotation:n}=t;e.disconnect();let s=new gs(this.videoContext,this.log,r,n);s=e.connect(s),t.fillMode||(t.fillMode=i),s.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:i,rotation:r}=t,n=e.output||e;n instanceof gs&&(j(i)||(n.mirror=i),j(r)||(n.rotation=r),n.resize(e.width,e.height)),this.mixNode.changeInputLayout(n,t)}removeCameraSource(e){let t=this.inputLocalVideoTracks.get(e);if(!t)return;t.close(),this.inputLocalVideoTracks.delete(e);let i=this.cameraNodeMap.get(e);i&&(i.output instanceof gs&&i.output.close(),i.close(),this.cameraNodeMap.delete(e)),this.checkAfterRemove(!0)}removeScreenSource(e){let t=this.inputLocalScreenTracks.get(e);if(!t)return;t.close(),this.inputLocalScreenTracks.delete(e);let i=this.screenNodeMap.get(e);i&&(i.output instanceof gs&&i.output.close(),i.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof gs&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof gs&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof gs&&t.output.close(),t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image),t.close(),this.videoNodeMap.delete(e)),this.checkAfterRemove()}checkAfterRemove(){arguments.length>0&&arguments[0]!==void 0&&arguments[0]&&this.setFpsAuto()}stopVideoElement(e){e.pause(),e.src="",e.srcObject=null,e.remove()}close(){var e;super.close(),ft.clearTask(this._checkId),(e=this.videoContext)==null||e.destroy(),delete this.mixNode,delete this.destination;for(let t of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])t.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),bi(this);for(let t of this.videoNodeMap.values())t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}},iE=sk();if(typeof navigator<"u"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:iE,exposeOrigin:!0,permittedOrigins:["*"]})}catch{}var FG=function(e){return P(this,null,function*(){let t=null,i=(function(s){let o={preferCurrentTab:s.preferDisplaySurface==="current-tab"||!!s.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},l={width:ri?{max:s.width}:{ideal:s.width,max:s.width},height:ri?{max:s.height}:{ideal:s.height,max:s.height},frameRate:s.frameRate,displaySurface:s.preferDisplaySurface||"monitor"};if(o.video=l,s.systemAudio){let{echoCancellation:c=!0,noiseSuppression:h=!1,autoGainControl:_=!1}=s;o.audio={echoCancellation:c,noiseSuppression:h,autoGainControl:_,sampleRate:48e3}}return o})(e);fe.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&r.getAudioTracks().length===0&&($h&&lr<74||ri||ut)&&fe.warn("Your browser not support capture system audio");let n=r.getVideoTracks()[0];if(n){if(e.frameRate)try{yield n.applyConstraints({frameRate:{min:e.frameRate,ideal:e.frameRate},width:e.width,height:e.height})}catch(s){fe.warn("screen applyConstraints failed: ".concat(s))}e.captureElement&&(yield(function(s,o){return P(this,null,function*(){var l;if("CropTarget"in window&&"fromElement"in CropTarget&&Ut(s.cropTo))try{if(((l=s.getCaptureHandle())==null?void 0:l.handle)!==iE)return;let c=yield CropTarget.fromElement(o);yield s.cropTo(c)}catch(c){fe.warn("cropTo target failed ".concat(c))}})})(n,e.captureElement))}if(e.audio){let s=(function(o){let l={echoCancellation:o.echoCancellation,autoGainControl:o.autoGainControl,noiseSuppression:o.noiseSuppression,sampleRate:o.sampleRate,channelCount:o.channelCount};return j(o.microphoneId)||(l.deviceId=o.microphoneId),{audio:l,video:!1}})(e);fe.info("getUserMedia with constraints: ".concat(JSON.stringify(s))),t=yield navigator.mediaDevices.getUserMedia(s),r.addTrack(t.getAudioTracks()[0])}return r})},Ra=class extends Rn{constructor(e){super(e,2),m(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),m(this,"objectFit","contain"),m(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}get isShareCurrentTab(){var e,t;try{return iE===((t=(e=this.mediaTrack)==null?void 0:e.getCaptureHandle())==null?void 0:t.handle)}catch{return}}capture(e){return P(this,arguments,function(t){var i=this;let{systemAudio:r=!1,autoGainControl:n,echoCancellation:s,noiseSuppression:o,audioTrack:l,videoTrack:c,captureElement:h,preferDisplaySurface:_}=t;return(function*(){try{let f;return c||l?(f=new MediaStream,c&&f.addTrack(c),l&&f.addTrack(l)):(f=yield FG({audio:!1,systemAudio:r,width:i.profile.width,height:i.profile.height,frameRate:i.profile.frameRate,autoGainControl:n,echoCancellation:s,noiseSuppression:o,captureElement:h,preferDisplaySurface:_}),i.sourceTrack=f.getVideoTracks()[0]),yield i.setInputMediaStreamTrack(f.getVideoTracks()[0]),f}catch(f){throw i.log.error("getDisplayMedia error observed ".concat(f)),f instanceof me?f:new me({code:te.INITIALIZE_FAILED,name:f.name,message:f.message})}})()})}switchDevice(e){return P(this,null,function*(){throw new Error("Method not implemented.")})}};_e([Ta(function(e){this.setContentHint(e.contentHint||"detail")})],Ra.prototype,"capture");var rE,nE=class extends Ia{constructor(e){super(e),this._log.id="s-".concat(this._log.id),this.isScreen=!0}addAudioProcessor(e,t,i){this.pipeline.silentNode.setNode(i),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e),this.enableTrackAEC(!1)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};function sE(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,r=arguments.length>3?arguments[3]:void 0;return P(this,null,function*(){let n=pi();rE||(rE=dp(n,URL.createObjectURL(new Blob(['registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;t<r.length;t++){o[t]=[];for(let e=0;e<r[t].length;e++)o[t][e]=this.resample(r[t][e],s,a)}return o}resample(t,e,r){if(e===r)return t;var s=Math.round(t.length*(this.targetSampleRate/this.sourceSampleRate)),a=new Float32Array(s),o=(t.length-1)/(s-1);a[0]=t[0];for(let e=1;e<s-1;e++){var l=e*o,p=Math.floor(l),h=Math.ceil(l);a[e]=t[p]+(t[h]-t[p])*(l-p)}return a[s-1]=t[t.length-1],a}});'],{type:"application/javascript"})))),yield rE;let s=n.sampleRate,o=new AudioWorkletNode(n,"dumper",{numberOfInputs:e.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:s,targetSampleRate:t}});return o.channelCountMode="explicit",o.channelCount=i,r&&o.port.postMessage({port:r},[r]),e.forEach((l,c)=>l.connect(o,0,c)),new ReadableStream({start(l){o.port.onmessage=c=>{l.enqueue(c.data)}},cancel(){e.forEach(l=>l.disconnect(o)),o.port.close()}})})}var BG=class extends tW{constructor(e){super(),this.room=e,m(this,"_localAudioTrack"),m(this,"_localScreenAudioTrack"),m(this,"log"),m(this,"denoiser"),m(this,"voiceChanger"),m(this,"mixChangedDebounce"),m(this,"audioProcessor"),m(this,"encodePipeline",[]),m(this,"decodePipeline",[]),m(this,"getPCMAbortCtrlMap",new Map),m(this,"audioFrameEventConfigMap",new Map),m(this,"audioReferenceMap",new Map),m(this,"isLocalAudioNeedAudioProcess",!1),m(this,"isScreenAudioNeedAudioProcess",!1),this.log=fe.createLogger({parent:e?.getLogger(),id:"am",userId:e?.userId,sdkAppId:e?.sdkAppId}),this.installEvent()}get localAudioTrack(){return this._localAudioTrack}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}get _localScreenAudioPipeline(){var e;return(e=this._localScreenAudioTrack)==null?void 0:e.pipeline}dump(e){var t,i;if(!this._localAudioTrack)return;let r=[],n=[];(t=this._localAudioPipline)!=null&&t.source.node&&(r.push(this._localAudioPipline.source.node),n.push("mic")),(i=this._localAudioPipline)!=null&&i.denoiser.node&&(r.push(this._localAudioPipline.denoiser.node),n.push("mic-processed")),this.mixWeight>1&&(r.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),n.push("mix")),this.log.info("dump audio track ".concat(n,", duration: ").concat(e));let s=new AbortController,o=[],l=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},1e3*e),c=()=>{for(let _=0;_<n.length;_++){let f=URL.createObjectURL(new Blob(o[_])),T=document.createElement("a");T.href=f,T.download="".concat(n[_],".pcm"),T.style.display="none",document.body.appendChild(T),T.click(),URL.revokeObjectURL(f),T.remove()}clearTimeout(l),s.abort("download")},h=sE(r).then(_=>_.pipeTo(new WritableStream({write(f){f.forEach((T,b)=>o[b]=o[b]?o[b].concat(T[0]):[T[0]])}}),s).catch(f=>c));return{then:h.then.bind(h),download:c}}getPCM(e,t){var i,r,n;if(typeof WritableStream>"u")return void this.log.warn("getPCM failed: browser not support WritableStream");let{enable:s,sampleRate:o=48e3,channelCount:l=1,port:c}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!s)return;this.log.info("getPCM ".concat(t||"local"));let h,_,f=Math.floor(.04*o),T=new Float32Array(f),b=new Float32Array(f),C=0,x=new AbortController,B=t===""?(i=this._localAudioTrack)==null?void 0:i.mediaTrack:(n=(r=this.room)==null?void 0:r.remotePublishedUserMap.get(t))==null?void 0:n.remoteAudioTrack.mediaTrack;if(B)return sE([pi().createMediaStreamSource(new MediaStream([B]))],o,l,c).then(Y=>Y.pipeTo(new WritableStream({write(G){G[0][0]&&(C+G[0][0].length>f?(T.set(G[0][0].subarray(0,f-C),C),h=G[0][0].subarray(f-C),G[0][1]&&(b.set(G[0][1].subarray(0,f-C),C),_=G[0][1].subarray(f-C)),C+=f-C):(h&&(T.set(h,C),C+=h.length,h=void 0),_&&(b.set(_,C),_=void 0),T.set(G[0][0],C),G[0][1]&&b.set(G[0][1],C),C+=G[0][0].length),C>=f&&(C=0,e({userId:t,sampleRate:o,channelCount:l,data:l===1?T:[T,b]}),T=new Float32Array(f),b=new Float32Array(f)))}}),x).catch(G=>this.log.warn("stop getPCM reason:".concat(G)))),x;this.log.info("getPCM failed: ".concat(t||"local"," has no audio track"))}get hasScreenAudioTrack(){return!j(this._localScreenAudioTrack)}get hasAudioTrack(){return!j(this._localAudioTrack)}changeInput(e){var t,i;return e instanceof nE?(this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&(t=this.audioProcessor)!=null&&t.screenAudioWorkletNode&&(e.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((r,n)=>{e.mixAudioReference(r,n)})),e.pipeline.connect(),this.mixOnChange()):e instanceof Ia?(this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&(i=this.audioProcessor)!=null&&i.localAudioWorkletNode&&(e.addAudioProcessor(this.audioProcessor.localAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((r,n)=>{e.mixAudioReference(r,n)})),e.pipeline.connect(),this.mixOnChange()):e instanceof kp?e.setOutputMediaStreamTrack(e.mediaTrack):void 0}mixAudioReference(e,t){var i;(i=this._localAudioTrack)==null||i.mixAudioReference(e,t)}unMixAudioReference(e){var t;(t=this._localAudioTrack)==null||t.unMixAudioReference(e)}setAudioReferenceVolume(e,t){var i;(i=this._localAudioTrack)==null||i.setAudioReferenceVolume(e,t)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof nE?delete this._localScreenAudioTrack:e instanceof Ia&&delete this._localAudioTrack}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}addAudioProcessor(e,t,i,r){var n;this.audioProcessor={localAudioWorkletNode:i,mixNode:e,silentNode:t,screenAudioWorkletNode:r},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&i&&(this._localAudioTrack.addAudioProcessor(i,e,t),this.audioReferenceMap.forEach((s,o)=>{var l;(l=this._localAudioTrack)==null||l.mixAudioReference(s,o)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&r&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(r,e,t),this.audioReferenceMap.forEach((s,o)=>{var l;(l=this._localScreenAudioTrack)==null||l.mixAudioReference(s,o)}))}removeDenoiser(e){var t;return delete this.denoiser,(t=this._localAudioTrack)==null?void 0:t.removeDenoiser(e)}addVoiceChanger(e,t){var i;this.voiceChanger=[e,t],(i=this._localAudioTrack)==null||i.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(e,t){var i,r;delete this.audioProcessor,(i=this._localAudioTrack)==null||i.removeAudioProcessor(e),(r=this._localScreenAudioTrack)==null||r.removeAudioProcessor(t)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach(e=>e?.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor(e){let{processor:t,type:i}=e;var r;this.encodePipeline.includes(t)||(this.encodePipeline[i]=t,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor(e){let{processor:t,type:i}=e;var r;this.decodePipeline.includes(t)||(this.decodePipeline[i]=t,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor(e){let{type:t}=e;this.encodePipeline[t]=void 0}removeDecodeProcessor(e){let{type:t}=e;this.decodePipeline[t]=void 0}handleLocalTrackStarted(e){let{room:t,userId:i}=e;var r;if(t!==this.room||this.getPCMAbortCtrlMap.get(i))return;let n=this.getPCM(s=>{var o;(o=this.room)==null||o.emit("audio-frame",s)},"");this.getPCMAbortCtrlMap.set(i,n),this.getPCMAbortCtrlMap.get(i)&&((r=this._localAudioTrack)==null||r.on("input-media-track-changed",()=>{let s=this.getPCMAbortCtrlMap.get(i);s&&(s.abort("inputMediaTrackChanged"),s=this.getPCM(o=>{var l;(l=this.room)==null||l.emit("audio-frame",o)},""),this.getPCMAbortCtrlMap.set(i,s))}))}handleLocalTrackStopped(e){let{room:t,userId:i}=e;if(t!==this.room)return;let r=this.getPCMAbortCtrlMap.get(i);r&&(r.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(i))}handleRemoteTrackStarted(e){let{room:t,userId:i}=e;if(t===this.room&&!this.getPCMAbortCtrlMap.get(i)){let r=this.room.audioManager.getPCM(n=>{var s;(s=this.room)==null||s.emit("audio-frame",n)},i);this.getPCMAbortCtrlMap.set(i,r)}}handleRemoteTrackStopped(e){let{room:t,userId:i}=e;if(t!==this.room)return;let r=this.getPCMAbortCtrlMap.get(i);r&&(r.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(i))}installEvent(){$.on("113",this.handleLocalTrackStarted,this),$.on("114",this.handleLocalTrackStopped,this),$.on("115",this.handleRemoteTrackStarted,this),$.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){$.off("113",this.handleLocalTrackStarted),$.off("114",this.handleLocalTrackStopped),$.off("115",this.handleRemoteTrackStarted),$.off("116",this.handleRemoteTrackStopped)}updateAudioReference(e){let{type:t,audioReference:i,refId:r,volume:n}=e;if(t==="add"){if(this.audioReferenceMap.get(r)||!i||(this.audioReferenceMap.set(r,i),!this.audioProcessor))return;this.mixAudioReference(i,r)}else if(t==="remove")this.audioReferenceMap.get(r)&&(this.audioReferenceMap.delete(r),this.unMixAudioReference(r));else if(t==="updateVolume"){if(!this.audioProcessor||j(n))return;this.setAudioReferenceVolume(r,n)}}};function Cp(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:30,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2;return _t((i,r)=>function(){for(var n=arguments.length,s=new Array(n),o=0;o<n;o++)s[o]=arguments[o];return new Promise((l,c)=>{let h=setTimeout(()=>{let _=new me({code:te.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(r,"() timeout ").concat(e,"s")});(this.log||this._log||fe).warn(_),t===2?c(_):t===1&&l()},1e3*e);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(h),i.apply(this,s).then(l,c).finally(()=>{clearTimeout(h),this._checkPendingPromiseSet&&h&&this._checkPendingPromiseSet.delete(h)})})})}var Aa=class ME extends Wv{constructor(t,i,r){super({userId:i.userId,sdkAppId:t.sdkAppId,mediaType:r,room:t}),this.room=t,this.user=i,m(this,"tinyId"),m(this,"isRemote",!0),m(this,"jitterBufferDelay",0),m(this,"availableState"),m(this,"remotePublishState"),m(this,"_triggerCheckDecodeSubject",zr(St(this,ME.STATE_SUBSCRIBE))),m(this,"ignoreUpdatePlayingState"),this.tinyId=i.tinyId,this.availableState=new et("".concat(i.userId,"-").concat(this.mediaType,"-available"),"remote-track-available"),this.remotePublishState=new et("".concat(i.userId,"-").concat(this.mediaType,"-remote-publish"),"remote-track-publish"),At(jv(St(this,et.STATECHANGED),St(this.remotePublishState,et.STATECHANGED)),Xv(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Qt(l=>{this.availableState.state!==(l?et.ON:et.OFF)&&(this.availableState.state=l?et.ON:et.OFF),(!this.isRemotePublished||!this.ignoreUpdatePlayingState)&&this.updatePlayingState(l)}));let n=At(St(this.player,Me.ERROR),Sa(l=>l.code===MediaError.MEDIA_ERR_DECODE)),s=At(Jv(5e3),Sa(()=>!!(!this.ignoreDecodeError&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived&&this.isRemotePublished)&&(!this.player.isPlaying&&!(this.kind===D.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)||(this.reportDecodeResult(!0),!1)))),o=At(sD(n,s),Ci(St(this,et.INIT)));At(this._triggerCheckDecodeSubject,Sa(()=>!this.ignoreDecodeError),Rp(o),Qt(l=>{this.reportDecodeResult(!1,l)}))}setMute(t){this.isRemotePublished&&super.setMute(t)}setInputMediaStreamTrack(t){super.setInputMediaStreamTrack(t),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(t=>{this.mediaTrack?t():this.once("input-media-track-changed",t)})}get ignoreDecodeError(){var t,i,r,n;return(n=(r=(i=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:i.hadRecentBadDownlink)==null?void 0:r.call(i,2))!=null&&n||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===ME.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===et.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(t){return t}unsubscribe(){this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(t,i){var r,n;let s=this.kind===D.AUDIO;if(ce[t?"addSuccessEvent":"addFailedEvent"]({key:s?504700:514702}),!s){let o=((r=this.room)==null?void 0:r.downlinkVideoCodec.toUpperCase())||"H264";ce[t?"addSuccessEvent":"addFailedEvent"]({key:nw["DECODE_".concat(o,"_RESULT")]}),t||this.log.warn("".concat((n=this.room)==null?void 0:n.downlinkVideoCodec," decode failed"))}t||(ce.addEnum({key:s?504701:514703,value:tp()}),dt.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(Lo()||xo()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===D.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0))),this.emit("decode-failed",{error:i}))}updatePlayingState(t){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),this.isPlayCalled&&this.player.isStopped===t){if(t&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack))return void this.log.info("abort play, isSubscribed: ".concat(this.isSubscribed," isAvailable: ").concat(this.isRemotePublished," hasTrack: ").concat(!!this.outMediaTrack," "));super.updatePlayingState(t)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?et.ON:et.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};m(Aa,"STATE_SUBSCRIBE","subscribe"),_e([Cp(5,1)],Aa.prototype,"waitHasMediaTrack"),_e([ni(et.INIT,Aa.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),$.emit(ie.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),ms(521716,!1)],Aa.prototype,"subscribe"),_e([ni(Aa.STATE_SUBSCRIBE,et.INIT,{sync:!0,success(){this.log.info("unsubscribed"),$.emit(ie.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],Aa.prototype,"unsubscribe");var wD=Aa,kp=class extends wD{constructor(e,t){super(e,t,1),m(this,"volume",0),m(this,"mediaType",1),m(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.audioManager}get dbVolume(){return mp.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(e){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var e,t;return!!this.manager&&(this.manager.decodePipeline.some(i=>i)||((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&Iv().AudioDecoder&&va)}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(e){if(!this.manager)return e;let t=e;for(let[i,r]of this.manager.decodePipeline.entries()){if(!r)continue;let n={frame:e,track:this};if(i===1&&this.isAvailable&&this.room.role==="audience"&&(n.onAudioFrameNTPTime=s=>{let{ntp:o,frame:l,hasLeavingTag:c}=s;this.emit("audio-frame-with-ntp",{ntp:o,frame:l,hasLeavingTag:c})}),t=r(n),!t)return}return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}},HG=class extends Gi{constructor(e,t,i,r,n){super(e,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:t}),this.setContainer=r,m(this,"initStat",{alphaStitchingType:1}),m(this,"end",zr()),m(this,"minSize",320),m(this,"maxSize",1280),m(this,"draggable",!1),m(this,"startDragX",0),m(this,"startDragY",0),m(this,"left",0),m(this,"top",0),m(this,"baseWidth",320),m(this,"baseRatio"),m(this,"container"),this.initStat=n,this.draggable=i,this.bindDragEvents(),ce.addEnum({key:515700,value:1}),this.draggable&&ce.addEnum({key:515700,value:11})}bindDragEvents(){let e=this.context._canvas;if(e)if(this.draggable){let t=Ci(this.end);At(St(e,"mousedown"),Qv(this.startDrag.bind(this)),Sp(()=>At(St(window,"mousemove"),Ci(St(window,"mouseup")))),t,Qt(this.doDrag.bind(this))),At(St(e,"dblclick"),t,Qt(this.resetPosition.bind(this))),At(St(e,"wheel"),t,Qt(this.handleZoom.bind(this))),this.renderCanvas()}else{if(!this.container)return;this.container.style.removeProperty("left"),this.container.style.removeProperty("top"),this.end.next()}}render(e){var t;return!((t=this.input)==null||!t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}startDrag(e){e.preventDefault(),e.button===0&&(this.startDragX=e.clientX-this.left,this.startDragY=e.clientY-this.top)}renderCanvas(){let{container:e}=this;e||this.setContainer(),e&&this.baseRatio&&this.draggable&&(e.style.setProperty("width","".concat(this.baseWidth,"px")),e.style.setProperty("height","".concat(this.baseWidth/this.baseRatio,"px")),e.style.setProperty("position","fixed"),e.style.setProperty("left","".concat(this.left,"px")),e.style.setProperty("top","".concat(this.top,"px")))}doDrag(e){e.preventDefault(),this.left=e.clientX-this.startDragX,this.top=e.clientY-this.startDragY,this.renderCanvas()}handleZoom(e){e.preventDefault();let t=e.deltaY,i=this.context._canvas;i&&(this.baseWidth||(this.baseWidth=i.offsetWidth),this.baseWidth=t<0?Math.min(1.1*this.baseWidth,this.maxSize):Math.max(.9*this.baseWidth,this.minSize),this.renderCanvas())}resetPosition(){this.left=0,this.top=0,this.renderCanvas()}onRatioReset(){this.renderCanvas()}draw2d(e,t,i,r,n){var s;let{ctx2d:o}=this,l=this.context._canvas;if(!o||!l)return!1;let c=super.draw2d(e,t,i,r,n),h=o.getImageData(0,0,r,n),{data:_}=h,f=!1;if(this.initStat.alphaStitchingType===1){let T=Math.floor(r/2);for(let b=0;b<n;b++)for(let C=0;C<T;C++){let x=4*(b*r+C),B=4*(b*r+(C+T)),Y=_[B];_[B+3]=0;let G=Y>=100;_[x+3]=G?255:0}f=super.draw2d(h,0,0,0,0,T,n),l.width=T}else if(this.initStat.alphaStitchingType===2){let T=Math.floor(n/2);for(let b=0;b<T;b++)for(let C=0;C<r;C++){let x=4*(b*r+C),B=4*((b+T)*r+C),Y=_[B];_[B+3]=0;let G=Y>=100;_[x+3]=G?255:0}f=super.draw2d(h,0,0,0,0,r,T),l.height=T}return(s=this.context.ctx)==null||s.clearRect(0,0,r,n),c&&f}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}},mu=class extends wD{constructor(e,t){super(e,t,arguments.length>2&&arguments[2]!==void 0?arguments[2]:4),m(this,"mediaType",4),m(this,"source"),m(this,"shouldRenderAlpha",!1),m(this,"alphaNode"),m(this,"shouldBeDraggable",!0),m(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0,keyFramesDecoded:0}),m(this,"_keyFrameCountLogged",!1),m(this,"_keyFrameStartTimestamp",0),m(this,"_keyFrameStartCount",0),m(this,"_keyFrameIntervals",[]),m(this,"_prevKeyFrameTimestamp",0),this.manager=e.videoManager,this.on("first-video-frame",i=>{this.room.emit("first-video-frame",i)})}isAlphaSei(e){if(this.userId!==e.userId||e.seiPayloadType!==50)return!1;let t=new Uint8Array(e.data);return t.length%3==0&&t[0]===0&&t[1]===1&&t}play(e,t){return t!=null&&t.canvasRender&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat(),$.emit("156",{track:this,player:this.player})})}updateAlphaRenderInfo(e){let t=this.isAlphaSei(e);if(t)if(this.alphaNode){let i=t[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===i)return;this.alphaNode.initStat={alphaStitchingType:i};let r=this.player.getElement();if(r){let n=r.videoWidth/r.videoHeight;n&&(this.alphaNode.baseRatio=n*(i===1?.5:2),this.alphaNode.onRatioReset())}this.player.canvas&&(this.player.canvas.id=this.generateAlphaCanvasName(i))}else this.shouldRenderAlpha=!0,this.player.shouldRenderAlpha=!0,this.useCanvasPlayer(t[2])}generateAlphaCanvasName(e){let t=cv[e];return"".concat("alpha","_").concat(t,"_").concat(this.userId)}useCanvasPlayer(e){if(this.log.info("useCanvasPlayer(), has element:".concat(!!this.player.element)),!this.player.element)return;let t=new Kr({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&e?this.generateAlphaCanvasName(e):this.userId});t.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let i=new $v(t,{name:"remotePlayer",logger:this.log});if(this.source=t.createVideoPlayerSource(this.player),this.player.setCanvas(t._canvas),this.shouldRenderAlpha&&e){let r=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},n=new HG(t,this.log,this.shouldBeDraggable,r,{alphaStitchingType:e});this.source.connect(n),n.connect(i),this.alphaNode=n}else this.source.connect(i);zc()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,t),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,i=(r=t,[15,30,45,60].reduce((n,s)=>Math.abs(s-r)<Math.abs(n-r)?s:n));var r;!nt(t)||t<=0?this.log.debug("updateCanvasPlayerFPS() ignore decoder: ".concat(t," ")):i!==e.frameRate?(this.log.info("updateCanvasPlayerFPS() decoder: ".concat(t,", closest: ").concat(i,", current: ").concat(e.frameRate)),e.frameRate=i):this.log.debug("updateCanvasPlayerFPS() ignore ClosestFPS ".concat(i," == ").concat(e.frameRate))}get decodeFPS(){var e;let{msg_video_status:t}=((e=this.room.heartbeatReport)==null?void 0:e.msg_down_stream_info.find(n=>n.msg_user_info.str_identifier===this.userId))||{},i=this.mediaType===2?7:this.isSmall?3:2;if(!t||t.length===0)return 0;let r=t.find(n=>n.uint32_video_stream_type===i);return r?.uint32_video_dec_fps||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),$.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&!(e=t({frame:e,track:this})))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}setDraggable(e){this.shouldBeDraggable=e,this.alphaNode&&(this.alphaNode.draggable=e,this.alphaNode.bindDragEvents())}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}updateKeyFramesDecoded(e){let t=this.stat.keyFramesDecoded||0;if(this.stat.keyFramesDecoded=e,this._keyFrameCountLogged)return;let i=Date.now();if(!this._keyFrameStartTimestamp)return this._keyFrameStartTimestamp=i,this._keyFrameStartCount=e,void(this._prevKeyFrameTimestamp=i);if(this._prevKeyFrameTimestamp&&e>t){let n=e-t,s=(i-this._prevKeyFrameTimestamp)/1e3/n;this._keyFrameIntervals.push(s)}this._prevKeyFrameTimestamp=i;let r=i-this._keyFrameStartTimestamp;if(r>=16e3){let n=e-this._keyFrameStartCount,s=n>0?r/1e3/n:0,o="".concat(n," keyframes in 16s ").concat(s," [").concat(this._keyFrameIntervals.map(c=>c.toFixed(1)).join(","),"] keyFramesDecoded ").concat(e),l=s<=2.5?"debug":"info";this.log[l](o),this._keyFrameCountLogged=!0}}},DD=class extends mu{constructor(e,t){super(e,t,2),m(this,"mediaType",2),m(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}},jo=new Map;function Ht(e,t){let i=xe(ve({},t),{timestamp:ac()});jo.has(e)?jo.get(e).push(i):jo.set(e,[i])}function WG(e,t,i,r){try{if(Jt(e))for(let n=0;n<e.length;n++)wp.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else wp.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}catch(n){throw fe.error(n),n}}function wp(e){let{rule:t,value:i,key:r,fnName:n,className:s}=e;if(j(i)){if(t.required)throw new me({code:te.INVALID_PARAMETER,message:He({key:Fe.INVALID_PARAMETER_REQUIRED,data:{key:r,rule:t,fnName:n,value:i},link:{className:s,fnName:n}})});if(j(t.defaultValue))return;i=t.defaultValue}if(Array.isArray(t.type)){let c=!1;for(let h=0;h<t.type.length;h++)t.type[h]===null&&i===null&&(c=!0),Ut(t.type[h])&&i instanceof t.type[h]&&(c=!0),pt(t.type[h])&&ii(i)===t.type[h].toLowerCase()&&(c=!0);if(!c)throw new me({code:te.INVALID_PARAMETER,message:He({key:Fe.INVALID_PARAMETER_TYPE,data:{key:r,rule:{type:t.type.map(h=>Tc(h)?Oh(h):pt(h)?h:ii(h))},fnName:n,value:i},link:{className:s,fnName:n}})})}else if(!j(t.type)&&ii(i)!==t.type)throw new me({code:te.INVALID_PARAMETER,message:He({key:Fe.INVALID_PARAMETER_TYPE,data:{key:r,rule:t,fnName:n,value:i},link:{className:s,fnName:n}})});if(t.allowEmpty===!1){let c=nt(i)&&(i===0||Number.isNaN(i)),h=pt(i)&&i.trim()==="";if(c||h)throw new me({code:te.INVALID_PARAMETER,message:He({key:Fe.INVALID_PARAMETER_EMPTY,data:{key:r,rule:t,fnName:n,value:i},link:{className:s,fnName:n}})})}if(t.notLessThanZero&&nt(i)&&i<0)throw new me({code:te.INVALID_PARAMETER,message:He({key:Fe.CANNOT_LESS_THAN_ZERO,data:{key:r,rule:t,fnName:n,value:i},link:{className:s,fnName:n}})});if(!j(t.min)&&nt(i)&&i<t.min)throw new me({code:te.INVALID_PARAMETER,message:He({key:Fe.INVALID_PARAMETER_MIN,data:{key:r,rule:t,fnName:n,value:i},link:{className:s,fnName:n}})});if(!j(t.max)&&nt(i)&&i>t.max)throw new me({code:te.INVALID_PARAMETER,message:He({key:Fe.INVALID_PARAMETER_MAX,data:{key:r,rule:t,fnName:n,value:i},link:{className:s,fnName:n}})});if(pt(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new me({code:te.INVALID_PARAMETER,message:He({key:Fe.INVALID_PARAMETER_INSTANCE,data:{key:r,rule:t,fnName:n,value:i},link:{className:s,fnName:n}})})}else if(Ut(t.instanceOf)&&!(i instanceof t.instanceOf))throw new me({code:te.INVALID_PARAMETER,message:He({key:Fe.INVALID_PARAMETER_INSTANCE,data:{key:r,rule:t,fnName:n,value:i},link:{className:s,fnName:n}})});if(t.values&&!t.values.includes(i))throw new me({code:te.INVALID_PARAMETER,message:He({key:Fe.INVALID_PARAMETER_RANGE,data:{key:r,rule:t,fnName:n,value:i},link:{className:s,fnName:n}})});let{properties:o}=t;nr(o)&&Fr(i)&&Object.keys(o).forEach(c=>{wp.call(this,{rule:o[c],value:i&&i[c],key:"".concat(r,".").concat(c),fnName:n,className:s})});let{arrayItem:l}=t;nr(l)&&Jt(i)&&i.forEach((c,h)=>{wp.call(this,{rule:l,value:c,key:"".concat(r,"[").concat(h,"]"),fnName:n,className:s})}),Ut(t.validate)&&t.validate.call(this,i,r,n,s,this)}$.on(ie.JOIN_SUCCESS,e=>{let{room:t}=e;Ht(t.userId,{eventId:32788})}),$.on(ie.LEAVE_START,e=>{let{room:t}=e;Ht(t.userId,{eventId:32789})}),$.on(ie.LOCAL_TRACK_PUBLISHED,e=>{let{track:t}=e;if(t.room){let i=32769;t.mediaType===4?i=32768:t.mediaType===2&&(i=32805),Ht(t.room.userId,{eventId:i})}}),$.on(ie.LOCAL_TRACK_UNPUBLISHED,e=>{let{track:t}=e;if(t.room){let i=32771;t.mediaType===4?i=32770:t.mediaType===2&&(i=32806),Ht(t.room.userId,{eventId:i})}}),$.on(ie.TRACK_MUTED,e=>{let{track:t}=e;t.room&&(t.kind===D.AUDIO?Ht(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):Ht(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))}),$.on(ie.TRACK_UNMUTED,e=>{let{track:t}=e;t.room&&(t.kind===D.AUDIO?Ht(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):Ht(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))}),$.on(ie.REMOTE_TRACK_SUBSCRIBED,e=>{let{track:t}=e;t.room&&(t.mediaType===1&&Ht(t.room.userId,{eventId:32777,remoteUserId:t.userId}),t.mediaType===4&&Ht(t.room.userId,{eventId:32776,remoteUserId:t.userId}),t.mediaType===8&&Ht(t.room.userId,{eventId:32803,remoteUserId:t.userId}))}),$.on(ie.REMOTE_TRACK_UNSUBSCRIBED,e=>{let{track:t}=e;t.room&&(t.mediaType===1&&Ht(t.room.userId,{eventId:32779,remoteUserId:t.userId}),t.mediaType===4&&Ht(t.room.userId,{eventId:32778,remoteUserId:t.userId}),t.mediaType===8&&Ht(t.room.userId,{eventId:32804,remoteUserId:t.userId}))}),$.on(ie.SWITCH_DEVICE_SUCCESS,e=>{let{track:t}=e;t.room&&Ht(t.room.userId,{eventId:t.kind===D.VIDEO?32780:32781})}),$.on(ie.LOCAL_TRACK_REPLACED,e=>{let{track:t}=e;t.room&&Ht(t.room.userId,{eventId:t.kind===D.VIDEO?32782:32783})}),$.on(ie.SIGNAL_CONNECTION_STATE_CHANGED,e=>{let t,{room:i,prevState:r,state:n}=e;switch(n){case"CONNECTED":t=r==="RECONNECTING"?32795:32791;break;case"DISCONNECTED":t=r==="RECONNECTING"?32796:32790;break;case"RECONNECTING":t=32794}t&&Ht(i.userId,{eventId:t})}),$.on(ie.PEER_CONNECTION_STATE_CHANGED,e=>{let t,{room:i,prevState:r,state:n,remoteUserId:s}=e,o=!!s;switch(n){case"CONNECTED":t=r==="RECONNECTING"?o?32801:32798:o?32793:32792;break;case"DISCONNECTED":r==="RECONNECTING"&&(t=o?32802:32799);break;case"RECONNECTING":t=o?32800:32797}t&&Ht(i.userId,{eventId:t,remoteUserId:s})}),$.on(ie.VIDEO_CODEC_IMPLEMENTATION_CHANGED,e=>{let{implementation:t,userId:i,remoteUserId:r,codec:n,isHWCodec:s,prevImplementation:o,streamType:l}=e,c=s?1:0;o||(c=s?3:2);let h={H264:0,H265:1,VP8:2}[n.toUpperCase()],_={eventId:4004,param1:c,param2:h,streamType:l||2};r&&(_.remoteUserId=r,_.eventId=4005),Ht(i,_),ce.addEnum({key:r?514701:513701,value:c}),ce.addEnum({key:r?514700:513700,value:h})}),$.on(ie.LOCAL_TRACK_RECAPTURE,e=>{let{track:t,error:i}=e;if(t.userId){let r={eventId:2003,param1:0};t.kind===D.AUDIO?(r.streamType=1,i&&(r.param1=2)):(r.streamType=t.streamType==="auxiliary"?7:2,i&&(r.param1=8)),Ht(t.userId,r)}});var GG=ti(Ri(),1),jG=class extends GG.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"userId";super(),this.mySelfId=e,this._log=t,this.key=i,m(this,"userMap",new Map),m(this,"remotePublishedUserMap",new Map),m(this,"asrRobotUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:i,tinyId:r,role:n,fromType:s}=e;if(s===Nh)return void this.addAsrRobotUser(e);if(this.userMap.has(t))return;let o={userId:i,tinyId:r,role:n===20?"anchor":"audience"};this.userMap.set(t,o),this.emit("1",o)}addAsrRobotUser(e){let t=e[this.key],{userId:i,tinyId:r,role:n}=e;if(this.asrRobotUserMap.has(t))return;let s={userId:i,tinyId:r,role:n===20?"anchor":"audience"};this.asrRobotUserMap.set(t,s),this.emit("8",s)}deleteUser(e,t){let i=this.userMap.get(e);if(!i)return;if(this.asrRobotUserMap.has(e))return void this.deleteAsrRobotUser(e);let r="peer leave [".concat(e,"]");j(t)||(r+=":".concat(u2[t])),this._log.info(r);let n=this.remotePublishedUserMap.get(e);if(n){let s=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:s,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",{userId:i.userId,reason:t})}deleteAsrRobotUser(e){if(!this.asrRobotUserMap.has(e))return;let t=this.asrRobotUserMap.get(e);t&&(this.asrRobotUserMap.delete(e),this.emit("9",t))}setUserList(e){this.userMap.forEach(t=>{e.findIndex(i=>i[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}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(r=>r[this.key]===t[this.key])<0){this._log.info("remote [".concat(i,"] unpublish"));let r=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(i),this.emit("6",{prevMuteState:r,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var i;let r=t[this.key];if(r===this.mySelfId)return void this.emit("7",t);let{flag:n,userId:s,tinyId:o,fromType:l}=t,c=ca(n,s),h=(i=this.remotePublishedUserMap.get(r))==null?void 0:i.muteState;if(h){let _=this.remotePublishedUserMap.get(r);_&&_.flag!==n&&(_.flag=n,this._log.info("remote publish updated: ".concat(JSON.stringify(_.muteState))),this.emit("6",{prevMuteState:h,muteState:c,flag:n}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(c))),this.addUser({userId:s,tinyId:o,role:20,fromType:l}),this.emit("3",t),this.emit("6",{prevMuteState:ca(0,s),muteState:c,flag:n})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function ND(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:r}=e;return _t((n,s)=>{let o=new WeakMap;return $.on(ie.ROOM_DESTROY,l=>{let{room:c}=l;return o.delete(c)}),function(){let l=o.get(this);for(var c=arguments.length,h=new Array(c),_=0;_<c;_++)h[_]=arguments[_];if(l||(l={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,l)),l.timestamp===0?l.timestamp=Date.now():Date.now()-l.timestamp>1e3&&(l.timestamp=Date.now(),l.callCountInSecond=0,l.totalSizeInSecond=0),r&&(l.totalSizeInSecond+=r(...h)),l.timestamp!==0&&Date.now()-l.timestamp<1e3&&(l.callCountInSecond>=t||l.totalSizeInSecond>i))throw new me({code:te.INVALID_OPERATION,message:He({key:Fe.CALL_FREQUENCY_LIMIT,data:{isTimes:l.callCountInSecond>=t,isSize:l.totalSizeInSecond>i,name:s,timesInSecond:t,maxSizeInSecond:i}})});l.callCountInSecond++,n.call(this,...h)}})}var ee,PD=!0,fu={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"},De={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},Dp=((ee=Dp||{})[ee.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",ee[ee.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",ee[ee.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",ee[ee.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",ee[ee.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",ee[ee.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",ee[ee.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",ee[ee.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",ee[ee.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",ee[ee.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",ee[ee.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",ee[ee.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",ee[ee.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",ee[ee.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",ee[ee.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",ee[ee.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",ee[ee.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",ee[ee.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",ee[ee.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",ee[ee.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",ee[ee.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",ee[ee.INVALID_OPERATION=5100]="INVALID_OPERATION",ee[ee.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",ee[ee.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",ee[ee.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",ee[ee.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",ee[ee.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",ee[ee.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",ee[ee.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",ee[ee.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",ee[ee.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",ee[ee.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",ee[ee.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",ee[ee.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",ee[ee.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",ee[ee.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",ee[ee.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",ee[ee.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",ee[ee.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",ee[ee.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",ee[ee.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",ee[ee.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",ee[ee.DEVICE_ERROR=5300]="DEVICE_ERROR",ee[ee.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",ee[ee.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",ee[ee.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",ee[ee.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",ee[ee.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",ee[ee.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",ee[ee.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",ee[ee.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",ee[ee.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",ee[ee.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",ee[ee.SERVER_ERROR=5400]="SERVER_ERROR",ee[ee.NEED_TO_BUY=5401]="NEED_TO_BUY",ee[ee.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",ee[ee.OPERATION_FAILED=5500]="OPERATION_FAILED",ee[ee.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",ee[ee.REJOIN_FAILED=5502]="REJOIN_FAILED",ee[ee.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",ee[ee.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",ee[ee.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",ee[ee.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",ee[ee.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",ee[ee.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",ee[ee.OPERATION_ABORT=5998]="OPERATION_ABORT",ee[ee.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",ee),OD=xe(ve({},Ir),{INVALID_PARAMETER(e){let{fnName:t}=e;return"the parameters of the '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_PARAMETER_REQUIRED(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' is a required param when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_TYPE(e){let{key:t,rule:i,fnName:r,value:n}=e,s="".concat(t||i.name),o="";return o=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(s,"' must be type of ").concat(o," when calling ").concat(r,"(), received type: ").concat(ii(n),".")},INVALID_PARAMETER_EMPTY(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' cannot be '").concat(n,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE(e){let{key:t,rule:i,fnName:r,value:n}=e,s="".concat(t||i.name),o="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(s,"' must be instanceof ").concat(o," when calling ").concat(r,"(), received type: ").concat(ii(n),".")},INVALID_PARAMETER_RANGE(e){let{key:t,rule:i,fnName:r,value:n}=e;return"'".concat(t||i.name,"' must be one of ").concat(i.values.join("|")," when calling ").concat(r,"(), received: ").concat(n,".")},INVALID_PARAMETER_LESS_THAN_ZERO(e){let{key:t,rule:i,fnName:r}=e;return"'".concat(t||i.name,"' cannot be less than 0 when calling ").concat(r,"().")},INVALID_PARAMETER_MIN(e){let{key:t,rule:i,value:r}=e;return"the min value of ".concat(t||i.name," is ").concat(i.min,", received: ").concat(r,".")},INVALID_PARAMETER_MAX(e){let{key:t,rule:i,value:r}=e;return"the max value of ".concat(t||i.name," is ").concat(i.max,", received: ").concat(r,".")},INVALID_ELEMENT_ID(e){let{key:t,fnName:i}=e;return"'".concat(t,"' is not found in the document object when calling ").concat(i,"().")},INVALID_ELEMENT_ID_TYPE(e){let{key:t,fnName:i,type:r}=e;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(i,"(), received: ").concat(r,".")},INVALID_STREAM_ID(e){let{key:t}=e;return"'".concat(t,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.")},INVALID_ROOM_ID_STRING(e){let{key:t}=e;return"'".concat(t,"' must be a valid string.")},INVALID_ROOM_ID_INTEGER(e){let{key:t}=e;return"'".concat(t,"' must be an integer between [1, 4294967294].")},INVALID_ROOM_ID_INTEGER_STRING(e){let{key:t}=e;return"'".concat(t,"' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.")},INVALID_ROOM_ID_REQUIRED:()=>"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required.",INVALID_ROOM_ID_TYPE_MISMATCH(e){let{key:t}=e;return"The type of target roomId must match the current roomId. Current room is using '".concat(t,"', but received '").concat(t==="strRoomId"?"roomId":"strRoomId","'.")},INVALID_ROOM_ID_DUPLICATE(e){let{key:t}=e;return"the target '".concat(t,"' must not be the same as the current '").concat(t,"'.")},INVALID_STREAM_TYPE:e=>{let{fnName:t}=e;return"'streamType' is required when 'userId' is not '*', calling ".concat(t,"()")},INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION(e){let{fnName:t}=e;return"the API '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_OPERATION_NOT_JOINED(e){let{fnName:t}=e;return"cannot ".concat(t," because you are not enter room yet.")},INVALID_OPERATION_REMOTE_USER_NOT_EXIST(e){let{fnName:t,value:i}=e;return"cannot ".concat(t," because remote user(userId: ").concat(i.userId,") does not publishing stream.")},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST(e){let{fnName:t,value:i}=e;return"cannot ".concat(t," because remote user(userId: ").concat(i.userId,") does not publishing ").concat(i.streamType," video.")},INVALID_OPERATION_REPEAT_CALL(e){let{fnName:t}=e;return"you are already ".concat(t,"(), cannot repeated call '").concat(t,"'.")},INVALID_OPERATION_NEED_VIDEO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the camera is not turned on.")},INVALID_OPERATION_NEED_AUDIO(e){let{fnName:t}=e;return"cannot call '".concat(t,"' because the microphone or screen share is not turned on.")},INVALID_BUFFER_EMPTY:e=>{let{key:t}=e;return"the buffer size of paramerter '".concat(t,"' cannot be empty")},INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:e=>{let{fnName:t}=e;return"you need to call ".concat(t,"() after publish stream.")},ENV_NOT_SUPPORTED(e){let{fnName:t}=e;return"the current browser does not support the capability of the function '".concat(t,"' you are calling, please check the API documentation.")},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION(e){let{fnName:t}=e;return"cannot call ".concat(t," because the browser version is too low, please upgrade to the latest version")},DEVICE_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' got device exception").concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_NOT_FOUND_ERROR(e){let{fnName:t,deviceType:i=ba(t),error:r}=e;return"NotFoundError, no ".concat(i," detected, please check your device and the configuration on '").concat(t,"'").concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_NOT_ALLOWED_ERROR(e){let{fnName:t,deviceType:i=ba(t),error:r}=e;return"NotAllowedError, you have disabled ".concat(i," access, please allow the current application to use the ").concat(i).concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_NOT_READABLE_ERROR(e){let{fnName:t,deviceType:i=ba(t),error:r}=e;return"NotReadableError, the ".concat(i," maybe in use by another APP, please check if the device is pre-occupied by another APP.")},DEVICE_OVERCONSTRAINED_ERROR(e){let{fnName:t,deviceType:i=ba(t),error:r}=e;return"OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct".concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_INVALID_STATE_ERROR(e){let{fnName:t,deviceType:i=ba(t),error:r}=e;return"InvalidStateError, after the user clicks and interacts with the page, turn on the ".concat(i).concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_SECURITY_ERROR(e){let{fnName:t,deviceType:i=ba(t),error:r}=e;return"SecurityError, check whether the system security policy restricts the use of the ".concat(i,", and it is recommended to turn on the ").concat(i," after the user interacts with the page").concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_ABORT_ERROR(e){let{fnName:t,deviceType:i=ba(t),error:r}=e;return"AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal".concat(r?" error: ".concat(r.toString(),"."):".")},CAMERA_RECOVER_FAILED(e){let{error:t}=e;return"camera recover capture failed ".concat(t?.name||"",": ").concat(t?.originMessage||t?.message)},MICROPHONE_RECOVER_FAILED(e){let{error:t}=e;return"microphone recover capture failed ".concat(t?.name||"",": ").concat(t?.originMessage||t?.message)},OPERATION_FAILED(e){let{fnName:t,error:i}=e;return"'".concat(t,"' failed, reason: ").concat(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(i?.name||""," ").concat(i?.message||"")},SERVER_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' got server error: ").concat(i?.toString(),", please check the SDK documentation.")},NEED_TO_BUY(e){let{value:t,url:i}=e;return"You need to buy packages for ".concat(t,". Refer to: ").concat(i)},ACCOUNT_NO_MONEY:e=>{let{fnParams:t}=e;return"your TRTC account run out of credit, please recharge.".concat(t.sdkAppId?" SDKAppId: ".concat(t.sdkAppId):"")},OPERATION_ABORT(e){let{fnName:t}=e;return"'".concat(t,"' abort")},UNKNOWN_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' throw unknown exception").concat(i?", error: ".concat(i.toString(),"."):".")}});function ba(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var zG=class $p extends Error{constructor(t){let{code:i,extraCode:r,message:n="",messageParams:s,fnName:o="",originError:l,data:c}=t;var h;let _;_=n||(function(f){let T,{code:b,params:C,enableDocLink:x=!1}=f,B="",Y=Dp[b];try{T=OD[Y]}catch{T=OD.UNKNOWN_ERROR}return Ut(T)?B=T(C):pt(T)&&(B=T),C.fnName&&!B.includes(C.fnName)&&(B[B.length-1]!=="."&&(B+="."),B+=" thrown from ".concat(C.fnName,"()")),x&&(B+=" doc:"),B})({code:i===De.SERVER_ERROR?i:r||i,params:ve({fnName:o,error:l},s)}),super(_),m(this,"name","RtcError"),m(this,"code"),m(this,"extraCode"),m(this,"functionName"),m(this,"message"),m(this,"data"),m(this,"handler"),m(this,"originError"),this.name=Dp[i],this.code=i,this.extraCode=r,this.functionName=o,this.originError=l,this.message=_,this.data=c,this.extraCode===5302&&(h=this.originError)!=null&&h.message.includes("system")&&(this.handler=()=>{let f=document.createElement("a");Po?f.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):us&&(f.href="x-apple.systempreferences:com.apple.preference.security?Privacy_".concat({startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"}[this.functionName])),f.href.length>0&&f.click()})}static convertFrom(t,i,r){let n=t;if(t instanceof me){let{stack:s}=t,o={code:De.UNKNOWN_ERROR,fnName:i,originError:t};switch(t.getCode()){case te.INVALID_PARAMETER:o.code=De.INVALID_PARAMETER,o.message=t.message;break;case te.INVALID_OPERATION:o.code=De.INVALID_OPERATION;break;case te.NOT_SUPPORTED:case te.NOT_SUPPORTED_H264:o.code=De.ENV_NOT_SUPPORTED,t.getCode()===te.NOT_SUPPORTED_H264&&(o.extraCode=t.message.includes(Ir.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case te.JOIN_ROOM_FAILED:o.messageParams={fnParams:r};case te.SERVER_TIMEOUT:case te.SWITCH_ROLE_FAILED:case te.SWITCH_ROOM_FAILED:o.code=De.SERVER_ERROR,o.extraCode=t.getExtraCode();break;case te.API_CALL_ABORTED:o.code=De.OPERATION_ABORT;break;case te.DEVICE_NOT_FOUND:case te.DEVICE_AUTO_RECOVER_FAILED:case te.INITIALIZE_FAILED:o.code=5300,t.name&&(o.extraCode=(function(l){let c;switch(l){case"NotFoundError":c=5301;break;case"NotAllowedError":c=5302;break;case"NotReadableError":c=5303;break;case"OverconstrainedError":c=5304;break;case"InvalidStateError":c=5305;break;case"SecurityError":c=5306;break;case"AbortError":c=5307;break;default:c=5300}return c})(t.name));break;case te.VIDEO_ENCODE_FAILED:o.extraCode=5505;case te.AUDIO_ENCODE_FAILED:o.extraCode=5506,o.code=De.OPERATION_FAILED;break;case te.UNKNOWN:break;default:o.code=De.OPERATION_FAILED}n=new $p(o),s&&(n.stack+=s.substr(s.indexOf(`
90
+ `)))}else{if(t instanceof $p)return t;n=new $p({code:De.UNKNOWN_ERROR,fnName:i,originError:t})}return n}},Ne=zG;function ji(e){return e==="sub"?"auxiliary":e==="auxiliary"?"sub":"main"}function Np(e){return e===fu.QOS_PREFERENCE_CLEAR?"detail":e===fu.QOS_PREFERENCE_SMOOTH?"motion":""}function Pp(e,t){let i=t?Z1:cc;return F2(e)?ve(ve({},i),e):fn[e]?fn[e]:i}var MD={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{type:["string","object","boolean"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},LD={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}}},zo={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(pt(e)&&!document.getElementById(e))throw new Ne({code:De.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}})}},xD={name:"userId",required:!0,type:"string"},UD={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{type:["string","object"],properties:{bitrate:{type:"number"},channelCount:{type:"number"}}},echoCancellation:{values:[!0,!1,"remote-only","all"]},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Ko(e,t){if(!e)throw new Ne({code:De.INVALID_OPERATION,extraCode:5101,fnName:t})}function VD(e,t,i){if(!e)throw new Ne({code:De.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}function FD(e,t,i){if(!(/^[1-9]\d*$/.test(String(e))&&e<4294967295))throw new Ne({code:De.INVALID_PARAMETER,extraCode:5013,fnName:t,messageParams:{key:i}})}function BD(e,t,i){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e))throw new Ne({code:De.INVALID_PARAMETER,extraCode:5012,fnName:t,messageParams:{key:i}})}function HD(e){var t;if((t=e?.option)==null||!t.small)return;if(!Ev())return fe.warn("small stream is not supported"),void delete e.option.small;let i=Pp(e.option.profile),r=Pp(e.option.small,!0);return((n,s)=>n.width*n.height>=s.width*s.height&&n.frameRate>=s.frameRate&&n.bitrate>=s.bitrate)(i,r)?void 0:(fe.warn("small stream profile must be less than big stream profile. Big: ".concat(JSON.stringify(i),", Small: ").concat(JSON.stringify(r))),void delete e.option.small)}var KG={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 Ne({code:De.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(pt(e.roomId))throw new Ne({code:De.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});FD(e.roomId,i,t)}else{if(!e.strRoomId)throw new Ne({code:De.INVALID_PARAMETER,extraCode:5015,fnName:i});BD(e.strRoomId,i,t)}},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:zo,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:MD},validate(e){var t,i;if(((t=e?.option)==null||!t.videoTrack)&&ga())throw new Ne({code:De.ENV_NOT_SUPPORTED,extraCode:5201});(i=e?.option)!=null&&i.small&&HD(e)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:xe(ve({},zo),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:MD},validate(e){var t;(t=e?.option)!=null&&t.small&&HD(e)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:UD},validate(e){var t;if(((t=e?.option)==null||!t.audioTrack)&&ga())throw new Ne({code:De.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:UD}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:zo,publish:{type:"boolean"},option:LD},validate(e,t,i,r,n){var s;if((s=e?.option)==null||!s.videoTrack){if(ga())throw new Ne({code:De.ENV_NOT_SUPPORTED,extraCode:5201});if(!rp())throw new Ne({code:De.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:zo,publish:{type:"boolean"},option:LD}},muteRemoteAudio:[xD,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[xD,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:zo,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){Ko(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(VD(!!r,i,e),r&&(e.streamType==="main"&&!r.muteState.videoAvailable||e.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new Ne({code:De.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:xe(ve({},zo),{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){Ko(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(VD(!!r,i,e),r){if(e.streamType==="main"&&!r.muteState.videoAvailable||e.streamType==="sub"&&!r.muteState.hasAuxiliary)throw new Ne({code:De.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}});if(e.option){let n=e.streamType==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack;if((e.option.pictureInPicture||e.option.fullScreen||e.option.fullScreen)&&(!n.isSubscribed||!n.player.isPlaying))throw new Ne({code:De.INVALID_OPERATION,message:"cannot set pictureInPicture or fullScreen when remote video is not playing"})}}}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(e,t,i){if(e.userId!=="*"&&j(e.streamType))throw new Ne({code:De.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){Ko(this._room.isJoining||this._room.isJoined,i)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(e,t,i,r){if(!Tv)throw new Ne({code:De.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new Ne({code:De.INVALID_OPERATION,fnName:i,extraCode:5108});if(e.byteLength>1e3)throw new Ne({code:De.INVALID_PARAMETER,extraCode:5018,fnName:i});if(e.byteLength===0)throw new Ne({code:De.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:i});Ko(this._room.isJoined,i)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(e,t,i){if(!e&&!this._room.isMainStreamPublished||e&&!this._room.isAuxStreamPublished)throw new Ne({code:De.INVALID_OPERATION,extraCode:5109,messageParams:{key:t},fnName:i})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(e,t,i,r){if(e.byteLength>1e3)throw new Ne({code:De.INVALID_PARAMETER,extraCode:5018,fnName:i});if(e.byteLength===0)throw new Ne({code:De.INVALID_PARAMETER,extraCode:5017,fnName:i,messageParams:{key:t}})}}},validate(e,t,i){if(Ko(this._room.isJoined,i),this._room.scene==="live"&&this._room.role==="audience")throw new Ne({code:De.INVALID_OPERATION,extraCode:5107,fnName:i,messageParams:{key:t}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(e,t,i){if(Ko(this._room.isJoined,i),this._room.useStringRoomId&&e.strRoomId===this._room.roomId||!this._room.useStringRoomId&&e.roomId===Number(this._room.roomId))throw new Ne({code:De.INVALID_PARAMETER,extraCode:5020,fnName:i,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(e.roomId&&this._room.useStringRoomId||!e.roomId&&e.strRoomId&&!this._room.useStringRoomId)throw new Ne({code:De.INVALID_PARAMETER,extraCode:5019,fnName:i,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(e.roomId)FD(e.roomId,i,t);else{if(!e.strRoomId)throw new Ne({code:De.INVALID_PARAMETER,extraCode:5015,fnName:i});BD(e.strRoomId,i,t)}},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},si={TRTC:KG},zi=class extends Error{};function JG(e,t){let i=ko(e);for(let r=0;r<t.length;r++)gn(i[r],t[r]);return i}function YG(e){this._resolve=Promise.resolve(e)}function qG(e){this._reject=Promise.reject(e)}var WD=class Zo{constructor(t,i){this.instance=t,this.group=i,m(this,"started",!1),m(this,"ops",[]),m(this,"startSame",()=>!0),m(this,"mergeUpdate",JG);let r=Zo.instances.get(t);r?r.set(i,this):Zo.instances.set(t,new Map([[i,this]]))}static get(t,i){if(!i)return;let r=Zo.instances.get(t);return r&&r.get(i)||new Zo(t,i)}static gets(t,i){let r=Zo.instances.get(t),n=[];return r&&r.forEach((s,o)=>{i.test(o)&&n.push(s)}),n}action(t,i,r){let n=l=>{var c;return t===0?this.started=!0:t===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),l},s=l=>{var c,h;throw this.ops.shift(),t===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new zi("start failed")),(h=this.currentOp)==null||h.action(),l},o={type:t,action:()=>i(...o.args).then(n,s),args:r,resolve:YG,reject:qG};try{switch(this.state){case 1:if(t===0)throw new zi("already started");break;case 4:if(t===2)throw new zi("not started");break;default:return this.cacheOp(o)}}catch(l){return Promise.reject(l)}return this.ops.push(o),o.promise=i(...o.args).then(n,s)}cacheOp(t){if(this.ops.length===1)switch(this.state){case 0:case 2:if(t.type===0)throw new zi("already start");break;case 3:switch(t.type){case 2:throw new zi("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new zi("unknown state")}else switch(t.type){case 3:if(this.lastOpType===3)return this.lastOp.promise;{let r=new zi("keep stop");if(this.ops.slice(1).forEach(n=>n.reject(r)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,t.args),this.lastOp.promise;case 3:throw new zi("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new zi("start not allowed after update");case 0:throw new zi("duplicate start");case 3:if(this.startSame(this.currentOp.args,t.args))throw this.ops.pop().reject(new zi("keep start")),new zi("already start")}}t.promise=new Promise((r,n)=>{t._resolve?t._resolve.then(r):t.resolve=r,t._reject?t._reject.catch(n):t.reject=n});let{action:i}=t;return t.action=()=>i().then(t.resolve,t.reject),this.ops.push(t),t.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}};m(WD,"instances",new WeakMap);var _u=WD,Op=new WeakMap,Mp=(e,t)=>{if(t instanceof zi){let{stack:i}=t;t=new Ne({code:De.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf(`
91
+ `)))}throw t};function Ca(e,t){return _t((i,r)=>function(){for(var n=arguments.length,s=new Array(n),o=0;o<n;o++)s[o]=arguments[o];let l=_u.get(this,typeof e=="string"?e:e.call(this,...s));return l?(t&&(l.startSame=t.bind(this)),l.action(0,i.bind(this),s).catch(Mp.bind(null,r))):i.apply(this,s)})}function Jo(e,t){let{merge:i,debounce:r}=t||{};return _t((n,s)=>function(){for(var o=arguments.length,l=new Array(o),c=0;c<o;c++)l[c]=arguments[c];let h=_u.get(this,typeof e=="string"?e:e.call(this,...l));if(!h)return n.apply(this,l);if(i&&(h.mergeUpdate=i.bind(this)),r&&r.isNeedToDebounce.apply(this,l)){let{delay:_,getKey:f}=r;return new Promise((T,b)=>{var C,x;let B=(C=Op.get(this))==null?void 0:C.get(f(...l));if(B){let{timeoutId:G,resolve:he}=B;clearTimeout(G),he()}let Y=setTimeout(()=>{if(h.state===3||h.state===4)return T();h.action(2,n.bind(this),l).catch(Mp.bind(null,s)).then(T,b)},_);Op.has(this)?(x=Op.get(this))==null||x.set(f(...l),{timeoutId:Y,resolve:T}):Op.set(this,new Map([[f(...l),{timeoutId:Y,resolve:T}]]))})}return h.action(2,n.bind(this),l).catch(Mp.bind(null,s))})}function ka(e){return _t((t,i)=>function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];let o=typeof e=="function"?e.call(this,...n):e;if(o instanceof RegExp)return Promise.all(_u.gets(this,o).map(c=>c.action(3,()=>Promise.resolve(),n))).then(()=>t.call(this,...n));let l=_u.get(this,o);return l?l.action(3,t.bind(this),n).catch(Mp.bind(null,i)):t.apply(this,n)})}function wa(){return function(e,t,i){return e.prototype[t]=function(){let r=this._log||console,n='"'.concat(t,'" is a static method. Use TRTC.').concat(t,"() instead. See: ").concat(mn,"/en/TRTC.html#.").concat(t);r.warn(n)},i}}var Se={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame",PERMISSION_STATE_CHANGE:"permission-state-change",VIDEO_SIZE_CHANGED:"video-size-changed",REALTIME_TRANSCRIBER_MESSAGE:"realtime-transcriber-message",REALTIME_TRANSCRIBER_STATE_CHANGED:"realtime-transcriber-state-changed",PICTURE_IN_PICTURE_STATE_CHANGED:"picture-in-picture-state-changed",FULL_SCREEN_STATE_CHANGED:"full-screen-state-changed"},XG=new Set([Se.AUDIO_VOLUME,Se.AUDIO_FRAME,Se.NETWORK_QUALITY,Se.STATISTICS,Se.SEI_MESSAGE,Se.CUSTOM_MESSAGE,Se.LAYER_DATA]),GD={};pn(GD,{ScheduleRequestType:()=>KD,getAbilityConfig:()=>ZG,getScheduleDomain:()=>lE,isNeedToSchedule:()=>Lp,scheduleProxy:()=>An,sendScheduleRequest:()=>zD,setIsNeedToSchedule:()=>Jr,setScheduleProxy:()=>oE});var aE=null,jD=0,QG=1728e5,Lp=!0;function Jr(e){Rt(e)&&e!==Lp&&(Lp=e,fe.info("setIsNeedToSchedule ".concat(e)),e||(jD=Date.now()+QG))}function zD(e){return P(this,arguments,function(t){let{userId:i,sdkAppId:r,useStringRoomId:n,roomId:s,userSig:o,version:l,frameWorkType:c,role:h,latencyLevel:_}=t;return(function*(){var f;if(!Lp&&aE&&jD>Date.now())return{isCached:!0,result:aE};let T={delta:0,count:[1,1],msg:[],detail:[]};try{let b=new FormData;b.append("userId",String(i)),b.append("sdkAppId",String(r)),b.append("isStrGroupId",String(n)),b.append("groupId",String(s)),b.append("sdkVersion",l),b.append("userSig",String(o));let C=((f=yield ep())==null?void 0:f.model)||nv();C&&b.append("model",C);let x=xo();x&&b.append("osString",x);let B=Mo();B&&b.append("gpu",B),h&&b.append("role",String(h)),_&&b.append("latencyLevel",String(_)),c&&b.append("frameWorkType",String(c));let Y=Ue(),G=yield(function(H,Z,de){return new Promise((pe,Pe)=>{let be=null;Sc([JD(je=>Z.count[0]=je+1,je=>{let{error:Oe,retry:Be,retriedCount:at,retryFuncArgs:yt}=je;Z.msg[0]=Oe.message,be||(at>=1&&(yt[0]=vs(de,"config",D.MAIN,!0)),Be())})(vs(de,"config",D.MAIN),H,{get timeout(){return 1e3*Co(2+Z.count[0])}}),JD(je=>Z.count[1]=je+1,je=>{let{error:Oe,retry:Be,retriedCount:at,retryFuncArgs:yt}=je;Z.msg[1]=Oe.message,be||(at>=2&&(yt[0]=vs(de,"config",D.BACKUP,!0)),Be())})(vs(de,"config",D.BACKUP),H,{get timeout(){return 1e3*Co(2+Z.count[1])}})]).then(je=>{be=je,pe(be)}).catch(Pe)})})(b,T,r);G.config&&(G.config.loggerDomain&&oc(G.config.loggerDomain),Rt(G.config.scheduleCache)&&Jr(!G.config.scheduleCache)),T.delta=Ue()-Y;let he=(function(H,Z,de){let pe={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let Pe=performance.getEntriesByType("resource"),be=vs(H,"config",D.MAIN),je=vs(H,"config",D.BACKUP);for(let Oe of Pe)if(Oe.startTime>=de&&(Oe.name===be||Oe.name===je)&&Oe.transferSize>0){let Be=Oe.name===be?D.MAIN:D.BACKUP,at=Math.round(Oe.duration),yt=Math.round(Oe.domainLookupStart-Oe.startTime),gt=Oe.redirectStart>0?Math.round(Oe.redirectEnd-Oe.redirectStart):0,Ma=Oe.fetchStart>0?Math.round(Oe.domainLookupStart-Oe.fetchStart):0,Vi=Math.round(Oe.domainLookupEnd-Oe.domainLookupStart),qN=Math.round(Oe.requestStart-Oe.secureConnectionStart),XN=Math.round(Oe.secureConnectionStart-Oe.connectStart),QN=Math.round(Oe.responseStart-Oe.requestStart),ZN=Math.round(Oe.responseEnd-Oe.responseStart),Rz=[Vi,qN,XN,QN,ZN];dt.uploadEvent({log:"stat-schedule-net:".concat(at,"(").concat(yt,"(").concat(gt,"->").concat(Ma,")->").concat(Rz.join("->"),") ").concat(Be),userId:Z}),pe=xe(ve({},pe),{totalCost:at,local:yt,dns:Vi,tcp:XN,tls:qN,request:QN,response:ZN});break}}catch(Pe){fe.error("getScheduleDetailCost error",Pe)}return pe})(Number(r),i,Y);return aE=G,{isCached:!1,result:G,detailCost:he}}catch(b){let C=Jt(b)?b[0]:b,x=nt(C.code)?C.code:0,B="schedule failed".concat(C.message?": ".concat(C.message):""),Y=new me({code:te.SCHEDULE_FAILED,extraCode:x,message:He({key:Fe.JOIN_ROOM_FAILED,data:{error:B,code:x}})});throw fe.error(B,x),Y}})()})}typeof document<"u"&&document.head.insertAdjacentHTML("beforeend",Object.values(as).map(e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">')).join(`\r
92
+ `)),$.on("28",()=>Jr(!0)),$.on("63",()=>Jr(!0)),$.on("84",()=>Jr(!0)),$.on("201",e=>{e.state==="RECONNECTING"&&Jr(!0)}),$.on("202",e=>{e.state==="RECONNECTING"&&Jr(!0)});var An={main:"",backup:""};function oE(e){Jt(e)?(An.main=e[0],An.backup=e[1]):(An.main=e,An.backup=e)}var KD=(e=>(e.CONFIG="config",e.TRTC_AUTO_CONF="trtcAutoConf",e.AUDIO_AI_AUTH="audioAiAuth",e))(KD||{});function vs(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:D.MAIN,r=arguments.length>3&&arguments[3]!==void 0&&arguments[3];return"https://".concat(An[i]||lE(e,i,r),"/api/v1/").concat(t)}function ZG(e,t,i){let r=vs(e,t),n=vs(e,t,D.BACKUP),s=new URLSearchParams(i).toString(),o=fetch("".concat(r,"?").concat(s)).then(c=>c.json()),l=fetch("".concat(n,"?").concat(s)).then(c=>c.json());return Sc([o,l])}function lE(e){let t,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:D.MAIN,r=arguments.length>2&&arguments[2]!==void 0&&arguments[2];return t=os(e)?r?i===D.MAIN?as.MAIN_OVERSEA_BACKUP:as.BACKUP_OVERSEA:i===D.MAIN?as.MAIN_OVERSEA:as.BACKUP_OVERSEA:i===D.MAIN?as.MAIN:as.BACKUP,t}function $G(e,t,i){return new Promise((r,n)=>{bc({url:e,body:t,timeout:i.timeout,priority:"high"}).then(s=>{s.data.code===0?r(s.data.data):n({code:s.data.code,message:s.data.msg})}).catch(n)})}var JD=(e,t)=>Cc({retryFunction:$G,settings:{retries:3,timeout:0},onError:t,onRetrying:e}),cE=class{constructor(){m(this,"_log"),this._log=fe.createLogger({id:"fd"})}download(e,t){return P(this,null,function*(){let{type:i="blob"}=t||{};e=A0(e);try{let r,n=Ue();if(r=Ut(fetch)?yield this.downloadWithFetch(e,i):yield this.downloadWithXHR(e,i),!r||!r.data)throw new Error("data is empty");let s=Ue()-n;return this._log.info("downloaded: ".concat(e,", return type: ").concat(i,", cost: ").concat(s,"ms")),ce.addSuccessEvent({key:522700,cost:Ue()-n}),r.data}catch(r){throw this._log.error("failed to download: ".concat(e,", error: ").concat(r)),ce.addFailedEvent({key:522700,error:r}),r}})}downloadWithFetch(e,t){return P(this,null,function*(){this._log.info("download with fetch: ".concat(e,", return type: ").concat(t));try{let i,r=yield fetch(e);if(!r.ok){let n=new Error("network response was not ok: ".concat(r.status));throw n.status=r.status,n}return i=t==="arraybuffer"?yield r.arrayBuffer():yield r.blob(),{data:i}}catch(i){throw i}})}downloadWithXHR(e,t){return this._log.info("download with xhr: ".concat(e,", return type: ").concat(t)),new Promise((i,r)=>{let n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType=t,n.onload=()=>{if(n.status===200||n.status===0&&n.response)i({data:n.response});else{let s=new Error("XHR failed, status: ".concat(n.status));s.status=n.status,r(s)}},n.onerror=r,n.send(null)})}loadWasm(e,t){return P(this,null,function*(){this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t)));let i=Ue(),r=null,n=null;if(Ut(WebAssembly.instantiateStreaming)&&!e.startsWith("data:application/octet-stream;base64,")&&!(s=>s.startsWith("file://"))(e)&&Ut(fetch))try{let s=fetch(e);r=(yield WebAssembly.instantiateStreaming(s,t)).instance}catch(s){n=s}if(!r)try{let s=yield this.download(e,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(s,t)).instance}catch(s){n=s}if(r){let s=Ue()-i;return this._log.info("loadedWasm ".concat(e,", cost: ").concat(s,"ms")),ce.addSuccessEvent({key:522701,cost:s}),r}throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(n)),ce.addFailedEvent({key:522701,error:n}),n})}loadScript(e){this._log.info("loadScript ".concat(e));let t=Ue();return new Promise((i,r)=>{let n=document.createElement("script");n.type="text/javascript",n.onload=()=>{this._log.info("loadedScript ".concat(e,", cost: ").concat(Ue()-t,"ms")),ce.addSuccessEvent({key:522702,cost:Ue()-t,split:1e3}),i(n)},n.onerror=s=>{this._log.error("failed to loadScript ".concat(e,", error: ").concat(s?.message||JSON.stringify(s))),ce.addFailedEvent({key:522702}),r(s)},n.crossOrigin="anonymous",n.src=e,document.head.append?document.head.append(n):document.getElementsByTagName("head")[0].appendChild(n)})}};_e([hs({settings:{timeout:0,retries:3},onError(e,t,i){var r;e?.status===404||(r=e?.message)!=null&&r.includes("404")?(this._log.warn("download 404, stop retry"),i(e)):t()},onRetrying(e){this._log.warn("download retrying: ".concat(e))}})],cE.prototype,"download"),_e([hs({settings:{timeout:3e3,retries:3},onRetrying(e){this._log.warn("loadScript retrying: ".concat(e))}})],cE.prototype,"loadScript");var uE=new cE;function YD(e){let[t,i]=e,r=i.byteLength,n=parseInt(String(r/255),10),s=r%255,o=[];o.push(0,0,0,1,6,t);for(let c=0;c<n;c++)o.push(255);o.push(s);let l=new DataView(i);return o.push(...new Uint8Array(l.buffer)),o.push(128),new bp(new DataView(new Uint8Array(o).buffer),!0)}function qD(e){return e.type==="empty"||e.data.byteLength===0}function XD(e){let t=new DataView(e),i=0;for(;i<t.byteLength;){let r=Ap(t,i);if(r===0){i+=1;continue}let n=i+r;if(n<t.byteLength&&(31&t.getUint8(n))==6)return!0;i+=r+1}return!1}function QD(e){let t=0,i=0,r=new DataView(e);for(let n=0;n<e.byteLength;n++)switch(r.getUint8(n)){case 0:t++;break;case 1:(t===2||t===3)&&i++,t=0;break;default:t=0}return i}function ZD(e){let{frame:t,seiMessageList:i}=e;if(!i||i.length===0||t.data.byteLength===0)return t;let r=9-QD(t.data);if(r<=0)return t;let n=i.splice(0,r).reverse().map(YD),s=n.reduce((_,f)=>_+f.dataView.byteLength,0),o=new ArrayBuffer(s+t.data.byteLength),l=new DataView(o),c=new DataView(t.data),h=0;for(let _=0;_<n.length;_++)for(let f=0;f<n[_].dataView.byteLength;f++)l.setInt8(h++,n[_].dataView.getInt8(f));for(let _=0;_<t.data.byteLength;_++)l.setInt8(h++,c.getInt8(_));return t.data=o,t}function $D(e){let{frame:t,onSEI:i}=e;try{if(qD(t)||!XD(t.data))return t;let r=ID(t.data,!1).filter(n=>n.isSEI);i?.(r.reverse())}catch{}return t}function eN(e){let{seiMessageList:t,isAudio:i,getNtpTime:r,isMain:n}=e;return new TransformStream({transform(s,o){let l=s;i?audioEncodePipeline.forEach(c=>{l=c({frame:l,ntp:r(),onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:l.data,userId:""})}})}):videoEncodePipeline.forEach(c=>{l=c({frame:l,seiMessageList:t,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:l.data,userId:"",streamType:n?"main":"auxiliary"})}})}),o.enqueue(l)}})}function tN(e){let{userId:t,streamType:i,isAudio:r}=e;return new TransformStream({transform(n,s){let o=n;r?(audioDecodePipeline.forEach(l=>{o=l({frame:o,onAudioFrameNTPTime:c=>{self.postMessage({type:"audio-ntp",data:c,userId:t,streamType:i})},onDump:()=>{self.postMessage({type:"dump",isAudio:r,data:o.data,userId:t})}})}),s.enqueue(o)):videoDecodePipeline.forEach(l=>{o=l({frame:o,onSEI:c=>{c.forEach(h=>{self.postMessage({type:"sei",seiPayloadType:h.seiPayloadType,data:h.seiPayload.buffer,userId:t,streamType:i})})},onDump:()=>{self.postMessage({type:"dump",isAudio:r,data:o.data,userId:t,streamType:i})}})}),s.enqueue(o)}})}function iN(e){let t=[bp],i=[QD,qD,ID,XD,YD,eN,tN,w0,k0,Ap],r="const videoEncodePipeline=[".concat(e.videoEncodePipeline.toString(),`];
93
+ const videoDecodePipeline=[`).concat(e.videoDecodePipeline.toString(),`];
94
+ const audioEncodePipeline = [`).concat(e.audioEncodePipeline.toString(),`];
95
+ const audioDecodePipeline = [`).concat(e.audioDecodePipeline.toString(),"];"),n="(()=>{".concat(t.map(c=>"const ".concat(c.name,"=(()=>").concat(c.toString(),")()")).join(`
96
+ `),`
97
+ `).concat(i.map(c=>c.toString()).join(`
98
+ `),";(").concat(()=>{let c=[],h=[],_=[],f=0;self.onmessage=T=>{switch(T.data.type){case"sei":T.data.isMain?(c.push(T.data.data),T.data.small&&_.push(T.data.data)):h.push(T.data.data);break;case"ntp-offset":f=T.data.data}},self.onrtctransform=T=>{let{options:b}=T.transformer,C=b.isReceiver?tN({userId:b.userId,streamType:b.streamType,isAudio:b.isAudio}):eN({getNtpTime:()=>Date.now()+f,isAudio:b.isAudio,isMain:b.isMain,seiMessageList:b.isMain?b.small?_:c:h});T.transformer.readable.pipeThrough(C).pipeTo(T.transformer.writable)}},")();").concat(r,"})()"),s=new Blob([n],{type:"text/javascript"}),o=URL.createObjectURL(s),l=new Worker(o);return URL.revokeObjectURL(o),l}var rN,dE=class{constructor(e){m(this,"audioPlayer"),m(this,"videoPlayer"),m(this,"log"),this.audioPlayer=e.audioPlayer,this.videoPlayer=e.videoPlayer,this.log=e.log.createChild({id:"pip"}),this.videoPlayer.on(Me.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.on(Me.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.on(Me.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(Me.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(Me.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.on(Me.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.on(Me.VOLUME_CHANGE,this.handleVolumeChange,this)}handleUserResumeInPIPOrFullScreen(){this.audioPlayer.isPaused&&(this.log.warn("resume audio in ".concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.doResume()),Vt&&Oo&&this.videoPlayer.resetSrcObjectToReplay()}handleUserPauseInPIPOrFullScreen(){this.audioPlayer.isPaused||(this.log.warn("pause audio in ".concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.doPause())}handleEnterPIPOrFullScreen(){this.videoPlayer.element&&this.audioPlayer.muted!==this.videoPlayer.element.muted&&(this.log.warn("sync video muted to ".concat(this.audioPlayer.muted," when enter ").concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.videoPlayer.element.muted=this.audioPlayer.muted)}handleLeavePIP(){this.audioPlayer.isPaused&&!this.audioPlayer.isPausedByUserCall&&(this.log.warn("resume after leave pip"),this.audioPlayer.doResume()),this.videoPlayer.isPaused&&!this.videoPlayer.isPausedByUserCall&&(this.log.warn("resume video after leave pip"),this.videoPlayer.doResume())}handleLeaveFullScreen(){this.audioPlayer.isPaused&&!this.audioPlayer.isPausedByUserCall&&(this.log.warn("resume audio after leave fullscreen"),this.audioPlayer.doResume()),this.videoPlayer.isPaused&&!this.videoPlayer.isPausedByUserCall&&(this.log.warn("resume video after leave fullscreen"),Vt&&Oo?this.videoPlayer.resetSrcObjectToReplay():this.videoPlayer.doResume())}handleVolumeChange(e){e.muted!==void 0&&this.audioPlayer.muted!==e.muted&&(this.log.warn("sync audio muted to ".concat(e.muted," in ").concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.setMuted(e.muted))}destroy(){this.videoPlayer.off(Me.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.off(Me.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.off(Me.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(Me.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(Me.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.off(Me.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.off(Me.VOLUME_CHANGE,this.handleVolumeChange,this)}},nN=!1;function ej(e){var t=this;let{TRTC:i,room:r,errorModule:n,assetsPath:s}=e;return{TRTC:i,LocalMixVideoTrack:tE,LocalVideoTrack:Rn,LocalScreenTrack:Ra,room:r,assetsPath:s,fileDownloader:uE,innerEmitter:$,INNER_EVENT:ie,constants:z1,environment:B2,utils:AD,eventLogger:dt,log:this.room.getLogger(),loggerManager:fe,errorModule:n,kvStatManager:ce,rtcDectection:Vc,trtc:this,rx:eD,enums:ak,schedule:GD,getDevices:fp,initVisionTaskRegistry:function(o,l){let c=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"/mediapipe/vision.js";return P(t,null,function*(){!window.VisionTaskRegistry&&!nN&&(nN=!0,rN=uE.loadScript("".concat(o,"/").concat(c).replace(/([^:]\/)\/+/g,"$1"))),yield rN,yield(yield window.VisionTaskRegistry.getInstance(o)).preloadModels(l)})},audioContext:pi(),deviceDetector:Xt,AudioPlayer:Hv,RemoteAudioPlayer:Yw,VideoPlayer:jr,showAutoPlayDialog:Mv,Timer:ft,clearStarted:(o,l)=>{let c=o.getAlias(),h=_u.instances.get(this);if(h)if(l){let _=h.get(c+l);if(!_)return;_.started=!1}else h.forEach((_,f)=>{f.startsWith(c)&&(_.started=!1)})},startGetPCM:sE,createAudioNode:Vv,getNetworkTimeOffset:H9,validateSourceNode:()=>{var o;if(ut&&((o=this.room.audioManager._localAudioPipline)==null||!o.source.node))throw new Ne({code:De.DEVICE_ERROR,extraCode:5310,message:"The audio processing plugin cannot be used due to the microphone's sampling rate is not 48KHz in Firefox. Please switch to another browser such as Chrome."})},createScriptTransformWorker:iN,AVPlayerStateSyncManager:dE,PlayerEvent:Me}}var Yo=new WeakMap,sN="5.15.0";function vi(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return _t((r,n)=>function(){for(var s=arguments.length,o=new Array(s),l=0;l<s;l++)o[l]=arguments[l];try{hE.call(this,t,o,n,this._name)}catch(c){return Promise.reject(c)}return r.apply(this,o)})}function aN(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return _t((r,n)=>function(){for(var s=arguments.length,o=new Array(s),l=0;l<s;l++)o[l]=arguments[l];try{hE.call(this,t,o,n,this._name)}catch(c){throw c}return r.apply(this,o)})}function hE(e,t,i,r){if(Jt(e))for(let n=0;n<e.length;n++)xp.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else xp.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function xp(e){let{rule:t,value:i,key:r,fnName:n,className:s}=e;function o(h){return{code:De.INVALID_PARAMETER,extraCode:h,fnName:n,messageParams:{key:r,rule:t,value:i}}}if(j(i)){if(t.required)throw new Ne(o(5001));if(j(t.defaultValue))return void(Ut(t.validate)&&t.validate.call(this,i,r,n,s,this));i=t.defaultValue}if(Array.isArray(t.type)){let h=!1;for(let _=0;_<t.type.length;_++)t.type[_]===null&&i===null&&(h=!0),Ut(t.type[_])&&i instanceof t.type[_]&&(h=!0),pt(t.type[_])&&ii(i)===t.type[_].toLowerCase()&&(h=!0);if(!h)throw new Ne({code:De.INVALID_PARAMETER,extraCode:5002,fnName:n,messageParams:{key:r,rule:{type:t.type.map(_=>Tc(_)?Oh(_):pt(_)?_:ii(_))},value:i}})}else if(!j(t.type)&&ii(i)!==t.type)throw new Ne(o(5002));if(t.allowEmpty===!1){let h=nt(i)&&(i===0||Number.isNaN(i)),_=pt(i)&&i.trim()==="";if(h||_)throw new Ne(o(5003))}if(t.notLessThanZero&&nt(i)&&i<0)throw new Ne(o(5006));if(!j(t.min)&&nt(i)&&i<t.min)throw new Ne(o(5007));if(!j(t.max)&&nt(i)&&i>t.max)throw new Ne(o(5008));if(pt(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new Ne(o(5004))}else if(Ut(t.instanceOf)&&!(i instanceof t.instanceOf))throw new Ne(o(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new Ne(o(5005));let{properties:l}=t;nr(l)&&Fr(i)&&Object.keys(l).forEach(h=>{xp.call(this,{rule:l[h],value:i&&i[h],key:"".concat(h),fnName:n,className:s})});let{arrayItem:c}=t;nr(c)&&Jt(i)&&i.forEach((h,_)=>{xp.call(this,{rule:c,value:h,key:"".concat(r,"[").concat(_,"]"),fnName:n,className:s})}),Ut(t.validate)&&t.validate.call(this,i,r,n,s,this)}var tj=0;function kt(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{getRemoteId:t=()=>"",replaceArg:i,getKVReportKey:r,ignoreLog:n,ignoreErrorLog:s}=e;return _t((o,l)=>function(){for(var c=arguments.length,h=new Array(c),_=0;_<c;_++)h[_]=arguments[_];var f,T,b;function C(he,H,Z){if(Z&&Z.includes(he))return"hided";if(i){let de=i(...h);if(h[de.argIndex]===H)return de.value}if(H===h||he in h)return H;try{return H instanceof HTMLElement?"id: ".concat(H.id," type:").concat(ii(H)):H instanceof MediaStreamTrack?b0(H):(JSON.stringify(H),H)}catch{return"type:".concat(ii(H))}}let x=(this==null?void 0:this._log)||fe,B=++tj;if(n!=null&&n(...h))return o.apply(this,h);h.length>0?x.info("".concat(l,"() ").concat(B," ").concat(JSON.stringify(h,(he,H)=>C(he,H,["userSig","privateMapKey"])))):x.info("".concat(l,"() ").concat(B));let Y=r?r(...h):ew[l],G=s?.(...h)||!1;try{let he=o.apply(this,h),H=Ue();if(yc(he)){let Z="".concat(l.includes("Plugin")?"".concat(((T=(f=h[0]).getName)==null?void 0:T.call(f))||""," "):" ");return he.then(de=>(x.info("".concat(l,"() success ").concat(B," ").concat(Z).concat(t.call(this,...h))),ce.addSuccessEvent({key:Y,cost:Ue()-H}),de)).catch(de=>{var pe;let Pe=(de=Ne.convertFrom.call(this,de,l,h.length===1?h[0]:h)).extraCode||de.code,be=(pe=de.message)!=null&&pe.includes(Pe)?"":" code:".concat(Pe),je=de?.code===De.OPERATION_ABORT;throw G||x[je?"warn":"error"]("".concat(l,"() failed ").concat(B," ").concat(Z).concat(t.call(this,...h)," ").concat(de).concat(be," params: ").concat(JSON.stringify(h,C))),ce.addFailedEvent({key:Y,error:de}),de})}return ce.addSuccessEvent({key:Y}),he}catch(he){let H=(he=Ne.convertFrom.call(this,he,l)).extraCode||he.code,Z=(b=he.message)!=null&&b.includes(H)?"":" code:".concat(H),de=he?.code===De.OPERATION_ABORT;throw G||x[de?"warn":"error"]("".concat(l,"() failed ").concat(B," ").concat(he).concat(Z," params: ").concat(JSON.stringify(h,C))),ce.addFailedEvent({key:Y,error:he}),he}})}var pE,mE=e=>_t((t,i)=>function(r,n){return P(this,null,function*(){let s=this._plugins.get(r);if(!s)throw this._log.error("plugin ".concat(String(r)," is not found")),new Ne({code:De.OPERATION_ABORT,message:"plugin ".concat(String(r)," is not found"),fnName:i});if(Ut(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error("plugin ".concat(String(r)," is not supported")),new Ne({code:De.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(r)," is not supported"),extraCode:5210,fnName:i});return hE.call(this,s.getValidateRule(e),[n],i,"TRTC"),t.call(this,s,n)})}),fE=0,Up=class Tu{constructor(t){this.core=t,m(this,"log"),m(this,"customAudioReferenceMap",new Map),m(this,"audioRefId",0),m(this,"audioContext",pi()),m(this,"localAudioWorkletNode"),m(this,"screenAudioWorkletNode"),m(this,"mixNode"),m(this,"silentNode"),fE+=1,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(fE)}),this.log.info("created id=".concat(this.getAlias()).concat(fE)),this.installEvent()}static getStartValidateRule(t){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(i,r,n,s){if(!t.room.audioManager.hasAudioTrack&&!t.room.audioManager.hasScreenAudioTrack)throw new Ne({code:De.INVALID_OPERATION,extraCode:5106,fnName:n})}}}preload(t){return pE||(pE=this.doPreload(t)),pE}doPreload(t){return P(this,null,function*(){let i=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(i);try{yield dp(this.audioContext,r)}catch(n){this.log.error("preload audioProcessor failed. ".concat(n))}finally{URL.revokeObjectURL(r)}})}getName(){return Tu.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return Tu.getStartValidateRule(this.core);case"update":return Tu.updateValidateRule;case"stop":return Tu.stopValidateRule}}start(t){return P(this,null,function*(){var i,r,n,s;let{room:o}=this.core,{sdkAppId:l,userId:c,userSig:h,assetsPath:_=this.core.assetsPath,audioReference:f,processLevel:T,enableDump:b,isLocalAudioNeedAudioProcess:C=!0,isScreenAudioNeedAudioProcess:x=!1}=t;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=C,this.core.room.audioManager.isScreenAudioNeedAudioProcess=x,!_)throw new Ne({code:De.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload("".concat(_,"/audioProcessor-wasm.js")),C&&!this.localAudioWorkletNode){let{sign:B,status:Y,timestamp:G}=yield this.getAuthData(l,c,h);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",l,c,G,B,Y,o)}if(x&&!this.screenAudioWorkletNode){let{sign:B,status:Y,timestamp:G}=yield this.getAuthData(l,c,h);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",l,c,G,B,Y,o)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),(i=this.localAudioWorkletNode)==null||i.port.postMessage({type:"enable"}),(r=this.screenAudioWorkletNode)==null||r.port.postMessage({type:"enable"}),o.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),j(f)||f.forEach(B=>{this.customAudioReferenceMap.set(B,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:B,refId:"o-".concat(this.audioRefId++)})}),j(T)||(n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:T}}),j(b)||(s=this.localAudioWorkletNode)==null||s.port.postMessage({type:"dump",data:{enable:b}})})}update(t){return P(this,null,function*(){var i,r,n;let{audioReference:s,enableDump:o,processLevel:l}=t;j(s)||(this.customAudioReferenceMap.forEach((c,h)=>{this.customAudioReferenceMap.delete(h),this.core.room.audioManager.updateAudioReference({type:"remove",refId:c})}),s.forEach(c=>{this.customAudioReferenceMap.set(c,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:c,refId:"o-".concat(this.audioRefId++)})})),j(l)||(i=this.localAudioWorkletNode)==null||i.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:l}}),j(o)||((r=this.localAudioWorkletNode)==null||r.port.postMessage({type:"dump",data:{enable:o}}),(n=this.screenAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:o}}))})}stop(){return P(this,null,function*(){var t,i;let{room:r}=this.core;(t=this.localAudioWorkletNode)==null||t.port.postMessage({type:"disable"}),(i=this.screenAudioWorkletNode)==null||i.port.postMessage({type:"disable"}),yield r.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(t,i,r){return P(this,null,function*(){let n=String(Date.now()).slice(0,-3),{auth:s,sign:o,status:l,message:c}=yield(function(h){return P(this,arguments,function(_){let{sdkAppId:f,userId:T,userSig:b,timestamp:C}=_;return(function*(){let x="".concat((function(Pe){let be=arguments.length>1&&arguments[1]!==void 0?arguments[1]:D.MAIN;return"https://".concat(An[be]||lE(Pe,be),"/api/v1/audioAiAuth")})(f),"?sdkAppId=").concat(f,"&userId=").concat(T,"&userSig=").concat(b,"&timestamp=").concat(C),B=yield fetch(x),{data:{errCode:Y,errMsg:G,sign:he,status:H}}=yield B.json();if(H==="1")return{auth:!0,sign:he,status:H,message:G};let Z=os(f)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",de="Init RTCAudioProcessor failed.",pe="";switch(Y){case 1:pe="Please check your params.";break;case 2:pe="You need to buy packages. Refer to: ".concat(Z);break;case 3:pe="Server is invalid. Please contact our engineer. ";break;case 4:pe="Your packages is not active. Refer to: ".concat(Z);break;case 5:pe="Your packages is expired. Refer to: ".concat(Z);break;case 6:pe="Your version is not supported."}return{auth:!1,status:H,message:G?"".concat(de," Reason: ").concat(G,". ").concat(pe):"".concat(de,", ").concat(pe)}})()})})({sdkAppId:t,userSig:r,userId:i,timestamp:n});if(!s)throw this.log.info("audioProcessor: ".concat(i," auth result: ").concat(s,". Message: ").concat(c)),new Ne({code:De.INVALID_PARAMETER,message:c});return{sign:o,status:l,timestamp:n}})}initWorkletNode(t,i,r,n,s,o,l,c){t.port.postMessage({type:"init",data:{sdkAppId:String(r),userId:n,timestamp:s,sign:o,status:l}}),t.port.onmessage=h=>{var _;let{data:f}=h;switch(f.type){case"cost":let T=f?.value>10?"info":"debug";return void this.log[T]("".concat(i==="localAudio"?"":"[".concat(i,"] "),"avg cost: ").concat(f.value," max: ").concat(f?.max,"(").concat(Jg(new Date(f?.maxCostTimestamp)),") hist: ").concat((_=f?.hist)==null?void 0:_.join(" ")));case"log":return void this.log[f.logLevel]("".concat(i==="localAudio"?"":"[".concat(i,"] ")).concat(f.value));case"dump":return void $.emit("265",{room:c,data:f.value,type:i==="localAudio"?"dump":"dump-screen-audio"})}}}handleLocalAudioStarted(t){return P(this,null,function*(){var i;if(this.hitTest(t.room)&&((i=this.core.room.scheduleResult.config)==null?void 0:i.audioProcessor)===!0)try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(r){this.log.warn("audio processor auto start failed, error: ".concat(r))}})}handleLocalAudioStopped(t){return P(this,null,function*(){var i;!this.hitTest(t.room)||((i=this.core.room.scheduleResult.config)==null?void 0:i.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(t){return t===this.core.room}};m(Up,"updateValidateRule",{type:"object"}),m(Up,"stopValidateRule",{type:"object"}),m(Up,"Name","AudioProcessor");var ij=Up,_E=0,rj=class{constructor(e,t){m(this,"audioObjectURL"),m(this,"player"),m(this,"publisher"),m(this,"mixInput"),this.mixInput=new Hw(t),e.url?(this.player=new Audio(e.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(e.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(e.track),this.mixInput.connect()}updateSettings(e){this.player&&(j(e.volume)||(this.volume=e.volume),j(e.loop)||(this.loop=e.loop),j(e.playbackRate)||(this.playbackRate=e.playbackRate))}updateListener(e){if(this.player){if(e.onDurationChange){let{onDurationChange:t}=e;this.player.ondurationchange=i=>{t(i.target.duration)}}if(e.onTimeUpdate){let t=e.onTimeUpdate,{player:i}=this;i.ontimeupdate=()=>{t(i.currentTime,i.duration)}}e.onEnded&&(this.player.onended=e.onEnded)}}reload(e){return P(this,null,function*(){if(e.url){let t=yield uE.download(e.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(t),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(e),this.updateSettings(e))}else this.mixInput.replaceSource(e.track)})}reset(){this.seek(0),this.mixInput.connect()}seek(e){this.player&&(e<0&&e>this.player.duration||(this.player.currentTime=e,this.publisher.currentTime=e))}play(){var e,t;return Promise.all([(e=this.player)==null?void 0:e.play(),(t=this.publisher)==null?void 0:t.play()])}pause(){var e,t;(e=this.player)==null||e.pause(),(t=this.publisher)==null||t.pause()}stop(){var e;(e=this.player)==null||e.pause(),this.mixInput.disconnect()}setOperation(e){e==="pause"&&this.pause(),e==="resume"&&(this.pause(),this.play()),e==="stop"&&(this.pause(),this.seek(0))}set volume(e){!this.player||!this.publisher||(this.player.volume=e,this.publisher.volume=e)}set loop(e){!this.player||!this.publisher||(this.player.loop=e,this.publisher.loop=e)}set playbackRate(e){!this.player||!this.publisher||(this.player.playbackRate=e,this.publisher.playbackRate=e)}};function qo(e,t){if(t&&typeof t!="function")throw new Ne({code:De.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(e," should be a function.")})}var gu=class Su{constructor(t){this.core=t,m(this,"log"),m(this,"mixedMusicMap",new Map),m(this,"cacheMusicMap",new Map),_E+=1,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(_E)}),this.log.info("created id=".concat(this.getAlias()).concat(_E))}getName(){return Su.Name}getAlias(){return"ax"}getGroup(t){return t?.id}getValidateRule(t){switch(t){case"start":return Su.startValidateRule;case"update":return Su.updateValidateRule;case"stop":return Su.stopValidateRule}}start(t){return P(this,null,function*(){let{room:i}=this.core;this.core.validateSourceNode(),this.log.info("add music source, id: ".concat(t.id," url: ").concat(t.url,", track: ").concat(t.track));let{id:r,url:n}=t;if(this.mixedMusicMap.has(r))return;let s=this.cacheMusicMap.get(r);s?t.url?s.reset():(s.mixInput.replaceSource(t.track),s.mixInput.connect()):(s=new rj(t,i.audioManager),this.cacheMusicMap.set(r,s)),s.updateListener(t),s.updateSettings(t);try{yield s.play()}catch(o){yield this.handleAutoPlayFailed(s,t,o)}this.mixedMusicMap.set(r,s),s.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s.mixInput.source.node,refId:"ax-".concat(r)}),this.log.info("start mix audio track ".concat(r," success.")),ce.addEnum({key:502700,value:3}),this.kvUpload(t)})}handleAutoPlayFailed(t,i,r){return P(this,null,function*(){if(r.name==="NotSupportedError")this.log.error("play failed, try to reload source. error: ".concat(r)),yield t.reload(i),yield t.play();else{if(r.name!=="NotAllowedError")throw r;if(this.core.room.enableAutoPlayDialog){let n=()=>{var s;(s=t.play())==null||s.finally(()=>{$.off("154",n,this)})};$.on("154",n,this),Mv()}else this.core.trtc.emit(Se.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>P(this,null,function*(){return t.play()})})}})}update(t){return P(this,null,function*(){let{id:i,operation:r,seekFrom:n,playbackRate:s}=t;this.log.info("update music source, ".concat(JSON.stringify(t)));let o=this.mixedMusicMap.get(i);o?(o.updateSettings(t),o.updateListener(t),j(r)||o.setOperation(r),j(n)||o.seek(n),this.kvUpload(t)):this.log.warn("update music source failed, music id: ".concat(i," not found."))})}stop(t){return P(this,arguments,function(i){var r=this;let{id:n}=i;return(function*(){if(r.mixedMusicMap.has(n)){r.log.info("remove music source, music id: ".concat(n));let s=r.mixedMusicMap.get(n);s!=null&&s.mixInput.source.node&&r.core.room.audioManager.updateAudioReference({type:"remove",audioReference:s.mixInput.source.node,refId:"ax-".concat(n)}),s?.stop(),r.mixedMusicMap.delete(n)}n==="*"&&r.destroyAllMusic()})()})}kvUpload(t){let{track:i,loop:r,volume:n,playbackRate:s,operation:o,seekFrom:l,onTimeUpdate:c,onDurationChange:h,onEnded:_}=t;i&&ce.addCount({key:502009}),r&&ce.addCount({key:502001}),n&&ce.addCount({key:502002}),s&&ce.addCount({key:502003}),o&&ce.addCount({key:502004}),l&&ce.addCount({key:502005}),typeof c!="function"&&ce.addCount({key:502007}),typeof _!="function"&&ce.addCount({key:502008}),typeof h!="function"&&ce.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((t,i)=>{t!=null&&t.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.track,refId:i}),this.stop({id:i})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};m(gu,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(e,t,i){if(e.url&&e.url!=="*"){let r=e.url.split("?")[0],n=["mp3","ogg","wav","flac"],s=r.split(".").pop(),o=n.indexOf(s)>=0,l=r.startsWith("blob"),c=r.startsWith("data");if(!(o||l||c))throw new Ne({code:De.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}if(!e.url&&!e.track)throw new Ne({code:De.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:i});qo("onTimeUpdate",e.onTimeUpdate),qo("onEnded",e.onEnded),qo("onDurationChange",e.onDurationChange)}}),m(gu,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(e,t,i){qo("onTimeUpdate",e.onTimeUpdate),qo("onEnded",e.onEnded),qo("onDurationChange",e.onDurationChange)}}),m(gu,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),m(gu,"Name","AudioMixer");var gE,nj=gu,vE=0,Vp=class Iu{constructor(t){this.core=t,m(this,"log"),m(this,"audioContext",pi()),m(this,"workletNode"),m(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5}),vE+=1,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(vE)}),this.log.info("created id=".concat(this.getAlias()).concat(vE))}static startValidateRule(t){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(i,r,n,s){if(!t.room.audioManager.hasAudioTrack)throw new Ne({code:De.INVALID_OPERATION,extraCode:5106,fnName:n})}}}preload(t){return gE||(gE=this.doPreload(t)),gE}doPreload(t){return P(this,null,function*(){let i=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(i);try{yield dp(this.audioContext,r)}catch(n){throw this.log.error("load worklet failed",n),n}finally{URL.revokeObjectURL(r)}})}getName(){return Iu.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(t){switch(t){case"start":return Iu.startValidateRule(this.core);case"update":return Iu.updateValidateRule;case"stop":return Iu.stopValidateRule}}start(t){return P(this,null,function*(){let{room:i,schedule:r}=this.core,{assetsPath:n=this.core.assetsPath}=t;if(!n)throw new Ne({code:De.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload("".concat(n,"/denoiser-wasm").concat(gw()?"":"-nosimd",".js")),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:o,sign:l,status:c,message:h}=yield(function(_,f){return P(this,arguments,function(T,b){let{sdkAppId:C,userId:x,userSig:B,timestamp:Y}=b;return(function*(){try{let{data:{errCode:G,errMsg:he,sign:H,status:Z}}=yield T.getAbilityConfig(C,T.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:C,userId:x,userSig:B,timestamp:Y});if(Z==="1")return{auth:!0,sign:H,status:Z,message:he};let de=os(C)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",pe="Init RTCAIDenoiser failed.",Pe="";switch(G){case 1:Pe="Please check your params.";break;case 2:Pe="You need to buy packages. Refer to: ".concat(de);break;case 3:Pe="Server is invalid. Please contact our engineer. ";break;case 4:Pe="Your packages is not active. Refer to: ".concat(de);break;case 5:Pe="Your packages is expired. Refer to: ".concat(de);break;case 6:Pe="Your version is not supported."}return{auth:!1,status:Z,message:he?"".concat(pe," Reason: ").concat(he,". ").concat(Pe):"".concat(pe,", ").concat(Pe)}}catch(G){return{auth:!1,status:"0",message:"Init RTCAIDenoiser failed. All requests failed. ".concat(G)}}})()})})(r,xe(ve({},t),{timestamp:s}));if(!o)throw this.log.info("RTCAIDenoiser: ".concat(t.userId," auth result: ").concat(o,". Message: ").concat(h)),new Ne({code:De.INVALID_PARAMETER,message:h});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(t.sdkAppId),userId:t.userId,timestamp:s,sign:l,status:c}}),this.workletNode.port.onmessage=_=>{var f;let{data:T}=_;if(T.type==="cost"){let b=T?.max>20?"warn":T?.max>10?"info":"debug";this.log[b]("avg cost: ".concat(T.value," max: ").concat(T?.max,"(").concat(Jg(new Date(T?.maxCostTimestamp)),") hist: ").concat((f=T?.hist)==null?void 0:f.join(" ")))}else T.type==="log"&&this.log[T.logLevel]("".concat(T.value))}}this.updateConfig(t),this.workletNode.port.postMessage({type:"enable"}),i.audioManager.addDenoiser(this.workletNode),i.sendAbilityStatus({ai_denoise:1})})}update(t){return P(this,null,function*(){this.updateConfig(t)})}stop(){return P(this,null,function*(){if(!this.workletNode)return;let{room:t}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield t.audioManager.removeDenoiser(this.workletNode)})}updateConfig(t){if(!this.workletNode)return;let i=!1;j(t.mode)||(t.mode===0?this.config.enableFarFieldReduce=!1:t.mode===1&&(this.config.enableFarFieldReduce=!0),i=!0),j(t.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=t.farFieldReduceThreshold,i=!0),i&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};m(Vp,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),m(Vp,"stopValidateRule",{type:"object"}),m(Vp,"Name","AIDenoiser");var sj=Vp,aj=ti(Ri(),1),oj=class extends aj.EventEmitter{constructor(){super(),m(this,"observer"),m(this,"state","nominal"),this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return P(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!Vt&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){dt.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,i=e[e.length-1];this.state=i.state,(this.stateNum>3||t>3)&&fe.info("".concat(i.source,": ").concat(i.state)),this.emit("state-changed",{type:i.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){dt.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},oN=new oj,EE=0,yE=class sP{constructor(t){this.core=t,m(this,"log"),m(this,"_seiMessageList",[]),m(this,"_smallSeiMessageList",[]),m(this,"_subStreamSeiMessageList",[]),EE++,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(EE)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(EE)),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode(t){let{frame:i,mediaType:r}=t;try{return ZD({frame:i,seiMessageList:r===8?this._smallSeiMessageList:r===2?this._subStreamSeiMessageList:this._seiMessageList})}catch(n){this.log.warn(n)}return i}decode(t){let{frame:i,track:r}=t;return $D({frame:i,onSEI:n=>{n.forEach(s=>{r!=null&&r.userId?this.core.trtc.emit(Se.SEI_MESSAGE,{seiPayloadType:s.seiPayloadType,data:s.seiPayload.buffer,userId:r.userId,streamType:r.mediaType===2?"sub":"main"}):this.core.innerEmitter.emit(this.core.INNER_EVENT.SEI_MESSAGE,{room:this.core.room,nalu:s})})}})}destroy(){this.log.debug("destroy"),this.stop(),delete this.core}getValidateRule(t){switch(t){case"start":case"update":case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:va?this.encode:ZD,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:va?this.decode:$D,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update(t){let{buffer:i,options:r}=t;var n;let s=[r.seiPayloadType,i],o=!!r.small;r.toSubStream?this._subStreamSeiMessageList.push(s):(this._seiMessageList.push(s),o&&this._smallSeiMessageList.push(s)),(n=this.core.room.scriptTransformWorker)==null||n.postMessage({type:"sei",data:s,isMain:!r.toSubStream,small:o})}getName(){return sP.Name}getAlias(){return"sei"}getGroup(){return"sei"}};m(yE,"autoStart",!0),m(yE,"Name","SEI");var Fp,lj=yE,cj=0,TE=class aP{constructor(t){this.core=t,m(this,"_core"),m(this,"log"),m(this,"dialog"),this._core=t,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(++cj)}),this.log.info("created")}getName(){return aP.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(t){switch(t){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return P(this,null,function*(){var t;!new URLSearchParams(location.search).has("trtcDebug")&&((t=window.sessionStorage)==null?void 0:t.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog())})}update(t){return P(this,arguments,function(i){var r=this;let{visible:n}=i;return(function*(){n?yield r.openDebugDiaLog():r.closeDebugDiaLog()})()})}stop(){this.closeDebugDiaLog()}destroy(){this.stop()}openDebugDiaLog(){return P(this,null,function*(){var t;if(!this.dialog)try{if(Fp)yield Fp;else{let i=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((t=window.sessionStorage)==null?void 0:t.getItem("TRTC_DEBUG_DIALOG_PATH"))||"https://unpkg.com/".concat("trtc-sdk-v5","@").concat(yr,"/assets/debug-dialog.js");Fp=this._core.fileDownloader.loadScript(i),yield Fp}this.dialog=new TRTCDebugDialog(this._core,this.log),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(i){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(i))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}};m(TE,"Name","Debug"),m(TE,"autoStart",!0);var uj=TE,lN=e=>{switch(e){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},cN=class{constructor(e,t,i){m(this,"trackDoneOB"),m(this,"startOB"),m(this,"stopOB"),m(this,"inputFrameCount",0),m(this,"decodedFrameCount",0),m(this,"type","auto"),m(this,"config"),m(this,"decoder"),m(this,"_decodeSink");let{kvStatManager:r,trtc:n}=e;this.config=i.config,this.trackDoneOB=St(t,et.INIT),this.stopOB=zr(),this.startOB=zr(),i.type==="auto"?this.type="webCodecs":this.type=i.type;let s=zr();At(this.startOB,zv(0),Sp(o=>{let l=this.pipe(t);return s.next("STARTING"),t.log.info("decoder type: ".concat(this.type)),At(l,Ci(this.stopOB),Qt(()=>{},c=>{t.log.error(c),r.addFailedEvent({key:lN(this.type),error:c}),o>4?this.startOB.error(c):this.startOB.next(o+1)})),At(l,Wo(1),SD(Yv))}),Ci(this.stopOB),Qt(()=>{t.player.setOutput(),s.next("STARTED")},o=>{s.next("FAILED")},()=>{r.addSuccessEvent({key:lN(this.type)}),r.addSuccessEvent({key:504702})}))}mock(e){this._decodeSink?this._decodeSink.error(e):this.startOB.next(0)}close(e){this.stopOB.next(e)}pipe(e){return nu()(t=>P(this,null,function*(){this._decodeSink=t,t.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:i}=this;try{i==="webCodecs"&&(this.decoder=new AudioDecoder({error:r=>{e.log.error(r),t.error(4)},output:r=>{this.decodedFrameCount++,t.next(r),e.player.write(r)}})),this.decoder.configure(this.config)}catch(r){e.log.error(r),t.error(i==="webCodecs"?2:6)}}))}decodeFrame(e){var t;this.inputFrameCount++,((t=this.decoder)==null?void 0:t.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:e.data,timestamp:e.timestamp,type:"key"}))}},dj={type:"object"},uN=class LE{constructor(t){this.core=t,m(this,"log"),m(this,"contextMap",new Map),m(this,"decodeProcessorMap",new WeakMap),this.log=t.log.createChild({id:"".concat(this.getAlias())})}getAlias(){return LE.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return LE.Name}getValidateRule(t){return dj}start(t){let{track:i}=t;this.decodeProcessorMap.set(i,this.decode(t)),this.core.room.audioManager.addDecodeProcessor({processor:r=>{let{frame:n,track:s}=r;return this.decodeProcessorMap.has(s)?this.decodeProcessorMap.get(s)({frame:n,track:s}):n},type:3})}decode(t){return i=>{let{frame:r,track:n}=i;if(n!==t.track)return r;if(this.contextMap.has(n))return this.contextMap.get(n).decodeFrame(r);let s=new cN(this.core,n,t);return At(s.trackDoneOB,Wo(1),Qt(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:n})})),this.contextMap.set(n,s),s.decodeFrame(r)}}stop(t){let{track:i}=t,r=this.contextMap.get(i);r&&(r.close("stop"),this.contextMap.delete(i),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(t){let i=this.contextMap.get(t.track);if(i){if(t.type==="mock")return void i.mock(10);i.close("update"),this.contextMap.set(t.track,new cN(this.core,t.track,t))}}};m(uN,"Name","TRTCAudioDecoder");var dN=uN,hN=class{constructor(){m(this,"log"),this.log=fe.createLogger({id:"exp"})}call(e,t){return P(this,null,function*(){return Ut(this[e])?this[e](t):Promise.reject(new me({code:te.INVALID_PARAMETER,message:He({key:Fe.API_NOT_EXIST,data:{name:e}})}))})}enableAudioFrameEvent(e){return P(this,null,function*(){let{trtcInstance:t,enable:i,userId:r,sampleRate:n=48e3,channelCount:s=1,port:o}=e,{audioManager:l}=t.room,{getPCMAbortCtrlMap:c,audioFrameEventConfigMap:h}=l;if(h.set(r,{enable:i,sampleRate:n,channelCount:s,port:o}),i)if(r==="*")t.room.remotePublishedUserMap.forEach(_=>{if(_.remoteAudioTrack.isAvailable){if(c.get(_.userId))return;let f=l.getPCM(T=>{t.emit(Se.AUDIO_FRAME,T)},_.userId);c.set(_.userId,f)}});else{if(c.get(r))return;let _=l.getPCM(f=>{t.emit(Se.AUDIO_FRAME,f)},r);c.set(r,_)}else if(r==="*")t.room.remotePublishedUserMap.forEach(_=>{if(_.remoteAudioTrack.isSubscribed){let{userId:f}=_,T=c.get(f);T?.abort("disable"),c.delete(f)}});else{let _=c.get(r);_?.abort("disable"),c.delete(r)}})}resumeRemotePlayer(e){return P(this,null,function*(){if(e.userId==="*"){let i=[];return e.trtcInstance.room.remotePublishedUserMap.forEach(r=>{let{remoteAudioTrack:n,remoteVideoTrack:s,remoteAuxiliaryTrack:o}=r;e.streamType?e.streamType==="main"?(n.isAvailable&&i.push(n.player.resume()),s.isAvailable&&i.push(s.player.resume())):o.isAvailable&&i.push(o.player.resume()):(n.isAvailable&&i.push(n.player.resume()),s.isAvailable&&i.push(s.player.resume()),o.isAvailable&&i.push(o.player.resume()))}),Promise.all(i)}let t=e.trtcInstance.room.remotePublishedUserMap.get(e.userId);if(t)return e.streamType==="main"?Promise.all([t.remoteAudioTrack.player.resume(),t.remoteVideoTrack.player.resume()]):t.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(e){if(e.userId==="*")e.trtcInstance.room.remotePublishedUserMap.forEach(t=>{let{remoteAudioTrack:i,remoteVideoTrack:r,remoteAuxiliaryTrack:n}=t;e.streamType?e.streamType==="main"?(i.isAvailable&&i.player.pause(),r.isAvailable&&r.player.pause(!1)):n.isAvailable&&n.player.pause(!1):(i.isAvailable&&i.player.pause(),r.isAvailable&&r.player.pause(!1),n.isAvailable&&n.player.pause(!1))});else{let t=e.trtcInstance.room.remotePublishedUserMap.get(e.userId);t&&(e.streamType==="main"?(t.remoteAudioTrack.player.pause(),t.remoteVideoTrack.player.pause(!1)):t.remoteAuxiliaryTrack.player.pause(!1))}}};_e([(function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return _t((r,n)=>function(){for(var s=arguments.length,o=new Array(s),l=0;l<s;l++)o[l]=arguments[l];return WG.call(this,t,o,n,this._name),r.apply(this,o)})})({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],hN.prototype,"enableAudioFrameEvent");var hj=new hN,pj=ti(Ri(),1),mj=class extends pj.EventEmitter{constructor(){super(),m(this,"states",{}),m(this,"permissionChangeHandler"),m(this,"log"),this.log=fe.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var e,t;this.emit("permission-state-change",{camera:(e=this.states.camera)==null?void 0:e.state,microphone:(t=this.states.microphone)==null?void 0:t.state})}}request(e){return P(this,null,function*(){if(this.log.info("request ".concat(e.join(", "))),e.length===0)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:e.includes("camera"),audio:e.includes("microphone")})).getTracks().forEach(t=>t.stop())})}get(e){return P(this,null,function*(){try{return this.states[e]||(this.states[e]=yield navigator.permissions.query({name:e}),this.states[e].addEventListener("change",this.permissionChangeHandler)),this.log.info("get ".concat(e," permission state: ").concat(this.states[e].state)),this.states[e].state}catch(t){return this.log.error("get ".concat(e," permission failed, error: ").concat(t instanceof Error?t.message:t)),null}})}destroy(){Object.values(this.states).forEach(e=>{e?.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},Bp=new mj,pN=0,vu=new Set,ai=null;K1(sN),av.checkStorage();var Ke=class kn extends B9.EventEmitter{constructor(t,i){super(),m(this,"_room"),m(this,"_eventListened",new Set),m(this,"_localVideoTrack",null),m(this,"_localAudioTrack",null),m(this,"_localScreenTrack",null),m(this,"_localScreenAudioTrack",null),m(this,"_localVideoConfig",null),m(this,"_localScreenConfig",null),m(this,"_localAudioConfig",null),m(this,"_remoteVideoConfigMap",new Map),m(this,"_remoteAudioConfigMap",new Map),m(this,"_remoteAudioVolumeMap",new Map),m(this,"_remoteAudioMuteMap",new Map),m(this,"_mediaTrackMap",new WeakMap),m(this,"_log",fe.createLogger({id:"t".concat(++pN)})),m(this,"_plugins",new Map),m(this,"_networkQuality",null),m(this,"_speakerId"),m(this,"enterRoomParams"),m(this,"_enableAutoSwitchWhenRecapturing",!0),m(this,"_autoSubscribeDataChannel",!1),this._room=new t(ve({logger:this._log,frameWorkType:kn.frameWorkType},i)),this._room.videoDecodeFallbackType=i.videoDecodeFallback,Rt(i.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=i.enableAutoSwitchWhenRecapturing),this._log.info("create() ".concat(JSON.stringify(i,(r,n)=>r==="plugins"?n.map(s=>s.Name):n))),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),i.plugins&&i.plugins.forEach(r=>{this._use(r,i.assetsPath)}),this._use(nj,i.assetsPath),this._use(ij,i.assetsPath),this._use(sj,i.assetsPath),this._use(dN,i.assetsPath),this._use(uj),i.enableSEI&&Tv&&this._use(lj),this._room.on("audio-volume",r=>{var n,s;!r.find(o=>o.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(100*((n=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?n:this._localAudioTrack.getAudioLevel())),floatVolume:(s=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?s:this._localAudioTrack.getInternalAudioLevel()}),i.volumeType===1&&r.forEach(o=>{var l;let c=o.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(o.userId))==null?void 0:l.remoteAudioTrack;c&&(o.volume=c.dbVolume)}),i.enableDbVolume&&r.forEach(o=>{var l;let c=o.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(o.userId))==null?void 0:l.remoteAudioTrack;c&&(o.volume=c.dbVolume)}),this.emit(Se.AUDIO_VOLUME,{result:r.sort((o,l)=>l.volume-o.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new Ne({code:De.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),((r,n)=>{let{emit:s}=r;r.emit=function(){for(var o=arguments.length,l=new Array(o),c=0;c<o;c++)l[c]=arguments[c];try{return s.apply(r,l)}catch(h){let _=He({key:Fe.CATCH_HANDLER_ERROR,data:{name:n,event:l[0]},addDocLink:!1});return fe.warn("".concat(_,`
99
+
100
+ `).concat(h.stack)),!1}}})(this,"trtc")}static create(t){}static _create(t,i){(function(){var n;if(PD){PD=!1,fe.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(mn,"/en/index.html")),console.info("* Changelog: ".concat(mn,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),fe.info("TRTC Web SDK Version:",yr),fa||fe.debug("Build Time:","2026-01-13 21:52:51");let s="UA: ".concat(navigator.userAgent,`
101
+ CPU core: `).concat(navigator.hardwareConcurrency,", GPU: ").concat(Mo());if(Gt&&window.screen&&(window.screen.width||window.screen.height)){let l="".concat(window.screen.width,"x").concat(window.screen.height,"@").concat(window.devicePixelRatio);s+=", screen: ".concat(l)}let o=navigator.deviceMemory;o&&(s+=", minRAM: ".concat(o,"GB")),fe.info(s),fe.info("URL: ".concat(location.href).concat(((n=self.frameElement)==null?void 0:n.tagName)==="IFRAME"?" in iframe":"")),ep().then(l=>{l&&fe.info(vn)})}})();let r=new kn(t,i||{});return vu.add(r),r.__v_skip=!0,r}get room(){return this._room}_listenEvents(){Ar(this,this._room).add("peer-join",t=>{let{userId:i}=t;this.emit(Se.REMOTE_USER_ENTER,{userId:i})}).add("peer-leave",t=>{let{userId:i,reason:r}=t;this.emit(Se.REMOTE_USER_EXIT,{userId:i,reason:r})}).add("banned",t=>{Jr(!0),this._exitRoom().finally(()=>{this.emit(Se.KICKED_OUT,{reason:t.reason})})}).add("error",t=>{this._exitRoom().finally(()=>{this.emit(Se.ERROR,Ne.convertFrom(t))})}).add("signal-connection-state-changed",t=>{this.emit(Se.CONNECTION_STATE_CHANGED,t)}).add("network-quality",t=>{this._networkQuality=t;let i=xe(ve({},t),{uplinkRTT:Math.min(t.uplinkRTT,Dh),downlinkRTT:Math.min(t.downlinkRTT,Dh)});this.emit(Se.NETWORK_QUALITY,i)}).add("remote-published",t=>{[t.remoteAudioTrack,t.remoteVideoTrack,t.remoteAuxiliaryTrack].forEach(i=>{Ar(i,i).add("player-state-changed",r=>{let n=xe(ve({},r),{userId:t.userId});i.kind===D.VIDEO&&(n.streamType=ji(i.streamType)),this.emit(i.kind===D.AUDIO?Se.AUDIO_PLAY_STATE_CHANGED:Se.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",r=>{r.getCode()===te.PLAY_NOT_ALLOWED&&this.emit(Se.AUTOPLAY_FAILED,{userId:i.userId,mediaType:i.strMediaType,resume:()=>i.player.resume()})})})}).add("remote-unpublished",t=>{[t.remoteAudioTrack,t.remoteVideoTrack,t.remoteAuxiliaryTrack].forEach(i=>{bi(i)})}).add("remote-publish-state-changed",t=>{let{prevMuteState:i,muteState:r}=t,{userId:n}=r,s=i.audioAvailable,o=i.videoAvailable,{audioAvailable:l,videoAvailable:c}=r;l||this._remoteAudioConfigMap.delete(n),c||this._removeRemoteVideoConfig(n,"main"),r.hasAuxiliary||this._removeRemoteVideoConfig(n,"sub"),o!==c&&(c?this._onVideoAvailable({userId:n,streamType:"main"}):this._onVideoUnavailable({userId:n,streamType:"main"}),this.emit(c?Se.REMOTE_VIDEO_AVAILABLE:Se.REMOTE_VIDEO_UNAVAILABLE,{userId:n,streamType:"main"})),s!==l&&(l?this._onAudioAvailable({userId:n}):this._onAudioUnavailable({userId:n,muteState:r}),this.emit(l?Se.REMOTE_AUDIO_AVAILABLE:Se.REMOTE_AUDIO_UNAVAILABLE,{userId:n})),i.hasAuxiliary!==r.hasAuxiliary&&(r.hasAuxiliary?this._onVideoAvailable({userId:n,streamType:"sub"}):this._onVideoUnavailable({userId:n,streamType:"sub"}),this.emit(r.hasAuxiliary?Se.REMOTE_VIDEO_AVAILABLE:Se.REMOTE_VIDEO_UNAVAILABLE,{userId:n,streamType:"sub"})),i.hasDatachannel!==r.hasDatachannel&&r.hasDatachannel&&this._onDataChannelAvailable()}).add("sei-message",t=>{this.emit(Se.SEI_MESSAGE,xe(ve({},t),{streamType:ji(t.streamType)}))}).add("firewall-restriction",()=>{this.emit(Se.ERROR,new Ne({code:De.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",t=>{var i,r,n,s,o,l,c;let h={2:"big",3:"small",7:"sub"},_={rtt:Math.min(t.msg_up_stream_info.msg_network_status.uint32_rtt||((i=t.msg_down_stream_info[0])==null?void 0:i.msg_network_status.uint32_rtt)||((r=this._networkQuality)==null?void 0:r.uplinkRTT)||((n=this._networkQuality)==null?void 0:n.downlinkRTT)||0,Dh),upLoss:((s=this._networkQuality)==null?void 0:s.uplinkLoss)||0,downLoss:((o=this._networkQuality)==null?void 0:o.downlinkLoss)||0,bytesSent:t.bytes_sent||0,bytesReceived:t.bytes_received||0,localStatistics:{audio:{bitrate:(((l=t.msg_up_stream_info.msg_audio_status)==null?void 0:l.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((c=t.msg_up_stream_info.msg_audio_status)==null?void 0:c.uint32_audio_level)||0)/Wr},video:t.msg_up_stream_info.msg_video_status.filter(f=>h[f.uint32_video_stream_type]).map(f=>({bitrate:(f.uint32_video_codec_bitrate||0)/1e3,width:f.uint32_video_width,height:f.uint32_video_height,frameRate:f.uint32_video_enc_fps,videoType:h[f.uint32_video_stream_type]}))},remoteStatistics:t.msg_down_stream_info.map(f=>({userId:f.msg_user_info.str_identifier,audio:{bitrate:(f.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(f.msg_audio_status.uint32_audio_level||0)/Wr,point2pointDelay:(f.msg_audio_status.uint32_audio_p2p_delay||0)+(f.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:f.msg_audio_status.uint32_audio_cache_ms||0},video:f.msg_video_status.map(T=>({bitrate:(T.uint32_video_codec_bitrate||0)/1e3,width:T.uint32_video_width,height:T.uint32_video_height,frameRate:T.uint32_video_dec_fps,videoType:h[T.uint32_video_stream_type],point2pointDelay:(T.uint32_video_p2p_delay||0)+(T.uint32_video_cache_ms||0),jitterBufferDelay:T.uint32_video_cache_ms||0,codec:T.uint32_video_codec}))}))};this.emit(Se.STATISTICS,_)}).add("custom-message",t=>{this.emit(Se.CUSTOM_MESSAGE,t)}).add("layerData",t=>this.emit(Se.LAYER_DATA,t)).add("first-video-frame",t=>{this.emit(Se.FIRST_VIDEO_FRAME,xe(ve({},t),{streamType:ji(t.streamType)}))}).add("audio-frame",t=>{this.emit(Se.AUDIO_FRAME,t)}).add("data-channel-message",t=>{var i,r,n,s,o;let{data:l}=t;if(l.sender==="")return;let c={segmentId:(i=l.payload)==null?void 0:i.roundid,speakerUserId:l.sender,sourceText:(r=l.payload)==null?void 0:r.text,translationTexts:(n=l.payload)==null?void 0:n.translate_msg,timestamp:(s=l.payload)==null?void 0:s.start_utc_ms,isCompleted:(o=l.payload)==null?void 0:o.end,robotId:l.robotid};c.sourceText!==""&&this.emit(Se.REALTIME_TRANSCRIBER_MESSAGE,c)}).add("asr-robot-peer-join",t=>{this.emit(Se.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"started",roomId:this.room.roomId,transcriberRobotId:t.userId})}).add("asr-robot-peer-leave",t=>{this.emit(Se.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"stopped",roomId:this.room.roomId,transcriberRobotId:t.userId})}).add("audioInputAdded",t=>{this.emit(Se.DEVICE_CHANGED,{type:"microphone",action:"add",device:t})}).add("audioInputRemoved",t=>{this.emit(Se.DEVICE_CHANGED,{type:"microphone",action:"remove",device:t})}).add("videoInputAdded",t=>{this.emit(Se.DEVICE_CHANGED,{type:"camera",action:"add",device:t})}).add("videoInputRemoved",t=>{this.emit(Se.DEVICE_CHANGED,{type:"camera",action:"remove",device:t})}).add("audioOutputAdded",t=>P(this,null,function*(){if(this.emit(Se.DEVICE_CHANGED,{type:"speaker",action:"add",device:t}),ai&&ai.deviceId===wh){let i=(yield ya()).find(r=>r.deviceId===wh);i&&ai.groupId!==i.groupId&&(ai=i,this.emit(Se.DEVICE_CHANGED,{type:"speaker",action:"active",device:i}))}})).add("audioOutputRemoved",t=>P(this,null,function*(){this.emit(Se.DEVICE_CHANGED,{type:"speaker",action:"remove",device:t});let i=(yield ya())[0];if(!i||!ai||ai.groupId===i.groupId)return;let r=ai.deviceId===t.deviceId,n=ai.deviceId===wh&&ai.deviceId===i.deviceId;(r||n)&&(ai=i,this.emit(Se.DEVICE_CHANGED,{type:"speaker",action:"active",device:i}))})),Ar(this,Bp).add("permission-state-change",t=>{this.emit(Se.PERMISSION_STATE_CHANGE,t)}),this.room.enableSEI&&this.on(Se.SEI_MESSAGE,t=>{var i;let r=(i=this.room.remotePublishedUserMap.get(t.userId))==null?void 0:i.remoteVideoTrack;r&&r.updateAlphaRenderInfo(t)})}getNetworkTime(){return ac()}use(t){let i,r;return"plugin"in t?(i=t.plugin,r=t.assetsPath):i=t,i.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(i,r)}_use(t,i){let r=this._plugins.get(t.Name);if(r)return this._log.warn("duplicate install plugin",t.Name),r;let n=new t(ej.call(this,{TRTC:kn,room:this._room,assetsPath:i,errorModule:{RtcError:Ne,ErrorCode:De,CoreErrorCode:te,ErrorCodeDictionary:Dp}}));return this._plugins.set(t.Name,n),n.__v_skip=!0,t.autoStart&&this.startPlugin(t.Name),n}enterRoom(t){return P(this,null,function*(){var i,r;this.enterRoomParams=t;let{scene:n="rtc",enableAutoPlayDialog:s=!0,autoReceiveAudio:o=!0,autoReceiveVideo:l=!1}=t;t.proxy&&(this._room.setProxyServer(t.proxy),!pt(t.proxy)&&t.proxy.turnServer&&((r=(i=this._room).setTurnServer)==null||r.call(i,t.proxy.turnServer,t.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=s,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=l,Rt(t.preferHW)&&(this._room.preferHW=t.preferHW),t.playoutDelay&&(this._room.playoutDelay=t.playoutDelay),t.jitterBufferDelay&&(this._room.jitterBufferDelay=t.jitterBufferDelay);let c={sdkAppId:t.sdkAppId,userId:t.userId,userSig:t.userSig,privateMapKey:t.privateMapKey||null,latencyLevel:t.latencyLevel,role:t.role==="audience"?21:20,roomId:t.roomId||0,strRoomId:t.strRoomId||"",businessInfo:t.businessInfo||null,streamId:null,userDefineRecordId:t.userDefineRecordId||null,enableDataChannel:this._plugins.has("RealtimeTranscriber"),frameWorkType:t.frameWorkType,component:t.component,language:t.language,priority:t.priority,useVp8:t.useVp8,useH265:t.useH265||!1,keepAlive:t.keepAlive};t.strRoomId&&!t.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(c,n,kn.frameWorkType),this._checkTrackToPublish(),oN.start()})}exitRoom(){return P(this,null,function*(){return yield this._exitRoom()})}switchRoom(t){return P(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(t)}catch(i){if(!(i instanceof H1)||i.code!==te.API_CALL_TIMEOUT&&i.code!==te.SWITCH_ROOM_FAILED)throw i;this._log.warn("switchRoom ".concat(i.code===te.API_CALL_TIMEOUT?"timeout":"failed",", fallback to exitRoom() and enterRoom()")),yield this._rejoinRoom(t)}else yield this._rejoinRoom(t)})}_rejoinRoom(t){return P(this,null,function*(){yield this.exitRoom();let i=ve(ve({},this.enterRoomParams),t);yield this.enterRoom(i)})}_clearRemoteTracks(){new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(t=>{this._stopRemoteAudio({userId:t}).catch(()=>{})}),[...this._remoteVideoConfigMap.keys()].forEach(t=>{let i=t.includes("main")?"main":"sub",r=t.split("_".concat(i))[0];r&&this._stopRemoteVideo({userId:r,streamType:i}).catch(()=>{})}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),(function(t){let i=Yo.get(t);i&&(i.forEach(r=>clearTimeout(r)),Yo.delete(t))})(this),this._room.remotePublishedUserMap.forEach(t=>{bi(t.remoteAudioTrack),bi(t.remoteVideoTrack),bi(t.remoteAuxiliaryTrack)})}switchRole(t,i){return P(this,null,function*(){i!=null&&i.privateMapKey&&(this._room.privateMapKey=i.privateMapKey),i!=null&&i.latencyLevel&&(this._room.latencyLevel=i.latencyLevel),yield this._room.switchRole(t),t==="anchor"&&this._checkTrackToPublish()})}destroy(){this._plugins.forEach(t=>{var i;return(i=t.destroy)==null?void 0:i.call(t)}),this._plugins.clear(),bi(this),this.removeAllListeners(),this._room.destroy(),vu.delete(this),vu.size===0&&oN.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),$.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return P(this,arguments,function(){var t=this;let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0};return(function*(){if(t._localAudioTrack)return void t._log.warn("local audio is already started");let{publish:r=!0,mute:n,option:s}=i,o=new Ia(t._room.audioManager),l={},c={muted:!0};s&&(j(s.microphoneId)?j(s.audioTrack)||(l.customSource=s.audioTrack):l.deviceId=s.microphoneId,s&&nt(s.captureVolume)&&o.setCaptureVolume(s.captureVolume),j(s.profile)||(pt(s.profile)?t0[s.profile]&&o.setProfile(t0[s.profile]):o.setProfile(s.profile)),nt(s.earMonitorVolume)&&(c.muted=!(s.earMonitorVolume>0),c.volume=s.earMonitorVolume),j(s.echoCancellation)||(o.profile.echoCancellation=s.echoCancellation),j(s.noiseSuppression)||(o.profile.noiseSuppression=s.noiseSuppression),j(s.autoGainControl)||(o.profile.autoGainControl=s.autoGainControl),Rt(t._enableAutoSwitchWhenRecapturing)&&(o.enableAutoSwitchWhenRecapturing=t._enableAutoSwitchWhenRecapturing)),o.on("5",h=>{t.emit(Se.ERROR,new Ne({code:De.DEVICE_ERROR,extraCode:5309,messageParams:{error:h}}))}),o.on("2",h=>{t.emit(Se.DEVICE_CHANGED,{type:"microphone",action:"active",device:h})}),o.on("4",h=>{let _;h.error&&(_=Ne.convertFrom(h.error)),t.emit(Se.PUBLISH_STATE_CHANGED,xe(ve({},h),{error:_}))}),o.on("6",()=>{}),t._listenOutputTrackChanged(o),t._speakerId&&o.setAudioOutput(t._speakerId),yield o.capture(l),j(n)||o.setMute(n),Ar(o,o).add("player-state-changed",h=>{t.emit(Se.AUDIO_PLAY_STATE_CHANGED,xe(ve({},h),{userId:""}))}),r&&t._room.isJoined&&t._room.publish(o).catch(()=>{}),t._localAudioTrack=o,t._room.capturedLocalMainAudioTrack=o,t._localAudioConfig=xe(ve({},i),{publish:r}),yield t._updateAudioPlayOption({playOption:c,track:o}),$.emit("113",{userId:"",room:t.room})})()})}updateLocalAudio(t){return P(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:i,mute:r,option:n}=t,s={};n&&(n.microphoneId?yield this._localAudioTrack.switchDevice(n.microphoneId):j(n.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(n.audioTrack)),j(n.captureVolume)||this._localAudioTrack.setCaptureVolume(n.captureVolume),j(n.earMonitorVolume)||(s.muted=!(n.earMonitorVolume>0),s.volume=n.earMonitorVolume),yield this._localAudioTrack.update3A(n)),this._room.isJoined&&!j(i)&&(i&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!i&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),j(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:s,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),gn(this._localAudioConfig,t)})}stopLocalAudio(){return P(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),$.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),bi(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,delete this._room.capturedLocalMainAudioTrack)})}startLocalVideo(){return P(this,arguments,function(){var t=this;let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0,view:null,capture:!0};return(function*(){var r;if(t._localVideoTrack)return void t._log.warn("local video is already started");let{view:n,publish:s=!0,capture:o=!0,mute:l,option:c}=i,h=new Rn(t._room.videoManager),_={},f={};c&&(Rt(c.avoidCropping)&&(h.avoidCropping=c.avoidCropping),c.cameraId?_.deviceId=c.cameraId:j(c.useFrontCamera)?j(c.videoTrack)||(_.customSource=c.videoTrack):_.facingMode=c.useFrontCamera?D.FACING_MODE_USER:D.FACING_MODE_ENVIRONMENT,j(c.retryWhenExactFailed)||(_.retryWhenExactFailed=c.retryWhenExactFailed),c.qosPreference&&(_.contentHint=Np(c.qosPreference)),j(c.profile)||(pt(c.profile)?fn[c.profile]&&h.setProfile(fn[c.profile]):h.setProfile(c.profile)),j(c.fillMode)||(f.objectFit=c.fillMode),j(c.mirror)||(f.mirror=c.mirror),j(c.small)||(j(c.smallMode)||(t._room.smallMode=c.smallMode),Rt(c.small)&&c.small===!1?h.stopSmall():h.updateSmallConfig(Pp(c.small,!0))),j(c.rotation)||h.setRotation(c.rotation),Rt(t._enableAutoSwitchWhenRecapturing)&&(h.enableAutoSwitchWhenRecapturing=t._enableAutoSwitchWhenRecapturing)),h.once("first-video-frame",T=>{t.emit(Se.FIRST_VIDEO_FRAME,xe(ve({},T),{streamType:ji(T.streamType)}))}),h.on("5",T=>{t.emit(Se.ERROR,new Ne({code:De.DEVICE_ERROR,extraCode:5308,messageParams:{error:T}}))}),h.on("2",T=>{t.emit(Se.DEVICE_CHANGED,{type:"camera",action:"active",device:T})}),h.on("4",T=>{let b;T.error&&(b=Ne.convertFrom(T.error)),t.emit(Se.PUBLISH_STATE_CHANGED,xe(ve({},T),{error:b}))}),h.on("6",()=>{}),t._listenOutputTrackChanged(h),o?yield h.capture(_):(r=h.manager)==null||r.changeInput(h),j(l)||(yield h.setMute(l)),Ar(h,h).add("player-state-changed",T=>{t.emit(Se.VIDEO_PLAY_STATE_CHANGED,xe(ve({},T),{userId:"",streamType:"main"}))}).add("video-size-changed",T=>{t.emit(Se.VIDEO_SIZE_CHANGED,xe(ve({},T),{streamType:ji(T.streamType)}))}),s&&t._room.isJoined&&t._room.publish(h).catch(()=>{}),t._localVideoTrack=h,t._room.capturedLocalMainVideoTrack=h,t._localVideoConfig=xe(ve({},i),{view:n,publish:s,capture:o}),yield t._updateVideoPlayOption({view:n,playOption:f,track:h})})()})}updateLocalVideo(t){return P(this,null,function*(){var i,r,n;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:s,publish:o,mute:l,capture:c,option:h}=t,_={};if(this._localVideoConfig.capture)c!==!1?h!=null&&h.cameraId?yield this._localVideoTrack.switchDevice(h?.cameraId):j(h?.useFrontCamera)?j(h?.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(h?.videoTrack)):yield this._localVideoTrack.switchDevice(h!=null&&h.useFrontCamera?D.FACING_MODE_USER:D.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(c){let f={};f.deviceId=h?.cameraId||((i=this._localVideoConfig.option)==null?void 0:i.cameraId),f.facingMode=h!=null&&h.useFrontCamera||(r=this._localVideoConfig.option)!=null&&r.useFrontCamera?D.FACING_MODE_USER:D.FACING_MODE_ENVIRONMENT,f.customSource=h?.videoTrack||((n=this._localVideoConfig.option)==null?void 0:n.videoTrack),yield this._localVideoTrack.capture(f)}h&&(j(h.profile)||(pt(h.profile)?fn[h.profile]&&this._localVideoTrack.setProfile(fn[h.profile]):this._localVideoTrack.setProfile(h.profile),(!h.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(h.cameraId))&&j(h.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),j(h.fillMode)||(_.objectFit=h.fillMode),j(h.mirror)||(_.mirror=h.mirror),j(h.rotation)||this._localVideoTrack.setRotation(h.rotation),h.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Np(h.qosPreference)),j(h.small)||(Rt(h.small)&&!h.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(Pp(h.small,!0)))),this._room.isJoined&&j(o)&&this._localVideoConfig.publish&&c&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&(o??this._localVideoConfig.publish?this._room.publish(this._localVideoTrack).catch(()=>{}):this._room.unpublish(this._localVideoTrack).catch(()=>{})),j(l)||(yield this._localVideoTrack.setMute(l)),yield this._updateVideoPlayOption({view:s,playOption:_,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),gn(this._localVideoConfig,t)})}stopLocalVideo(){return P(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),bi(this._localVideoTrack),this._localVideoTrack=null,delete this._room.capturedLocalMainVideoTrack,this._localVideoConfig=null)})}startScreenShare(){return P(this,arguments,function(){var t=this;let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0,view:null};return(function*(){var r,n;if(t._localScreenTrack)return void t._log.warn("screen share is already started");let{view:s=null,publish:o=!0,muteSystemAudio:l,option:c}=i,h=new Ra(t._room.videoManager);h.on("4",C=>{let x;C.error&&(x=Ne.convertFrom(C.error)),t.emit(Se.PUBLISH_STATE_CHANGED,xe(ve({},C),{error:x}))}),h.once("first-video-frame",C=>{t.emit(Se.FIRST_VIDEO_FRAME,xe(ve({},C),{streamType:ji(C.streamType)}))}),t._listenOutputTrackChanged(h),i.streamType==="main"&&(h.mediaType=4);let _=null,f={},T={};c&&(j(c.profile)||(pt(c.profile)?i0[c.profile]&&h.setProfile(i0[c.profile]):h.setProfile(c.profile)),c.systemAudio&&(f.systemAudio=!0,f.echoCancellation=c.echoCancellation,f.noiseSuppression=c.noiseSuppression,f.autoGainControl=c.autoGainControl),j(c.fillMode)||(T.objectFit=c.fillMode),c.videoTrack&&(f.videoTrack=c.videoTrack),c.audioTrack&&(f.audioTrack=c.audioTrack),c.captureElement&&(f.captureElement=c.captureElement),c.preferDisplaySurface&&(f.preferDisplaySurface=c.preferDisplaySurface),c.qosPreference&&(f.contentHint=Np(c.qosPreference)));let b=yield h.capture(f);if(h.mediaTrack.addEventListener(D.ENDED,()=>{t._stopScreenShare(),t.emit(Se.SCREEN_SHARE_STOPPED)}),b.getAudioTracks()[0]){_=new nE(t._room.audioManager);let C=b.getAudioTracks()[0];(r=i.option)!=null&&r.systemAudio&&!((n=i.option)!=null&&n.audioTrack)&&(_.sourceTrack=C),yield _.setInputMediaStreamTrack(C),Rt(l)&&_.mediaTrack&&(_.mediaTrack.enabled=!l),t._speakerId&&_.setAudioOutput(t._speakerId)}if(Ar(h,h).add("player-state-changed",C=>{t.emit(Se.VIDEO_PLAY_STATE_CHANGED,xe(ve({},C),{userId:"",streamType:"sub"}))}),o&&t._room.isJoined){let C=[h];_&&(C.push(_),t._checkScreenAudioEchoCancellation(h,_)),C.forEach(x=>t._room.publish(x).catch(()=>{}))}t._localScreenTrack=h,t._room.capturedLocalAuxVideoTrack=h,t._localScreenAudioTrack=_,t._localScreenConfig=xe(ve({},i),{view:s,publish:o}),yield t._updateVideoPlayOption({view:s,playOption:T,track:h})})()})}updateScreenShare(t){return P(this,null,function*(){var i;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:n,muteSystemAudio:s,option:o}=t,l={};if(o){if(j(o.fillMode)||(l.objectFit=o.fillMode),o.qosPreference){let c=Np(o.qosPreference);this._localScreenTrack.setContentHint(c)}o.videoTrack&&this._localScreenTrack.setInputMediaStreamTrack(o.videoTrack),o.audioTrack&&this._localScreenAudioTrack&&this._localScreenAudioTrack.setInputMediaStreamTrack(o.audioTrack)}if(this._room.isJoined&&!j(n)){if(n&&!this._localScreenConfig.publish){let c=[this._localScreenTrack];this._localScreenAudioTrack&&c.push(this._localScreenAudioTrack),c.forEach(h=>this._room.publish(h).catch(()=>{}))}if(this._localScreenConfig.publish&&!n){let c=[this._localScreenTrack];this._localScreenAudioTrack&&c.push(this._localScreenAudioTrack),c.forEach(h=>this._room.unpublish(h).catch(()=>{}))}}(i=this._localScreenAudioTrack)!=null&&i.mediaTrack&&Rt(s)&&(this._localScreenAudioTrack.mediaTrack.enabled=!s),yield this._updateVideoPlayOption({view:r,playOption:l,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),gn(this._localScreenConfig,t)})}stopScreenShare(){return P(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(t){return P(this,null,function*(){let{view:i,userId:r,streamType:n,option:s}=t,o="".concat(r,"_").concat(n);if(this._remoteVideoConfigMap.has(o))return void this._log.warn("remote video has already started. userId:".concat(r,", streamType:").concat(n));let l=this._room.remotePublishedUserMap.get(r);if(!l)return;let c={},h=n==="main"?l.remoteVideoTrack:l.remoteAuxiliaryTrack,_=this._bindRemoteVideoTrackEvents(h);this._listenOutputTrackChanged(h),s&&(j(s.fillMode)||(c.objectFit=s.fillMode),j(s.mirror)||(c.mirror=s.mirror),j(s.poster)||(c.poster=s.poster),c.canvasRender=s.canvasRender,n==="main"&&!j(s.small)&&(!l.remoteVideoTrack.isSubscribing&&!l.remoteVideoTrack.isSubscribed&&l.remoteVideoTrack.setMediaType(s.small?8:4),this._room.changeType(s.small,h.user)),j(s.draggable)||h.setDraggable(s.draggable)),yield this._room.subscribe(h),yield this._enableVideoDecodeFallback(h,n),yield this._updateVideoPlayOption({view:i,playOption:c,track:h}),this._emitTrackEvent(h),this._remoteVideoConfigMap.set(o,{config:t,handlers:_}),s&&!j(s.receiveWhenViewVisible)&&this._observeView({remoteTrack:h,view:i,receiveWhenViewVisible:s.receiveWhenViewVisible,viewRoot:s?.viewRoot})})}updateRemoteVideo(t){return P(this,null,function*(){var i,r;let{view:n,userId:s,streamType:o,option:l,mute:c}=t,h="".concat(s,"_").concat(o),_=this._remoteVideoConfigMap.get(h);if(!_||!this._room.remotePublishedUserMap.has(s))return;let f={};l&&(j(l.fillMode)||(f.objectFit=l.fillMode),j(l.mirror)||(f.mirror=l.mirror));let T=null,b=this._room.remotePublishedUserMap.get(s);if(o==="main"&&b!=null&&b.muteState.hasVideo&&(T=b.remoteVideoTrack),o==="sub"&&b!=null&&b.muteState.hasAuxiliary&&(T=b.remoteAuxiliaryTrack),!T)return;let{config:C}=_;o==="main"&&l&&!j(l.small)&&this._room.changeType(l.small,T.user),l&&!j(l.draggable)&&T.setDraggable(l.draggable),l&&(Rt(l.pictureInPicture)&&(l.pictureInPicture?yield T.player.enterPictureInPicture():yield T.player.exitPictureInPicture()),Rt(l.fullScreen)&&(l.fullScreen?yield T.player.enterFullscreen():yield T.player.exitFullscreen())),Rt(c)&&(T.ignoreUpdatePlayingState=!0,c?(yield T.player.pause(),yield this.room.unsubscribe(T)):(yield this.room.subscribe(T),yield T.player.resume(!0))),yield this._updateVideoPlayOption({view:n,playOption:f,track:T,prevConfig:C}),gn(C,t);let x=j(l?.receiveWhenViewVisible)?(i=C.option)==null?void 0:i.receiveWhenViewVisible:l.receiveWhenViewVisible,B=j(n)?C.view:n,Y=j(l?.viewRoot)?(r=C.option)==null?void 0:r.viewRoot:l.viewRoot;this._observeView({remoteTrack:T,view:B,receiveWhenViewVisible:x,viewRoot:Y})})}stopRemoteVideo(t){return P(this,null,function*(){return this._stopRemoteVideo(t)})}_stopRemoteVideo(t){let i=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return P(this,null,function*(){let r=[],n=this._room.remotePublishedUserMap.get(t.userId);if(n){let{muteState:s,remoteVideoTrack:o,remoteAuxiliaryTrack:l}=n;t.streamType==="main"&&(o.stop(),s.hasVideo&&r.push(o)),t.streamType==="sub"&&(l.stop(),s.hasAuxiliary&&r.push(l))}for(let s of r)i&&(delete s.ignoreUpdatePlayingState,yield this._room.unsubscribe(s),this._mediaTrackMap.delete(s.outMediaTrack));this._removeRemoteVideoConfig(t.userId,t.streamType)})}_removeRemoteVideoConfig(t,i){let r="".concat(t,"_").concat(i),n=this._remoteVideoConfigMap.get(r);if(n&&(n.observer&&n.observer.disconnect(),n.handlers)){let s=this._room.remotePublishedUserMap.get(t);if(s){let o=i==="main"?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._unbindRemoteVideoTrackEvents(o,n.handlers)}}this._remoteVideoConfigMap.delete(r)}_bindRemoteVideoTrackEvents(t){let i={onEnterPIP:()=>P(this,null,function*(){yield t.player.enterPIPPromise,this.emit(Se.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:ji(t.streamType),userId:t.userId,isPictureInPicture:!0,pictureInPictureWindow:t.player.pipWindow})}),onLeavePIP:()=>{this.emit(Se.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:ji(t.streamType),userId:t.userId,isPictureInPicture:!1})},onEnterFullScreen:()=>{this.emit(Se.FULL_SCREEN_STATE_CHANGED,{streamType:ji(t.streamType),userId:t.userId,isFullScreen:!0})},onLeaveFullScreen:()=>{this.emit(Se.FULL_SCREEN_STATE_CHANGED,{streamType:ji(t.streamType),userId:t.userId,isFullScreen:!1})},onDecodeFailed:()=>{this.emit(Se.ERROR,new Ne({code:De.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))},onVideoSizeChanged:r=>{this.emit(Se.VIDEO_SIZE_CHANGED,xe(ve({},r),{streamType:ji(r.streamType)}))}};return t.player.on(Me.ENTER_PICTURE_IN_PICTURE,i.onEnterPIP),t.player.on(Me.LEAVE_PICTURE_IN_PICTURE,i.onLeavePIP),t.player.on(Me.ENTER_FULL_SCREEN,i.onEnterFullScreen),t.player.on(Me.LEAVE_FULL_SCREEN,i.onLeaveFullScreen),t.on("decode-failed",i.onDecodeFailed),t.on("video-size-changed",i.onVideoSizeChanged),i}_unbindRemoteVideoTrackEvents(t,i){t.player.off(Me.ENTER_PICTURE_IN_PICTURE,i.onEnterPIP),t.player.off(Me.LEAVE_PICTURE_IN_PICTURE,i.onLeavePIP),t.player.off(Me.ENTER_FULL_SCREEN,i.onEnterFullScreen),t.player.off(Me.LEAVE_FULL_SCREEN,i.onLeaveFullScreen),t.off("decode-failed",i.onDecodeFailed),t.off("video-size-changed",i.onVideoSizeChanged)}muteRemoteAudio(t,i){return P(this,null,function*(){this._remoteAudioMuteMap.set(t,i);try{if(t==="*")if(i)yield this._stopRemoteAudio({userId:t});else{let r=[...this._room.remotePublishedUserMap.values()];for(let n of r)n.muteState.hasAudio&&!this._remoteAudioConfigMap.has(n.userId)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:n.userId}))}else i?yield this._stopRemoteAudio({userId:t}):!this._remoteAudioConfigMap.has(t)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:t}))}catch(r){throw r.code!==De.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(t),r}})}setRemoteAudioVolume(t,i){if(t==="*"){this._remoteAudioVolumeMap.set("*",i),this._remoteAudioVolumeMap.forEach((n,s)=>this._remoteAudioVolumeMap.set(s,i));let r=[...this._room.remotePublishedUserMap.values()];for(let n of r)this._remoteAudioVolumeMap.set(n.userId,i),n.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:i},track:n.remoteAudioTrack})}else if(t){let r=this._room.remotePublishedUserMap.get(t);this._remoteAudioVolumeMap.set(t,i),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:i},track:r.remoteAudioTrack})}}startPlugin(t,i){return P(this,null,function*(){return t.start(i)})}updatePlugin(t,i){return P(this,null,function*(){return t.update(i)})}stopPlugin(t,i){return P(this,null,function*(){return t.stop(i)})}enableAudioVolumeEvaluation(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3,i=arguments.length>1&&arguments[1]!==void 0&&arguments[1];this._room.enableAudioVolumeEvaluation(t,i)}on(t,i,r){if(this.listeners(t).includes(i))return this;if(this._log.debug("on",t),super.on(t,i,r),this._eventListened.add(t),this.listeners(Se.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:n}=this.room.audioManager;n.get("")||n.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return t==="realtime-transcriber-message"&&this._room.subscribeDataChannel(),this}emit(t){for(var i=arguments.length,r=new Array(i>1?i-1:0),n=1;n<i;n++)r[n-1]=arguments[n];try{XG.has(t)||this._log.debug("emit ".concat(t," ").concat(JSON.stringify(r)))}catch{}return super.emit(t,...r)}off(t,i,r){if(this._log.debug("off",t),t==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(t,i,r),(t==="realtime-transcriber-message"||t==="*")&&this.listeners("realtime-transcriber-message").length===0&&this._room.unsubscribeDataChannel(),(t===kn.EVENT.AUDIO_FRAME||t==="*")&&this.listeners(kn.EVENT.AUDIO_FRAME).length===0){let{getPCMAbortCtrlMap:n}=this.room.audioManager;n.forEach(s=>{s?.abort("off")}),n.clear()}return this}getAudioTrack(){let t,i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{userId:"",streamType:"main"},r=null,n="main",s=!1;if(pt(i)?t=i:(t=i.userId,s=i.processed===!0,i.streamType&&(n=i.streamType)),t){let o=this._room.remotePublishedUserMap.get(t);o&&(r=o.remoteAudioTrack)}else r=n==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?s&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{userId:"",streamType:"main"},{userId:i="",streamType:r="main",processed:n=!1}=t,s=null;if(i==="")r==="main"&&this._localVideoTrack&&(s=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(s=this._localScreenTrack);else{let o=this._room.remotePublishedUserMap.get(i);o&&(s=r==="main"?o.remoteVideoTrack:o.remoteAuxiliaryTrack)}return s?n&&s.outMediaTrack&&s.outMediaTrack!==s.mediaTrack?s.outMediaTrack.clone():s.mediaTrack:null}getVideoSnapshot(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{userId:i,streamType:r="main"}=t;if(i){let n=this._room.remotePublishedUserMap.get(i);if(r==="main"&&n!=null&&n.muteState.hasVideo)return n.remoteVideoTrack.getVideoFrame();if(r==="sub"&&n!=null&&n.muteState.hasAuxiliary)return n.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(t){var i,r;this._speakerId=t,(i=this._localAudioTrack)==null||i.setAudioOutput(t),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(t),this._room.remotePublishedUserMap.forEach(n=>n.remoteAudioTrack.setAudioOutput(t))}setCurrentSpeaker(t){return P(this,null,function*(){(yield ya()).forEach(i=>{i.deviceId===t&&(this._setCurrentSpeaker(t),this.emit(Se.DEVICE_CHANGED,{type:"speaker",action:"active",device:i}),ai=i)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: '.concat(mn,"/en/TRTC.html#.setCurrentSpeaker"))})}_startRemoteAudio(t){return this._doStartRemoteAudio(t)}_doStartRemoteAudio(t){return P(this,null,function*(){var i;let{userId:r}=t;if(this._remoteAudioConfigMap.has(r))return void this._log.warn("remote audio has already started. userId:".concat(r));let n=this._room.remotePublishedUserMap.get(r);if(!n)return;let s={},o=n.remoteAudioTrack;o.on("decode-failed",l=>{this.emit(Se.ERROR,new Ne({code:De.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(o),this._speakerId&&o.setAudioOutput(this._speakerId);try{let l=(i=this._remoteAudioVolumeMap.get(r))!=null?i:this._remoteAudioVolumeMap.get("*"),c=nt(l)?l:100;s.volume=c,this._remoteAudioConfigMap.set(r,t),yield this._room.subscribe(o),At(St(o,"decode-failed"),Ci(St(o,et.INIT)),Qt(()=>{this.startPlugin(dN.Name,{track:o,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:o}),$.emit("115",{userId:r,room:this.room}),o.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:o.outMediaTrack,refId:"ra-".concat(r)})}catch(l){throw this._remoteAudioConfigMap.delete(r),l}this._emitTrackEvent(o)})}_stopRemoteAudio(t){let i=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return P(this,null,function*(){let r=this._room.remotePublishedUserMap.get(t.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&i&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete("".concat(t.userId)),$.emit("116",{userId:t.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:"ra-".concat(t.userId)})})}_enableVideoDecodeFallback(t,i){let r,n=this._room.videoDecodeFallbackType;n&&this._plugins.has("TRTCVideoDecoder")&&(t.log.debug("remote video will fall back when decode failed",t.id),At(St(t,"decode-failed"),Ci(St(t,et.INIT)),Qv(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:t,config:{codec:"avc1.420028"},fallback:n})}),Rp(St(t,"decode-downgrade-state-changed")),Qt(s=>{r=s.state,this.emit(Se.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,xe(ve({},s),{streamType:i,userId:t.userId}))},s=>{t.log.error("fallback",s)},()=>{r==="STARTED"&&t.log.info("fallback complete")})))}_updateVideoPlayOption(t){return P(this,arguments,function(i){let{view:r,playOption:n,track:s,prevConfig:o}=i;return(function*(){if(s.setMirror(n.mirror),j(r)&&o&&o.view&&!Mh(n)){let l=Rc(o.view);l.length>0&&(yield s.play(l,n))}if(!j(r)){let l=Rc(r);l.length>0?yield s.play(l,n):s.stop()}})()})}_updateAudioPlayOption(t){return P(this,arguments,function(i){var r=this;let{playOption:n={},track:s,prevConfig:o}=i;return(function*(){if(!s.isPlayCalled)try{yield s.play(null,n)}catch{}if(j(n.muted)||s.setPlayerMute(n.muted),j(n.volume)||s.setAudioVolume(n.volume/100),s instanceof Ia&&s.mediaTrack){let l=n.muted===!1&&!j(n.volume)&&n.volume>0?"add":"remove";r.room.audioManager.updateAudioReference({type:l,audioReference:s.mediaTrack,refId:"em"})}else if(s instanceof kp){let l=n.muted?0:n.volume;if(j(l))return;r.room.audioManager.updateAudioReference({type:"updateVolume",refId:"ra-".concat(s.userId),volume:n.volume})}})()})}_listenOutputTrackChanged(t){t.listeners("output-media-track-changed").length===0&&t.on("output-media-track-changed",()=>this._emitTrackEvent(t,!1))}_emitTrackEvent(t){let i=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],r=t.isRemote?t.userId:"";t.outMediaTrack&&(i&&this._mediaTrackMap.get(t.outMediaTrack)===r||(this._mediaTrackMap.set(t.outMediaTrack,r),this.emit(Se.TRACK,{userId:r,streamType:ji(t.streamType),track:t.outMediaTrack,sourceTrack:t.mediaTrack})))}_checkTrackToPublish(){var t,i,r;let n=[];if((t=this._localAudioConfig)!=null&&t.publish&&this._localAudioTrack&&n.push(this._localAudioTrack),(i=this._localVideoConfig)!=null&&i.publish&&this._localVideoTrack&&n.push(this._localVideoTrack),(r=this._localScreenConfig)!=null&&r.publish&&(this._localScreenTrack&&n.push(this._localScreenTrack),this._localScreenAudioTrack&&n.push(this._localScreenAudioTrack),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),n.length!==0)return Promise.all(n.map(s=>this._room.publish(s).catch(()=>{})))}_observeView(t){let{remoteTrack:i,view:r,receiveWhenViewVisible:n,viewRoot:s}=t;if(j(r)||j(n))return;let o=this._remoteVideoConfigMap.get("".concat(i.userId,"_").concat(ji(i.streamType)));if(!o)return;let l=o.observer||void 0;if(r===null||Jt(r)&&r.length===0||!n)return l?.disconnect(),void(i.isSubscribed||(this._log.info("_observeView observer disconnect, resubscribe",i.userId,i.strMediaType),this._room.subscribe(i).catch(()=>{})));let c=o.visibleViewMap||new Map,h=-1;(!l||l.root!==s)&&(l?.disconnect(),c.clear(),l=new IntersectionObserver(f=>{f.forEach(T=>{c.set(T.target,T.isIntersecting),i.log.info("view ".concat(T.target.id," is").concat(T.isIntersecting?"":" not"," visible"))}),clearTimeout(h),h=window.setTimeout(()=>{[...c.values()].find(T=>T)?i.isSubscribed||this._room.subscribe(i).catch(()=>{}):i.isSubscribed&&this._room.unsubscribe(i).catch(()=>{})},200)},{root:s}));let _=new Set(Rc(r));c.forEach((f,T)=>{_.has(T)||(l.unobserve(T),c.delete(T))}),_.forEach(f=>{c.set(f,!0),l.observe(f)}),l.takeRecords().forEach(f=>{c.set(f.target,f.isIntersecting)}),o.visibleViewMap=c,o.observer=l}_exitRoom(){return P(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return P(this,null,function*(){var t;if(this._localScreenTrack){if(this._room.isJoined){let i=[this._localScreenTrack];this._localScreenAudioTrack&&i.push(this._localScreenAudioTrack),yield Promise.all(i.map(r=>this._room.unpublish(r).catch(()=>{})))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(((t=this._localScreenAudioTrack.trackSettings)==null?void 0:t.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),bi(this._localScreenTrack),this._localScreenTrack=null,delete this._room.capturedLocalAuxVideoTrack,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(t,i){return P(this,null,function*(){var r,n;if(!t||!i)return;let s=(r=t.trackSettings)==null?void 0:r.displaySurface;if(((n=i.trackSettings)==null?void 0:n.echoCancellation)===!1&&(s==="monitor"||s==="browser"&&t.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(o){this._log.warn("start audioProcessor plugin failed: ",o)}}})}_onLocalTrackCaptured(t){let{track:i}=t;i.kind==="audio"&&(!ai||iu(ai))&&(this._initActiveSpeaker(),$.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return P(this,null,function*(){if(ai&&!iu(ai))this.emit(Se.DEVICE_CHANGED,{type:"speaker",action:"active",device:ai});else{let t=yield ya();t[0]&&!iu(t[0])?(ai=t[0],this.emit(Se.DEVICE_CHANGED,{type:"speaker",action:"active",device:t[0]})):$.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable(t){let{userId:i}=t,r=this._remoteAudioMuteMap.has(i)?this._remoteAudioMuteMap.get(i):this._remoteAudioMuteMap.get("*");(r===!1||this._room.autoReceiveAudio&&!r)&&this._doStartRemoteAudio({userId:i}).catch(()=>{})}_onVideoAvailable(t){let{userId:i,streamType:r}=t;if(!this._room.autoReceiveVideo)return;let n=this._room.remotePublishedUserMap.get(i);if(n){let s=r==="main"?n.remoteVideoTrack:n.remoteAuxiliaryTrack,o=[s];this._room.autoReceiveAudio&&n.remoteAudioTrack.isAvailable&&o.push(n.remoteAudioTrack),this._room.subscribe(...o).then(()=>{this._emitTrackEvent(s)}).catch(()=>{})}}_onAudioUnavailable(t){let{userId:i,muteState:r}=t;r.hasAudio&&r.audioMuted||this._stopRemoteAudio({userId:i},!1).catch(()=>{})}_onVideoUnavailable(t){let{userId:i,streamType:r}=t;this._stopRemoteVideo({userId:i,streamType:r},!1).catch(()=>{})}_onDataChannelAvailable(){if(this.listeners("realtime-transcriber-message").length>0)return this._room.subscribeDataChannel()}sendSEIMessage(t,i){var r;let n=this._plugins.get("SEI");n&&(n.update({buffer:t,options:xe(ve({seiPayloadType:243},i),{small:!((r=this._localVideoTrack)==null||!r.small)})}),ce.addCount({key:5e5,useUV:!0}))}sendCustomMessage(t){var i,r;(r=(i=this._room).sendCustomMessage)==null||r.call(i,t),ce.addCount({key:500001,useUV:!0})}callExperimentalAPI(t,i){return P(this,null,function*(){return this._log.info("callExperimentalAPI(".concat(t,", ").concat(JSON.stringify(i),")")),hj.call(t,ve({trtcInstance:this},i))})}static setLogLevel(t,i){fe.setLogLevel(t),j(i)||(i?fe.enableUploadLog():fe.disableUploadLog())}static isSupported(){return fv(kn.frameWorkType)}static getPermissions(t){return P(this,arguments,function(i){let{request:r=!0,types:n=["camera","microphone"]}=i;return(function*(){r&&(yield Bp.request(n).catch(l=>{var c;return fe.error("getPermissions request failed, error: ".concat((c=l?.message)!=null?c:l))}));let[s,o]=yield Promise.all([Bp.get("camera"),Bp.get("microphone")]);return{camera:s,microphone:o}})()})}static getCameraList(){return Sn(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static getMicrophoneList(){return Tn(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static getSpeakerList(){return ya(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static setCurrentSpeaker(t){return P(this,null,function*(){if(Vt&&(t===fu.SPEAKER||t===fu.HEADSET)){let i=yield kn.getMicrophoneList(),r="";return i.forEach(n=>{n.label===t&&(r=n.deviceId)}),r?void vu.forEach(n=>P(null,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:r}}))})):void 0}(yield ya()).forEach(i=>{i.deviceId===t&&(vu.forEach(r=>{r._setCurrentSpeaker(t),r.emit(Se.DEVICE_CHANGED,{type:"speaker",action:"active",device:i})}),ai=i)})})}static _addKVStat(t){let{type:i,key:r,value:n,base:s,useUV:o,version:l,max:c}=t;switch(l&&(Bc.version=l),i){case"count":Bc.addCount({key:r,useUV:o});break;case"enum":Bc.addEnum({key:r,value:n,useUV:o});break;case"number":Bc.addNumber({key:r,value:n,split:s,max:c})}}};m(Ke,"VERSION",sN),m(Ke,"_loggerManager",fe),m(Ke,"EVENT",Se),m(Ke,"ERROR_CODE",De),m(Ke,"TYPE",fu),m(Ke,"frameWorkType",30),_e([kt({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?e?.assetsPath:"default"}})})],Ke.prototype,"use"),_e([vi(si.TRTC.enterRoom),Ca("room",(e,t)=>{let[i]=e,[r]=t;return(i.roomId||i.strRoomId)===(r.roomId||r.strRoomId)&&i.userId===r.userId&&i.sdkAppId===r.sdkAppId}),_t(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),kt()],Ke.prototype,"enterRoom"),_e([kt()],Ke.prototype,"exitRoom"),_e([vi(si.TRTC.switchRoom),kt(),ru()],Ke.prototype,"switchRoom"),_e([vi(si.TRTC.switchRole),Jo("room",{merge:(e,t)=>t}),kt()],Ke.prototype,"switchRole"),_e([kt()],Ke.prototype,"destroy"),_e([vi(si.TRTC.startLocalAudio),Ca("audio",(e,t)=>{let[i]=e,[r]=t;var n,s;return((n=i?.option)==null?void 0:n.microphoneId)===((s=r?.option)==null?void 0:s.microphoneId)}),kt()],Ke.prototype,"startLocalAudio"),_e([vi(si.TRTC.updateLocalAudio),Jo("audio",{debounce:{delay:200,getKey:()=>"".concat(pN,"-localAudio"),isNeedToDebounce:e=>{var t;return!j((t=e.option)==null?void 0:t.captureVolume)}}}),kt()],Ke.prototype,"updateLocalAudio"),_e([ka("audio"),kt()],Ke.prototype,"stopLocalAudio"),_e([vi(si.TRTC.startLocalVideo),Ca("video",(e,t)=>{let[i]=e,[r]=t;var n,s;return((n=i?.option)==null?void 0:n.cameraId)===((s=r?.option)==null?void 0:s.cameraId)}),kt()],Ke.prototype,"startLocalVideo"),_e([vi(si.TRTC.updateLocalVideo),Jo("video"),kt()],Ke.prototype,"updateLocalVideo"),_e([ka("video"),kt()],Ke.prototype,"stopLocalVideo"),_e([vi(si.TRTC.startScreenShare),Ca("screen",()=>!0),kt()],Ke.prototype,"startScreenShare"),_e([vi(si.TRTC.updateScreenShare),Jo("screen"),kt()],Ke.prototype,"updateScreenShare"),_e([kt()],Ke.prototype,"stopScreenShare"),_e([vi(si.TRTC.startRemoteVideo),Ca(e=>"v".concat(e.userId).concat(e.streamType),()=>!0),kt({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Ke.prototype,"startRemoteVideo"),_e([vi(si.TRTC.updateRemoteVideo),Jo(e=>"v".concat(e.userId).concat(e.streamType)),kt({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Ke.prototype,"updateRemoteVideo"),_e([vi(si.TRTC.stopRemoteVideo),_t(e=>function(t){return P(this,null,function*(){if(t.userId==="*"){let i=[];return this._room.remotePublishedUserMap.forEach(r=>{this._remoteVideoConfigMap.has("".concat(r.userId,"_main"))&&i.push(this.stopRemoteVideo({streamType:"main",userId:r.userId}).catch(()=>{})),this._remoteVideoConfigMap.has("".concat(r.userId,"_sub"))&&i.push(this.stopRemoteVideo({streamType:"sub",userId:r.userId}).catch(()=>{}))}),Promise.all(i)}return e.call(this,t)})}),kt({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Ke.prototype,"stopRemoteVideo"),_e([ka(e=>"v".concat(e.userId).concat(e.streamType))],Ke.prototype,"_stopRemoteVideo"),_e([vi(...si.TRTC.muteRemoteAudio),kt({getRemoteId:e=>e})],Ke.prototype,"muteRemoteAudio"),_e([aN(...si.TRTC.setRemoteAudioVolume),(function(e,t){return _t((i,r)=>function(){for(var n=arguments.length,s=new Array(n),o=0;o<n;o++)s[o]=arguments[o];let l=Yo.get(this);l||(l=new Map,Yo.set(this,l));let c=t(...s),h=l.get(c);if(!h||h<=0){i.apply(this,s);let _=setTimeout(()=>{var f;(f=Yo.get(this))==null||f.delete(c)},e);l.set(c,_)}else{clearTimeout(h);let _=window.setTimeout(()=>{var f;i.apply(this,s),(f=Yo.get(this))==null||f.delete(c)},e);l.set(c,_)}})})(200,e=>e),kt({getRemoteId:e=>e})],Ke.prototype,"setRemoteAudioVolume"),_e([mE("start"),Ta(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),Ca((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),kt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>tw[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],Ke.prototype,"startPlugin"),_e([mE("update"),Jo((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t),{merge:(e,t)=>(gn(e[1],t[1]),e)}),kt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>iw[e.getName()]})],Ke.prototype,"updatePlugin"),_e([mE("stop"),ka((e,t)=>{if(e.disableRandomCall)return null;let i=e.getGroup(t),r=e.getAlias();return i==="*"?new RegExp("".concat(r,".*")):r+i}),kt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>rw[e.getName()]})],Ke.prototype,"stopPlugin"),_e([aN(...si.TRTC.enableAudioVolumeEvaluation)],Ke.prototype,"enableAudioVolumeEvaluation"),_e([kt()],Ke.prototype,"getVideoSnapshot"),_e([kt()],Ke.prototype,"_setCurrentSpeaker"),_e([Ca(e=>"a".concat(e.userId),()=>!0)],Ke.prototype,"_startRemoteAudio"),_e([_t(e=>function(t){return P(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(i=>this._stopRemoteAudio(xe(ve({},t),{userId:i.userId})).catch(()=>{}))):e.call(this,t)})}),ka(e=>"a".concat(e.userId))],Ke.prototype,"_stopRemoteAudio"),_e([ka("room")],Ke.prototype,"_exitRoom"),_e([ka("screen")],Ke.prototype,"_stopScreenShare"),_e([vi(...si.TRTC.sendSEIMessage),ND({timesInSecond:30,maxSizeInSecond:8e3,getSize:function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].byteLength}})],Ke.prototype,"sendSEIMessage"),_e([vi(si.TRTC.sendCustomMessage),ND({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],Ke.prototype,"sendCustomMessage"),_e([wa()],Ke,"create"),_e([vi(si.TRTC.create)],Ke,"_create"),_e([wa()],Ke,"setLogLevel"),_e([wa()],Ke,"isSupported"),_e([wa(),kt()],Ke,"getPermissions"),_e([wa()],Ke,"getCameraList"),_e([wa()],Ke,"getMicrophoneList"),_e([wa()],Ke,"getSpeakerList");var Hp=Ke,fj=class{constructor(){m(this,"_set",new Set),$.on(ie.LEAVE_SUCCESS,this.delete,this),$.on(ie.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add(e){let{room:t,roomId:i}=e;if(t.scene==="rtc")return;let r=this.getKey(t.userId,i||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(r)}delete(e){let{room:t,roomId:i}=e;if(t.scene==="rtc")return;let r=this.getKey(t.userId,t.roomId||i,t.sdkAppId,t.useStringRoomId);this._set.delete(r)}getKey(e,t,i,r){return"".concat(i,"_").concat(t,"_").concat(e,"_").concat(r)}isJoined(e){let{userId:t,roomId:i,sdkAppId:r,room:n}=e;return n.scene!=="rtc"&&this._set.has(this.getKey(t,i,r,n.useStringRoomId))}handleSwitchRoomSuccess(e){let{room:t,currentRoomId:i,targetRoomId:r}=e;t.scene!=="rtc"&&(this._set.delete(this.getKey(t.userId,i,t.sdkAppId,t.useStringRoomId)),this._set.add(this.getKey(t.userId,r,t.sdkAppId,t.useStringRoomId)))}};function _j(){return P(this,null,function*(){let e,t;try{let b=yield Tn();e=b&&b.length}catch{}try{let b=yield Sn();t=b&&b.length}catch{}let i={microphone:e,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:n,isH264DecodeSupported:s,isVp8DecodeSupported:o,isH265EncodeSupported:l,isH265DecodeSupported:c}=this.checkSystemResult.detail,h=Vc.basis(),_={webRTC:h.isWebRTCSupported,getUserMedia:h.isGetUserMediaSupported,webSocket:h.isWebSocketsSupported,screenShare:h.isScreenShareSupported,webAudio:h.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:n,vp8Decode:o,h265Encode:l,h265Decode:c},f={browser:h.browser,os:h.os,trtc:_,devices:i},T={isWebCodecSupported:h.isWebCodecSupported,isMediaSessionSupported:h.isMediaSessionSupported,isWebTransportSupported:h.isWebTransportSupported};dt.uploadEvent({log:"trtcstats-".concat(JSON.stringify(f)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(f))),dt.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(T)),userId:this.userId}),Iw()})}var gj=ti(Ri()),mN="1",SE="2",Eu="3",vj="4",Wp="5",Ej="6",Gp="7",fN="8",br={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140,FALLBACK_CODEC:66,SEND_SWITCH_ROOM_RES:4160,SEND_SWITCH_ROOM_SUBED_REQ:4161,UPDATE_NETWORK_TIME_RESULT:5001,CUSTOM_CMD_RES:8220},yj=[br.UPDATE_REMOTE_MUTE_STAT,br.UPLINK_NETWORK_STATS,br.USER_LIST_RES,br.MUTE_RESULT,br.SERVER_FIRST_PACKAGE_RECEIVED,br.RECEIVE_CUSTOM_MSG,br.UPDATE_NETWORK_TIME_RESULT],Ge={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg",FALLBACK_CODEC:"fallback-codec",SEND_SWITCH_ROOM_RES:"send-switch-room-res",SEND_SWITCH_ROOM_SUBED_REQ:"send-switch-room-subed-res",UPDATE_NETWORK_TIME_RESULT:"update_network_time_result",CUSTOM_CMD_RES:"custom-cmd-res"},_N="publish_change",Tj="join",Sj="leave",Ij="quality_report",gN="mute_uplink",vN="publish",IE="publish_state_change",jp="unpublish",EN="subscribe",RE="unsubscribe",AE="subscribe_change",Rj="start_publishing",Aj="stop_publishing",bj="start_push_user_cdn",Cj="stop_push_user_cdn",kj="start_mcu_mix",wj="stop_mcu_mix",Dj="start_publish_cdn_stream",Nj="update_publish_cdn_stream",Pj="stop_publish_cdn_stream",Oj="get_user_list",Mj="change_role",bE="update_constraint_config",Lj="rebuild_pc",xj="join/v2",yN="publish/v2",TN="subscribe/v3",Uj="ability_status_report",Vj="reconnect",Fj="channel_msg",Bj="switch_room",Hj="update_network_time",Wj=new Set([vN,_N,IE,jp,EN,AE,RE,yN,TN]),zp=new Set,Gj=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],jj=0,SN=class extends gj.default{constructor(e){var t,i,r;super(),m(this,"room"),m(this,"sdkAppId"),m(this,"userId"),m(this,"userSig"),m(this,"url"),m(this,"backupUrl"),m(this,"destroyed",!1),m(this,"_socketInUse"),m(this,"_socket"),m(this,"_backupSocket"),m(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[],reportToken:void 0}),m(this,"_currentState","DISCONNECTED"),m(this,"_isReconnecting",!1),m(this,"_seq",0),m(this,"_log"),m(this,"_lastMessageTime",-1),m(this,"_connectStartTime",-1),m(this,"_stopConnectRetry"),m(this,"_isFirstConnect",!0),m(this,"bytesSent",0),m(this,"bytesReceived",0),m(this,"keepAlive",!1),m(this,"signalDomainWhenUnifiedProxy"),m(this,"stopKeepAliveTimeout"),m(this,"rtt",0),this.room=e.room,this.sdkAppId=e.sdkAppId,this.userId=e.userId,this.userSig=e.userSig,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy;let n=((i=(t=this.room.scheduleResult)==null?void 0:t.config)==null?void 0:i.keepAliveClient)||0;(r=this.room.joinParams)!=null&&r.keepAlive&&!n&&(n=1),n-zp.size>0&&this.room.enableSPC&&(this.keepAlive=!0,zp.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=fe.createLogger({parent:this.room.getLogger(),id:"ws".concat(++jj),userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let e="?sdkAppId=".concat(encodeURIComponent(this.sdkAppId),"&userId=").concat(encodeURIComponent(this.userId),"&userSig=").concat(encodeURIComponent(this.userSig),"&keepAlive=").concat(encodeURIComponent(Number(this.keepAlive)));this.signalDomainWhenUnifiedProxy&&(e+="&signalDomain=".concat(encodeURIComponent(this.signalDomainWhenUnifiedProxy)));let t=new URLSearchParams(location.search);return Gj.forEach(i=>{let r=t.get("trtc_".concat(i));r&&(e+="&".concat(i,"=").concat(encodeURIComponent(r)))}),this.race?"".concat(e,"&race=1"):e}get _urlWithParam(){return"".concat(this.url).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get _backupUrlWithParam(){return"".concat(this.backupUrl).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12e3}connect(){return P(this,arguments,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1e4;return(function*(){if(e.isConnected)return Promise.resolve();e._log.info("connect to [".concat(e.url,", ").concat(e.backupUrl,"] ").concat(e.race?"race":"").concat(t?" timeout: ".concat(t):""," keepAlive: ").concat(Number(e.keepAlive))),e.emitConnectionStateChanged("CONNECTING"),e._connectStartTime=Ue();let i=[e.connectWS({url:e._urlWithParam,isMain:!0,timeout:t})];e.race&&e._backupUrlWithParam!==e._urlWithParam&&i.push(e.connectWS({url:e._backupUrlWithParam,isMain:!1,timeout:t})),e._socketInUse=yield Sc(i),e.unbindAndCloseSocket(e._socketInUse===e._socket?D.BACKUP:D.MAIN),e._isFirstConnect&&(ce.addSuccessEvent({key:521720}),e._isFirstConnect=!1),e.emitConnectionStateChanged("CONNECTED")})()})}connectWS(e){let{url:t,timeout:i,isMain:r}=e,n=new WebSocket(t);this.bindSocket(n),r?this._socket=n:this._backupSocket=n;let s=-1;return new Promise((o,l)=>{n.onclose=l,n.onerror=l,n.onopen=()=>o(n),i&&(s=setTimeout(()=>{this.unbindAndCloseSocket(r?D.MAIN:D.BACKUP),l(new me({code:te.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},i))}).finally(()=>{n.onclose=null,n.onerror=null,n.onopen=null,clearTimeout(s)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===D.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch{}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch{}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn("".concat(e.target===this._socket?"main":"backup"," is closed code:").concat(e.code," ").concat(e.reason)),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||e.code!==1e3)&&this.startReconnection(),this.room.isJoining&&this.emit(Wp,new me({code:te.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error("".concat(e.target===this._socket?"main":"backup"," error observed")),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(D.MAIN),this.unbindAndCloseSocket(D.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(Wp,new me({code:te.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;let{isOnline:t}=this;this._lastMessageTime=Date.now(),t||this.emit(fN),this.bytesReceived+=xh(e.data);let i=JSON.parse(e.data),{cmd:r,data:n}=i,s=Object.values(br),o=Object.keys(br)[s.indexOf(r)],l=Ge[o]||r;switch(yj.includes(r)||(this._log.debug("received ".concat(r," msg: ").concat(e.data)),l&&this._log.info("Received event: [ ".concat(l," ]"))),r){case br.CHANNEL_SETUP_RESULT:if(i.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&G1(n.svrTime-new Date().getTime()),this._log.info("ChannelSetup Success ".concat(Ue()-this._connectStartTime)),ce.addSuccessEvent({key:521701,cost:Ue()-this._connectStartTime}),this._connectStartTime=-1,this.emit(mN,{signalInfo:this._signalInfo});else{let c=new me({code:te.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:i.code,message:He({key:Fe.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:i.code,errorMsg:i.message}})});this._log.error("".concat(i.code,", ").concat(i.message)),this.close(),ce.addFailedEvent({key:521701,error:c}),this.emit(Wp,c)}break;case br.JOIN_ROOM_RESULT:i.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.bakRelayIps=n.bakRelayIps,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=i.tinyId,this._signalInfo.endReportExtend=n.endReportExtend,this._signalInfo.reportToken=n.reportToken,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(l,{data:i});break;default:this.emit(String(l),{data:i})}}reGetSignalChannelUrl(){return P(this,null,function*(){try{if(!this.room.joinParams)return;Jr(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch{}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?D.MAIN:D.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return P(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive)return void this.close();this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:i,relayInnerIp:r,relayPort:n}=this._signalInfo,{data:s}=yield this.sendWaitForResponse({command:Vj,data:{roomId:e,useStringRoomId:t,relayInnerIp:r,relayOuterIp:i,relayPort:n},responseCommand:Ge.CHANNEL_RECONNECT_RESULT});s.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),ce.addSuccessEvent({key:521702,cost:Ue()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(ce.addFailedEvent({key:521702,error:s.code}),this._log.warn("reconnect failed, ".concat(s.code," ").concat(s.message)),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.isConnected&&!this.room.isLeft){let i={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},r=JSON.stringify(i);return this._socketInUse.send(r),Wj.has(e)&&this._log.info("send",e,t),this.bytesSent+=xh(r),i.seq}}sendWaitForResponse(e){let{command:t,data:i,timeout:r=5e3,responseCommand:n,commandDesc:s,enableLog:o=!0,addReceiveTime:l=!1}=e;return new Promise((c,h)=>{let _=()=>{clearTimeout(f),h(new me({code:te.API_CALL_ABORTED,message:"".concat(t," aborted due to connection closed")}))};this.once(Gp,_);let f=setTimeout(()=>{this.off(n,T),this.off(Gp,_);let C=new me({code:te.API_CALL_TIMEOUT,message:He({key:Fe.API_CALL_TIMEOUT,data:{commandDesc:s,command:t}})});o&&this._log.warn(C),h(C)},r),T=C=>{C.data.seq===b&&(clearTimeout(f),this.off(n,T),this.off(Gp,_),l&&(C.data.receiveTime=Date.now()),c(C))};this.on(n,T);let b=this.send(t,i)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:i,retries:r=0,retryTimeout:n=0}=e;return Cc({retryFunction:this.sendWaitForResponse,onError:s=>{let{retry:o,reject:l,error:c}=s;!this.room.isJoined||this.destroyed||c.code===te.API_CALL_ABORTED?l(c):this.isOnline?o():(this._log.warn("retry ".concat(i," when connected")),this.once(fN,o))},onRetrying:s=>{this._log.warn("".concat(t||i," timeout observed, retrying [").concat(s,"/").concat(r,"]"))},settings:{retries:r,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),zp.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0,reportToken:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(D.MAIN),this.unbindAndCloseSocket(D.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(Gp)}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var e;let t=(e=this._signalInfo.bakRelayIps)==null?void 0:e.shift();return t&&(t.relayPort=t.relayPort||this._signalInfo.relayPort),t}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:3600;if(this.keepAlive){this._log.info("stopKeepAlive in ".concat(e,"s")),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info("close due to not used ".concat(e,"s")),this.close(),this.off(Ge.JOIN_ROOM_RESULT,t)},1e3*e);let t=i=>{i.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(Ge.JOIN_ROOM_RESULT,t))};this.on(Ge.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){if(e===this._currentState)return;this._log.info("".concat(this._currentState," -> ").concat(e));let t={prevState:this._currentState,state:e};e==="CONNECTING"&&(t.isReconnecting=this._isReconnecting),this.emit(SE,t),this._currentState=e,e==="CONNECTED"?this.emit(Eu):e==="DISCONNECTED"&&this.emit(Ej)}};_e([hs({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&(this._isFirstConnect&&(ce.addFailedEvent({key:521720,error:e}),this._isFirstConnect=!1),t())},onRetrying(e,t){this._log.warn("retrying to connect ".concat(e)),e>=3&&e%3==0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],SN.prototype,"connect");var zj=ti(Ri()),CE=0,kE=!1,Kp=new Set,IN=!1,bn=class{constructor(e){m(this,"userId"),m(this,"tinyId"),m(this,"_sdpSemantics"),m(this,"_isUplink"),m(this,"_room"),m(this,"_log"),m(this,"_signalChannel"),m(this,"_isErrorObserved",!1),m(this,"_waitForPeerConnectionConnectedPromise"),m(this,"_waitForPeerConnectionConnectedPromiseReject",null),m(this,"_peerConnection",null),m(this,"_emitter",new zj.default),m(this,"_currentState","DISCONNECTED"),m(this,"_isReconnecting",!1),m(this,"_reconnectionCount",0),m(this,"_reconnectionTimer",-1),m(this,"_isFirstConnection",!0),m(this,"_prevTime",-1),m(this,"_localAddress"),m(this,"_remoteAddress"),m(this,"isDestoyed",!1),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=e.room.getLogger().createChild({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=e.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=Ue())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,ce.addSuccessEvent({key:521705,cost:Math.min(Ue()-this._prevTime,3e4)})):this._isReconnecting&&ce.addSuccessEvent({key:521706,cost:Ue()-this._prevTime}),this._prevTime=-1}catch(e){throw this._isFirstConnection?(this._isFirstConnection=!1,ce.addFailedEvent({key:521705,error:e})):this._isReconnecting&&this._reconnectionCount>=3&&ce.addFailedEvent({key:521706,error:e}),e}}initialize(){let e={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(e),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(e){this._log.info("close connection"),this._emitter.emit("closed",e),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),Kp.delete(this)}destroy(){this.isDestoyed=!0}closePeerConnection(){let e=arguments.length>0&&arguments[0]!==void 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 me({code:te.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return ss;let e=null;if(this._isUplink){if(!Wc()||this._peerConnection.getSenders().length===0)return ss;e=this._peerConnection.getSenders()[0].transport}else{if(!np()||this._peerConnection.getReceivers().length===0)return ss;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:ss}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===Kt.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===Kt.FAILED||e.target.connectionState===Kt.CLOSED){let r="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),n=new me({message:r,code:te.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(e.target.connectionState===Kt.CONNECTED||e.target.connectionState===Kt.COMPLETED)&&(this.logSelectedCandidate(),dt.logSuccessEvent({userId:this._room.userId,eventType:di.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&(e==="CONNECTED"?(CE=0,kE=!1,IN=!0,Kp.add(this)):Kp.delete(this),$.emit(ie.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 P(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(Hc(t)){let i=e.get(t.localCandidateId),r=e.get(t.remoteCandidateId);i&&(this._log.info("local candidate: ".concat(i.candidateType," ").concat(i.protocol,":").concat(i.ip||i.address,":").concat(i.port," ").concat(i.networkType||""," ").concat(i.candidateType==="relay"?"relayProtocol:".concat(i.relayProtocol):"")),this._localAddress="".concat(i.ip||i.address,":").concat(i.port)),r&&(this._log.info("remote candidate: ".concat(r.candidateType," ").concat(r.protocol,":").concat(r.ip||r.address,":").concat(r.port)),this._remoteAddress="".concat(r.protocol,":").concat(r.ip||r.address));break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise||(this._waitForPeerConnectionConnectedPromise=new Promise((e,t)=>{if(this._currentState==="CONNECTED")return e();this._waitForPeerConnectionConnectedPromiseReject=t;let i=o=>{o.state==="CONNECTED"&&(clearTimeout(s),n(),e())},r=o=>{let{room:l}=o;l===this._room&&(clearTimeout(s),n(),t(new me({code:te.API_CALL_ABORTED,message:He({key:Fe.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{$.off(ie.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",i,this)},s=setTimeout(()=>{n();let o=new me({code:te.API_CALL_TIMEOUT,message:"connection timeout"});var l;CE+=1,l=this._signalChannel.isConnected,CE>2&&!kE&&Kp.size===0&&l&&(this._log.warn("firewall restriction"),kE=!0,this._emitter.emit("firewall-restriction")),t(o)},l0);$.on(ie.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",i,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null})),this._waitForPeerConnectionConnectedPromise}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(Eu,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Ro()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let e=new me({code:this._isUplink?te.UPLINK_RECONNECTION_FAILED:te.DOWNLINK_RECONNECTION_FAILED,message:He({key:this._isUplink?Fe.UPLINK_RECONNECTION_FAILED:Fe.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(Eu,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!((t=(e=this._peerConnection)==null?void 0:e.remoteDescription)==null||!t.sdp.includes("H264"))}setOffer(e){var t;return(t=this._peerConnection)==null?void 0:t.setLocalDescription(e)}setAnswer(e){var t;return(t=this._peerConnection)==null?void 0:t.setRemoteDescription(e)}};_e([ms(521712,!1)],bn.prototype,"setOffer"),_e([ms(521713,!1)],bn.prototype,"setAnswer");var RN=ti(F1()),zt=function(e){return RN.default.parse(e)},Es=function(e){return RN.default.write(e)};function wE(e){return Object.keys(e).filter(t=>e[t])}var Jp=class oP extends bn{constructor(t){super(xe(ve({},t),{isUplink:!1})),m(this,"_flag",0),m(this,"isRobot",!1),m(this,"role","anchor"),m(this,"remoteAudioTrack"),m(this,"remoteVideoTrack"),m(this,"remoteAuxiliaryTrack"),m(this,"avPlayerStateSyncManager"),m(this,"ssrc",{audio:0,video:0,auxiliary:0}),m(this,"_isSDPExchanging",!1),m(this,"_videoCodec"),m(this,"fromType"),this.flag=t.flag,this.isRobot=t.isRobot||!1,this.remoteAudioTrack=t.remoteAudioTrack||new kp(this._room,this),this.remoteVideoTrack=t.remoteVideoTrack||new mu(this._room,this),this.remoteAuxiliaryTrack=t.remoteAuxiliaryTrack||new DD(this._room,this),this.avPlayerStateSyncManager=new dE({log:this._log,audioPlayer:this.remoteAudioTrack.player,videoPlayer:this.remoteVideoTrack.player})}get videoCodec(){var t,i;let r=(i=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:i.sdp;return r?r.includes("H264")?"h264":"vp8":this._videoCodec||"h264"}set videoCodec(t){this._videoCodec=t}get subscribeState(){let t={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(8&this.remoteVideoTrack.mediaType?t.smallVideo=!0:t.video=!0),this.remoteAudioTrack.isSubscribed&&(t.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(t.auxiliary=!0),t}get muteState(){return ca(this.flag,this.userId)}get flag(){return this._flag}set flag(t){var i,r,n;t!==this._flag&&(this._flag=t,(i=this.remoteAudioTrack)==null||i.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(n=this.remoteAuxiliaryTrack)==null||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(t){return t===D.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(t){super.close(t),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.avPlayerStateSyncManager.destroy(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(t){var i,r;let n=this._currentState,s=super.emitConnectionStateChangedEvent(t);return s&&n!==t&&((i=this.remoteVideoTrack)==null||i.emit("connection-state-changed",{prevState:n,state:t}),(r=this.remoteAuxiliaryTrack)==null||r.emit("connection-state-changed",{prevState:n,state:t})),s}onTrack(t){let i=t.streams[0],{track:r}=t,n=i.id===bh?D.MAIN:D.AUXILIARY;this._log.debug("ontrack ".concat(n," ").concat(r.kind));let s=D.AUDIO;r.kind===D.VIDEO&&(s=n===D.MAIN?D.VIDEO:D.AUXILIARY);let o=this.remoteAudioTrack;s===D.VIDEO?o=this.remoteVideoTrack:s===D.AUXILIARY&&(o=this.remoteAuxiliaryTrack),o.setInputMediaStreamTrack(r)}addRRTRLine(t){let i=t.split(`\r
102
+ `),r=new Map;i.forEach((s,o)=>{/^a=rtcp-fb:/.test(s)&&i[o+1]&&!/^a=rtcp-fb:/.test(i[o+1])&&r.set(o+1,"".concat(s.match(/^a=rtcp-fb:\d+/)[0]," rrtr"))});let n=[...r];for(let s=0;s<n.length;s++){let[o,l]=n[s];i.splice(o+s,0,l)}return i.join(`\r
103
+ `)}addSPSDescription(t){let i=zt(t);return i.media.forEach(r=>{r.type===D.VIDEO&&r.fmtp.forEach(n=>{n.config+=";sps-pps-idr-in-keyframe=1"})}),Es(i)}removeSDESDescription(t){let i=["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"],r=zt(t);return r.media.forEach(n=>{n.ext&&(n.ext=n.ext.filter(s=>!i.includes(s.uri)))}),Es(r)}isSubscriptionStateNotChanged(t){return JSON.stringify(t)===JSON.stringify(this.subscribeState)}subscribe(t,i){return P(this,null,function*(){var r,n;try{if((((r=this._peerConnection)==null?void 0:r.connectionState)===Kt.NEW||((n=this._peerConnection)==null?void 0:n.connectionState)===Kt.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(t))return void(this._peerConnection||(this.initialize(),yield this.connect(t)));if(this._log.info("subscribe ".concat(i," ").concat(JSON.stringify(t))),this._peerConnection||this._isSDPExchanging){let s="subscribe_change";Object.values(t).find(o=>o===!0)||(s="unsubscribe"),yield this.sendSubscription(s,t)}else this.initialize(),yield this.connect(t)}catch(s){throw this._room.isJoined&&this.isStreamUnpublished(i)?(this._log.warn("".concat(s.message," ").concat(JSON.stringify(this.muteState))),new me({code:te.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):s}})}unsubscribe(t){return P(this,arguments,function(i){var r=this;let{remoteTracks:n,streamType:s}=i;return(function*(){if(r._currentState==="CONNECTED"&&(s==="main"&&!r.isMainStreamSubscribed||s==="auxiliary"&&!r.isAuxStreamSubscribed))return void r._log.info("".concat(s," stream already unsubscribed"));let o=ve({},r.subscribeState);n.forEach(c=>{switch(c.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1}});let l="subscribe_change";Object.values(o).find(c=>c===!0)||(l="unsubscribe"),r._log.info("".concat(l==="unsubscribe"?l:"subscribe"," ").concat(s," [").concat(wE(o),"]")),yield r.sendSubscription(l,o),l==="unsubscribe"&&(r.closePeerConnection(),r.emitConnectionStateChangedEvent("DISCONNECTED"))})()})}unsubscribeDataChannel(){return P(this,null,function*(){})}sendSubscription(t){let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscribeState,r={srcTinyId:this.tinyId,srcUserId:this.userId},n=RE,s=Ge.UNSUBSCRIBE_RESULT;return t==="subscribe_change"&&(r={audio:i.audio,bigVideo:i.video,auxVideo:i.auxiliary,smallVideo:i.smallVideo,srcTinyId:this.tinyId},n=AE,s=Ge.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:n,data:r,responseCommand:s,timeout:1e4}).then(o=>{let{data:l}=o;if(l.code!==0){let c=new me({code:l.code,message:He({key:Fe.ERROR_MESSAGE,data:{type:t,message:l.message}})});throw this._log.error(c),c}})}connect(){return P(this,arguments,function(){var t=this;let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.subscribeState;return(function*(){try{yield t.exchangeSDP(i),yield t.waitForPeerConnectionConnected()}catch(r){throw t.closePeerConnection(!0),r}})()})}exchangeSDP(t){return P(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:i,sdp:r}=this._peerConnection.localDescription,n={type:i,sdp:r,srcUserId:this.userId,srcTinyId:this.tinyId,audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo},s=yield this._signalChannel.sendWaitForResponse({command:EN,commandDesc:"exchange sdp",data:n,responseCommand:Ge.SUBSCRIBE_RESULT,timeout:l2});if(!this._peerConnection){let o=new me({code:te.INVALID_OPERATION,message:He({key:Fe.CONNECTION_CLOSED})});throw this._log.warn(o),o}yield this.onSubscribeResult(s),this._isSDPExchanging=!1}catch(i){throw this._isSDPExchanging=!1,i}})}createOffer(){return P(this,null,function*(){let t={voiceActivityDetection:!1};Rr()&&this._sdpSemantics===hc?(this._peerConnection.addTransceiver(D.AUDIO,{direction:rt.RECVONLY}),this._peerConnection.addTransceiver(D.VIDEO,{direction:rt.RECVONLY}),this._peerConnection.addTransceiver(D.VIDEO,{direction:rt.RECVONLY})):(t.offerToReceiveAudio=!0,t.offerToReceiveVideo=!0);let i=yield this._peerConnection.createOffer(t);if(i.sdp){let{isH264DecodeSupported:r}=yield mv();r||(this._log.warn("remove h264 desc from sdp"),i.sdp=(function(n){let s=zt(n);return s.media.forEach(o=>{var l,c;if(o.type===D.VIDEO){let h=new Set;o.rtp.forEach(f=>{let{payload:T,codec:b}=f;return b==="H264"&&h.add(T)}),o.fmtp.forEach(f=>{let{payload:T,config:b}=f,C=b.match(/apt=(\d+)/);C&&C[1]&&h.has(Number(C[1]))&&h.add(T)});let _=f=>{let{payload:T}=f;return!h.has(T)};o.rtp=o.rtp.filter(_),o.rtcpFb=(l=o.rtcpFb)==null?void 0:l.filter(_),o.fmtp=o.fmtp.filter(_),o.payloads=(c=o.payloads)==null?void 0:c.split(" ").filter(f=>!h.has(Number(f))).join(" ")}}),Es(s)})(i.sdp)),i.sdp=this.addRRTRLine(i.sdp),i.sdp=this.addSPSDescription(i.sdp),i.sdp=(function(n){let s=zt(n);return s.media.forEach(o=>{o.type===D.AUDIO&&o.fmtp.forEach(l=>{l.config+=";sprop-stereo=1;stereo=1"})}),Es(s)})(i.sdp),this._sdpSemantics===hc&&(i.sdp=this.removeSDESDescription(i.sdp))}yield this.setOffer(i)})}onSubscribeResult(t){return P(this,null,function*(){let{code:i,message:r=""}=t&&t.data||{},{type:n,sdp:s}=t&&t.data&&t.data.data||{};if(i===kh)throw new me({code:te.NOT_SUPPORTED_H264,message:He({key:Fe.NOT_SUPPORTED_H264DECODE})});try{if(i!==0)throw new me({code:i,message:He({key:Fe.EXCHANGE_SDP_FAILED,data:{errMsg:r}})});this._log.debug("accept remote answer: ".concat(s)),yield this.setAnswer({type:n,sdp:s}),this.updateSSRC(s)}catch(o){throw this._log.error(o),o}})}updateSSRC(t){try{zt(t).media.forEach(i=>{if(i.ssrcs)if(i.type===D.AUDIO){let r=i.ssrcs.find(n=>{var s;return(s=n.value)==null?void 0:s.includes(bh)});r&&(this.ssrc.audio=Number(r.id))}else{let r=i.ssrcs.find(s=>{var o;return(o=s.value)==null?void 0:o.includes(bh)}),n=i.ssrcs.find(s=>{var o;return(o=s.value)==null?void 0:o.includes(i2)});r&&(this.ssrc.video=Number(r.id)),n&&(this.ssrc.auxiliary=Number(n.id))}})}catch{}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return P(this,null,function*(){if(!(xi(oP.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch{let i=la(this._reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(i/1e3,"s")),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},i)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay(t){let{audioDelay:i,videoDelay:r}=t;this.remoteAudioTrack.stat.end2EndDelay=i,this.remoteVideoTrack.stat.end2EndDelay=r}get audioReceiver(){var t;return((t=this._peerConnection)==null?void 0:t.getReceivers()[0])||null}};_e([_t(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return new Promise((n,s)=>{let o=l=>{this._emitter.off("closed",o),s(new me({code:te.API_CALL_ABORTED,message:He({key:Fe.CONNECTION_ABORTED,data:l})}))};this._emitter.on("closed",o),e.apply(this,i).then(n,s).finally(()=>{this._emitter.off("closed",o)})})})],Jp.prototype,"subscribe"),_e([ms(521717,!1)],Jp.prototype,"unsubscribe"),_e([Ta(bn.prototype.afterConnect),Xw(bn.prototype.beforeConnect)],Jp.prototype,"connect");var AN=Jp,bN={voiceActivityDetection:!1},Yp=class lP extends bn{constructor(t){super(xe(ve({},t),{isUplink:!0})),m(this,"localMainAudioTrack",null),m(this,"localMainVideoTrack",null),m(this,"localAuxAudioTrack",null),m(this,"localAuxVideoTrack",null),m(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),m(this,"_isPublishingAux",!1),m(this,"_publishingLocalAudioTrack"),m(this,"_publishingLocalVideoTrack"),m(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}),m(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(t){super.close(t),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(t,i){var r,n,s;let o=this._currentState,l=super.emitConnectionStateChangedEvent(t);return l&&o!==t&&(i?i.emit("connection-state-changed",{prevState:o,state:t}):((r=this.localMainVideoTrack)==null||r.emit("connection-state-changed",{prevState:o,state:t}),(n=this.localAuxVideoTrack)==null||n.emit("connection-state-changed",{prevState:o,state:t}),(s=this._publishingLocalVideoTrack)==null||s.emit("connection-state-changed",{prevState:o,state:t}))),l}publish(t){return P(this,arguments,function(i){var r=this;let{localAudioTrack:n,localVideoTrack:s,isAuxiliary:o}=i;return(function*(){let l;r._peerConnection||r.initialize(),n&&(r._publishingLocalAudioTrack=n),s&&(r._publishingLocalVideoTrack=s),r._isPublishingAux=o,s&&!o&&s.small&&(l=r._room.videoManager.smallTrack),r.sendMediaSettings(),Rr()?yield r.publishByTransceiver({localAudioTrack:n,localVideoTrack:s,smallTrack:l,isAuxiliary:o}):yield r.publishByAddTrack({localAudioTrack:n,localVideoTrack:s,smallTrack:l}),r._publishingLocalAudioTrack=null,r._publishingLocalVideoTrack=null,r._isPublishingAux=!1,o?(s&&(r.localAuxVideoTrack=s),n&&(r.localAuxAudioTrack=n)):(s&&(r.localMainVideoTrack=s),n&&(r.localMainAudioTrack=n)),r.installTrackMuteEvents(n,s),r.sendMutedFlag()})()})}publishByTransceiver(t){return P(this,arguments,function(i){var r=this;let{localAudioTrack:n,localVideoTrack:s,smallTrack:o,isAuxiliary:l}=i;return(function*(){r._log.info("publish by transceiver");let c=new MediaStream,h=s?.outMediaTrack,_=n?.outMediaTrack;_&&c.addTrack(_),h&&c.addTrack(h);let f=r._peerConnection.getTransceivers();if(f.length===0)r._peerConnection.addTransceiver(_||D.AUDIO,{direction:rt.SENDONLY,streams:[c]}),r._peerConnection.addTransceiver(l?D.VIDEO:h||D.VIDEO,{direction:rt.SENDONLY,streams:[c]}),r._peerConnection.addTransceiver(o||D.VIDEO,{direction:rt.SENDONLY,streams:[c]}),r._peerConnection.addTransceiver(l&&h||D.VIDEO,{direction:rt.SENDONLY,streams:[c]}),yield r.connect();else{let T=[];if(_&&(f[0].sender.track||T.push(0),yield f[0].sender.replaceTrack(_),yield r.setBandwidth({bandwidth:n?.profile.bitrate||40,type:D.AUDIO})),h){let b=l?3:1;yield f[b].sender.replaceTrack(h),yield r.setBandwidth({bandwidth:s.profile.bitrate,type:D.VIDEO,videoType:l?D.AUXILIARY:D.BIG}),T.push(b),o&&(yield f[2].sender.replaceTrack(o),yield r.setBandwidth({bandwidth:s.small.bitrate,type:D.VIDEO,videoType:D.SMALL}),T.push(2))}yield r.setTransceiverDirection(rt.SENDONLY,T),yield r.doPublishChange(),s?.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),s?.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})()})}publishByAddTrack(t){return P(this,arguments,function(i){var r=this;let{localAudioTrack:n,localVideoTrack:s,smallTrack:o}=i;return(function*(){r._log.info("publish by addtrack");let l=s?.outMediaTrack,c=n?.outMediaTrack;if(r._peerConnection&&r._peerConnection.connectionState!=="new")return n&&c&&(yield r.addTrack(n)),void(l&&(yield r.addTrack(s)));let h=new MediaStream;if(c&&h.addTrack(c),l&&h.addTrack(l),c&&r._peerConnection.addTrack(c,h),l&&(r._peerConnection.addTrack(l,h),o)){let _=new MediaStream;_.addTrack(o),r._peerConnection.addTrack(o,_)}yield r.connect()})()})}enableSmall(t){return P(this,null,function*(){let i=this._peerConnection.getTransceivers();t?this._room.videoManager.smallTrack&&(yield i[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(rt.SENDONLY,[2])):(yield i[2].sender.replaceTrack(null),yield this.setTransceiverDirection(rt.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];i.forEach(n=>{n&&(n?.on("mute",this.sendMutedFlag,this),n?.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];i.forEach(n=>{n&&(n?.off("mute",this.sendMutedFlag,this),n?.off("unmute",this.sendMutedFlag,this))})}unpublish(t){return P(this,arguments,function(i){var r=this;let{localAudioTrack:n,localVideoTrack:s}=i;return(function*(){if(!Vo())return n&&n.outMediaTrack&&!s&&r.localMainVideoTrack?(yield r.removeTrack(n),void(r.localMainAudioTrack=null)):s&&s.outMediaTrack&&!n&&r.localMainAudioTrack?(yield r.removeTrack(s),void(r.localMainVideoTrack=null)):(yield r.doUnpublish(),r.uninstallTrackMuteEvents(n,s),void r.emitConnectionStateChangedEvent("DISCONNECTED",s));let o=s&&s===r.localAuxVideoTrack,l=s?.outMediaTrack,c=r._peerConnection.getSenders(),h=[];n&&(o?r.localAuxAudioTrack=null:r.localMainAudioTrack=null,!r.localAuxAudioTrack&&!r.localMainAudioTrack&&(yield c[0].replaceTrack(null),h.push(0))),l&&(o?(yield c[3].replaceTrack(null),r.localAuxVideoTrack=null,r._mediaSettings=xe(ve({},r._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),h.push(3)):(yield c[1].replaceTrack(null),yield c[2].replaceTrack(null),r.localMainVideoTrack=null,r._mediaSettings=xe(ve({},r._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),h.push(1,2))),r.isMainStreamPublished||r.isAuxStreamPublished?(yield r.setTransceiverDirection(rt.INACTIVE,h),yield r.doPublishChange(!1)):yield r.doUnpublish(),r.uninstallTrackMuteEvents(n,s),s?.emit("connection-state-changed",{prevState:r._currentState,state:"DISCONNECTED"})})()})}doPublishChange(){let t=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return P(this,null,function*(){let i={state:this._room.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponse({command:IE,data:i,responseCommand:Ge.PUBLISH_STATE_CHANGE_RESULT,enableLog:t});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this._signalChannel.sendWaitForResponse({command:jp,commandDesc:"unpublish",responseCommand:Ge.UNPUBLISH_RESULT,enableLog:t}).catch(i=>{if(i.getCode()===te.API_CALL_TIMEOUT)return Promise.resolve();throw i})}updateMediaSettings(){let{detail:{isH264EncodeSupported:t,isVp8EncodeSupported:i}}=this._room.checkSystemResult;t?this._mediaSettings.videoCodec="H264":i&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:n,localAuxVideoTrack:s}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?s=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),Fo){if(r&&r.outMediaTrack){let o=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=o.channelCount||1,this._mediaSettings.audioBps=1e3*r.profile.bitrate,this._mediaSettings.audioFs=o.sampleRate||0}if(n&&n.outMediaTrack){let o=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=o.width||0,this._mediaSettings.videoHeight=o.height||0,this._mediaSettings.videoFps=o.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(s&&s.outMediaTrack){let o=s.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=o.width||0,this._mediaSettings.auxVideoHeight=o.height||0,this._mediaSettings.auxVideoFps=o.frameRate||0,this._mediaSettings.auxVideoBps=1e3*s.profile.bitrate}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=1e3*r.profile.bitrate,this._mediaSettings.audioFs=r.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:bE,data:this._mediaSettings,responseCommand:Ge.UPDATE_CONSTRAINT_CONFIG_RES}).then(t=>{t.data.code!==0&&this._log.warn(t.data.message)}).catch(()=>{})}addTrack(t){return P(this,null,function*(){if(!this._peerConnection)return;let i=t===this.localAuxAudioTrack||t===this.localAuxVideoTrack;this._log.info("is adding ".concat(t.kind," track to current published local ").concat(i?D.AUXILIARY:D.MAIN," stream")),Rr()?yield this.addTrackByTransceiver(t,i):yield this.addTrackBySender(t)})}addTrackByTransceiver(t,i){return P(this,null,function*(){var r;if(!t.mediaTrack)return;let n=this._peerConnection.getTransceivers();if(t.kind===D.AUDIO)yield n[0].sender.replaceTrack(t.outMediaTrack);else{let s=i?3:1;yield n[s].sender.replaceTrack(t.outMediaTrack),s===1&&(r=this.localMainVideoTrack)!=null&&r.small&&(yield n[2].sender.replaceTrack(this._room.videoManager.smallTrack)),n[s].direction===rt.INACTIVE&&(yield this.setTransceiverDirection(rt.SENDONLY,[s]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(t){return P(this,null,function*(){if(!t.outMediaTrack)return;let i=t.outMediaTrack;Vo()&&this._peerConnection.getTransceivers().findIndex(n=>n.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",i));let r=this._peerConnection.getSenders().find(n=>n.track&&n.track.kind===i.kind);if(r&&r.track){this._log.warn("sender already exists, remove sender first");let n=r.track;this.removeSender(r),yield this.updateOffer("remove",n)}if(i&&this._peerConnection.addTrack(i,new MediaStream([i])),i.kind===D.VIDEO&&t instanceof Rn&&t.small){let n=new MediaStream,{smallTrack:s}=this._room.videoManager;n.addTrack(s),this._peerConnection.addTrack(s,n)}yield this.updateOffer("add",i)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===Ch||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:t}=this._peerConnection.localDescription,i=zt(t);for(let r=0;r<i.media.length;r++)if(Number(i.media[r].mid)===0&&i.media[r].type===D.VIDEO)return!0;return!1}removeSender(t){let i=null;Vo()&&(i=this._peerConnection.getTransceivers().find(r=>r.sender&&r.sender.track===t.track)),this._peerConnection.removeTrack(t),i&&Ut(i.stop)&&(this._log.info("stop transceiver"),i.stop())}removeTrack(t){return P(this,null,function*(){if(!this._peerConnection)return;let i=t===this.localAuxAudioTrack||t===this.localAuxVideoTrack;this._log.info("is removing ".concat(t.kind," track from current published local ").concat(i?D.AUXILIARY:D.MAIN," stream")),Rr()?yield this.removeTrackByTransceiver(t,i):yield this.removeTrackBySender(t)})}removeTrackByTransceiver(t,i){return P(this,null,function*(){if(!t.outMediaTrack)return;let r=this._peerConnection.getTransceivers();if(t.kind===D.AUDIO)yield r[0].sender.replaceTrack(null);else{let n=i?3:1;yield r[n].sender.replaceTrack(null),n===1&&t.small&&(yield r[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(rt.INACTIVE,[n])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(t,i){return P(this,null,function*(){if(!ut)return;let r=!1,n=!1;this._log.info("setting transceiver ".concat(i.join(",")," direction to ").concat(t));let s=this._peerConnection.getTransceivers();if(i.forEach(c=>{s[c].direction!==t&&(s[c].direction=t,r=!0)}),r){this._log.info("updating offer");let c=yield this._peerConnection.createOffer();yield this.setOffer(c)}let o=-1,l=this._peerConnection.remoteDescription.sdp.split(`\r
104
+ `).map(c=>{if(c.match(new RegExp("a=(".concat(rt.INACTIVE,"|").concat(rt.RECVONLY,"|").concat(rt.SENDONLY,")")))&&o++,i.includes(o)){if(t===rt.INACTIVE&&c.includes("a=".concat(rt.RECVONLY)))return n=!0,"a=".concat(t);if(t===rt.SENDONLY&&c.includes("a=".concat(rt.INACTIVE)))return n=!0,"a=".concat(rt.RECVONLY)}return c}).join(`\r
105
+ `);n&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:l}))})}removeTrackBySender(t){return P(this,null,function*(){if(!t.outMediaTrack)return;if(t.kind===D.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack)return this.reset(),this.initialize(),void(yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1}));let i=this._peerConnection.getSenders().find(r=>r.track===t.outMediaTrack);i&&(this.removeSender(i),t.kind===D.VIDEO&&t.small&&this._peerConnection.getSenders().forEach(r=>{r.track&&r.track.kind===D.VIDEO&&this.removeSender(r)})),yield this.updateOffer("remove",t.outMediaTrack)})}replaceTrack(t){return P(this,null,function*(){var i;let r,n=(i=this._peerConnection)==null?void 0:i.getSenders();if(!n||n.length===0||!t.mediaTrack||(r=Rr()?t.kind===D.AUDIO?n[0]:n[1]:n.find(o=>o.track&&o.track.kind===t.kind),!r))return!1;let s=t===this.localAuxAudioTrack||t===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(t.kind," track on ").concat(s?D.AUXILIARY:D.MAIN," stream")),t.kind===D.AUDIO?yield r.replaceTrack(t.outMediaTrack):t.kind===D.VIDEO&&(s?n[3]&&(yield n[3].replaceTrack(t.outMediaTrack)):yield r.replaceTrack(t.outMediaTrack)),!0})}updateOffer(t,i){return P(this,null,function*(){try{let r=yield this._peerConnection.createOffer(bN);ut&&r.sdp&&(r.sdp=this.setSDPDirection(r.sdp,"sendrecv")),yield this.setOffer(r);let n=this.updateMediaSettings(),s={action:t,trackId:i.id,kind:i.kind===D.VIDEO?"bigVideo":i.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:n,state:this._room.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug("updatedOffer: ".concat(s.sdp));let o=yield this._signalChannel.sendWaitForResponse({command:_N,data:s,responseCommand:Ge.UPDATE_OFFER_RESULT,timeout:o2,commandDesc:"update offer"}),{code:l,message:c}=o.data;l!==0&&this.checkPublishResultCode(l,c),yield this.acceptAnswer(o.data.data),r.sdp&&this.updateSSRC(r.sdp)}catch(r){throw this._log.error(r),r}})}setBandwidth(t){return P(this,arguments,function(i){var r=this;let{bandwidth:n,type:s,videoType:o,sdp:l}=i;return(function*(){if(!yv())return l?s===D.VIDEO?r.updateVideoBandwidthRestriction(l,n,o):r.updateAudioBandwidthRestriction(l,n):void 0;let c,h=r._peerConnection.getSenders();if(Rr()){let _=0;s===D.VIDEO&&(_=o===D.SMALL?2:o===D.AUXILIARY?3:1),c=h[_]}else c=h.find(_=>_.track&&_.track.kind===s);if(c){let _=c.getParameters();(!_.encodings||_.encodings.length===0)&&(_.encodings=[{}]),_.encodings[0].maxBitrate=1e3*n;try{return yield c.setParameters(_),r._log.info("".concat(o||"").concat(s," bandwidth ").concat(n," kbps")),l}catch(f){if(r._log.info("failed to set bandwidth by setting maxBitrate: ".concat(f)),l)return s===D.VIDEO?r.updateVideoBandwidthRestriction(l,n,o):r.updateAudioBandwidthRestriction(l,n)}}return l})()})}updateVideoBandwidthRestriction(t,i,r){let n="AS";ut&&(n="TIAS",i*=1e3);let s=0,o=-1;return r===D.SMALL?s=1:r===D.AUXILIARY&&(s=2),t=t.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,l=>(o+=1,o===s?"".concat(l,"b=").concat(n,":").concat(i,`\r
106
+ `):l)),t}updateAudioBandwidthRestriction(t,i){let r="AS";return ut&&(r="TIAS",i*=1e3),t=t.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
107
+ c=IN $2\r
108
+ b=`.concat(r,":").concat(i,`\r
109
+ `))}removeBandwidthRestriction(t){return t.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(t){return t.replace(/urn:3gpp:video-orientation/,"")}connect(){return P(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),this.uninstallEvents(),t}})}exchangeSDP(){return P(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(t){throw t}})}createOffer(){return P(this,null,function*(){try{let t=yield this._peerConnection.createOffer(bN);yield this.setOffer(t),t.sdp&&this.updateSSRC(t.sdp)}catch(t){throw t}})}doExchangeSDP(){let t={command:vN,responseCommand:Ge.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof Ra||this.localAuxVideoTrack instanceof Ra,state:this._room.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug("sending sdp offer: ".concat(t.data.sdp)),this._signalChannel.sendWaitForResponse(t).then(i=>{let{code:r,message:n,data:s}=i.data;return r===0?this.acceptAnswer(s):this.checkPublishResultCode(r,n)})}setSDPDirection(t,i){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"all",n=zt(t);return n.media.forEach(s=>{(r==="all"||s.type===r)&&(s.direction=i)}),Es(n)}acceptAnswer(t){return P(this,null,function*(){var i,r,n,s,o;try{let l;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let h=((i=this._publishingLocalVideoTrack)==null?void 0:i.profile.bitrate)||((r=this.localMainVideoTrack)==null?void 0:r.profile.bitrate),_=((n=this._publishingLocalAudioTrack)==null?void 0:n.profile.bitrate)||((s=this.localMainAudioTrack)==null?void 0:s.profile.bitrate);if(h){let f=this._isPublishingAux?D.AUXILIARY:D.BIG;l=yield this.setBandwidth({bandwidth:h,type:D.VIDEO,sdp:l,videoType:f})}_&&(l=yield this.setBandwidth({bandwidth:_,type:D.AUDIO,sdp:l}))}if(l=this.removeVideoOrientation(t.sdp),(o=this._publishingLocalVideoTrack)!=null&&o.small){let{smallStreamConfig:h}=this._room;l=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||h.bitrate,type:D.VIDEO,videoType:D.SMALL,sdp:l})}let c={type:t.type,sdp:l};yield this.setAnswer(c),this._log.debug("accepted answer: ".concat(l))}catch(l){throw this._log.error("failed to accept remote answer ".concat(l)),l}})}sendMutedFlag(t){t===this.localAuxAudioTrack||t===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this._room.muteState))),this._signalChannel.send(gN,this._room.muteState))}getIsReconnecting(){return this._isReconnecting}reconnect(){return P(this,null,function*(){if(!(xi(lP.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:jp,responseCommand:Ge.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{let i=la(this._reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(i/1e3,"s")),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},i)}})}handleConnectionStateChange(t){t.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&$.emit(ie.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(t){try{zt(t).media.forEach((i,r)=>{if(i.type===D.AUDIO){let n=i.ssrcs&&i.ssrcs[0];n&&(this.ssrc.audio=Number(n.id))}else{if(this._sdpSemantics===Ch&&i.ssrcGroups)return void i.ssrcGroups.forEach((s,o)=>{let l=Number(s.ssrcs.split(" ")[0]);o===0?this.ssrc.video=l:o===1&&(this.ssrc.small=l)});let n=i.ssrcs&&i.ssrcs[0];if(!n)return;switch(r){case 1:this.ssrc.video=Number(n.id);break;case 2:this.ssrc.small=Number(n.id);break;case 3:this.ssrc.auxiliary=Number(n.id)}}})}catch{}}getVideoTrackId(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:D.VIDEO;if(this._peerConnection){let i=this._peerConnection.getSenders();if(t===D.AUXILIARY&&i[3]&&i[3].track)return i[3].track.id;if(t===D.VIDEO&&i[1]&&i[1].track)return i[1].track.id}if(this.localMainVideoTrack&&t===D.VIDEO){let i=this.localMainVideoTrack.mediaTrack;if(i)return i.id}if(this.localAuxVideoTrack&&t===D.AUXILIARY){let i=this.localAuxVideoTrack.mediaTrack;if(i)return i.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(t,i){if(t!==0)throw t===kh?(this._log.error(Ir.NOT_SUPPORTED_H264ENCODE),new me({code:te.NOT_SUPPORTED_H264,message:He({key:Fe.NOT_SUPPORTED_H264ENCODE})})):new me({code:te.UNKNOWN,message:He({key:Fe.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Ge.PUBLISH_RESULT,code:t,message:i}})})}};_e([_t(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return new Promise((n,s)=>{let o=l=>{this._emitter.off("closed",o),s(new me({code:te.API_CALL_ABORTED,message:He({key:Fe.CONNECTION_ABORTED,data:l})}))};this._emitter.on("closed",o),e.apply(this,i).then(n,s).finally(()=>{this._emitter.off("closed",o)})})})],Yp.prototype,"publish"),_e([ms(521715,!1)],Yp.prototype,"unpublish"),_e([Ta(bn.prototype.afterConnect),Xw(bn.prototype.beforeConnect)],Yp.prototype,"connect");var qp=Yp,Kj=class{constructor(e,t){this.room=e,m(this,"_log"),m(this,"_prevReportTime",0),m(this,"_prevReport",{}),m(this,"_prevStats",null),m(this,"_prevEncoderImplementation",""),m(this,"_prevAuxEncoderImpl",""),m(this,"_prevQualityLimitationReason",""),m(this,"_prevAuxQualityLimitationReason",""),m(this,"_prevDecoderImplementationMap",new Map),m(this,"_decodeMap",new Map),m(this,"_prevQpSum",0),m(this,"_prevAuxQpSum",0),m(this,"totalBytesSent",0),m(this,"totalBytesReceived",0),m(this,"_spcStats",null),this._log=t}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e){return P(this,null,function*(){var t,i,r,n,s,o,l;let c={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},h=e.getPeerConnection(),_=e.getSSRC();if(h)try{if((this._spcStats||(yield h.getStats())).forEach(f=>{var T,b,C,x,B,Y,G,he,H,Z,de,pe,Pe;let be,je;if(f.type==="outbound-rtp")if((f.mediaType||f.kind)===D.VIDEO){if(f.ssrc===_.video?(be=D.VIDEO,je=e.localMainVideoTrack):f.ssrc===_.small?be=D.SMALL:f.ssrc===_.auxiliary&&(je=e.localAuxVideoTrack,be=D.AUXILIARY),!be)return;c[be].bytesSent=f.bytesSent,c[be].packetsSent=f.packetsSent,c[be].framesEncoded=f.framesEncoded,j(f.keyFramesEncoded)||(c[be].keyFramesEncoded=f.keyFramesEncoded),j(f.nackCount)||(c[be].nackCount=f.nackCount),j(f.pliCount)||(c[be].pliCount=f.pliCount),j(f.retransmittedPacketsSent)||(c[be].retransmittedPacketsSent=f.retransmittedPacketsSent),j(f.totalEncodeTime)||(c[be].totalEncodeTime=f.totalEncodeTime),j(f.totalPacketSendDelay)||(c[be].totalPacketSendDelay=f.totalPacketSendDelay);let Oe=0;if(!j(f.qpSum)&&!j(f.framesEncoded)&&f.framesEncoded>0){let Be=f.qpSum,at=f.framesEncoded,yt=be===D.VIDEO?this._prevQpSum:this._prevAuxQpSum,gt=be===D.VIDEO?((b=(T=e.localMainVideoTrack)==null?void 0:T.stat)==null?void 0:b.framesEncoded)||0:((x=(C=e.localAuxVideoTrack)==null?void 0:C.stat)==null?void 0:x.framesEncoded)||0;if(at>gt&&Be>yt){let Ma=Be-yt,Vi=at-gt;Oe=Math.round(Ma/Vi),Oe>35&&this._log.warn("".concat(be===D.AUXILIARY?"aux ":"","video encoder QP is high: ").concat(Oe,", resolution: ").concat(f.frameWidth,"x").concat(f.frameHeight,", codec: ").concat(e.videoCodec,", "))}be===D.VIDEO?this._prevQpSum=Be:be===D.AUXILIARY&&(this._prevAuxQpSum=Be)}if(!j(f.encoderImplementation)&&(be===D.VIDEO&&this._prevEncoderImplementation!==f.encoderImplementation||be===D.AUXILIARY&&this._prevAuxEncoderImpl!==f.encoderImplementation)){let Be=2,at=this._prevEncoderImplementation;be===D.AUXILIARY&&(Be=7,at=this._prevAuxEncoderImpl),$.emit("262",{userId:e.userId,streamType:Be,prevImplementation:at,implementation:f.encoderImplementation,codec:e.videoCodec,isHWCodec:f.powerEfficientEncoder}),this[be===D.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=f.encoderImplementation,je?.log.info("encoderImplementation change to ".concat(f.encoderImplementation,"(").concat(e.videoCodec,") HWEncoder: ").concat(f.powerEfficientEncoder))}f.ssrc===_.video?!j(f.qualityLimitationReason)&&f.bytesSent!==0&&this._prevQualityLimitationReason!==f.qualityLimitationReason&&(je?.log.info("qualityLimitationReason change to ".concat(f.qualityLimitationReason)),$.emit("263",{userId:e.userId,reason:f.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(B=e.localMainVideoTrack)==null?void 0:B.isQosClearFirst}),this._prevQualityLimitationReason=f.qualityLimitationReason):f.ssrc===_.auxiliary&&!j(f.qualityLimitationReason)&&f.bytesSent!==0&&this._prevAuxQualityLimitationReason!==f.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(f.qualityLimitationReason)),$.emit("263",{userId:e.userId,reason:f.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(Y=e.localAuxVideoTrack)==null?void 0:Y.isQosClearFirst}),this._prevAuxQualityLimitationReason=f.qualityLimitationReason)}else c.audio.bytesSent=f.bytesSent,c.audio.packetsSent=f.packetsSent;else if(f.type==="candidate-pair")Hc(f)&&(this.totalBytesSent=f.bytesSent,nt(f.currentRoundTripTime)&&(c.rtt=Math.floor(1e3*f.currentRoundTripTime)));else if(f.type==="media-source"){if(f.kind===D.AUDIO)c.audio.audioLevel=f.audioLevel||0,c.audio.totalAudioEnergy=f.totalAudioEnergy||0,f.echoReturnLoss,j((H=(he=(G=e.localMainAudioTrack)==null?void 0:G.sourceTrack)==null?void 0:he.stats)==null?void 0:H.deliveredFramesDuration)?f.totalSamplesDuration&&(c.audio.totalSamplesDuration=f.totalSamplesDuration):c.audio.totalSamplesDuration=e.localMainAudioTrack.sourceTrack.stats.deliveredFramesDuration/1e3;else if(f.kind===D.VIDEO)if(f.trackIdentifier===e.getVideoTrackId(D.VIDEO))if((pe=(de=(Z=e.localMainVideoTrack)==null?void 0:Z.sourceTrack)==null?void 0:de.stats)!=null&&pe.deliveredFrames){let{deliveredFrames:Oe}=e.localMainVideoTrack.sourceTrack.stats;c.video.framesCaptured=Oe,e.localMainVideoTrack.stat.framesCaptured&&e.localMainVideoTrack.stat.framesCaptured>0&&Oe>=e.localMainVideoTrack.stat.framesCaptured?c.video.fpsCapture=Math.floor((Oe-e.localMainVideoTrack.stat.framesCaptured)/this.statInterval):c.video.fpsCapture=f.framesPerSecond}else c.video.fpsCapture=f.framesPerSecond;else f.trackIdentifier===e.getVideoTrackId(D.AUXILIARY)?c.auxiliary.fpsCapture=f.framesPerSecond:c.small.fpsCapture=f.framesPerSecond}if(!j(f.audioLevel)&&(Pe=e.localMainAudioTrack)!=null&&Pe.mediaTrack&&f.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(c.audio.audioLevel=f.audioLevel||0),!j(f.frameWidth)){let Oe=D.SMALL;f.trackIdentifier===e.getVideoTrackId(D.VIDEO)||f.ssrc===_.video?Oe=D.VIDEO:(f.trackIdentifier===e.getVideoTrackId(D.AUXILIARY)||f.ssrc===_.auxiliary)&&(Oe=D.AUXILIARY),c[Oe].frameWidth=f.frameWidth,c[Oe].frameHeight=f.frameHeight,c[Oe].framesSent=f.framesSent}}),e.localMainAudioTrack||e.getRoom().capturedLocalMainAudioTrack){let f=e.localMainAudioTrack||e.getRoom().capturedLocalMainAudioTrack;if(f){let T=f.getInternalAudioLevel(),b=f.getInternalAudioLevelAfter3A();c.audio.audioCaptureEnergyAfter3a=b,c.audio.micAudioLevel=T,c.audio.audioLevel===0&&e.localMainAudioTrack&&(c.audio.audioLevel=b??T),!e.localMainAudioTrack&&!j((i=(t=f.sourceTrack)==null?void 0:t.stats)==null?void 0:i.deliveredFramesDuration)&&(c.audio.totalSamplesDuration=f.sourceTrack.stats.deliveredFramesDuration/1e3)}}if(!e.localMainVideoTrack&&e.getRoom().capturedLocalMainVideoTrack){let f=e.getRoom().capturedLocalMainVideoTrack;if((n=(r=f?.sourceTrack)==null?void 0:r.stats)!=null&&n.deliveredFrames){let{deliveredFrames:T}=f.sourceTrack.stats;c.video.framesCaptured=T,f.stat.framesCaptured&&f.stat.framesCaptured>0&&T>=f.stat.framesCaptured&&(c.video.fpsCapture=Math.floor((T-f.stat.framesCaptured)/this.statInterval)),f.stat.framesCaptured=T}}if(!e.localAuxVideoTrack&&e.getRoom().capturedLocalAuxVideoTrack){let f=e.getRoom().capturedLocalAuxVideoTrack;if((o=(s=f?.sourceTrack)==null?void 0:s.stats)!=null&&o.deliveredFrames){let{deliveredFrames:T}=f.sourceTrack.stats;c.auxiliary.framesCaptured=T,f.stat.framesCaptured&&f.stat.framesCaptured>0&&T>=f.stat.framesCaptured&&(c.auxiliary.fpsCapture=Math.floor((T-f.stat.framesCaptured)/this.statInterval)),f.stat.framesCaptured=T}}this.totalBytesSent||(this.totalBytesSent+=c.audio.bytesSent+c.video.bytesSent+c.auxiliary.bytesSent),Object.keys(c).forEach(f=>{f===D.AUDIO?(e.localMainAudioTrack&&(e.localMainAudioTrack.stat=c[f]),e.localAuxAudioTrack&&(e.localAuxAudioTrack.stat=c[f])):f===D.VIDEO?e.localMainVideoTrack&&(e.localMainVideoTrack.stat=c[f]):f===D.AUXILIARY&&e.localAuxVideoTrack&&(e.localAuxVideoTrack.stat=c[f])})}catch(f){this._log.warn("failed to getStats on sender connection ".concat(f))}return c.rtt===0&&(c.rtt=((l=this.room.networkQuality)==null?void 0:l.uplinkRTT)||0),c})}getReceiverStats(e){return P(this,null,function*(){var t,i,r;let n={tinyId:e.tinyId,userId:e.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,avSyncDelay:0,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""}},s=e.getPeerConnection();if(s)try{let{ssrc:o}=e,{muteState:l,subscribeState:c}=e;(this._spcStats||(yield s.getStats())).forEach(f=>{var T,b;if(f.type==="codec"&&this._decodeMap.set(f.id,f),f.type==="inbound-rtp"){let C=(f.mediaType||f.kind)===D.AUDIO;if(C){if(f.ssrc!==o.audio||!l.hasAudio)return;n.audio.packetsReceived=f.packetsReceived,n.audio.bytesReceived=f.bytesReceived,n.audio.packetsLost=f.packetsLost,f.insertedSamplesForDeceleration&&(n.audio.insertedSamplesForDeceleration=f.insertedSamplesForDeceleration),f.removedSamplesForAcceleration&&(n.audio.removedSamplesForAcceleration=f.removedSamplesForAcceleration),f.totalSamplesDuration&&(n.audio.totalSamplesDuration=f.totalSamplesDuration),f.totalSamplesReceived&&(n.audio.totalSamplesReceived=f.totalSamplesReceived),f.concealedSamples&&(n.audio.concealedSamples=f.concealedSamples),f.silentConcealedSamples&&(n.audio.silentConcealedSamples=f.silentConcealedSamples);let{remoteAudioTrack:x}=e;x.stat.packetsReceived=f.packetsReceived,x.stat.bytesReceived=f.bytesReceived,x.stat.packetsLost=f.packetsLost,n.audio.p2pDelay=x.stat.end2EndDelay,n.hasAudio=!0}else{if(ut&&f.bytesReceived===0)return;let x;f.ssrc===o.video&&l.hasVideo&&(n.video.packetsReceived=f.packetsReceived,n.video.bytesReceived=f.bytesReceived,n.video.packetsLost=f.packetsLost,n.video.framesReceived=f.framesReceived,n.video.framesDecoded=f.framesDecoded,n.video.fpsDecoded=f.framesPerSecond,n.hasVideo=!0,e.videoCodec=lv[(T=this._decodeMap.get(f.codecId))==null?void 0:T.mimeType.split("/")[1]]||"h264",n.video.codec=e.videoCodec,x=e.remoteVideoTrack,l.hasSmall&&c.smallVideo&&(n.isSmallSubscribed=!0),f.decoderImplementation&&(!this._prevDecoderImplementationMap.has(n.userId)||this._prevDecoderImplementationMap.get(n.userId)!==f.decoderImplementation)&&(x.log.info("decoderImplementation change to ".concat(f.decoderImplementation,"(").concat(e.videoCodec,") HWDecoder: ").concat(f.powerEfficientDecoder)),$.emit("262",{userId:this.room.userId,remoteUserId:n.userId,prevImplementation:this._prevDecoderImplementationMap.get(n.userId),implementation:f.decoderImplementation,codec:e.videoCodec,isHWCodec:f.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(n.userId,f.decoderImplementation)),j(f.keyFramesDecoded)||x.updateKeyFramesDecoded(f.keyFramesDecoded)),f.ssrc===o.auxiliary&&l.hasAuxiliary&&(n.auxiliary.packetsReceived=f.packetsReceived,n.auxiliary.bytesReceived=f.bytesReceived,n.auxiliary.packetsLost=f.packetsLost,n.auxiliary.framesReceived=f.framesReceived,n.auxiliary.framesDecoded=f.framesDecoded,n.auxiliary.fpsDecoded=f.framesPerSecond,x=e.remoteAuxiliaryTrack,n.auxiliary.p2pDelay=x.stat.end2EndDelay,n.hasAuxiliary=!0,n.video.codec=((b=this._decodeMap.get(f.codecId))==null?void 0:b.mimeType.split("/")[1].toLowerCase())||"h264",j(f.keyFramesDecoded)||x.updateKeyFramesDecoded(f.keyFramesDecoded)),x&&(x.stat.packetsReceived=f.packetsReceived,x.stat.bytesReceived=f.bytesReceived,x.stat.packetsLost=f.packetsLost,x.stat.framesReceived=f.framesReceived,x.stat.framesDecoded=f.framesDecoded,f.jitterBufferDelay&&(x.stat.jitterBufferDelay=Math.floor(f.jitterBufferDelay/f.jitterBufferEmittedCount*1e3)),n.video.p2pDelay=x.stat.end2EndDelay)}f.jitterBufferDelay&&(C?(n.audio.totalJitter=f.jitterBufferDelay,n.audio.totalJitterCount=f.jitterBufferEmittedCount,n.audio.estimatedPlayoutTimestamp=f.estimatedPlayoutTimestamp):f.ssrc===o.video&&l.hasVideo?(n.video.totalJitter=f.jitterBufferDelay,n.video.totalJitterCount=f.jitterBufferEmittedCount,n.video.estimatedPlayoutTimestamp=f.estimatedPlayoutTimestamp):f.ssrc===o.auxiliary&&l.hasAuxiliary&&(n.auxiliary.totalJitter=f.jitterBufferDelay,n.auxiliary.totalJitterCount=f.jitterBufferEmittedCount))}else f.type==="candidate-pair"&&Hc(f)&&(this.totalBytesReceived=f.bytesReceived,nt(f.currentRoundTripTime)&&(n.rtt=Math.floor(1e3*f.currentRoundTripTime)));j(f.frameWidth)||((f.trackIdentifier===e.getMainStreamVideoTrackId()||f.ssrc===o.video)&&(n.video.frameWidth=f.frameWidth,n.video.frameHeight=f.frameHeight,e.remoteVideoTrack.stat.frameWidth=f.frameWidth,e.remoteVideoTrack.stat.frameHeight=f.frameHeight),(f.trackIdentifier===e.getAuxStreamVideoTrackId()||f.ssrc===o.auxiliary)&&(n.auxiliary.frameWidth=f.frameWidth,n.auxiliary.frameHeight=f.frameHeight,e.remoteAuxiliaryTrack.stat.frameWidth=f.frameWidth,e.remoteAuxiliaryTrack.stat.frameHeight=f.frameHeight)),!j(f.audioLevel)&&e.muteState.audioAvailable&&e.remoteAudioTrack.mediaTrack&&f.trackIdentifier===e.remoteAudioTrack.mediaTrack.id&&(n.audio.audioLevel=f.audioLevel||0,n.audio.totalAudioEnergy=f.totalAudioEnergy||0)}),n.audio.audioLevel===0&&e.muteState.audioAvailable&&(n.audio.audioLevel=e.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=n.audio.bytesReceived+n.video.bytesReceived+n.auxiliary.bytesReceived),j((t=e.remoteVideoTrack.player.stat)==null?void 0:t.fps)||(n.video.fpsRender=e.remoteVideoTrack.player.stat.fps),j((i=e.remoteAuxiliaryTrack.player.stat)==null?void 0:i.fps)||(n.auxiliary.fpsRender=e.remoteAuxiliaryTrack.player.stat.fps);let h=n.audio.estimatedPlayoutTimestamp,_=n.video.estimatedPlayoutTimestamp;if(h&&_&&e.remoteAudioTrack.isAvailable&&e.remoteVideoTrack.isAvailable){let f=_-h;Math.abs(f)<=1e4&&(n.avSyncDelay=f,Math.abs(f)>150&&this._log.warn("av sync delay",f))}}catch(o){this._log.warn("failed to getStats on receiver connection ".concat(o))}return n.rtt===0&&(n.rtt=((r=this.room.networkQuality)==null?void 0:r.uplinkRTT)||0),n})}getStats(e,t){return P(this,null,function*(){let i,r={},n=[];if(this.room.singlePC){let s=this.room.singlePC.getPeerConnection();if(!s)return{senderStats:r,receiverStats:n};let o=Ue(),l=yield s.getStats(),c=Ue();c-o>2e3&&this._log.warn("getStats cost ".concat(c-o,"ms"));let h=[],_=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source","codec","media-playout"]);l.forEach(f=>_.has(f.type)&&h.push(f)),this._spcStats=h}e&&(r=yield this.getSenderStats(e));for(let[s,o]of t){let l=yield this.getReceiverStats(o);l&&n.push(l)}return t.size&&(i=this.getMediaPlayoutStats(this._spcStats)),{senderStats:r,receiverStats:n,mediaPlayoutStats:i}})}getDifferenceValue(e,t){if(In(e))return t;let i=t-e;return i<0?0:i}prepareReport(e){let{stats:t,report:i,freezeMap:r,uplinkConnection:n}=e;var s,o,l,c,h,_,f,T,b;if(!In(t.senderStats)){let H={uint32_audio_level:t.senderStats.audio.audioLevel*Wr,uint32_audio_energy:1e6*(t.senderStats.audio.totalAudioEnergy||0),uint32_audio_codec_bitrate:t.senderStats.audio.bytesSent};t.senderStats.audio.micAudioLevel&&(H.uint32_mic_audio_level=t.senderStats.audio.micAudioLevel*Wr),j(t.senderStats.audio.audioCaptureEnergyAfter3a)||(H.uint32_audio_capture_energy_after3a=t.senderStats.audio.audioCaptureEnergyAfter3a*Wr),t.senderStats.audio.totalSamplesDuration&&(i.msg_device_info.uint32_audio_capture_cost=t.senderStats.audio.totalSamplesDuration);let Z=[];if(t.senderStats.video.bytesSent){let pe={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};Z.push(pe)}if(t.senderStats.small.bytesSent){let pe={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};Z.push(pe)}if(t.senderStats.auxiliary.bytesSent){let pe={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};Z.push(pe)}let de={uint32_bitrate:0,uint32_lost:0,uint32_rtt:t.senderStats.rtt};i.msg_up_stream_info={msg_audio_status:H,msg_video_status:Z,msg_network_status:de}}let{statInterval:C}=this;i.msg_down_stream_info=[],t.receiverStats.forEach(H=>{let Z={msg_user_info:{str_identifier:H.userId,uint64_tinyid:H.tinyId},msg_network_status:{uint32_rtt:H.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(H.hasAudio){let de={uint32_audio_p2p_delay:H.audio.p2pDelay,uint32_audio_cache_ms:H.audio.totalJitter,uint32_audio_cache_ms_count:H.audio.totalJitterCount,uint32_audio_codec_bitrate:H.audio.bytesReceived,uint32_audio_total_bitrate:H.audio.bytesReceived,uint32_audio_level:1e8*H.audio.audioLevel,uint32_audio_energy:1e6*H.audio.totalAudioEnergy,uint32_audio_receive:H.audio.packetsReceived,uint32_audio_origin_lost:H.audio.packetsLost};Z.msg_audio_status=de}if(H.hasVideo){let de=r.get("".concat(H.userId,"_").concat(r2)),pe=de?de.duration:0,Pe={uint32_video_stream_type:H.isSmallSubscribed?3:2,uint32_video_receive_fps:H.video.framesReceived,uint32_video_width:H.video.frameWidth,uint32_video_height:H.video.frameHeight,uint32_video_codec_bitrate:H.video.bytesReceived,uint32_video_receive:H.video.packetsReceived,uint32_video_origin_lost:H.video.packetsLost,uint32_video_block_time:pe,uint32_video_dec_fps:H.video.framesDecoded,uint32_video_codec_fps:H.video.fpsRender,uint32_video_cache_ms:H.video.totalJitter,uint32_video_cache_ms_count:H.video.totalJitterCount,uint32_video_p2p_delay:H.video.p2pDelay,uint32_video_codec:H.video.codec,int32_video_audio_relative_delay:H.avSyncDelay+5e3};Z.msg_video_status.push(Pe)}if(H.hasAuxiliary){let de=r.get("".concat(H.userId,"_").concat(n2)),pe=de?de.duration:0,Pe={uint32_video_stream_type:7,uint32_video_receive_fps:H.auxiliary.framesReceived,uint32_video_width:H.auxiliary.frameWidth,uint32_video_height:H.auxiliary.frameHeight,uint32_video_codec_bitrate:H.auxiliary.bytesReceived,uint32_video_receive:H.auxiliary.packetsReceived+H.auxiliary.packetsLost,uint32_video_origin_lost:H.auxiliary.packetsLost,uint32_video_block_time:pe,uint32_video_dec_fps:H.auxiliary.framesDecoded,uint32_video_codec_fps:H.video.fpsRender,uint32_video_cache_ms:H.auxiliary.totalJitter,uint32_video_cache_ms_count:H.auxiliary.totalJitterCount,uint32_video_p2p_delay:H.auxiliary.p2pDelay,uint32_video_codec:H.video.codec};Z.msg_video_status.push(Pe)}i.msg_down_stream_info.push(Z)}),t.mediaPlayoutStats&&!In(t.mediaPlayoutStats)&&(t.mediaPlayoutStats.synthesizedSamplesDuration*=1e3,t.mediaPlayoutStats.totalSamplesDuration*=1e3);let x=this._prevReport,B=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(i)),this._prevStats=JSON.parse(JSON.stringify(t)),i.msg_up_stream_info.msg_audio_status&&x.msg_up_stream_info.msg_audio_status){let H=x.msg_up_stream_info.msg_audio_status,Z=i.msg_up_stream_info.msg_audio_status;if(H.uint32_audio_codec_bitrate===0)Z.uint32_audio_codec_bitrate=0;else{let de=this.getDifferenceValue(H.uint32_audio_codec_bitrate,Z.uint32_audio_codec_bitrate);Z.uint32_audio_codec_bitrate=Math.round(8*de/C),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=Z.uint32_audio_codec_bitrate}(s=x.msg_device_info)!=null&&s.uint32_audio_capture_cost?(i.msg_device_info.uint32_audio_capture_cost=2*Math.floor(1e3*this.getDifferenceValue(x.msg_device_info.uint32_audio_capture_cost,i.msg_device_info.uint32_audio_capture_cost)/C),i.msg_device_info.uint32_audio_capture_cost>0&&((l=n?.localMainAudioTrack)==null||l.updateAfter3aSilenceStartTime((o=t.senderStats.audio.audioCaptureEnergyAfter3a)!=null?o:t.senderStats.audio.micAudioLevel))):delete i.msg_device_info.uint32_audio_capture_cost}let Y=x.msg_up_stream_info.msg_video_status;i.msg_up_stream_info.msg_video_status.forEach(H=>{let Z=Y.find(je=>je.uint32_video_stream_type===H.uint32_video_stream_type);if(!Z||Z.uint32_video_codec_bitrate===0)return H.uint32_video_codec_bitrate=0,H.uint32_video_enc_fps=0,void(H.uint32_video_codec_fps=0);let de=0,pe=0,Pe=0;Z&&H.uint32_video_codec_bitrate>=Z.uint32_video_codec_bitrate&&(de=Z.uint32_video_codec_bitrate,pe=Z.uint32_video_enc_fps,Pe=Z.uint32_video_codec_fps);let be=this.getDifferenceValue(de,H.uint32_video_codec_bitrate);H.uint32_video_codec_bitrate=Math.round(8*be/C),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=H.uint32_video_codec_bitrate,H.uint32_video_enc_fps=Math.round(this.getDifferenceValue(pe,H.uint32_video_enc_fps)/C),H.uint32_video_codec_fps=Math.round(this.getDifferenceValue(Pe,H.uint32_video_codec_fps)/C),Z.uint32_video_width===0&&Z.uint32_video_height===0&&Z.uint32_video_codec_fps===0&&(H.uint32_video_codec_fps=H.uint32_video_enc_fps),j(Z.uint32_key_frame_count)||(H.uint32_key_frame_count=Math.round(this.getDifferenceValue(Z.uint32_key_frame_count,H.uint32_key_frame_count))),j(Z.uint32_nack_count)||(H.uint32_nack_count=Math.round(this.getDifferenceValue(Z.uint32_nack_count,H.uint32_nack_count))),j(Z.uint32_pli_count)||(H.uint32_pli_count=Math.round(this.getDifferenceValue(Z.uint32_pli_count,H.uint32_pli_count))),j(Z.uint32_video_arq_packets)||(H.uint32_video_arq_packets=Math.round(this.getDifferenceValue(Z.uint32_video_arq_packets,H.uint32_video_arq_packets))),j(Z.uint32_encode_cost)||(H.uint32_encode_cost=Math.round(this.getDifferenceValue(Z.uint32_encode_cost,H.uint32_encode_cost)/C)),j(Z.uint32_send_packet_cost)||(H.uint32_send_packet_cost=Math.round(this.getDifferenceValue(Z.uint32_send_packet_cost,H.uint32_send_packet_cost)/C))});let G=x.msg_down_stream_info;i.msg_down_stream_info=i.msg_down_stream_info.filter(H=>G.find(Z=>Z.msg_user_info.uint64_tinyid===H.msg_user_info.uint64_tinyid));let he=i.msg_down_stream_info;if(he.forEach(H=>{let Z=G.find(de=>de.msg_user_info.uint64_tinyid===H.msg_user_info.uint64_tinyid);if(In(H.msg_audio_status)||In(Z.msg_audio_status))H.msg_audio_status={};else{let de=H.msg_audio_status,pe=Z.msg_audio_status,Pe=this.getDifferenceValue(pe.uint32_audio_cache_ms_count,de.uint32_audio_cache_ms_count);delete de.uint32_audio_cache_ms_count,de.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(pe.uint32_audio_cache_ms,de.uint32_audio_cache_ms)/Pe)||0;let be=this.room.remotePublishedUserMap.get(H.msg_user_info.str_identifier);be&&(be.remoteAudioTrack.stat.jitterBufferDelay=de.uint32_audio_cache_ms),de.uint32_audio_origin_lost=this.getDifferenceValue(pe.uint32_audio_origin_lost,de.uint32_audio_origin_lost),de.uint32_audio_receive=this.getDifferenceValue(pe.uint32_audio_receive,de.uint32_audio_receive),de.uint32_audio_receive+=de.uint32_audio_origin_lost;let je=this.getDifferenceValue(pe.uint32_audio_codec_bitrate,de.uint32_audio_codec_bitrate);de.uint32_audio_codec_bitrate=Math.round(8*je/C),de.uint32_audio_total_bitrate=Math.round(8*je/C)}if(H.msg_video_status&&Z.msg_video_status){let de=Z.msg_video_status;H.msg_video_status=H.msg_video_status.filter(pe=>de.find(Pe=>Pe.uint32_video_stream_type===pe.uint32_video_stream_type)),H.msg_video_status.forEach(pe=>{let Pe=de.find(Vi=>Vi.uint32_video_stream_type===pe.uint32_video_stream_type),be=Pe.uint32_video_receive,je=Pe.uint32_video_origin_lost,Oe=Pe.uint32_video_codec_bitrate,Be=Pe.uint32_video_receive_fps,at=Pe.uint32_video_dec_fps;pe.uint32_video_origin_lost=this.getDifferenceValue(je,pe.uint32_video_origin_lost),pe.uint32_video_receive=this.getDifferenceValue(be,pe.uint32_video_receive)+pe.uint32_video_origin_lost;let yt=this.getDifferenceValue(Oe,pe.uint32_video_codec_bitrate);pe.uint32_video_codec_bitrate=Math.round(8*yt/C);let gt=this.getDifferenceValue(Be,pe.uint32_video_receive_fps);pe.uint32_video_receive_fps=Math.round(gt/C),pe.uint32_video_dec_fps=Math.round(this.getDifferenceValue(at,pe.uint32_video_dec_fps)/C);let Ma=this.getDifferenceValue(Pe.uint32_video_cache_ms_count,pe.uint32_video_cache_ms_count);delete pe.uint32_video_cache_ms_count,pe.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(Pe.uint32_video_cache_ms,pe.uint32_video_cache_ms)/Ma)||0})}}),!j((c=B?.mediaPlayoutStats)==null?void 0:c.totalSamplesDuration)&&!j((h=t.mediaPlayoutStats)==null?void 0:h.totalSamplesDuration)){let H=2*Math.floor(this.getDifferenceValue((_=B?.mediaPlayoutStats)==null?void 0:_.synthesizedSamplesDuration,(f=t.mediaPlayoutStats)==null?void 0:f.synthesizedSamplesDuration)/C),Z=2*Math.floor(this.getDifferenceValue((T=B?.mediaPlayoutStats)==null?void 0:T.totalSamplesDuration,(b=t.mediaPlayoutStats)==null?void 0:b.totalSamplesDuration)/C);i.msg_device_info.uint32_audio_play_cost=Z-H}return B&&t.receiverStats.forEach(H=>{if(H.audio.concealedSamples&&H.audio.totalSamplesReceived){let Z=B.receiverStats.find(de=>de.userId===H.userId);if(Z&&Z.audio.concealedSamples&&Z.audio.totalSamplesReceived){let de=(H.audio.silentConcealedSamples||0)-(Z.audio.silentConcealedSamples||0),pe=H.audio.concealedSamples-Z.audio.concealedSamples,Pe=H.audio.totalSamplesReceived-Z.audio.totalSamplesReceived,be=Math.floor((pe-de)/Pe*1e3*C);if(be>1e3*C/5){let je=he.find(Oe=>Oe.msg_user_info.str_identifier===H.userId);je&&(je.msg_audio_status.uint32_audio_block_time=be)}}}}),i.msg_down_stream_info.forEach(H=>{H.msg_video_status.forEach(Z=>{Z.uint32_video_codec_bitrate===0&&Z.uint32_video_receive_fps===0&&(Z.uint32_video_width=0,Z.uint32_video_height=0)})}),i}getStatsReport(e){return P(this,arguments,function(t){var i=this;let{uplinkConnection:r,downlinkConnections:n,freezeMap:s}=t;return(function*(){let o={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_capture_energy_after3a:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0,uint32_video_codec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},l=yield i.getStats(r,n);return JSON.stringify(i._prevReport)==="{}"&&(i._prevReport=JSON.parse(JSON.stringify(o))),i.prepareReport({stats:l,report:o,freezeMap:s,uplinkConnection:r}),i._prevReportTime=Date.now(),o})()})}getMediaPlayoutStats(e){let t;if(Jt(e)){for(let i of e)if(i.type==="media-playout"){let{synthesizedSamplesDuration:r,totalSamplesDuration:n}=i;t={synthesizedSamplesDuration:r,totalSamplesDuration:n};break}return t}}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map,[this.room.localMainVideoTrack,this.room.capturedLocalMainVideoTrack,this.room.localAuxVideoTrack,this.room.capturedLocalAuxVideoTrack].forEach(e=>{e!=null&&e.stat&&(e.stat.framesCaptured=0)})}},Jj=ti(Ri());function Yj(e){return new Promise(t=>P(null,null,function*(){let i=setTimeout(()=>{t({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})},1e4),r=Date.now(),n="https://".concat(e,"/?t=").concat(r);try{yield fetch(n)}catch{}clearTimeout(i);let s=(function(o){let l={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let c=performance.getEntriesByType("resource").reverse();for(let h of c)if(h.name===o){let _=Math.round(h.duration),f=Math.max(Math.round(h.domainLookupStart-h.startTime),0),T=h.redirectStart>0?Math.max(Math.round(h.redirectEnd-h.redirectStart),0):0,b=h.fetchStart>0?Math.max(Math.round(h.domainLookupStart-h.fetchStart),0):0,C=Math.round(h.domainLookupEnd-h.domainLookupStart),x=Math.round(h.requestStart-h.secureConnectionStart),B=Math.round(h.secureConnectionStart-h.connectStart),Y=Math.round(h.responseStart-h.requestStart),G=Math.round(h.responseEnd-(h.responseStart||h.startTime));l=xe(ve({},l),{totalCost:_,local:f,redirect:T,httpCache:b,dns:C,tcp:B,tls:x,request:Y,response:G});break}}catch{}return l})(n);s.totalCost===0&&(s.totalCost=Date.now()-r),t(s)}))}var Xp=class $o extends Jj.default{constructor(t){let{signalChannel:i,room:r}=t;super(),m(this,"_room"),m(this,"_signalChannel"),m(this,"_log"),m(this,"uplinkRTT",0),m(this,"uplinkLoss",0),m(this,"downlinkRTT",0),m(this,"downlinkLoss",0),m(this,"pingResults",{}),m(this,"_downlinkPrevStatMap",new Map),m(this,"_downlinkLossAndRTTMap",new Map),m(this,"_interval",-1),m(this,"_uplinkNetworkQuality",0),m(this,"_downlinkNetworkQuality",0),m(this,"_uplinkQualityHistory",[]),m(this,"_downlinkQualityHistory",[]),this._room=r,this._signalChannel=i,this._log=fe.createLogger({parent:r.getLogger(),id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(t){t!==this._uplinkNetworkQuality&&this._log.info("uplink ".concat(this.uplinkNetworkQuality," -> ").concat(t,", rtt: ").concat(this.uplinkRTT,", loss: ").concat(this.uplinkLoss," ws-rtt: ").concat(this._signalChannel.rtt)),this._uplinkNetworkQuality=t,this._uplinkQualityHistory.push(t),this._uplinkQualityHistory.length>$o.HISTORY_SIZE&&this._uplinkQualityHistory.shift()}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(t){if(t!==this._downlinkNetworkQuality){let{rtt:i,loss:r}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info("downlink ".concat(this.downlinkNetworkQuality," -> ").concat(t,", rtt: ").concat(i,", loss: ").concat(r," ws-rtt: ").concat(this._signalChannel.rtt))}this._downlinkNetworkQuality=t,this._downlinkQualityHistory.push(t),this._downlinkQualityHistory.length>$o.HISTORY_SIZE&&this._downlinkQualityHistory.shift()}initialize(){this._signalChannel.on(Ge.UPLINK_NETWORK_STATS,t=>{this.handleUplinkNetworkQuality(t)}),this._signalChannel.on(SE,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(t){var i,r;if(t.data.code!==0)return;let n=t.data.data;if(n.delay&&this.updateDelay(n.delay),this._room.signalChannel&&n.wsRtt&&(this._room.signalChannel.rtt=n.wsRtt),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this.uplinkLoss=0,void(this.uplinkRTT=0);let s=(r=(i=this._room)==null?void 0:i.uplinkConnection)==null?void 0:r.getPeerConnection();if(s&&this.isPeerConnectionDisconnected(s))return this.uplinkNetworkQuality=6,this.uplinkLoss=0,void(this.uplinkRTT=0);let o=n.expectAudPkg+n.expectVidPkg,l=n.recvAudPkg+n.recvVidPkg,c=o-l;o===0&&l===0||(this.uplinkLoss=c<=0?0:Math.round(c/o*100),this.uplinkRTT=n.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return P(this,null,function*(){if(this._room.remotePublishedUserMap.size===0)return void(this.downlinkNetworkQuality=0);let t=[...this._room.remotePublishedUserMap.values()],i=t.filter(s=>{var o;return((o=s.getPeerConnection())==null?void 0:o.connectionState)===Kt.CONNECTED});if(t.filter(s=>this.isPeerConnectionDisconnected(s.getPeerConnection())).length===t.length)return void(this.downlinkNetworkQuality=6);for(let s=0;s<i.length;s++){let o=i[s].getPeerConnection();if(!o)return;let{rtt:l,totalPacketsLost:c,totalPacketsReceived:h}=yield this.getStat(o);if(!this._downlinkPrevStatMap.has(o)){this._downlinkPrevStatMap.set(o,{totalPacketsLost:c,totalPacketsReceived:h});continue}let _=0,f=this._downlinkPrevStatMap.get(o),T=c-f.totalPacketsLost,b=h-f.totalPacketsReceived;_=T<=0||b<0?0:Math.round(T/(T+b)*100),this._downlinkPrevStatMap.set(o,{totalPacketsLost:c,totalPacketsReceived:h}),this._downlinkLossAndRTTMap.set(o,{rtt:l,loss:_,userId:i[s].getUserId(),audioDelay:i[s].remoteAudioTrack.stat.end2EndDelay,videoDelay:i[s].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(s=>{this.isPeerConnectionDisconnected(s)&&(this._downlinkPrevStatMap.delete(s),this._downlinkLossAndRTTMap.delete(s))}),this._downlinkLossAndRTTMap.size===0)return this.downlinkRTT=0,this.downlinkLoss=0,void(this.downlinkNetworkQuality=0);let{rtt:r,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=r,this.downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,r)})}getStat(t){return P(this,null,function*(){let i={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!t||!np())return i;let r=t.getReceivers();try{for(let n=0;n<r.length;n++)(yield r[n].getStats()).forEach(s=>{s.type==="candidate-pair"&&nt(s.currentRoundTripTime)&&(i.rtt=Math.round(1e3*s.currentRoundTripTime)),s.type==="inbound-rtp"&&(s.mediaType===D.AUDIO||s.mediaType===D.VIDEO)&&(i.totalPacketsLost+=s.packetsLost,i.totalPacketsReceived+=s.packetsReceived)});return i.rtt===0&&(i.rtt=this.uplinkRTT),i}catch{return i}})}getAverageLossAndRTT(t){let i={rtt:0,loss:0};return Array.isArray(t)&&t.length>0&&(t.forEach(r=>{i.rtt+=r.rtt,i.loss+=r.loss}),Object.keys(i).forEach(r=>{i[r]=Math.round(i[r]/t.length)})),i}getNetworkQuality(t,i){return t>50||i>500?5:t>30||i>350?4:t>20||i>200?3:t>10||i>100?2:t>=0||i>=0?1:0}handleSignalConnectionStateChange(t){t.state==="DISCONNECTED"?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):t.state==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange(t){let{state:i}=t;i==="DISCONNECTED"?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):i==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(t){return!(!t||t.connectionState!==Kt.DISCONNECTED&&t.connectionState!==Kt.FAILED&&t.connectionState!==Kt.CLOSED)}setUplinkConnection(t){this._room.uplinkConnection=t,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT=0,this.uplinkLoss=0)}start(){this._interval===-1?(this._log.debug("start network quality calculating"),this._interval=ft.run("ric",()=>{var t;this.handleDownlinkNetworkQuality();let i=[...this._downlinkLossAndRTTMap.values()];$.emit(ie.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:i});let r=(t=this._room.scheduleResult.config)==null?void 0:t.pingDomainInfo,n={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};r&&(n=xe(ve({},n),{pingResults:this.uplinkRTT>r.rttThreshold||this.downlinkRTT>r.rttThreshold?this.pingResults:{}})),this.emit($o.EVENT_NETWORK_QUALITY,n);let s=Date.now();if(r&&(this.uplinkRTT>r.rttThreshold||this.downlinkRTT>r.rttThreshold)&&s-$o.lastPingTime>1e3*r.interval){$o.lastPingTime=Date.now();let o=r.domain.map(l=>Yj(l).then(c=>({domain:l,cost:c.totalCost})));Promise.all(o).then(l=>{this.pingResults.isPoorNetwork=l.some(c=>c.cost>700),this.pingResults.timestamp=s,this.pingResults.data=l,l.forEach(c=>{ce.addSuccessEvent({key:521718,cost:c.cost})}),this._log.warn("All ping results: ".concat(JSON.stringify(l)))}).catch(l=>{this._log.warn("Error during pinging domains: ".concat(l))})}},{delay:2e3})):this._log.info("network quality calculating is already started")}hadRecentBadUplink(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2;return this._uplinkQualityHistory.some(i=>i>t)}hadRecentBadDownlink(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2;return this._downlinkQualityHistory.some(i=>i>t)}stop(){this._log.debug("stopped"),this._interval!==-1&&(ft.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(t){let{tinyIdToUserIdMap:i}=this._room;t.forEach(r=>{let{srcTinyId:n,videoDelay:s,audioDelay:o}=r,l=i.get(n);if(l){let c=this._room.remotePublishedUserMap.get(l);c?.setDelay({videoDelay:s,audioDelay:o})}})}};m(Xp,"HISTORY_SIZE",10),m(Xp,"EVENT_NETWORK_QUALITY","0"),m(Xp,"lastPingTime",0);var CN=Xp,kN=class{constructor(e){m(this,"_frameWorkType"),m(this,"_component"),m(this,"_language"),m(this,"connectionType"),m(this,"_room"),m(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,reportToken:void 0}),m(this,"_keyPrefix"),m(this,"_log"),m(this,"_intervalId"),m(this,"_firstPublishedUserList"),m(this,"_networkQuality"),m(this,"_basicInfo"),m(this,"_pathJoinRoom"),m(this,"_pathLeaveRoom"),m(this,"_pathMainVideoMap"),m(this,"_pathMainAudioMap"),m(this,"_pathAuxiliaryMap"),m(this,"_remoteStreamStatMap"),m(this,"_localStreamStat"),m(this,"_eventMap",new Map),m(this,"_captureCostSum",0),m(this,"_captureCostCount",0),m(this,"isDestroyed",!1),this._frameWorkType=e.frameWorkType||30,this._component=e.component||0,this.connectionType=e.connectionType||1,this._language=e.language||0,this._room=e.room,this._keyPrefix="key_point",this._log=fe.createLogger({parent:this._room.getLogger(),id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(t=>{t.startsWith("handle")&&Ut(this[t])&&(this[t]=(function(i){let{fn:r,context:n}=i;return function(){try{for(var s=arguments.length,o=new Array(s),l=0;l<s;l++)o[l]=arguments[l];let c=r.apply(n,o);return yc(c)?c.catch(h=>fe.error("".concat(r.name,"() error observed ").concat(h))):c}catch(c){fe.error("".concat(r.name,"() error observed ").concat(c))}}})({fn:this[t],context:this}))}),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:yr,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:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0,uint32_audio_capture_thread_health_zero_cnt:0,uint32_after3a_silence_duration:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,ep().then(()=>{this._basicInfo.string_os_version=xo(),this._basicInfo.string_device_name=Lo()||this._basicInfo.string_os_version})}addEvent(e,t){return this._eventMap.set(e,t),$.on(e,t),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(ie.JOIN_START,this.handleJoinStart).addEvent(ie.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(ie.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(ie.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(ie.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(ie.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(ie.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(ie.JOIN_FAILED,this.handleJoinFailed).addEvent(ie.LEAVE_START,this.handleLeaveStart).addEvent(ie.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(ie.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(ie.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(ie.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(ie.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(ie.PUBLISH_START,this.handlePublishStart).addEvent(ie.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(ie.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(ie.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(ie.PLAY_TRACK_START,this.handlePlayStart).addEvent(ie.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(ie.PLAYER_STATE_CHANGED,e=>{let{track:t,state:i,type:r}=e;!t.isRemote||!this.hitTest(t.room)||i==="PLAYING"&&(r===D.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(ie.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(ie.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(ie.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(ie.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(ie.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(ie.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(ie.REMOTE_PUBLISH_STATE_CHANGED,e=>{let{room:t,prevMuteState:i,muteState:r}=e;if(!this.hitTest(t))return;let n=i.hasAudio||i.hasVideo||i.hasSmall,s=i.hasAuxiliary,o=r.hasAudio||r.hasVideo||r.hasSmall,l=r.hasAuxiliary;!n&&o&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&l&&this.handleRemoteStreamAdded(r.userId,"auxiliary")}).addEvent(ie.SINGLE_CONNECTION_STAT,e=>{let{room:t,stat:i}=e;this.hitTest(t)&&(this._pathJoinRoom.int32_ice_cost=i.ice,this._pathJoinRoom.int32_dtls_cost=i.dtls,this._pathJoinRoom.int32_peer_connection_cost=i.peerConnection)})}uninstallEvents(){window.removeEventListener("pagehide",this.handleUnload),this._eventMap.forEach((e,t)=>$.off(t,e)),this._eventMap.clear()}destroy(){this.uninstallEvents(),ft.clearTask(this._intervalId),this._pathJoinRoom.uint64_start_time===0&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(e){this.hitTest(e.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),e.params&&(j(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),j(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),j(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:r,local:n,dns:s,tcp:o,tls:l,request:c,response:h}=i;this._pathJoinRoom.int32_schedule_cost=r,this._pathJoinRoom.int32_schedule_local=n,this._pathJoinRoom.int32_schedule_dns=s,this._pathJoinRoom.int32_schedule_tcp=o,this._pathJoinRoom.int32_schedule_tls=l,this._pathJoinRoom.int32_schedule_request=c,this._pathJoinRoom.int32_schedule_response=h}}handleSignalConnectionStart(e){let{room:t}=e;this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd(e){let{room:t,error:i}=e;this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),i&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=i instanceof me?Number(i.getExtraCode()||i.getCode()):te.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(e){this.hitTest(e.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(e){this.hitTest(e.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=e.code,e.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(e){this.hitTest(e.room)&&this._pathJoinRoom.uint64_end_time===0&&(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(),this._pathJoinRoom.int32_end_ret===0&&(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)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=e.publishedUserList||[])}handleSendFirstVideoFrame(e){let{room:t}=e;this.hitTest(t)&&this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(e){var t;if(this.hitTest(e.room)&&this._pathLeaveRoom.uint64_end_time===0){if(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0){this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time;let i=(t=this._room.audioManager.localAudioTrack)==null?void 0:t.after3aSilenceStartTime;i&&(this._localStreamStat.statsToReport.uint32_after3a_silence_duration=Ue()-i)}else this._log.warn("pathJoinRoom endTime is 0");this.report()}}handleLeaveSendCMD(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleSwitchRoomStart(e){if(this.hitTest(e.room)){let t=Date.now();this.report().then(()=>{this._pathJoinRoom.uint64_start_time=t,this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=t})}}handleSwitchRoomSuccess(e){let{room:t}=e;if(this.hitTest(t)&&this._pathJoinRoom.uint64_end_time===0){let i=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=i,this._pathJoinRoom.uint64_end_time=i,this._pathJoinRoom.int32_end_ret}}handleSwitchRoomFailed(e){let{room:t,error:i}=e;if(this.hitTest(t)){let r=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=r,this._pathJoinRoom.uint64_end_time=r,i&&(this._pathJoinRoom.int32_end_ret=i instanceof me?Number(i.getExtraCode()||i.getCode()):te.UNKNOWN)}}handleRemoteStreamAdded(e,t){var i;let r="".concat(e,"_").concat(t);if(!this._remoteStreamStatMap.has(r)){let n={userId:e,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:xe(ve({},qj),{msg_user_info:new DE({userId:e,tinyId:(i=this._room.remotePublishedUserMap.get(e))==null?void 0:i.tinyId,role:20})})};n.statsToReport.uint32_stream_type=t==="main"?2:7,this._remoteStreamStatMap.set(r,n)}}handleSubscribeStart(e){let{room:t,remotePublishedUser:i,streamType:r,subscribeState:n}=e;if(!this.hitTest(t))return;let{userId:s,tinyId:o,role:l}=i,c=new DE({userId:s,tinyId:o,role:l==="anchor"?20:21}),h=Date.now(),_="".concat(s,"_").concat(r),f=this._remoteStreamStatMap.get(_);f&&f.subscribeStartTime===0&&(f.subscribeStartTime=h),r==="main"?(i.muteState.hasVideo&&(n.video||n.smallVideo)&&!this._pathMainVideoMap.has(_)&&this._pathMainVideoMap.set(_,{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:s,sendSubscribeCMDTime:h}),i.muteState.hasAudio&&n.audio&&!this._pathMainAudioMap.has(_)&&this._pathMainAudioMap.set(_,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,sendSubscribeCMDTime:h})):i.muteState.hasAuxiliary&&n.auxiliary&&!this._pathAuxiliaryMap.has(_)&&this._pathAuxiliaryMap.set(_,{sendSubscribeCMDTime:h})}handleSubscribed(e){let{room:t,remotePublishedUser:i,streamType:r}=e;if(this.hitTest(t)){let n="".concat(i.userId,"_").concat(r),s=this._remoteStreamStatMap.get(n);s&&s.subscribedTime===0&&(s.subscribedTime=Date.now())}}handlePlayStart(e){let{track:t}=e;if(!t.isRemote||!this.hitTest(t.room))return;let i="".concat(t.userId,"_").concat(t.streamType),r=this._remoteStreamStatMap.get(i);r?.playStreamTime===0&&(r.playStreamTime=Date.now())}handleVideoLoadedData(e){let{track:t}=e;if(!t.isRemote||!this.hitTest(t.room))return;let i="".concat(t.userId,"_").concat(t.streamType),r=this._pathMainVideoMap.get(i);r&&r.statsToReport.uint64_combine_first_frame_time===0&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=Date.now(),r=this._pathMainVideoMap.get(t),n=this._remoteStreamStatMap.get(t);if(n){let{statsToReport:s}=n;if(s.uint32_video_render_first||e.streamType!=="main"?this.hasAuxFlag(e.userId):this.hasVideoFlag(e.userId)){let o=i-this._pathJoinRoom.uint64_start_time;s.uint32_video_render_first=o,ce.addNumber({key:516820,value:o})}}r?.statsToReport.uint64_render_first_frame_time===0&&(r.statsToReport.uint64_render_first_frame_time=i)}handleAudioPlaying(e){let t="".concat(e.userId,"_").concat(e.streamType),i=this._pathMainAudioMap.get(t);i&&i.statsToReport.uint64_play_first_frame_time===0&&(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(t=>{let{rtt:i,loss:r,userId:n,videoDelay:s,audioDelay:o}=t,l=this._networkQuality.totalDownlinkRTTAndLossMap.get(n);if(l)l.totalRTT+=i,l.totalLoss+=r,s&&(l.totalVideoDelay=(l.totalVideoDelay||0)+s,l.videoDelayCount=(l.videoDelayCount||0)+1),o&&(l.totalAudioDelay=(l.totalAudioDelay||0)+o,l.audioDelayCount=(l.audioDelayCount||0)+1),l.count++;else{let c,h,_,f;s&&(h=s,_=1),o&&(c=o,f=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(n,{totalRTT:i,totalLoss:r,count:1,totalAudioDelay:c,totalVideoDelay:h,audioDelayCount:f,videoDelayCount:_})}}))}handleHeartbeatStats(e){var t;if(this.hitTest(e.room)){let{msg_device_info:i,msg_up_stream_info:r,msg_down_stream_info:n}=e.report;if(r.msg_video_status[0]){let{uint32_video_codec_bitrate:s,uint32_video_enc_fps:o,uint32_video_width:l,uint32_video_height:c}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=s,this._localStreamStat.totalVideoFPS+=o,this._localStreamStat.totalVideoWidth+=l,this._localStreamStat.totalVideoHeight+=c,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:s}=r.msg_audio_status;Math.floor(s/Wr*100)>0&&(this._localStreamStat.totalAudioLevel+=s/Wr,this._localStreamStat.audioLevelCount++)}n.forEach(s=>{let{msg_user_info:o,msg_audio_status:l,msg_video_status:c}=s,h=o.str_identifier,_=this._room.remotePublishedUserMap.get(h);if(c.forEach(f=>{let T=f.uint32_video_stream_type===2,b=f.uint32_video_stream_type===7,C="".concat(h,"_").concat(T?"main":"auxiliary"),x=this._remoteStreamStatMap.get(C);if(x&&(T&&_!=null&&_.remoteVideoTrack.isSubscribed||b&&_!=null&&_.remoteAuxiliaryTrack)){x.totalVideoFPS+=f.uint32_video_receive_fps,x.totalVideoBitrate+=f.uint32_video_codec_bitrate,x.videoCount++,x.statsToReport.uint32_video_width===0&&(x.statsToReport.uint32_video_width=f.uint32_video_width),x.statsToReport.uint32_video_height===0&&(x.statsToReport.uint32_video_height=f.uint32_video_height);let B=T?_.remoteVideoTrack:_.remoteAuxiliaryTrack;B.stat.jitterBufferDelay&&(x.videoJitterBufferDelay=B.stat.jitterBufferDelay),B.stat.framesReceived&&(x.statsToReport.uint32_video_consume_render_rate=Math.floor(B.stat.framesDecoded/B.stat.framesReceived*sc(10,6)))}}),!Mh(l)){let f="".concat(h,"_main"),T=this._remoteStreamStatMap.get(f);this._remoteStreamStatMap.has(f)&&T&&_!=null&&_.remoteAudioTrack.isSubscribed&&(T.totalAudioBitrate+=l.uint32_audio_codec_bitrate,T.audioCount++,_.remoteAudioTrack.stat.jitterBufferDelay&&(T.audioJitterBufferDelay=_.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(l.uint32_audio_level/Wr*100)>0&&(T.totalAudioLevel+=l.uint32_audio_level/Wr,T.audioLevelCount++),l.uint32_audio_block_time&&(T.statsToReport.uint32_audio_block_time+=l.uint32_audio_block_time))}}),i.uint32_audio_capture_cost&&(this._captureCostSum+=i.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0)),i.uint32_audio_capture_cost===0&&((t=this._room.audioManager.localAudioTrack)==null?void 0:t.muted)===!1&&(this._localStreamStat.statsToReport.uint32_audio_capture_thread_health_zero_cnt+=1)}}handlePublishStart(e){let{room:t}=e;this.hitTest(t)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart(e){let{track:t}=e;t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess(e){let{track:t}=e;t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed(e){let{track:t,error:i}=e,r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[i.name]||(i instanceof me?i.getExtraCode()||i.getCode():te.UNKNOWN);t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=r,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(e){return this._firstPublishedUserList.findIndex(t=>t.userId===e&&t.flag&uc)>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex(t=>t.userId===e&&t.flag&dc)>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex(t=>t.userId===e&&t.flag&Ah)>=0}hitTest(e){return e===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let e=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),t=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=e<<16|t}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((e,t)=>{let{userId:i}=e,r=this._networkQuality.totalDownlinkRTTAndLossMap.get(i);if(r){let{totalLoss:h,count:_,audioDelayCount:f,videoDelayCount:T,totalAudioDelay:b,totalVideoDelay:C}=r;e.statsToReport.uint32_avg_down_loss=Math.floor(h/_),f&&b&&(e.statsToReport.uint32_audio_network_p2p_delay=Math.floor(b/f),e.audioJitterBufferDelay&&(e.statsToReport.uint32_p2p_delay=Math.floor(e.statsToReport.uint32_audio_network_p2p_delay+e.audioJitterBufferDelay))),T&&C&&(e.statsToReport.uint32_video_network_p2p_delay=Math.floor(C/T))}e.videoCount>0&&(e.statsToReport.uint32_video_avg_fps=Math.floor(e.totalVideoFPS/e.videoCount),e.statsToReport.uint32_video_avg_bitrate=Math.floor(e.totalVideoBitrate/e.videoCount)),e.audioCount>0&&(e.statsToReport.uint32_audio_recv_bitrate=e.statsToReport.uint32_audio_bitrate=Math.floor(e.totalAudioBitrate/e.audioCount)),e.audioLevelCount>0&&(e.statsToReport.uint32_audio_play_db=Math.floor(e.totalAudioLevel/e.audioLevelCount*100));let{callDurationCalculator:n}=this._room;n&&(e.statsToReport.uint32_audio_play_time=n.getDuration(t,D.AUDIO),e.statsToReport.uint32_video_play_time=n.getDuration(t,D.VIDEO)),e.statsToReport.uint32_video_render_first&&(e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,Da));let{badCaseDetector:s}=this._room,{dataFreeze:o,count:l}=s.getDataFreezeDuration(t),{renderFreeze:c}=s.getRenderFreezeDuration(t);e.statsToReport.uint32_video_block_count=l,e.statsToReport.uint32_video_block_time=Math.min(o,e.statsToReport.uint32_video_play_time),e.statsToReport.uint32_video_external_block_time=Math.min(c,e.statsToReport.uint32_video_play_time),e.statsToReport.uint32_audio_block_time=Math.min(e.statsToReport.uint32_audio_block_time,e.statsToReport.uint32_audio_play_time),s.isBlackStream(t)&&e.statsToReport.uint32_video_avg_fps===0?e.statsToReport.uint32_video_black_screen_subjective=1:e.statsToReport.uint32_video_black_screen_subjective=0}),this._pathMainAudioMap.forEach((e,t)=>{this.hasAudioFlag(e.userId)?e.statsToReport.uint64_play_first_frame_time-e.statsToReport.uint64_start_enter_time>Da&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+Da):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>Da&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+Da):this._pathMainVideoMap.delete(t)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>Da&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+Da)}getReportData(){this._basicInfo.uint32_networkType=Ec();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new DE({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Ic(this._signalInfo.relayIp),uint32_client_ip:Ic(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*sc(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(t=>t.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(t=>t.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(t=>t.statsToReport),uint32_info_client_ip:Ic(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend,str_user_sig:this._room.userSig,bytes_report_token:this._signalInfo.reportToken};return Uh(e),e}report(){return P(this,null,function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),this.initData()}catch(e){this._log.warn(e)}finally{this.isDestroyed&&(this._room=null)}})}upload(e){return P(this,null,function*(){if(e.msg_path_enter_room.uint64_start_time===0)return;let t=Number(this._room.sdkAppId),i=Uc.enable?wo(e,2001,t):yield U2(e),r=i instanceof ArrayBuffer,n="".concat(bo(t,lc.KEY_POINT),"&gzip=").concat(+r),s=!1;navigator.sendBeacon&&(s=navigator.sendBeacon(n,i));let o=[this.uploadKVStat(ce),this.uploadKVStat(Bc)];s||o.push(bc({url:n,body:i,priority:"low"})),yield Promise.all(o)})}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return P(this,arguments,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this._room.sdkAppId;return(function*(){var n,s;let o=t.getReportData((n=i._room)==null?void 0:n.userSig,(s=i._signalInfo)==null?void 0:s.reportToken);if(o.stats_count.length===0&&o.stats_distribution.length===0)return;o.msg_sdk_basic_info=xe(ve({},o.msg_sdk_basic_info),{bytes_device_name:i._basicInfo.string_device_name||"",bytes_os_version:i._basicInfo.string_os_version||"",uint32_framework:i._frameWorkType,uint32_network_type:i._basicInfo.uint32_networkType||0}),i._log.debug(o);let l=Uc.enable?wo(o,2003,r):yield U2(o),c=l instanceof ArrayBuffer,h="".concat(bo(+r,lc.KV_STAT),"&gzip=").concat(+c),_=!1;navigator.sendBeacon&&(_=navigator.sendBeacon(h,l)),_||bc({url:h,body:l})})()})}};_e([hs({settings:{timeout:500,retries:3}})],kN.prototype,"upload");var Da=5e3,qj={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},DE=class{constructor(e){m(this,"str_identifier"),m(this,"str_tinyid"),m(this,"uint32_role"),this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},Xj=kN,wN=class{constructor(){m(this,"_startTime"),m(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=Ue())}stop(){this._endTime===0&&(this._endTime=Ue())}getDuration(){return this._endTime===0?Ue()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},Qj=class{constructor(e){m(this,"_room",null),m(this,"_durationMap"),m(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(ie.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(ie.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(ie.REMOTE_PUBLISH_STATE_CHANGED,e=>{let{room:t,prevMuteState:i,muteState:r}=e;var n;let{userId:s}=r;if(!this.hitTest(t))return;i.hasAudio&&!r.hasAudio&&this.stopDurationItem("".concat(s,"_main"),D.AUDIO),i.hasVideo&&!r.hasVideo&&this.stopDurationItem("".concat(s,"_main"),D.VIDEO),i.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem("".concat(s,"_auxiliary"),D.VIDEO);let o=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(s);o&&(!i.hasAudio&&r.hasAudio&&o.remoteAudioTrack.isSubscribed&&this.addDuractionItem(s,D.AUDIO,"main"),!i.hasVideo&&r.hasVideo&&o.remoteVideoTrack.isSubscribed&&this.addDuractionItem(s,D.VIDEO,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(s,D.VIDEO,"auxiliary"))}),this._eventMap.forEach((e,t)=>$.on(t,e,this))}uninstallEvents(){this._eventMap.forEach((e,t)=>$.off(t,e,this)),this._eventMap.clear()}handleSubscribed(e){let{track:t}=e;if(!this.hitTest(t.room))return;let{userId:i,streamType:r,kind:n}=t;t.isSubscribed?this.addDuractionItem(i,n,r):this.stopDurationItem("".concat(i,"_").concat(r),n)}handleUnsubscribed(e){let{track:t}=e;this.hitTest(t.room)&&this.stopDurationItem("".concat(t.userId,"_").concat(t.streamType),t.kind)}isRecording(e){return e.findIndex(t=>t.endTime===0)>=0}addDuractionItem(e,t,i){let r="".concat(e,"_").concat(i),n=new wN,s=this._durationMap.get(r);s?this.isRecording(s[t])||s[t].push(n):this._durationMap.set(r,{userId:e,type:i,audio:t===D.AUDIO?[n]:[],video:t===D.AUDIO?[]:[n]})}stopDurationItem(e,t){if(this._durationMap.has(e)){let i=this._durationMap.get(e)[t].find(r=>r.endTime===0);i&&i.stop()}}hitTest(e){return this._room===e}getDuration(e,t){return this._durationMap.has(e)?this._durationMap.get(e)[t].reduce((i,r)=>i+r.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},Zj=class{constructor(){m(this,"renderFreezeMap",new Map),m(this,"dataFreezeMap",new Map)}get(e,t){let i=this.renderFreezeMap.get(e),r=this.dataFreezeMap.get(e);return t?t==="data"?r:i:(ri||ut)&&i&&r&&i.duration>r.duration?i:r}set(e,t,i){i==="data"?this.dataFreezeMap.set(e,t):this.renderFreezeMap.set(e,t)}clear(){this.renderFreezeMap.clear(),this.dataFreezeMap.clear()}},$j=class{constructor(e){m(this,"_room"),m(this,"_renderFreezeMap",new Map),m(this,"_isVideoPlayingEventFiredMap",new Map),m(this,"_dataFreezeMap",new Map),m(this,"_monitorFreezeData",new Zj),m(this,"_eventMap",new Map),m(this,"_videoEncodeFailedCount",0),m(this,"_audioEncodeFailedCount",0),m(this,"_encodeFailedThreshold",3),m(this,"ABNORMAL_TIME_LOWER_LIMIT",3e3),m(this,"ABNORMAL_TIME_UPPER_LIMIT",5e3),m(this,"_videoAbnormalTimestampMap",new Map),m(this,"_remoteVideoAbnormalTimestampMap",new Map),m(this,"_audioAbnormalTimestampMap",new Map),m(this,"eventListenerMap",new Map),this._room=e.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(ie.LEAVE_SUCCESS,e=>{let{room:t}=e;this.hitTest(t)&&this.stop()}).set(ie.PLAY_TRACK_START,this.onPlayTrackStart).set(ie.UNSUBSCRIBE_SUCCESS,e=>{let{room:t,streamType:i,remotePublishedUser:r}=e;if(!this.hitTest(t))return;let{userId:n}=r,s="".concat(n,"_").concat(i);this.stopDataFreeze({key:s,userId:n,type:i})}).set(ie.REMOTE_PUBLISH_STATE_CHANGED,e=>{let{room:t,prevMuteState:i,muteState:r}=e;if(!this.hitTest(t))return;let{userId:n}=r;if(i.hasVideo&&!r.hasVideo){let s="main",o="".concat(r.userId,"_").concat(s);this.stopDataFreeze({key:o,userId:n,type:s})}if(i.hasAuxiliary&&!r.hasAuxiliary){let s="auxiliary",o="".concat(r.userId,"_").concat(s);this.stopDataFreeze({key:o,userId:n,type:s})}}).set(ie.PLAYER_STATE_CHANGED,e=>{let{track:t,state:i,reason:r,type:n}=e;if(t.isRemote&&t.room&&this.hitTest(t.room)&&n===D.VIDEO){if(i==="PLAYING"){let s="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(s,!0)}r===D.MUTE?this.onVideoTrackMuted(t):r===D.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(ie.HEARTBEAT_REPORT,this.onHearBeatReport).set(ie.REMOTE_VIDEO_PLAY_START,this.onRemoteVideoPlayStart).set(ie.REMOTE_VIDEO_PLAY_FINISH,this.onRemoteVideoPlayEnd),this._eventMap.forEach((e,t)=>$.on(t,e,this))}uninstallEvents(){this._eventMap.forEach((e,t)=>$.off(t,e,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,r="".concat(t,"_").concat(i),n=this._dataFreezeMap.get(r),s=new wN;n?n.durationItemList.push(s):this._dataFreezeMap.set(r,{userId:t,type:i,durationItemList:[s],isFreezing(){let o=this.durationItemList[this.durationItemList.length-1];return o&&o.endTime===0}})}onVideoTrackUnmuted(e){if(!e.isSubscribed)return;let{userId:t,streamType:i}=e,r="".concat(t,"_").concat(i);this.stopDataFreeze({key:r,userId:t,type:i})}onHearBeatReport(e){let{room:t,report:i}=e;this.hitTest(t)&&(this.localMediaTrackDetector(i),this.remoteMediaTrackDetector(i))}remoteMediaTrackDetector(e){e.msg_down_stream_info.length>0&&e.msg_down_stream_info.forEach(t=>{var i;if(t.msg_video_status.length===0)return;let r=t.msg_user_info.str_identifier,n=(i=this._room.remotePublishedUserMap.get(r))==null?void 0:i.remoteVideoTrack;t.msg_video_status.forEach(s=>{let o=Ue();if(s.uint32_video_codec_bitrate!==void 0&&s.uint32_video_codec_bitrate>0&&s.uint32_video_receive_fps===0&&n!=null&&n.muted)if(this._remoteVideoAbnormalTimestampMap.has("".concat(r,"-decode"))){let l=this._remoteVideoAbnormalTimestampMap.get("".concat(r,"-decode"));l&&o-l>this.ABNORMAL_TIME_LOWER_LIMIT&&o-l<this.ABNORMAL_TIME_UPPER_LIMIT&&dt.uploadEvent({userId:this._room.userId,log:"stat-".concat(di.VIDEO_DECODE_FAILED_DURING_CALL)})}else this._remoteVideoAbnormalTimestampMap.set("".concat(r,"-decode"),o);else{let l=this._remoteVideoAbnormalTimestampMap.get("".concat(r,"-decode"));l&&o-l>=this.ABNORMAL_TIME_UPPER_LIMIT&&(dt.uploadEvent({userId:this._room.userId,log:"stat-".concat(di.VIDEO_DECODE_RESUME_DURING_CALL)}),this._remoteVideoAbnormalTimestampMap.delete("".concat(r,"-decode")))}if(s.uint32_video_codec_bitrate!==void 0&&s.uint32_video_codec_bitrate>5e5&&s.uint32_video_dec_fps!==void 0&&s.uint32_video_dec_fps<=5)if(this._remoteVideoAbnormalTimestampMap.has("".concat(r,"-hardware"))){let l=this._remoteVideoAbnormalTimestampMap.get("".concat(r,"-hardware"));if(l&&o-l>this.ABNORMAL_TIME_LOWER_LIMIT/2&&o-l<2*this.ABNORMAL_TIME_UPPER_LIMIT){dt.uploadEvent({userId:this._room.userId,log:"stat-".concat(di.VIDEO_HARDWARE_DECODE_FAILED)});let c=this._room.remotePublishedUserMap.get(r);if(c){let h=s.uint32_video_stream_type===2?c.remoteVideoTrack:c.remoteAuxiliaryTrack;h&&(h.log.warn("decode failed during call"),h.emit("decode-failed-during-call"))}}}else this._remoteVideoAbnormalTimestampMap.set("".concat(r,"-hardware"),o);else{let l=this._remoteVideoAbnormalTimestampMap.get("".concat(r,"-hardware"));l&&o-l>=2*this.ABNORMAL_TIME_UPPER_LIMIT&&(dt.uploadEvent({userId:this._room.userId,log:"stat-".concat(di.VIDEO_HARDWARE_DECODE_RESUME)}),this._remoteVideoAbnormalTimestampMap.delete("".concat(r,"-hardware")))}})})}localMediaTrackDetector(e){if(e.msg_up_stream_info.msg_video_status){let t=e.msg_up_stream_info.msg_video_status,i=Array.from(this._room.localTracks).find(n=>n.kind==="video"&&!n.isScreen),r=i?.stat.bytesSent||0;if(i?.isMediaTrackActive===!1||r<=0||i!=null&&i.isUseCustomSource)return;t.forEach(n=>{let s=Ue();if(n.uint32_video_stream_type===2)if(n.uint32_video_capture_fps!==0&&n.uint32_video_codec_bitrate===0&&n.uint32_video_enc_fps===0&&i!=null&&i.isPublished)if(this._videoAbnormalTimestampMap.has("local-encode")){let o=this._videoAbnormalTimestampMap.get("local-encode");o&&s-o>this.ABNORMAL_TIME_LOWER_LIMIT&&s-o<this.ABNORMAL_TIME_UPPER_LIMIT&&dt.uploadEvent({userId:this._room.userId,log:"stat-".concat(di.VIDEO_ENCODE_FAILED_DURING_CALL)})}else this._videoAbnormalTimestampMap.set("local-encode",s);else{let o=this._videoAbnormalTimestampMap.get("local-encode");o&&s-o>=this.ABNORMAL_TIME_UPPER_LIMIT&&dt.uploadEvent({userId:this._room.userId,log:"stat-".concat(di.VIDEO_ENCODE_RESUME_DURING_CALL)}),this._videoAbnormalTimestampMap.delete("local-encode")}})}if(e.msg_up_stream_info.msg_audio_status){let t=e.msg_up_stream_info.msg_audio_status,i=Array.from(this._room.localTracks).find(s=>s.kind==="audio"),r=i?.stat.bytesSent||0;if(i?.isMediaTrackActive===!1||r<=0||i!=null&&i.isUseCustomSource)return;let n=Ue();if(t.uint32_audio_codec_bitrate===0&&i!=null&&i.isPublished)if(this._audioAbnormalTimestampMap.has("local-encode")){let s=this._audioAbnormalTimestampMap.get("local-encode");s&&n-s>this.ABNORMAL_TIME_LOWER_LIMIT&&n-s<this.ABNORMAL_TIME_UPPER_LIMIT&&dt.uploadEvent({userId:this._room.userId,log:"stat-".concat(di.AUDIO_ENCODE_FAILED_DURING_CALL)})}else this._audioAbnormalTimestampMap.set("local-encode",n);else{let s=this._audioAbnormalTimestampMap.get("local-encode");s&&n-s>=this.ABNORMAL_TIME_UPPER_LIMIT&&dt.uploadEvent({userId:this._room.userId,log:"stat-".concat(di.AUDIO_ENCODE_RESUME_DURING_CALL)}),this._audioAbnormalTimestampMap.delete("local-encode")}}}stopDataFreeze(e){let{key:t,userId:i,type:r}=e,n=this._dataFreezeMap.get(t);if(!n||!n.isFreezing())return;let s=n.durationItemList[n.durationItemList.length-1];s.stop();let o=s.getDuration();if(o>o0){let l=this._monitorFreezeData.get(t,"data");this._monitorFreezeData.set(t,{userId:i,type:r,duration:l?l.duration+o:o},"data")}else n.durationItemList.pop()}getTotalDuration(e){return e.reduce((t,i)=>{let r=i.getDuration();return t+Math.min(r,5e3)},0)}onPlayTrackStart(e){let{track:t}=e;if(!t.isRemote||!this.hitTest(t.room)||t.kind!==D.VIDEO||!t.isRemotePublished)return;let i="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.has(i)||this._isVideoPlayingEventFiredMap.set(i,!1)}getDataFreezeDuration(e){let t={dataFreeze:0,count:0},i=this._dataFreezeMap.get(e);if(i){if(i.isFreezing()){let r=i.durationItemList[i.durationItemList.length-1];r.stop(),r.getDuration()<o0&&i.durationItemList.pop()}t.dataFreeze=this.getTotalDuration(i.durationItemList),t.count=i.durationItemList.length}return t}getRenderFreezeDuration(e){let t={renderFreeze:0,count:0},i=this._renderFreezeMap.get(e);return i&&(t.renderFreeze=i.totalDuration,t.count=i.count),t}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(e){return!!this._isVideoPlayingEventFiredMap.has(e)&&!this._isVideoPlayingEventFiredMap.get(e)}onRemoteVideoPlayStart(e){let{track:t,player:i}=e;var r;if(!zc())return;let n=0,s=()=>{document.hidden||(n=0)};document.addEventListener("visibilitychange",s);let o=(l,c)=>{var h;if(n){let _=t.decodeFPS,f=_>0&&_<=5?600+1e3/_:600,T=c.presentationTime-n;if(T>f){T=Math.min(T,5e3);let b="".concat(t.userId,"_").concat(t.streamType),C=this._monitorFreezeData.get(b,"render");C?C.duration+=T:this._monitorFreezeData.set(b,{userId:t.userId,type:t.streamType,duration:T},"render");let x=this._renderFreezeMap.get(b);x?(x.totalDuration+=T,x.count+=1):this._renderFreezeMap.set(b,{userId:t.userId,type:t.streamType,totalDuration:T,count:1})}}n=c.presentationTime,(h=i.element)==null||h.requestVideoFrameCallback(o)};(r=i.element)==null||r.requestVideoFrameCallback(o),this.eventListenerMap.set("".concat(t.userId,"_").concat(t.streamType),{onVisibilityChange:s})}onRemoteVideoPlayEnd(e){let{track:t,player:i}=e,r="".concat(t.userId,"_").concat(t.streamType),n=this.eventListenerMap.get(r);n&&document.removeEventListener("visibilitychange",n.onVisibilityChange)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(e){return e===this._room}destroy(){this.uninstallEvents()}},ez=ti(Ri(),1),tz=class{constructor(e,t,i,r,n){let s=arguments.length>5&&arguments[5]!==void 0?arguments[5]:1.3333333333333333;this.vbMode=e,this.faceDetectorHash=i,this.visionTaskRegistry=r,this.logger=n,m(this,"animationState"),m(this,"originalAspect"),m(this,"totalOffsetX",0),m(this,"totalOffsetY",0),m(this,"defaultScaleRatio",.1),m(this,"isRecovering",!1),m(this,"boundaryY",280),m(this,"lastActionTime",0),m(this,"restTime",400),this.animationState={current:null,target:null,animating:!1,debounceTimer:null,startTime:0,duration:3e3,debounceTime:150,movementThreshold:30,debounceThreshold:15},this.addEvent(this.vbMode,!!this.faceDetectorHash),this.originalAspect=s||4/3,this.visionTaskRegistry.setVideo(this.faceDetectorHash,t)}addEvent(e,t,i){let r=[{key:570704,error:i??(t?void 0:11)},{key:570705,error:i??(t?void 0:22)}][e-1];r&&(t?ce.addSuccessEvent({key:r.key}):ce.addFailedEvent({key:r.key,error:r.error}))}actionCentering(e){let t=Date.now();if(this.animation(),!this.faceDetectorHash||t-this.lastActionTime<this.restTime||this.animationState.animating)return;let{videoWidth:i,videoHeight:r}=e;this.animationState.debounceThreshold=i/30,this.animationState.movementThreshold=i/20,this.boundaryY=.6*r;try{let n=this.visionTaskRegistry.getResult(this.faceDetectorHash);if(n.detections.length<=0)return void(this.vbMode===1&&this.recoverOriginal(i,r));let s=n.detections[0].boundingBox,o=s.originX,l=s.originY,c=s.width,h=s.height;this.vbMode===1?this.dualStageCropping(i,r,o,l,c,h):this.vbMode===2&&this.movingPortrait(i,r,o,l,c,h)}catch(n){this.logger.error(n)}this.lastActionTime=t}calculateBoundary(e,t,i,r){let n,s;return e>t/2?(n=t-i-r,s=i-n):(n=i,s=0),{min:n,offset:s}}calculateTargetPosition(e,t,i,r,n,s){let o,l,c=arguments.length>6&&arguments[6]!==void 0?arguments[6]:.4,h=e+i/2,_=t+r/2,{min:f,offset:T}=this.calculateBoundary(h,n,e,i),{min:b,offset:C}=this.calculateBoundary(_,s,t,r);return o=2*f+i,l=2*b+r,o/l>this.originalAspect?(o=l*this.originalAspect,T=h-o/2):(l=o/this.originalAspect,C=_-l/2),i/n>c&&(T=0,C=0,o=n,l=s),T=Math.max(0,Math.min(T,n-o)),C=Math.max(0,Math.min(C,s-l)),{sx:T,sy:C,cropWidth:o,cropHeight:l,timestamp:Date.now()}}processFacePositionCrop(e,t,i){if(!this.animationState.current||!this.animationState.target){let o={sx:0,sy:0,cropWidth:t,cropHeight:i,timestamp:Date.now()};return this.animationState.current=o,void(this.animationState.target=o)}let r=this.positionDistance(this.animationState.target,e),n=this.positionDistance(this.animationState.current,e),s=this.animationState.current.cropWidth/t;r>this.animationState.debounceThreshold*s&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&n>this.animationState.movementThreshold*s&&(this.animationState.target=e,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}processFacePositionPortrait(e){if(!this.animationState.current||!this.animationState.target)return this.animationState.current=ve({},e),void(this.animationState.target=ve({},e));let t=this.positionDistance(this.animationState.current,e),i=this.positionDistance(this.animationState.target,e);t>this.animationState.debounceThreshold&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&i>this.animationState.movementThreshold&&(this.animationState.current=e,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}animation(){if(!this.animationState.animating)return;let e=Date.now()-this.animationState.startTime,t=Math.min(e/this.animationState.duration,1),i=r=>r<.5?2*r*r:(4-2*r)*r-1;if(this.animationState.current&&this.animationState.target){let r=(this.animationState.target.sx-this.animationState.current.sx)*i(t);this.animationState.current.sx+=r,this.totalOffsetX+=r;let n=(this.animationState.target.sy-this.animationState.current.sy)*i(t);if(this.animationState.current.sy+=n,this.totalOffsetY+=n,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*i(t),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*i(t),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*i(t)),nt(this.animationState.current.scaleOffsetX)&&nt(this.animationState.target.scaleOffsetX)&&nt(this.animationState.current.scaleOffsetY)&&nt(this.animationState.target.scaleOffsetY)){let s=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*i(t);this.animationState.current.scaleOffsetX+=s;let o=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*i(t);this.animationState.current.scaleOffsetY+=o}}t>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(e,t){return Math.sqrt(sc(e.sx-t.sx,2)+sc(e.sy-t.sy,2))}recoverOriginal(e,t){this.animationState.target={sx:0,sy:0,cropWidth:e,cropHeight:t,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(e,t,i,r,n,s){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:.3;if(this.isRecovering)return;let l=this.calculateTargetPosition(i,r,n,s,e,t);this.processFacePositionCrop(l,e,t),n*s/l.cropWidth/l.cropHeight>o&&this.recoverOriginal(e,t)}movingPortrait(e,t,i,r,n,s){var o,l,c,h,_,f,T,b,C,x,B,Y;let G={sx:i+n/2+this.totalOffsetX,sy:r+s/2+this.totalOffsetY,cropWidth:e,cropHeight:t,scaleRatio:(l=(o=this.animationState.current)==null?void 0:o.scaleRatio)!=null?l:1,scaleOffsetX:(h=(c=this.animationState.current)==null?void 0:c.scaleOffsetX)!=null?h:0,scaleOffsetY:(f=(_=this.animationState.current)==null?void 0:_.scaleOffsetY)!=null?f:0,timestamp:Date.now()};this.animationState.target={sx:e/2,sy:r+s/2,cropWidth:e,cropHeight:t,scaleRatio:(b=(T=this.animationState.target)==null?void 0:T.scaleRatio)!=null?b:1,scaleOffsetX:(x=(C=this.animationState.target)==null?void 0:C.scaleOffsetX)!=null?x:0,scaleOffsetY:(Y=(B=this.animationState.target)==null?void 0:B.scaleOffsetY)!=null?Y:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(n*s/e/t/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=1-this.animationState.target.scaleRatio,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio<this.boundaryY&&(this.animationState.target.scaleOffsetY=(this.animationState.target.sy-this.boundaryY*this.animationState.target.scaleRatio)/this.animationState.target.cropHeight)),this.processFacePositionPortrait(G)}set aspectRatio(e){this.originalAspect=e}get current(){return this.animationState.current}get offset(){return{offsetX:this.totalOffsetX,offsetY:this.totalOffsetY}}get targetCrop(){return this.animationState.target}},iz=class extends Go{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,width:t.width,height:t.height,logger:e.log}),m(this,"_bgTexture"),m(this,"_waterMarkTexture"),m(this,"_lastMaskTexture"),m(this,"_lastMaskFbo"),m(this,"_textureValid",!1),m(this,"_selfieTextureValid",!1),m(this,"_selfieSegmentationHash"),m(this,"wasm"),m(this,"predictReady"),m(this,"_color"),m(this,"_prePrograme"),m(this,"_segmentationMask"),m(this,"_weixin",!1),m(this,"_centerFace"),m(this,"_textureMatrixLocation"),m(this,"_offsetMatrixLocation"),m(this,"_colorLocation"),m(this,"_enableFaceCentering",!1),m(this,"_enableEffectOptimization",!1),m(this,"_mat4"),m(this,"_postProcessing"),m(this,"_onAbort"),m(this,"_visionTaskRegistry"),m(this,"resolvePreditReady"),this.init(t).catch(i=>{e.log.error(i),e.destroy(new me({code:te.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(i.message||i)})),this.resolvePreditReady()})}init(e){return P(this,null,function*(){var t,i,r;this.predictReady=new Promise(l=>{this.resolvePreditReady=l});let n=e.Wasm,s=this.context.ctx;if(e.color&&(this._color=e.color),e.mat4&&(this._mat4=e.mat4),e.postProcessing&&(this._postProcessing=e.postProcessing),this._enableFaceCentering=(t=e.enableFaceCentering)!=null&&t,this._enableEffectOptimization=(i=e.enableEffectOptimization)!=null&&i,this.wasm=new n.AllIn1(s),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.rotation=e.rotation||0,this.wasm.vbMode=e.bg==="blur"?1:e.bg instanceof HTMLImageElement?2:e.bg==="color"?3:0,this._onAbort=e.onAbort,e.bg||this.resolvePreditReady(),e.waterMark){let{x:l,y:c,width:h,height:_}=e.waterMark;this.wasm.setWaterMark(l,c,h,_)}if(e.beautyParams){let{beauty:l,brightness:c,ruddy:h}=e.beautyParams;this.wasm.setBeauty(l,c,h,e?.width,e?.height)}this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),s.uniform1i(s.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(s.uniform1i(s.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(s.uniform1i(s.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image));let o=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(this._textureMatrixLocation=s.getUniformLocation(this.program,"u_textureMatrix"),s.uniformMatrix4fv(this._textureMatrixLocation,!1,o),this._offsetMatrixLocation=s.getUniformLocation(this.program,"u_offsetMatrix"),s.uniformMatrix4fv(this._offsetMatrixLocation,!1,o),this._colorLocation=s.getUniformLocation(this.program,"u_color"),s.uniform1i(s.getUniformLocation(this.program,"lastMask"),4),this._weixin){let l=this.context.createShader(s.FRAGMENT_SHADER,`#version 300 es
110
+ precision highp float;
111
+ uniform sampler2D u_texture;
112
+ uniform sampler2D mask;
113
+
114
+ in vec2 v_texCoord;
115
+ out vec4 outColor;
116
+ void main() {
117
+ outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);
118
+ }`),c=this.context.createShader(s.VERTEX_SHADER,`#version 300 es
119
+ in vec2 a_position;
120
+ in vec2 a_texCoord;
121
+ out vec2 v_texCoord;
122
+ void main() {
123
+ gl_Position = vec4(a_position.x, a_position.y, 0, 1);
124
+ v_texCoord = a_texCoord;
125
+ }`);this._prePrograme=this.context.createProgram(c,l),s.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),s.uniform1i(s.getUniformLocation(this._prePrograme,"mask"),1)}!this._enableEffectOptimization||this.wasm.vbMode!==2&&this.wasm.vbMode!==3?this._postProcessing=void 0:iv()?(this._postProcessing=void 0,this.log.warn("Virtual background post-processing isn't allowed on mobile.")):(r=this._postProcessing)==null||r.init(s,this.positionBuffer,this.texCoordBuffer,4/3),yield this.initVisionTasks(e)})}initVisionTasks(e){return P(this,null,function*(){if(e.bg){if(this._visionTaskRegistry=yield window.VisionTaskRegistry.getInstance(),!window.VisionTaskRegistry||!this._visionTaskRegistry||!this._visionTaskRegistry.visionWasm)throw new Error("Virtual background assets not found. Please redeploy the assets of the npm package.");if(this._selfieSegmentationHash=yield this._visionTaskRegistry.register(window.VisionTaskType.ImageSegmenter,{canvas:this.context._canvas}),this._visionTaskRegistry.setVideo(this._selfieSegmentationHash,this.image),this._enableFaceCentering)try{this._visionTaskRegistry.models.has(window.VisionTaskType.FaceDetector)||(yield this._visionTaskRegistry.preloadModels([window.VisionTaskType.FaceDetector]));let t=yield this._visionTaskRegistry.register(window.VisionTaskType.FaceDetector);if(!t)return;this._centerFace=new tz(this.wasm.vbMode,this.image,t,this._visionTaskRegistry,this.context.log)}catch{this.log.error("Face detector model not found. Please redeploy the assets of the npm package.")}}})}onPredict(e){let t=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture)));let i=this.getMaskTexture(e);if(!i)return;let r=i;this._postProcessing&&(this._postProcessing.ratio=this.image.videoWidth/this.image.videoHeight,r=this._postProcessing.postProcessing(i)),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),this.useTexture(),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,r||null),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),this.wasm.vbMode===3&&t.uniform3fv(this._colorLocation,this._color),this.useBufferFrame(),this._segmentationMask=e,this.totalFrames++,this.centerFace(),ls(this.wasm.rotation)&&this.resize(this.image.height,this.image.width),t.viewport(0,0,t.canvas.width,t.canvas.height),t.drawArrays(t.TRIANGLE_STRIP,0,4),e.close()}getMaskTexture(e){return e.confidenceMasks?e.confidenceMasks[0].getAsWebGLTexture():void 0}onFirstFrame(){this.waitingFirstFrame=!1;let e=this.context.ctx;this.useTexture(),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)}render(e){let t=this.context.ctx,{image:i}=this;this.tryVideoFrameCallback();let{videoWidth:r,videoHeight:n}=i;if(ls(this.wasm.rotation)&&!this._visionTaskRegistry&&([r,n]=[n,r]),r===0||n===0||!this.available)return!1;i.width=r,i.height=n;let s=!1;if(this.totalFrames)this.useTexture(),s=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),s=this._textureValid,this._textureValid=!0}if(this.width===r&&this.height===n&&s?t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,i):(this.resize(r,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,i)),this._weixin){if(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask){let o=this.getMaskTexture(this._segmentationMask);t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,o||null),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)}t.drawArrays(t.TRIANGLE_STRIP,0,4),this.useTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,r,n):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,r,n,0)}try{if(this._selfieSegmentationHash&&this._visionTaskRegistry){let o=this._visionTaskRegistry.getResult(this._selfieSegmentationHash);this.totalFrames===1&&this.context._canvas&&this.resolvePreditReady(),this.onPredict(o)}}catch(o){this._onAbort&&this._onAbort(o)}return this.totalFrames||(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.drawArrays(t.TRIANGLE_STRIP,0,4)),this._visionTaskRegistry&&this._visionTaskRegistry.resetHashResults(),!1}centerFace(){if(!this._centerFace||!this._enableFaceCentering)return;let e=this.context.ctx;this._centerFace.aspectRatio=e.canvas.width/e.canvas.height,this._centerFace.actionCentering(this.image);let{current:t,offset:i}=this._centerFace;if(t&&(this.wasm.vbMode===1&&this.drawImage(t.sx,t.sy,t.cropWidth,t.cropHeight),i&&this.wasm.vbMode===2)){if(!this._mat4)return;let r=this._mat4.create(),{scaleRatio:n=1,scaleOffsetX:s=0,scaleOffsetY:o=0}=t;this._mat4.fromTranslation(r,[-i.offsetX/e.canvas.width+s,o,0]),this._mat4.scale(r,r,[n,n,1]),e.uniformMatrix4fv(this._offsetMatrixLocation,!1,r)}}drawImage(e,t,i,r){let n=this.context.ctx;if(!this._mat4)return;let{width:s,height:o}=n.canvas,l=this._mat4.create();this._mat4.fromTranslation(l,[e/s,1-(t+r)/o,0]),this._mat4.scale(l,l,[i/s,r/o,1]),n.uniformMatrix4fv(this._textureMatrixLocation,!1,l)}close(){var e;super.close();let t=this.context.ctx;this._bgTexture&&t.deleteTexture(this._bgTexture),this._waterMarkTexture&&t.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&t.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&t.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&t.deleteProgram(this._prePrograme),this._postProcessing&&this._postProcessing.close(),(e=this.wasm)==null||e.close()}},rz=class extends Gi{constructor(e){super(e,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:e.log,fragmentShaderSource:`
126
+ precision highp float;
127
+ uniform sampler2D ySampler;
128
+ uniform sampler2D uSampler;
129
+ uniform sampler2D vSampler;
130
+ varying highp vec2 textureCoord;
131
+ const mat4 YUV2RGB = mat4(
132
+ 1.1643828125, 0, 1.59602734375, -.87078515625,
133
+ 1.1643828125, -.39176171875, -.81296875, .52959375,
134
+ 1.1643828125, 2.017234375, 0, -1.081390625,
135
+ 0, 0, 0, 1);
136
+ void main() {
137
+ vec3 yuv;
138
+ yuv.r = texture2D(ySampler, textureCoord).r;
139
+ yuv.g = texture2D(uSampler, textureCoord).r;
140
+ yuv.b = texture2D(vSampler, textureCoord).r;
141
+ gl_FragColor = vec4(yuv,1) * YUV2RGB;
142
+ }
143
+ `,vertexShaderSource:`
144
+ attribute vec4 vertexPos;
145
+ attribute vec2 texturePos;
146
+ varying vec2 textureCoord;
147
+ void main() {
148
+ gl_Position = vertexPos;
149
+ textureCoord = texturePos;
150
+ }`}),m(this,"yTextureRef"),m(this,"uTextureRef"),m(this,"vTextureRef"),m(this,"Y"),m(this,"U"),m(this,"V"),this.useProgram();let t=this.context.ctx;t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=e._canvas}_initTexture(e,t){let i=this.context.ctx,r=i.createTexture();return i.bindTexture(i.TEXTURE_2D,r),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.bindTexture(i.TEXTURE_2D,null),i.uniform1i(i.getUniformLocation(this.program,e),t),r}render(e){let t=this.context.ctx,i=this.width,r=this.height;return this.useProgram(),t.viewport(0,0,i,r),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.yTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,i,r,t.LUMINANCE,t.UNSIGNED_BYTE,this.Y),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.uTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,i/2,r/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.U),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.vTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,i/2,r/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(e,t){super.resize(e,t);let i=this.context.ctx;i.activeTexture(i.TEXTURE0),i.bindTexture(i.TEXTURE_2D,this.yTextureRef),i.texImage2D(i.TEXTURE_2D,0,i.LUMINANCE,e,t,0,i.LUMINANCE,i.UNSIGNED_BYTE,null),i.activeTexture(i.TEXTURE1),i.bindTexture(i.TEXTURE_2D,this.uTextureRef),i.texImage2D(i.TEXTURE_2D,0,i.LUMINANCE,e/2,t/2,0,i.LUMINANCE,i.UNSIGNED_BYTE,null),i.activeTexture(i.TEXTURE2),i.bindTexture(i.TEXTURE_2D,this.vTextureRef),i.texImage2D(i.TEXTURE_2D,0,i.LUMINANCE,e/2,t/2,0,i.LUMINANCE,i.UNSIGNED_BYTE,null)}},DN=(e,t)=>{switch(e){case"webCodecs":return t==="videoFrame"?514705:514706;case"wasm":return t==="webgl"?514707:t==="videoFrame"?514708:514709}throw new Error("decoder type not supported")},nz=0,sz=class{constructor(e){m(this,"id",nz++),m(this,"trackDoneOB"),m(this,"startOB"),m(this,"stopOB"),m(this,"decoder"),m(this,"videoContext"),m(this,"gop",0),m(this,"gop_helper",0),m(this,"waitFirstKeyFrame",!0),m(this,"startTimestamp",0),m(this,"startTime",0),m(this,"startPerformanceTime",0),m(this,"inputFrameCount",0),m(this,"decodedFrameCount",0),m(this,"decodeFrameCount",0),m(this,"downgradeLevel",0),m(this,"lastDowngradeTime",0),m(this,"lastFrameDiff",0),m(this,"lastDecodeFrameTimestamp",0),m(this,"config"),m(this,"gop_before_configure",[]),m(this,"videoElement"),m(this,"type","wasm"),m(this,"goodType"),m(this,"renderer","2d"),m(this,"wasmOption"),m(this,"createDecoder"),m(this,"_decodeSink"),m(this,"isReported",!1),m(this,"track"),m(this,"stateChangeOB"),m(this,"failedReason");let{track:t,createDecoder:i}=e;if(this.stateChangeOB=zr(),this.track=t,this.createDecoder=i,this.wasmOption={yuvMode:e.renderer==="webgl",wasmPath:e.wasmPath,workerMode:e.workerMode,canvas:e.canvas},this.config=e.config,this.videoElement=e.videoElement,this.renderer=e.renderer,this.trackDoneOB=St(t.availableState,et.OFF),this.stopOB=zr(),e.type==="auto"){switch(e.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode=this.renderer==="webgl"}else this.type=e.type;this.changeRenderer(this.renderer),At(this.stateChangeOB,fD((r,n)=>(r!==n&&t.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:r,state:n}),n),"INITIALIZED"),Ci(this.stopOB),Qt()),this.start()}start(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let t=At(this.pipe(this.track),Ci(this.stopOB),nu());At(t,Qt(()=>{this.track.stat.framesDecoded++},i=>{if(this.track.log.error("".concat(this.id," play failed: ").concat(i," retryCount: ").concat(e)),ce.addFailedEvent({key:DN(this.type,this.renderer),error:i}),e>4)this.failedReason=i,this.stateChangeOB.next("FAILED"),ce.addFailedEvent({key:514704});else{if(this.goodType)return void this.start(e);switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":this.renderer==="webgl"&&this.changeRenderer("videoFrame")}this.start(e+1)}},()=>{this.track.log.warn("".concat(this.id," decoderOB completed")),ce.addSuccessEvent({key:DN(this.type,this.renderer)}),ce.addSuccessEvent({key:514704})})),At(t,Wo(1),Qt(()=>{this.track.player.handlePlaying("canvas"),this.goodType=this.type,this.stateChangeOB.next("STARTED")}))}mock(e){this._decodeSink?this._decodeSink.error(e):this.start()}close(e){this.stopOB.next(e)}changeRenderer(e){this.renderer=e,this.renderer==="videoFrame"&&!hv()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(e){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];var i,r;if(this.failedReason)return;this.inputFrameCount++;let n=new Uint8Array(e.data);if((s=n)[0]!==0||s[1]!==0||s[2]!==0||s[3]!==1||n.length<5)return this.stateChangeOB.next("FAILED"),this.close("not h26x frame ".concat(n.subarray(0,5))),e;var s;let o=!1;switch(31&n[4]){case 5:case 7:o=!0}if(((i=this.decoder)==null?void 0:i.state)!=="configured")return this.track.log.debug("not configured ".concat(this.inputFrameCount)),o&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:e.data,timestamp:e.timestamp,type:e.type}),e;this.gop_before_configure.length>0&&!t&&(this.gop_before_configure.forEach(c=>this.decode(c,!0)),this.gop_before_configure=[]);let{timestamp:l}=e;if(o?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame){if(!o)return void this.track.log.debug("wait first key frame ".concat(this.inputFrameCount," ").concat(n.subarray(0,5).join(" ")));this.waitFirstKeyFrame=!1,this.startTimestamp=l,this.startTime=Date.now(),this.startPerformanceTime=Ue()}switch(this.downgradeLevel){case 0:case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}return(this.decodeFrameCount<10||this.decodeFrameCount%500==0)&&this.track.log.debug("decode ".concat(this.decodeFrameCount," gop: ").concat(this.gop," ").concat(l," ").concat((r=e.getMetadata)==null?void 0:r.call(e).rtpTimestamp)),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=l,void this.decoder.decode({data:e.data,type:e.type,timestamp:this.lastDecodeFrameTimestamp})}return e}checkDowngradeByFrameDiff(){let e=this.downgradeLevel,t=this.decodeFrameCount-this.decodedFrameCount;t>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):t<=this.lastFrameDiff&&this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==e&&this.track.log.debug("downgrade level ".concat(e," to ").concat(this.downgradeLevel," ").concat(this.decodeFrameCount," frameDiff: ").concat(t,", lastFrameDiff: ").concat(this.lastFrameDiff)),this.lastFrameDiff=t,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(e){let t=this.downgradeLevel;this.lastDecodeFrameTimestamp-e>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==t&&this.track.log.debug("downgrade level ".concat(t," to ").concat(this.downgradeLevel))}pipe(e){return t=>P(this,null,function*(){this._decodeSink=t;let i,r=e.mediaTrack;t.defer(()=>{var o;r&&(e.player.setCanvas(),e.setInputMediaStreamTrack(r)),i?.close(),(o=this.videoContext)==null||o.destroy(),delete this._decodeSink});let{renderer:n,type:s}=this;e.log.info("decoder type: ".concat(this.type," renderer: ").concat(this.renderer));try{switch(s){case"wasm":i=this.createDecoder(s,this.wasmOption);break;case"webCodecs":i=this.createDecoder(s);break;default:throw new Error("not supported yet")}let o=0;if(i.on("videoFrame",l=>{this.decodedFrameCount++,o++,(o<=10||o%500==0)&&e.log.debug("frame ".concat(o," ").concat(this.decodedFrameCount,"/").concat(this.decodeFrameCount," decoded ").concat(l.timestamp)),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(l.timestamp)),t.next(l)}),i.on("error",l=>{e.log.error(l),t.error(s==="webCodecs"?4:8)}),yield i.initialize(this.videoElement),!this._decodeSink)return;if(i.configure(this.config),s==="wasm"&&n==="webgl"){this.videoContext=new ur({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create(),this.videoContext.on(ur.UNAVAILABLE,c=>{e.log.error(c),t.error(7)});let l=new rz(this.videoContext);i.on("videoCodecInfo",c=>l.resize(c.width,c.height)),i.on("videoFrame",c=>{({y:l.Y,u:l.U,v:l.V}=c),this.downgradeLevel===1?this.decodedFrameCount%2==0&&l.render(this.decodedFrameCount):l.render(this.decodedFrameCount)}),e.source=l,e.player.setCanvas(this.videoContext._canvas,2)}else if(n==="videoFrame"){e.player.setCanvas();let l=new MediaStreamTrackGenerator({kind:"video"}),c=l.writable.getWriter();e.setInputMediaStreamTrack(l),i.on("videoFrame",h=>c.write(h))}else{this.videoContext=new Kr({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create({alpha:!1});let l=this.videoContext.createVideoImageSource();i.on("videoFrame",h=>{try{l.image=h,l.update()}catch(_){delete this.goodType,e.log.error(_),t.error(11)}});let c=new $v(this.videoContext,{name:"remotePlayer",logger:e.log});l.connect(c),e.source=l,e.player.setCanvas(this.videoContext._canvas,2)}this.decoder=i}catch(o){e.log.error(o),t.error(s==="webCodecs"?2:6)}})}},NN=Promise.resolve(),PN=class extends ez.EventEmitter{constructor(e){super(),this.room=e,m(this,"videoContext"),m(this,"_glVideoContext"),m(this,"_2dVideoContext"),m(this,"destination"),m(this,"smallVideoContext"),m(this,"smallDestination"),m(this,"smallTrackSource"),m(this,"smallImageSource"),m(this,"_isMirror",!1),m(this,"_rotation",0),m(this,"cameraTrack"),m(this,"cameraNode"),m(this,"transformNode"),m(this,"mixNode"),m(this,"screenTrack"),m(this,"screenNode"),m(this,"selfModel",!1),m(this,"blurRadius",3),m(this,"arTrack"),m(this,"_enableFaceCentering",!1),m(this,"_enableEffectOptimization",!1),m(this,"onAbort"),m(this,"_color"),m(this,"Wasm"),m(this,"waterMarkNode"),m(this,"_waterMarkOption"),m(this,"watermarkImageList",[]),m(this,"_beautyParams"),m(this,"isUsingArTrack",!1),m(this,"mixTrack"),m(this,"_isMixScreen",!1),m(this,"_virtualBackground"),m(this,"_virtualBackgroundAbortCallback"),m(this,"virtualBackgroundInstance"),m(this,"_bgAssetPath"),m(this,"log"),m(this,"_mat4"),m(this,"_postProcessing"),m(this,"_checkId",0),m(this,"_use2d",!1),m(this,"_autoSwitchRenderMode",!0),m(this,"encodePipeline",[]),m(this,"decodePipeline",[]),m(this,"updated",NN),m(this,"_updateFlag",!1),this.log=fe.createLogger({parent:e?.getLogger(),id:"vm",userId:e?.userId,sdkAppId:e?.sdkAppId}),this.smallVideoContext=new Kr({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get smallMode(){var e;return((e=this.room)==null?void 0:e.smallMode)||"canvas"}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get _isRotate(){return this._rotation!==0}get _isTransform(){return this._isMirror||this._isRotate}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode=e==="auto",this._autoSwitchRenderMode)return;let t=e==="2d";this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get cameraResolution(){var e;let{width:t,height:i}=((e=this.cameraTrack)==null?void 0:e.settings)||{};return ls(this._rotation)?{width:i,height:t}:{width:t,height:i}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Kr({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(this._glVideoContext){if(this._glVideoContext.available)return this._glVideoContext}else this._glVideoContext=new ur({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(Y2<=22),this._glVideoContext.on(ur.UNAVAILABLE,e=>{var t;this.emit("error",e),this.log.warn("video context unavailable",e),(t=this._virtualBackgroundAbortCallback)==null||t.call(this,e),this.update().catch(i=>{this.log.error(i)})})}catch(e){this.emit("error",e)}}initVirtualBackground(e,t,i){this.onAbort=e,this._mat4=t,this._postProcessing=i}enablePrintDetail(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3;this._checkId=ft.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,t;(e=this._2dVideoContext)==null||e.destroy(),(t=this._glVideoContext)==null||t.destroy(),this.smallVideoContext.destroy(),ft.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(pa||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(){let e=arguments.length>1?arguments[1]:void 0,t=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:"videoCtxGl")==="videoCtxGl"?512700:512701;e?ce.addFailedEvent({key:t,error:e}):ce.addSuccessEvent({key:t})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else{if(!t||!this._use2d)return!0;this.clear()}}else{if(this._glVideoContext=new ur({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}setSmallVideo(e,t){if(this.smallMode!=="api")if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new MG(this.smallVideoContext,e,this.log),this.smallVideoContext.on(ur.UNAVAILABLE,i=>{this.log.warn("small video context lost",i)})}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,t)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=t:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(t),this.smallImageSource.resize(t.width,t.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:i,height:r}=this.cameraTrack.settings;this.smallTrackSource.resize(i,r),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(e){var t;try{let i=this.cameraTrack,{small:r,player:n}=i;pa&&n.setCanvas(e);let s=e&&((t=this.destination)==null?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),s=this.arTrack),this.log.info("set main output ".concat(s?s.label:"no output track")),this.setSmallVideo(r,e),i.setOutputMediaStreamTrack(s)}catch(i){this.log.error("set main output failed",i)}}update(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return P(this,null,function*(){var t;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:i,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams)this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(Gi.RENDER,n=>{var s;(s=this.cameraTrack)==null||s.emit("render",n)})),Sr===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Go?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof Go?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(i.width,i.height);else if(e&&this.cameraNode&&this.destination)this.cameraNode.replaceTrack(this.initialTrack);else{this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():(this.destination=new OG(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(Gi.RENDER,l=>{var c;(c=this.cameraTrack)==null||c.emit("render",l)}));let{width:n,height:s}=this.cameraResolution,o=yield this.getWatermarkImage(n,s);this._waterMarkOption={x:0,y:0,width:o.width,height:o.height,image:o},this.cameraNode=new iz(this.videoContext,{input:this.initialTrack,width:n,height:s,mirror:this._isMirror,rotation:this._rotation,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,Wasm:this.Wasm,enableFaceCentering:this._enableFaceCentering,enableEffectOptimization:this._enableEffectOptimization,onAbort:this.onAbort,mat4:this._mat4,postProcessing:this._postProcessing,color:this._color}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute(),yield this.cameraNode.predictReady}if(this.videoContext.frameRate=r.frameRate,this._use2d){let n=this.cameraNode;if(n.disconnect(),this._isTransform&&(this.transformNode?(this.transformNode.mirror=this._isMirror,this.transformNode.rotation=this._rotation):this.transformNode=new gs(this.videoContext,this.log,this._isMirror,this._rotation),n=n.connect(this.transformNode),n.disconnect(),this.log.info("start mirror ".concat(this._isMirror," rotate ").concat(this.rotation))),this.mixNode&&this.mixNode.close(),delete this.mixNode,this._isMixScreen||this._hasWaterMark){if(this.mixNode=new kD(this.videoContext,this.log),n.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption)this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y;else if(this.waterMarkNode){let{width:s,height:o}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(s,o),s&&o&&this.waterMarkNode.resize(s,o)}(t=this.waterMarkNode)==null||t.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&(this.screenNode||(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource"),this.screenNode.resize(this.screenTrack.settings.width,this.screenTrack.settings.height)),this.screenNode.shouldUpdate=!1,this.screenNode.connect(this.mixNode,{zIndex:0})),n=this.mixNode,this.log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height))}n.connect(this.destination)}return this.log.info("update ".concat(this._use2d?"2d":"webgl")),this._setMainOutput(this.videoContext.canvas)})}clearLastFrame(){var e;this.destination&&((e=this.destination.ctx2d)==null||e.clearRect(0,0,this.destination.width,this.destination.height))}changeInput(e){var t,i,r,n,s;if(e instanceof Ra)return this.log.info("change screen input",(t=e.mediaTrack)==null?void 0:t.label),this.setScreenTrack(e);if(e instanceof Rn)return this.log.info("change video input",(i=e.mediaTrack)==null?void 0:i.label),this.setCameraTrack(e);if(e instanceof mu){this.log.info("change remote input",(r=e.mediaTrack)==null?void 0:r.label);let o=e.mediaTrack;return e.setOutputMediaStreamTrack(o)}if(e instanceof tE)return this.log.info("change mix input",(n=e.outMediaTrack)==null?void 0:n.label),this.setMixTrack(e);this.log.warn("change unknown input",(s=e.mediaTrack)==null?void 0:s.label)}removeInput(e){var t;e instanceof Ra?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof Rn?this._isMixScreen?(delete this.cameraNode,this.cameraTrack._inputTrack=null,this.update()):(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof mu?e.source&&e.source.context.destroy():e instanceof tE&&(delete this.mixTrack,this.update())}setMixTrack(e){this.mixTrack=e}setCameraTrack(e){return this.cameraTrack=e,this.update(!0)}setScreenTrack(e){return P(this,null,function*(){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):yield this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)})}getWatermarkImage(e,t){return P(this,null,function*(){let i=document.createElement("canvas");t&&e&&(i.height=t,i.width=e);let r=i.getContext("2d");if(!r)throw new me({code:te.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,s)=>n.zIndex-s.zIndex),this.watermarkImageList.forEach(n=>{let{image:s,x:o,y:l,width:c,height:h,fillVideo:_}=n,f=_&&e||c,T=_&&t||h,b=_?0:o,C=_?0:l;r.drawImage(s,b,C,f,T)}),Ac(i.toDataURL())})}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some(i=>i.imageUrl===e.imageUrl&&i.height===e.height&&i.width===e.width&&i.x===e.x&&i.y===e.y&&i.type===e.type&&i.zIndex===e.zIndex&&i.fillVideo===e.fillVideo)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(i=>i.type!==t)),this.watermarkImageList.push(e))}setBeautyParams(e){return P(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return P(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return P(this,null,function*(){let t;try{t=yield Ac(e?.imageElement||e.imageUrl)}catch{throw new me({code:te.INVALID_PARAMETER,message:"load image failed, url: ".concat(e.imageUrl)})}let{x:i=0,y:r=0,width:n=t.width,height:s=t.height,type:o="watermark",zIndex:l=2,fillVideo:c=!1}=e;this.watermarkImageList.some(h=>h.type===o)?(this.watermarkImageList=this.watermarkImageList.filter(h=>h.type!==o),this.pushWaterMarkImageList({x:i,y:r,width:n,height:s,image:t,zIndex:l,type:o,imageUrl:e.imageUrl,fillVideo:c}),t=yield this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.height),this._waterMarkOption={x:0,y:0,width:t.width,height:t.height,image:t},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(t.width,t.height),this.waterMarkNode.image=t):this.update()):(this.pushWaterMarkImageList({x:i,y:r,width:n,height:s,image:t,zIndex:l,type:o,imageUrl:e.imageUrl,fillVideo:c}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(h,_)=>h==="imageUrl"?void 0:_))})}deleteWatermark(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"watermark";return P(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(t=>t.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList,(t,i)=>t==="imageUrl"?void 0:i)),yield this.freshWatermark()})}freshWatermark(){return P(this,null,function*(){var e;(e=this.waterMarkNode)==null||e.close(),delete this.waterMarkNode,delete this._waterMarkOption;let{width:t,height:i}=this.cameraResolution,r=yield this.getWatermarkImage(t,i);this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.update()})}setVirtualBackground(e){return P(this,null,function*(){var t,i,r;if(e){if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield Ac(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type),this._enableFaceCentering=(t=e.enableFaceCentering)!=null?t:this._enableFaceCentering,this._enableEffectOptimization=(i=e.enableEffectOptimization)!=null?i:this._enableEffectOptimization,this._color=(r=e.color)!=null?r:[0,1,0]}else delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;if(this.log.info("".concat(this._virtualBackground?"start":"stop"," virtual background, ").concat(e?.type||"",", ").concat(this.blurRadius||"")),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new me({code:te.INVALID_OPERATION,message:"webgl context create failed, ".concat(this._glVideoContext.error)})})}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||((t=this.screenNode)==null||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isTransform||((t=this.transformNode)==null||t.close(),delete this.transformNode),this.update())}get mirror(){return this._isMirror}set rotation(e){var t;this._rotation!==e&&(this._rotation=e,this._isTransform||((t=this.transformNode)==null||t.close(),delete this.transformNode),this.update())}get rotation(){return this._rotation}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return P(this,null,function*(){var e;(e=this.cameraTrack)!=null&&e.mediaTrack&&(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var e;this.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}createDecodeContext(e){return new sz(e)}clear(){var e,t;(e=this.videoContext)==null||e.disconnect(),(t=this.destination)==null||t.removeAllListeners(),delete this.destination,delete this.cameraNode,delete this.transformNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor(e){let{processor:t,type:i}=e;var r;this.encodePipeline.includes(t)||(this.encodePipeline[i]=t,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor(e){let{processor:t,type:i}=e;var r;this.decodePipeline.includes(t)||(this.decodePipeline[i]=t,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor(e){let{type:t}=e;this.encodePipeline[t]=void 0}removeDecodeProcessor(e){let{type:t}=e;this.decodePipeline[t]=void 0}};_e([Qw(function(e){this.log.error("update failed",e)}),_t(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return P(this,null,function*(){this._updateFlag||(this._updateFlag=!0,yield NN,this.updated=new Promise((n,s)=>{e.apply(this,i).then(n,s),setTimeout(s,5e3,new me({code:te.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],PN.prototype,"update");var az=0,oz=class extends et{constructor(e){super("room"),m(this,"seq",++az),m(this,"sdkAppId"),m(this,"userId"),m(this,"userSig"),m(this,"privateMapKey"),m(this,"latencyLevel"),m(this,"tinyId"),m(this,"scene"),m(this,"roomId"),m(this,"useStringRoomId"),m(this,"role","anchor"),m(this,"joinParams",null),m(this,"localPublishFlag",0),m(this,"localTracks",new Set),m(this,"enableAutoPlayDialog",!0),m(this,"autoReceiveAudio",!0),m(this,"autoReceiveVideo",!0),m(this,"proxy_ws"),m(this,"proxy_wt"),m(this,"proxy_unified"),m(this,"checkSystemResult",{result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0,isH265EncodeSupported:!0,isH265DecodeSupported:!0}}),m(this,"keyPointManager"),m(this,"audioManager"),m(this,"videoManager"),m(this,"callDurationCalculator"),m(this,"badCaseDetector"),m(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}),m(this,"videoDecodeFallbackType"),m(this,"smallMode","canvas"),m(this,"enableChorus",!1),m(this,"_isUsingCachedSchedule",!1),m(this,"_log"),m(this,"_joinedTimestamp",0),m(this,"_sdkType"),m(this,"heartbeatReport"),m(this,"heartbeatCount",0),m(this,"quality"),m(this,"enableSEI"),m(this,"isDestroyed",!1),this._log=fe.createLogger({parent:e.logger,id:"r".concat(this.seq)}),this.useStringRoomId=!!e.useStringRoomId,Rt(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),Rt(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),Rt(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new Xj({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new Qj({room:this}),this.badCaseDetector=new $j({room:this}),this.audioManager=new BG(this),this.videoManager=new PN(this)}get videoCodec(){return"h264"}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(4&e.mediaType)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(2&e.mediaType)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainAudioTrack(){for(let e of this.localTracks)if(1&e.mediaType)return e;return null}get localMainVideoTrack(){for(let e of this.localTracks)if(4&e.mediaType)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(2&e.mediaType)return e;return null}get publishState(){let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};return this.localTracks.forEach(t=>{if(t.isPublished||t.isPublishing)switch(t.mediaType){case 1:e.audio=!0;break;case 4:e.bigVideo=!0,e.smallVideo=t.hasSmall;break;case 2:e.auxVideo=!0}}),e}get muteState(){var e,t,i;return{audio:!((e=this.localMainAudioTrack)==null||!e.muted),bigVideo:!((t=this.localMainVideoTrack)==null||!t.muted),auxVideo:!((i=this.localAuxVideoTrack)==null||!i.muted)}}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return P(this,null,function*(){return this.publish(e)})}removeTrack(e){return P(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return P(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(pt(e))/^wss?:\/\//i.test(e)?this.proxy_ws=e:/^https?:\/\//i.test(e)&&(this.proxy_wt=e);else if(nr(e)){let{websocketProxy:t,webtransportProxy:i,loggerProxy:r,scheduleProxy:n,unifiedProxy:s}=e;this.proxy_ws=t,this.proxy_wt=i,this.proxy_unified=s,s?(oE([s,s]),oc("https://".concat(s))):(r&&oc(r),n&&oE(n))}$.once(ie.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:An.main,sched_back_domain:An.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return P(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return P(this,null,function*(){var e;let t={rtt:((e=this.quality)==null?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 P(this,arguments,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"main";return(function*(){let i={};return e.remotePublishedUserMap.forEach(r=>{let n=t==="auxiliary"?r.remoteAuxiliaryTrack:r.remoteVideoTrack;i[r.userId]=n.stat}),i})()})}checkDestroy(){if(this.isDestroyed)throw new me({code:te.INVALID_OPERATION,message:He({key:Fe.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Ir.INVALID_DESTROY),new me({code:te.INVALID_OPERATION,message:He({key:Fe.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,$.emit(ie.ROOM_DESTROY,{room:this})}schedule(e,t){return P(this,null,function*(){var i,r,n,s;let o=Ue();try{let{isCached:l,result:c,detailCost:h}=yield zD({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:yr,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=l,this._log.info("schedule cache:".concat(+l," ").concat(Tr(c,{keysToExclude:["username","credential"]}))),l&&$.once(ie.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=ve(ve({},this.scheduleResult),c),nt((i=c.config)==null?void 0:i.retryCount)&&a2(c.config.retryCount),pt((r=c.config)==null?void 0:r.loggerDomain)&&oc(c.config.loggerDomain),this.videoDecodeFallbackType=((n=c.config)==null?void 0:n.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=((s=c.config)==null?void 0:s.smallMode)||this.smallMode,$.emit(ie.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:h}),ce.addSuccessEvent({key:521700,cost:Ue()-o})}catch(l){throw ce.addFailedEvent({key:521700,error:l}),l}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}},lz=ti(Ri()),ON=ti(F1());function MN(e){var t;let i=[];for(let r=0;r<e.rtp.length;r++){if(["rtx","red","ulpfec"].includes(e.rtp[r].codec))continue;let n=e.fmtp.filter(s=>s.payload===e.rtp[r].payload)[0];i.push({payload:e.rtp[r].payload,codec:e.rtp[r].codec,fmtp:n?n.config:"",rate:e.rtp[r].rate,rtx:((t=e.rtp[r+1])==null?void 0:t.codec)==="rtx"?e.rtp[r+1].payload:0,rtcpfb:(e?.rtcpFb||[]).filter(s=>s.payload===e.rtp[r].payload).map(s=>{let{type:o,subtype:l}=s;return{id:o,params:l?[l]:[]}})})}return i}var cz=(e,t,i)=>P(null,null,function*(){var r;let n=zt(e),s={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:i};s.ice.ufrag=String(n.media[0].iceUfrag),s.ice.password=n.media[0].icePwd||"",n.fingerprint&&(s.dtls.hash=n.fingerprint.type,s.dtls.fingerprint=n.fingerprint.hash,s.dtls.setup=n.setup||""),n.media[0].fingerprint&&(s.dtls.hash=n.media[0].fingerprint.type,s.dtls.fingerprint=n.media[0].fingerprint.hash),s.dtls.setup=n.media[0].setup||"";let o=n.media[0],l=n.media[1];o.ext&&(s.audio.extensions=o.ext.map(h=>({id:h.value,uri:h.uri}))),l.ext&&(s.video.extensions=l.ext.map(h=>({id:h.value,uri:h.uri})));for(let h of o.rtp){if(h.codec!=="opus")continue;let _=o.fmtp.find(T=>T.payload===h.payload);if(!_)continue;let f={codec:h.codec,fmtp:_.config,payload:_.payload,rate:h.rate,channels:h.encoding,rtcpfb:[],rtx:0};(r=o.rtcpFb)==null||r.forEach(T=>{let{payload:b,type:C,subtype:x}=T;if(b===f.payload){let B={id:C,params:[]};x&&B.params.push(x),f.rtcpfb.push(B)}}),s.audio.codecs.push(f);break}let c=["h264","vp8","h265"];return t&&c.shift(),s.video.codecs=[...MN(l)].filter(h=>c.includes(h.codec.toLocaleLowerCase())),s.video.decoders=(yield(function(){return P(this,null,function*(){let h=new RTCPeerConnection;h.addTransceiver(D.VIDEO,{direction:D.TRANSCEIVER_DIRECTION_RECVONLY});let _=yield h.createOffer();if(!_.sdp)return[];let f=MN(zt(_.sdp).media[0]);return h.close(),f})})()).filter(h=>["h264","vp8","h265"].includes(h.codec.toLocaleLowerCase())),s}),LN=(e,t)=>{let i=(e||"").trim(),r=(t||"").trim(),n="profile-level-id",s="".concat(n,"=[0-9a-fA-F]{6}");if(new RegExp(s).test(i)){let l=new RegExp(s,"g");return i.replace(l,"".concat(n,"=").concat(r))}if(!i)return"".concat(n,"=").concat(r);let o=i.endsWith(";")?"":";";return"".concat(i).concat(o).concat(n,"=").concat(r)},uz=e=>{let{serverAbility:t,clientAbility:i,offerSDP:r,enableCustomMessage:n,profileLevelIdConfig:s}=e,o=zt(r),l={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},c={candidates:t.candidates.map(_=>({component:1,foundation:"1",generation:0,ip:_.ip,port:_.port,priority:_.priority,transport:_.foundation,type:_.type})),connection:{version:4,ip:"0.0.0.0"},direction:D.TRANSCEIVER_DIRECTION_RECVONLY,ext:t.audio.extensions.map(_=>({value:_.id,uri:_.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:D.AUDIO,setup:t.dtls.setup,rtcpFb:t.audio.codecs[0].rtcpfb.map(_=>({payload:t.audio.codecs[0].payload,type:_.id,subtype:_.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}]};l.media.push(c);let h=[s?.big,s?.small,s?.aux];return[1,2,3].forEach((_,f)=>{l.media.push(xN({mid:_,serverAbility:t,clientAbility:i,parsedOffer:o,profileLevelId:h[f]}))}),n&&l.media.push(o.media.find(_=>_.mid==="dc")),Es(l)},xN=e=>{let{mid:t,serverAbility:i,clientAbility:r,parsedOffer:n,isDownlink:s=!1,profileLevelId:o}=e,l={candidates:i.candidates.map(c=>({component:1,foundation:"1",generation:0,ip:c.ip,port:c.port,priority:c.priority,transport:c.foundation,type:c.type})),connection:{version:4,ip:"0.0.0.0"},direction:D.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(c=>({value:c.id,uri:c.uri})),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(t),payloads:"",port:n.media[0].port,protocol:n.media[0].protocol,type:D.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(s){let c=i.video.decoders;(!c||c.length===0)&&(c=i.video.codecs),(!c||c.length===0)&&(c=r.video.decoders),c.forEach(h=>{Xo(l,h)})}else{let c;c=i.useH265?i.video.codecs.findIndex(_=>_.codec.toLowerCase()==="h265"):i.video.codecs.findIndex(_=>_.codec.toLowerCase()===(i.useVp8?"vp8":"h264"));let h=i.video.codecs[c]||r.video.codecs[0];Xo(l,h)}if(!s&&o){let c=l.fmtp,h=l.rtp.find(_=>{var f;return((f=_.codec)==null?void 0:f.toLowerCase())==="h264"});if(h){let _=c.find(f=>String(f.payload)===String(h.payload));_&&(_.config=LN(_.config,o))}}return l},Xo=(e,t)=>{e.payloads="".concat(e.payloads," ").concat(t.payload).trim(),e.fmtp.push({payload:t.payload,config:t.fmtp}),e.rtcpFb=[...e.rtcpFb||[],...t.rtcpfb.map(i=>({payload:t.payload,type:i.id,subtype:i.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}))},dz=(e,t,i)=>{let r=ON.default.parse(e);return r.media.forEach((n,s)=>{var o;if((n.type===D.AUDIO||n.type===D.VIDEO)&&((function(l){if(!l.rtcpFb)return;let c=[];l.rtcpFb.forEach((h,_)=>{var f;c.push(h),l.rtcpFb&&((f=l.rtcpFb[_+1])==null?void 0:f.payload)!==h.payload&&h.type!=="rrtr"&&c.push({payload:h.payload,type:"rrtr"})}),l.rtcpFb=c})(n),(function(l){l.type===D.VIDEO&&l.fmtp&&l.fmtp.forEach(c=>{c.config.includes("apt")||(c.config+=";sps-pps-idr-in-keyframe=1")})})(n),(function(l){l.type===D.AUDIO&&l.fmtp&&l.fmtp.forEach(c=>{c.config+=";sprop-stereo=1;stereo=1"})})(n),(function(l){let c=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"]);l.ext&&(l.ext=l.ext.filter(h=>!c.has(h.uri)))})(n),n.type===D.VIDEO)){if(s<4)n.payloads="",n.fmtp=[],n.rtp=[],n.rtcpFb=[],t.video.codecs.forEach(l=>Xo(n,l));else if(i){n.payloads="",n.fmtp=[],n.rtp=[],n.rtcpFb=[];let l=i.video.decoders;(!l||l.length===0)&&(l=i.video.codecs),(!l||l.length===0)&&(l=t.video.decoders),l.forEach(c=>Xo(n,c))}}(o=n.payloads)!=null&&o.includes("datachannel")&&r.groups&&n.mid&&(r.groups[0].mids=r.groups[0].mids.replace(n.mid,"dc"),n.mid="dc")}),ON.default.write(r)};function NE(e){var t,i;let r=/profile-level-id=([0-9a-fA-F]{6})/.exec(e);return(i=(t=r?.[1])==null?void 0:t.toLowerCase())!=null?i:null}function PE(e){let t=e.toLowerCase();if(!/^[0-9a-f]{6}$/.test(t))return"unknown";let i=parseInt(t.slice(0,2),16);return i===66?"baseline":i===77?"main":i===100?"high":"unknown"}function UN(e,t){if(!t)return"";let i=e.trim().toLowerCase().replace(/_/g,"-");if(!i)return"";if(/^[0-9a-f]{6}$/.test(i))return i;if(i!=="baseline"&&i!=="main"&&i!=="high")return"";for(let r of t.video.codecs){let n=NE(r.fmtp);if(n&&PE(n)===i)return n}return""}var hz=ti(Ri()),VN=class extends hz.EventEmitter{constructor(e){super(),this.room=e,m(this,"mainFpsHealth",1),m(this,"mainBitrateHealth",1),m(this,"badMainBitrateHealthCount",0),m(this,"lastEmitBadHealthTime",0),m(this,"log"),!Vt&&or&&$.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged(e){let{remoteUserId:t,streamType:i,isHWCodec:r,codec:n}=e;if(!t&&i!==7&&n==="h264"){if(!r)return void this.room.off("heartbeat-report",this.onHeartbeatReport,this);this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}onHeartbeatReport(e){Date.now()-this.lastEmitBadHealthTime<3e4||(e.msg_up_stream_info.msg_video_status.forEach(t=>{if(t.uint32_video_enc_fps&&t.uint32_video_capture_fps){let i=t.uint32_video_enc_fps/t.uint32_video_capture_fps;t.uint32_video_stream_type===2&&(this.mainFpsHealth=i)}if(t.uint32_video_codec_bitrate&&t.uint32_video_stream_type===2){let{localMainVideoTrack:i}=this.room;i&&(this.mainBitrateHealth=t.uint32_video_codec_bitrate/1e3/i.profile.bitrate)}}),this.log.debug("mainBitrateHealth: ".concat(this.mainBitrateHealth," mainFpsHealth: ").concat(this.mainFpsHealth)),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn("bad main bitrate health: ".concat(this.mainBitrateHealth)),this.emit("1",{isAux:!1}))))}destroy(){$.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};m(VN,"EVENT_BAD_HEALTH","bad_health");var pz=VN,Na=(e=>(e.TRACK="track",e.DATA_CHANNEL_MESSAGE="data_channel_msg",e[e.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",e[e.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",e.RECONNECTED="spc-reconnected",e.RECONNECT_FAILED="spc-reconnect-failed",e.ERROR="error",e.SEI_MESSAGE="sei-message",e.DUMP="dump",e))(Na||{}),FN=0,BN=!1,mz=new Set,fz=1,ys=class extends lz.default{constructor(e){let{signalChannel:t,room:i,enableDataChannel:r}=e;super(),m(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),m(this,"isDestroyed",!1),m(this,"currentState","DISCONNECTED"),m(this,"_room"),m(this,"_signalChannel"),m(this,"_peerConnection",null),m(this,"_datachannel",null),m(this,"_enableDataChannel"),m(this,"_log"),m(this,"_downlinkMIDMap",new Map),m(this,"_downlinkMIDUserIDMap",new Map),m(this,"_reconnectionTimer",-1),m(this,"reconnectionCount",0),m(this,"clientAbility"),m(this,"_serverAbility",null),m(this,"addDownlinkQueue",new Set),m(this,"removeDownlinkQueue",new Set),m(this,"_parsedAnswer",null),m(this,"_updateSDPPromise",null),m(this,"_waitForPCConnectedPromise"),m(this,"clearWaitForConnectedPromise"),m(this,"clearConnectTimeout"),m(this,"_isSDPLogged",!1),m(this,"enableInsertableStreams",!1),m(this,"insertableStreamsAbortMap",new Map),m(this,"receiverRemoteTrackMap",new WeakMap),m(this,"scriptTransformWorker"),m(this,"_isRelayTried",!1),m(this,"_rttOverCount",0),m(this,"originOffer",null),m(this,"autoSubscribedSsrcGroups",new Map),m(this,"autoSubscribedUserMap",new Map),m(this,"_h265DecodeFailed",!1),this._room=i,this._enableDataChannel=r,this._signalChannel=t,this._log=fe.createLogger({parent:this._room.getLogger(),id:"spc".concat(fz++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(va?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h264")),e}addAbortController(e,t){var i;(i=this.insertableStreamsAbortMap.get(e))==null||i.abort("destroy"),this.insertableStreamsAbortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="vp8")),e}get isH265EncodeSupported(){let e=this._room.checkSystemResult.detail.isH265EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h265")),e}get videoCodec(){var e,t,i;let r=(e=this._parsedAnswer)==null?void 0:e.media[1].rtp.find(n=>["h264","vp8","h265"].includes(n.codec.toLowerCase()));return r?r.codec.toLowerCase():(t=this._serverAbility)!=null&&t.useH265?"h265":(i=this._serverAbility)!=null&&i.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e,t,i;return(e=this._serverAbility)!=null&&e.useH265&&(t=this._serverAbility)!=null&&t.video.decoders.find(r=>r.codec.toLowerCase()==="h265")&&!this._h265DecodeFailed?"h265":(i=this._serverAbility)!=null&&i.video.decoders.find(r=>r.codec.toLowerCase()==="h264")?"h264":"vp8"}get isUsingH264(){return this.videoCodec==="h264"}get isUsingH265(){return this.videoCodec==="h265"}get isUsingVP8(){return this.videoCodec==="vp8"}get is42001fSupported(){return!!this.clientAbility&&!!this.clientAbility.video.codecs.find(e=>e.fmtp.includes("42001f"))}isProfileLevelIdSupported(e){return!!this.clientAbility&&!!this.clientAbility.video.codecs.find(t=>t.fmtp.includes(e))}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(e=>{let t=zt(e),i={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return t.media.forEach((r,n)=>{var s;if(r.ssrcs&&!j(r.ssrcs[0].id)){let o=Number(r.ssrcs[0].id),l=Number((s=r.ssrcs.filter(c=>c.attribute==="cname")[1])==null?void 0:s.id);switch(n){case 0:i.audioSsrc=o;break;case 1:i.bigVideoSsrc=o,i.bigVideoRtxSsrc=l;break;case 2:i.smallVideoSsrc=o,i.smallVideoRtxSsrc=l;break;case 3:i.auxVideoSsrc=o,i.auxVideoRtxSsrc=l}}}),i})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth(e){}initScriptTransformWorker(){sp&&(this.scriptTransformWorker=iN({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=e=>{e.data.type==="sei"?this.emit("sei-message",e.data):e.data.type,e.data.type==="dump"&&this.emit("dump",e.data)},this.scriptTransformWorker.onerror=e=>{this._log.error("scriptTransformWorker error: ",e.message)})}get isReconnecting(){return this.currentState==="RECONNECTING"||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return e.length===0?null:e[0].transport}getPeerConnectionConfig(e){var t;let i={encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:e,iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},r=(t=this._peerConnection)==null?void 0:t.getConfiguration().encodedInsertableStreams;return V2(r)&&(i.encodedInsertableStreams=r),this._log.debug("getPeerConnectionConfig",JSON.stringify(i)),i}initialize(e){return P(this,null,function*(){var t;let i;try{return this._peerConnection=new RTCPeerConnection(this.getPeerConnectionConfig(e)),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let r=this._peerConnection.iceConnectionState;this._log.debug("ice state: ".concat(r)),r==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():r==="connected"&&this.stat.iceEndTime===0?(this.stat.iceEndTime=Date.now(),this._signalChannel.clearBakRelayIps(),ce.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):r==="failed"&&ce.addFailedEvent({key:521711})},this._peerConnection.onsignalingstatechange=()=>{var r;let n=((r=this._peerConnection)==null?void 0:r.signalingState)||"";this._log[n==="closed"?"debug":"info"]("signaling state: ".concat(n))},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=r=>this.emit("track",r),this._enableDataChannel&&(this._datachannel=this._peerConnection.createDataChannel("".concat(this._room.userId,"dc")),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=r=>{let n=new gz(r.data);this.emit("data_channel_msg",{data:n})},this._datachannel.onerror=r=>{this._log.warn("datachannel error",r)}),this._peerConnection.addTransceiver(D.AUDIO,{direction:D.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(D.VIDEO,{direction:D.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(D.VIDEO,{direction:D.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(D.VIDEO,{direction:D.TRANSCEIVER_DIRECTION_SENDONLY}),i=yield this._peerConnection.createOffer(),this.clientAbility=yield cz(i.sdp,((t=this._room.scheduleResult.config)==null?void 0:t.remove264FromSDP)||!1,this._enableDataChannel),this.originOffer=i,this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:r}=this;r&&(this._log.debug("dtls state: ".concat(r.state)),r.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():r.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),ce.addSuccessEvent({key:521707}),this.clientAbility}catch(r){throw ce.addFailedEvent({key:521707,error:r}),this._log.error("initialize failed ".concat(r,`
151
+ offer: `).concat(i?.sdp)),r}})}setIceServers(e){return P(this,null,function*(){var t;if(this._peerConnection&&e.length!==0)try{if(this._log.info("setIceServers",JSON.stringify(e,(i,r)=>i==="username"||i==="credential"?"hided":r)),this._peerConnection.setConfiguration(this.getPeerConnectionConfig(e)),(t=this._peerConnection)!=null&&t.localDescription||!this.originOffer)return void this._log.warn("setIceServers already has localDescription or no origin Offer");yield this.setOffer(this.originOffer)}catch(i){this._log.warn("setIceServers error ",i)}})}setPriority(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"high";if(this._peerConnection)try{this._peerConnection.getSenders().forEach(t=>{let i=t.getParameters();i.encodings[0]&&(i.encodings[0].priority=e,i.encodings[0].networkPriority=e,t.setParameters(i).catch(r=>{this._log.warn("setPriority error ",r)}))})}catch(t){this._log.warn("setPriority error ",t)}}connect(e){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return P(this,null,function*(){var i,r,n;try{if(this.currentState==="CONNECTED")return;((i=this._peerConnection)==null||!i.localDescription)&&this.originOffer&&(yield this.setOffer(this.originOffer));let s=Ue(),o=this.getProfileLevelIdConfig(),l={type:"answer",sdp:uz({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableDataChannel,profileLevelIdConfig:o})};this._serverAbility=e,yield this.setAnswer(l),yield this.waitForPeerConnectionConnected();let c=((r=this._room.scheduleResult.config)==null?void 0:r.priority)||((n=this._room.joinParams)==null?void 0:n.priority)||new URLSearchParams(location.search).get("priority");c&&this.setPriority(c),t||ce.addSuccessEvent({key:521703,cost:Ue()-s})}catch(s){let o=s instanceof me&&s.code===te.API_CALL_ABORTED;throw o||this._log.error("connect failed: ".concat(s),e),this.reset(),!o&&!this.isReconnecting&&!this.isDestroyed&&(ce.addFailedEvent({key:521703,error:s}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),s}})}reconnect(){return P(this,null,function*(){if(this._reconnectionTimer===-1){if(!this._signalChannel.isConnected)return this._log.warn("reconnect() wait signal channel is connected"),void this._signalChannel.once(Eu,this.reconnect,this);try{this.reconnectionCount+=1,this._log.warn("reconnect() trying [".concat(this.reconnectionCount,"]")),this.reset();let e=this._signalChannel.getBackupRelayIpPair(),t=yield this.initialize(this._room.getIceServers(e!=null&&e.iceServer?[e.iceServer]:[])),i=ve({ability:t},e),r=yield this._signalChannel.sendWaitForResponse({command:Lj,responseCommand:Ge.REBUILD_PEER_CONNECTION_RES,data:i,enableLog:!1});if(r.data.code!==0)throw new me({code:r.data.code,message:r.data.message});yield this.connect(r.data.data.ability,!0),ce.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),$.emit(ie.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting||this.isDestroyed)return;if(e!=null&&e.message.includes("timeout")){let t=la(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(t/1e3,"s")),yield Br(t,i=>{this._reconnectionTimer=i}),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error("reconnect() failed ".concat(e?.code," ").concat(e)),ce.addFailedEvent({key:521704,error:e}),this.reconnectionCount>=Ro()&&this._log.warn("SDK has tried reconnect for ".concat(Ro()," 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 P(this,null,function*(){this.isReconnecting||(this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect())})}stopReconnection(){var e;this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),(e=this.clearConnectTimeout)==null||e.call(this),this._signalChannel.off(Eu,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===Kt.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){var t;let i=((t=this._peerConnection)==null?void 0:t.iceConnectionState)||"closed",r=this.getDTLSTransportState();this._log.info("connectionState: ".concat(e.target.connectionState," ICE: ").concat(i," DTLS: ").concat(r)),e.target.connectionState===Kt.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===Kt.FAILED||e.target.connectionState===Kt.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===Kt.CONNECTED||e.target.connectionState===Kt.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),$.emit(ie.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 ss;let e=null;return Wc()&&this._peerConnection.getSenders().length!==0?(e=this._peerConnection.getSenders()[0].transport,np()&&this._peerConnection.getReceivers().length!==0&&e?e.state:ss):ss}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(Na.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return P(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(Hc(i)){let r=e.get(i.localCandidateId),n=e.get(i.remoteCandidateId);r&&(this._log.info("local candidate: ".concat(r.candidateType," ").concat(r.protocol,":").concat(r.ip||r.address,":").concat(r.port," ").concat(r.networkType||""," ").concat(r.relayProtocol?"relayProtocol:".concat(r.relayProtocol," url: ").concat(r.url):"")),r.networkType&&E0(r.networkType)),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(this.currentState==="CONNECTED")return e();let i=o=>{o.state==="CONNECTED"&&(clearTimeout(s),n(),e())},r=o=>{let{room:l}=o;l===this._room&&(clearTimeout(s),n(),t(new me({code:te.API_CALL_ABORTED,message:He({key:Fe.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{$.off(ie.LEAVE_SUCCESS,r,this),this.off(Na.CONNECTION_STATE_CHANGED,i,this)},s=setTimeout(()=>{n();let o=new me({code:te.API_CALL_TIMEOUT,message:"connection timeout"});var l;FN+=1,l=this._signalChannel.isConnected,FN>2&&!BN&&mz.size===0&&l&&(this._log.warn("firewall restriction"),BN=!0,this.emit(Na.FIREWALL_RESTRICTION)),t(o)},l0);this.clearConnectTimeout=()=>{n(),clearTimeout(s),delete this.clearConnectTimeout},this.clearWaitForConnectedPromise=()=>{this._waitForPCConnectedPromise=null,t(new me({code:te.API_CALL_TIMEOUT,message:"connection timeout"}))},$.on(ie.LEAVE_SUCCESS,r,this),this.on(Na.CONNECTION_STATE_CHANGED,i,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,delete this.clearConnectTimeout})),this._waitForPCConnectedPromise}waitForReconnected(){return this.isReconnecting?new Promise((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)}):Promise.resolve()}addDownlink(e){return P(this,null,function*(){if(this._log.info("addDownlink(".concat(e.userId,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),this.addDownlinkQueue.size===0)try{yield this.updateSDP(),this._log.info("addDownlink(".concat(e.userId,") done"))}catch(t){this._log.error("addDownlink(".concat(e.userId,") failed ").concat(t)),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig(e){let{ssrc:t,userId:i,tinyId:r}=e;if(!this._peerConnection)return;this._log.info("updateLocalAndRemoteSDPConfig ".concat(i," ").concat(JSON.stringify(t)));let n=this._peerConnection.getTransceivers().slice(4).filter(f=>f.direction==="inactive").slice(0,3).map(f=>(f.direction=D.TRANSCEIVER_DIRECTION_RECVONLY,Number(f.mid)));this._parsedAnswer||(this._parsedAnswer=zt(this._peerConnection.remoteDescription.sdp));let s,o,l,c=this._parsedAnswer.media.filter(f=>{var T;return(T=f.ssrcs)==null?void 0:T.find(b=>{var C;return(C=b.value)==null?void 0:C.includes(r)})});if(c.length===3)s=c[0],o=c[1],l=c[2];else if(n.length===3)s=this._parsedAnswer.media.find(f=>Number(f.mid)===Number(n[0])),o=this._parsedAnswer.media.find(f=>Number(f.mid)===Number(n[1])),l=this._parsedAnswer.media.find(f=>Number(f.mid)===Number(n[2]));else if(n.length===0){this._peerConnection.addTransceiver(D.AUDIO,{direction:D.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(D.VIDEO,{direction:D.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(D.VIDEO,{direction:D.TRANSCEIVER_DIRECTION_RECVONLY}),s=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let f=xN({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:zt(this._peerConnection.localDescription.sdp),isDownlink:!0});o=JSON.parse(JSON.stringify(f)),l=JSON.parse(JSON.stringify(f)),s.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(s),o.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(o),l.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(l)}s.direction=D.TRANSCEIVER_DIRECTION_SENDONLY;let h="".concat(r,"-").concat(t.audio);s.ssrcs=[{id:t.audio,attribute:"cname",value:"".concat(h)},{id:t.audio,attribute:"msid",value:"".concat(h,"-").concat(D.MAIN," ").concat(h,"-audio")}],o.direction=D.TRANSCEIVER_DIRECTION_SENDONLY,o.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(h)},{id:t.video,attribute:"msid",value:"".concat(h,"-").concat(D.MAIN," ").concat(h,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(h)},{id:t.videoRtx,attribute:"msid",value:"".concat(h,"-").concat(D.MAIN," ").concat(h,"-bigvideo")}],o.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],l.direction=D.TRANSCEIVER_DIRECTION_SENDONLY;let _="".concat(h,"-aux");l.ssrcs=[{id:t.auxiliary,attribute:"cname",value:_},{id:t.auxiliary,attribute:"msid",value:"".concat(_," ").concat(h,"-aux").concat(D.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(_," ").concat(h,"-aux").concat(D.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(_," ").concat(h,"-aux").concat(D.VIDEO)}],l.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.auxiliary," ").concat(t.auxiliaryRtx)}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(f=>f.mid).join(" ")),this._downlinkMIDMap.set(i,[s.mid,o.mid,l.mid]),this._downlinkMIDUserIDMap.set(s.mid,i),this._downlinkMIDUserIDMap.set(o.mid,i),this._downlinkMIDUserIDMap.set(l.mid,i)}removeDownlink(e){return P(this,null,function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info("removeDownlink(".concat(e,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(e),i=!1;this._peerConnection.getTransceivers().forEach(r=>{t!=null&&t.includes(Number(r.mid))&&(i=!0,r.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=zt(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(r=>{t!=null&&t.includes(Number(r.mid))&&(i=!0,r.direction="inactive",r.ssrcs=[],r.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&i&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),t?.forEach(r=>this._downlinkMIDUserIDMap.delete(r)),this._log.info("removeDownlink(".concat(e,") done"))})}setBandwidth(e){return P(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;try{if(yv()){let s=this._peerConnection.getSenders().slice(0,4);for(let l=0;l<s.length;l++){let c,h=s[l];l===0&&t?c=t:l===1&&i?c=i:l===2&&r?c=r:l===3&&n&&(c=n),c&&(yield this.setSenderMaxBitrate(h,c))}let o=!1;i&&s[1].track&&(o=this.setStartBitrate(1,i)),n&&s[3].track&&(o=this.setStartBitrate(3,n)||o),o&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info("setBandwidth ".concat(JSON.stringify(e)))}catch(s){this._log.error("failed to set bandwidth: ".concat(s))}})}setStartBitrate(e,t){var i,r;return!((i=this._peerConnection)==null||!i.remoteDescription||(this._parsedAnswer||(this._parsedAnswer=zt(this._peerConnection.remoteDescription.sdp)),(r=this._parsedAnswer.media[e])==null||!r.fmtp[0]))&&(this._parsedAnswer.media[e].fmtp[0].config+=";x-google-start-bitrate=".concat(t>5e3?5e3:t),!0)}setSenderMaxBitrate(e,t){let i=e.getParameters();if((!i.encodings||i.encodings.length===0)&&(i.encodings=[{}]),t==="unlimited")delete i.encodings[0].maxBitrate;else{if(i.encodings[0].maxBitrate===1e3*t)return;i.encodings[0].maxBitrate=1e3*t}return e.setParameters(i)}setBandwidthBySDP(e){let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;if(!this._peerConnection||!this._peerConnection.localDescription)return;let s=zt(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=zt(this._peerConnection.remoteDescription.sdp));let o=ut?"TIAS":"AS";t&&(s.media[0].bandwidth=[{type:o,limit:ut?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:o,limit:ut?1e3*t:t}]),i&&(s.media[1].bandwidth=[{type:o,limit:ut?1e3*i:i}],this._parsedAnswer.media[1].bandwidth=[{type:o,limit:ut?1e3*i:i}]),r&&(s.media[2].bandwidth=[{type:o,limit:ut?1e3*r:r}],this._parsedAnswer.media[2].bandwidth=[{type:o,limit:ut?1e3*r:r}]),n&&(s.media[3].bandwidth=[{type:o,limit:ut?1e3*n:n}],this._parsedAnswer.media[3].bandwidth=[{type:o,limit:ut?1e3*n:n}]);let l={type:"offer",sdp:Es(s)};return this.updateSDP({localDescription:l})}setScaleResolutionDownBy(e,t,i){let r=e.getParameters();(!r.encodings||r.encodings.length===0)&&(r.encodings=[{}]);let n=r.encodings[0].scaleResolutionDownBy;if(j(n)?t===1:t===n)return;let s="setScaleResolutionDownBy ".concat(i," ").concat(t);return n&&(s+=" prevScale: ".concat(n)),this._log.warn(s),r.encodings[0].scaleResolutionDownBy=t,e.setParameters(r)}setDegradationPreference(e,t,i){if(or&&lr<83||Gt&&ev(cr,"12.1")||ut&&Wh<138)return;let r=e.getParameters(),n="balanced";if(t==="motion"?n="maintain-framerate":t==="detail"&&(n="maintain-resolution"),r.degradationPreference===n)return;let s="setDegradationPreference ".concat(i," ").concat(n);return this._log.info(s),r.degradationPreference=n,e.setParameters(r).catch(o=>this._log.warn("".concat(s," failed: ").concat(o)))}updateSDP(){let{localDescription:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!this._parsedAnswer)return Promise.resolve();let t=Es(this._parsedAnswer);return this._updateSDPPromise=new Promise((i,r)=>P(this,null,function*(){var n,s;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,i()}catch(o){this._log.error(o),!this._isSDPLogged&&this._peerConnection&&(this._log.warn("current offer: ".concat(this.filterSDPDirection((n=this._peerConnection.localDescription)==null?void 0:n.sdp),`
152
+ next offer: `).concat(this.filterSDPDirection(e?.sdp))),this._log.warn("current answer: ".concat(this.filterSDPDirection((s=this._peerConnection.remoteDescription)==null?void 0:s.sdp),`
153
+ next answer: `).concat(this.filterSDPDirection(t))),this._log.warn("offer: ".concat(e?.sdp)),this._log.warn("answer: ".concat(t)),this._log.warn("transceivers: ".concat(JSON.stringify(this._peerConnection.getTransceivers().map(l=>{let{mid:c,currentDirection:h,direction:_,stopped:f}=l;return{mid:c,currentDirection:h,direction:_,stopped:f}})))),this._log.warn("parsedAnswer: ".concat(JSON.stringify(this._parsedAnswer))),this._isSDPLogged=!0),this._updateSDPPromise=null,r(o)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return P(this,null,function*(){if(!ut||!this._peerConnection||!this._parsedAnswer)return;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e));let i=this._peerConnection.getTransceivers();t.forEach(r=>{i[r].direction!==e&&(i[r].direction=e)});for(let r of t){let n=this._parsedAnswer.media[r].direction;e===rt.INACTIVE&&n===rt.RECVONLY&&(this._parsedAnswer.media[r].direction=e),e===rt.SENDONLY&&n===rt.INACTIVE&&(this._parsedAnswer.media[r].direction=rt.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(){return zt(arguments.length>0&&arguments[0]!==void 0?arguments[0]:"").media.map(e=>e.direction)}setOffer(e){this._log.info("setting offer");let t=dz(e.sdp,this.clientAbility,this._serverAbility);return this._log.debug(t),this._peerConnection.setLocalDescription({type:"offer",sdp:t})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return P(this,null,function*(){if(e==="h265"&&!this._parsedAnswer&&(this._parsedAnswer=zt(this._peerConnection.remoteDescription.sdp)),!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(i=>{var r;if(i.type===D.VIDEO){let n=this._serverAbility.video.codecs.find(s=>s.codec.toLowerCase()===e);n&&((r=i.payloads)==null||!r.includes(String(n.payload)))&&(i.fmtp=[],i.payloads="",i.rtp=[],i.rtcpFb=[],Xo(i,n),t=!0)}}),t&&(this._log.warn("switch video encoder to ".concat(e)),yield this.updateSDP())})}getScheduleProfileLevelId(e){var t;try{let i=(t=this._room.scheduleResult.config)==null?void 0:t.profileLevelId,r="";if(e===2?r=N0(i?.big)?i.big:"":e===3?r=N0(i?.small)?i.small:"":e===7&&(r=N0(i?.aux)?i.aux:""),!r)return"";let n=UN(r,this.clientAbility);return n?this._log.info("use schedule profile level id: streamType=".concat(e,", raw=").concat(r,", resolved=").concat(n)):this._log.warn("schedule profile level id not resolved: streamType=".concat(e,", raw=").concat(r)),n}catch(i){return this._log.warn("getScheduleProfileLevelId error: ".concat(i)),""}}getProfileLevelIdConfig(){try{let e=new URLSearchParams(location.search).get("profileLevelId")||"",t=UN(e,this.clientAbility);if(t)return this._log.info("use url profile level id: raw=".concat(e,", resolved=").concat(t)),{big:t,small:t,aux:t};let i=this.getScheduleProfileLevelId(2),r=this.getScheduleProfileLevelId(3),n=this.getScheduleProfileLevelId(7);if(!i&&!r&&!n)return;let s={};return i&&(s.big=i),r&&(s.small=r),n&&(s.aux=n),s}catch(e){return void this._log.warn("getProfileLevelIdConfig error: ".concat(e))}}setH264ProfileLevelId(e,t){return P(this,null,function*(){if(!this._peerConnection||!this._serverAbility)return;this._updateSDPPromise&&(yield this._updateSDPPromise),this._log.info("set H264 profile-level-id to ".concat(t?"high":"default"," for ").concat(e)),this._parsedAnswer||(this._parsedAnswer=zt(this._peerConnection.remoteDescription.sdp));let i=e==="main"?1:3,r=this._parsedAnswer.media[i];if(!r||r.type!==D.VIDEO)return;let n=r.rtp||[],s=r.fmtp||[],o=n.find(T=>{var b;return((b=T.codec)==null?void 0:b.toLowerCase())==="h264"});if(!o)return;let l=s.find(T=>String(T.payload)===String(o.payload));if(!l)return;let c=NE(l.config);if(!c)return;let h=PE(c)==="high";if(t&&h||!t&&!h)return;let _=this._serverAbility.video.codecs.map(T=>NE(T.fmtp)).filter(Boolean).find(T=>{let b=PE(T);return t?b==="high":b!=="high"});if(!_)return;let f=l.config;l.config=LN(l.config,_),l.config!==f&&(yield this.updateSDP(),this._log.info("set H264 profile-level-id to ".concat(t?"high":"default"," success")))})}useHWEncoder(){let e=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0],t=arguments.length>1?arguments[1]:void 0;return P(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let i=!1,r=[];j(t)?r=this._parsedAnswer.media.slice(1,4):t===2?r.push(this._parsedAnswer.media[1]):t===3?r.push(this._parsedAnswer.media[2]):t===7&&r.push(this._parsedAnswer.media[3]),r.forEach(n=>{var s;if(n.type===D.VIDEO){let o;e&&this.is42001fSupported?o=this.clientAbility.video.codecs.find(l=>l.fmtp.includes("42001f")):e||(o=this._serverAbility.video.codecs.find(l=>l.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),o&&((s=n.payloads)==null||!s.includes(String(o.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],Xo(n,o),i=!0)}}),i&&(this._log.warn("use ".concat(e?"hw":"sw"," encoder")),yield this.updateSDP())})}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){var e;this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),this._datachannel=null,(e=this.clearWaitForConnectedPromise)==null||e.call(this),this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.isDestroyed=!0,this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(e=>ua(e.abort)&&e.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map(i=>t[i])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP(e){let{uplinkRTT:t,downlinkRTT:i}=e;var r;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let n=this._signalChannel.rtt,s=Math.max(t,i),{rttRatioThreshold:o,rttThreshold:l}=((r=this._room.scheduleResult.config)==null?void 0:r.useTurnTcpInfo)||{};if(!(o&&l&&n&&s))return;let c=Math.floor(s/n),h=(this._isRelayTried||c>o)&&s>l;h?++this._rttOverCount<5||(this._log.warn("detectTCPAndUDP ws-rtt: ".concat(n," upRTT: ").concat(t," downRTT: ").concat(i," ratio: ").concat(c," over-count: ").concat(this._rttOverCount," isOver: ").concat(h," isRelayTried: ").concat(this._isRelayTried," force-relay: ").concat(this._room.forceRelay)),this.isUsingRelay||this._isRelayTried?this._room.forceRelay&&this.switchRelay(!1):(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0))):this._rttOverCount=0}switchRelay(e){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return P(this,null,function*(){if(this.isUsingRelay===e)return;let i=e?"relay":"udp",r=e?521709:521710;try{this._room.forceRelay=e,this._log.warn("switchRelay ".concat(i));let n=Date.now();yield this.doSwitchRelay(i),this._log.warn("switchRelay ".concat(i," success")),ce.addSuccessEvent({key:r,cost:Date.now()-n})}catch(n){this._log.warn("switchRelay ".concat(i," failed"),n),ce.addFailedEvent({key:r,error:n}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}})}doSwitchRelay(e){return new Promise((t,i)=>{let r=setTimeout(()=>{this.stopReconnection(),i(new Error("switch ".concat(e," timeout")))},1e4);this.startReconnection().then(t,i).finally(()=>clearTimeout(r))})}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}requestRemoteFallbackToH264(){this._log.warn("H265 decode failed, remote need to fallback h264"),this._h265DecodeFailed=!0,this._signalChannel.sendWaitForResponse({command:bE,data:{videoDecCodec:"h264"},responseCommand:Ge.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)})}};_e([$w("reconnect")],ys.prototype,"startReconnection"),_e([ps(e=>e.userId)],ys.prototype,"addDownlink"),_e([ps(e=>e)],ys.prototype,"removeDownlink"),_e([ru(!0)],ys.prototype,"updateSDP"),_e([ms(521712,!1),Cp(10,0)],ys.prototype,"setOffer"),_e([ms(521713,!1),Cp(10,0)],ys.prototype,"setAnswer"),_e([_t((e,t)=>function(){for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return this._checkPendingPromiseSet&&(this._checkPendingPromiseSet.forEach(s=>clearTimeout(s)),this._checkPendingPromiseSet.clear()),e.apply(this,r)})],ys.prototype,"close");var _z=class{constructor(e){m(this,"tag"),m(this,"len"),m(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}},gz=class{constructor(e){m(this,"tinyId"),m(this,"data");let t=new DataView(e),i=0,r=[];for(;i<t.byteLength;){let c=t.getUint16(i+2),h=new _z(new Uint8Array(e).slice(i,i+2+2+c).buffer);r.push(h),i+=4+c}let n=[];r.forEach(c=>{c.tag===1?this.tinyId=new TextDecoder().decode(c.data):c.tag===2&&n.push(c.data)});let s=n.reduce((c,h)=>c+h.byteLength,0),o=new Uint8Array(s),l=0;n.forEach(c=>{o.set(new Uint8Array(c),l),l+=c.byteLength}),this.data=o.buffer}},HN=new Set;function Cr(){let e=Math.floor(4294967296*Math.random());return HN.has(e)?Cr():(HN.add(e),e)}var vz=ti(Ri()),WN=class extends vz.default{constructor(e){super(),m(this,"userId"),m(this,"tinyId"),m(this,"_sdpSemantics"),m(this,"_isUplink"),m(this,"_room"),m(this,"_log"),m(this,"_currentState","DISCONNECTED"),m(this,"_prevTime",-1),m(this,"_blackSmallVideoDetectionId"),m(this,"isDestroyed",!1),this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=fe.createLogger({parent:this._room.getLogger(),id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink})}get _peerConnection(){var e;return((e=this.singlePC)==null?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}get _signalChannel(){return this._room.signalChannel}close(e){this._log.info("close connection"),this.emit("closed",e)}destroy(){this.isDestroyed=!0}emitConnectionStateChangedEvent(e){return e!==this._currentState&&($.emit(ie.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!((t=(e=this._peerConnection)==null?void 0:e.remoteDescription)==null||!t.sdp.includes("H264"))}};function GN(e){let{when:t,onSkip:i}=e;return _t((r,n)=>function(){for(var s=arguments.length,o=new Array(s),l=0;l<s;l++)o[l]=arguments[l];return P(this,null,function*(){if(!t.apply(this,o))return r.apply(this,o);i?.call(this,n,...o)})})}var Pa=new class{constructor(){m(this,"worker"),m(this,"callbacks",new Map),m(this,"_log"),m(this,"sleep",{}),m(this,"heartbeatListenerCleaner",new Map),m(this,"userIdMap",new Map),this._log=fe.createLogger({id:"bvd"})}getWorker(){if(!this.worker){let e=new Blob([`
154
+ const tracks=new Map;let canvas,ctx;const log=(...t)=>postMessage({type:"log",message:"[worker] "+t.join(" ")});function startDetection(e,t,a){if(!tracks.has(e)){const c={reader:a.getReader(),blackCount:0,timeoutId:null,intervalId:null};tracks.set(e,c),c.timeoutId=setTimeout(()=>stopDetection(e,"timeout"),t),c.intervalId=setInterval(async()=>{try{await isFrameBlack(e)?(c.blackCount++,postMessage({type:"blackCount",trackId:e,count:c.blackCount}),3<=c.blackCount&&(postMessage({type:"black",trackId:e}),stopDetection(e,"black"))):c.blackCount=0}catch(t){log("check black video error:",t.message),stopDetection(e,"error")}},1e3)}}function stopDetection(t,e){var a=tracks.get(t);a&&(a.timeoutId&&clearTimeout(a.timeoutId),a.intervalId&&clearInterval(a.intervalId),a.reader&&a.reader.cancel(),tracks.delete(t),postMessage({type:e,trackId:t}))}async function isFrameBlack(t){t=tracks.get(t);if(!t)return!1;var t=t.reader,{done:t,value:e}=await t.read();if(!e||t)return!1;canvas||(canvas=new OffscreenCanvas(e.codedWidth,e.codedHeight),ctx=canvas.getContext("2d",{willReadFrequently:!0})),canvas.width===e.codedWidth&&canvas.height===e.codedHeight||(canvas.width=e.codedWidth,canvas.height=e.codedHeight,ctx=canvas.getContext("2d",{willReadFrequently:!0})),ctx.drawImage(e,0,0,canvas.width,canvas.height);t=getFrameBlackRatio(ctx.getImageData(0,0,canvas.width,canvas.height));return e.close(),1===t}function getFrameBlackRatio(t){var e=t.data;let a=0;for(let t=0;t<100;t++){var c=4*Math.floor(Math.random()*(e.length/4)),[c,r,n,o]=[e[c],e[1+c],e[2+c],e[3+c]];0<o&&0===c&&0===r&&0===n&&a++}return a/100}self.onmessage=t=>{var{type:t,trackId:e,timeout:a,readable:c}=t.data;"addTrack"===t&&startDetection(e,a,c),"removeTrack"===t&&stopDetection(e)};
155
+ `],{type:"application/javascript"}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.onerror=i=>this._log.warn("worker error:",i.message,i.filename||"unknown",i.lineno||"unknown"),this.worker.onmessage=i=>{var r;let{type:n,trackId:s,message:o,count:l}=i.data;if(n==="black")(r=this.callbacks.get(s))==null||r();else if(n==="log")this._log.warn(o);else if(n==="blackCount"){let c=this.userIdMap.get(s);this._log.warn("".concat(c||s," black count: ").concat(l))}}}return this.worker}start(e){let{track:t,isUplink:i,room:r,userId:n,onBlack:s}=e;if(this._log.debug("start detect black video",t.id),!hv()||!s||!t||typeof Worker>"u")return void this._log.warn("black video detector not supported");let o=l=>{var c,h,_,f;let T;if(i)T=(h=(c=l.msg_up_stream_info)==null?void 0:c.msg_video_status)==null?void 0:h.filter(b=>b.uint32_video_stream_type===3)[0];else{let b=(_=l.msg_down_stream_info)==null?void 0:_.filter(C=>{var x;return((x=C.msg_user_info)==null?void 0:x.str_identifier)===n})[0];T=(f=b?.msg_video_status)==null?void 0:f.filter(C=>C.uint32_video_stream_type===3)[0]}if(T){let b=(T.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[t.id]&&this.sleep[t.id]>0)return void(this.sleep[t.id]-=1);b>0&&b<10&&(this.sleep[t.id]=30,this._log.info("track bitrate",b,"start check"),this.checkOnce(t,3e4))}};return r.on("heartbeat-report",o),this.heartbeatListenerCleaner.set(t.id,()=>r.off("heartbeat-report",o)),this.callbacks.set(t.id,s),this.userIdMap.set(t.id,n),t.id}checkOnce(e,t){try{let i=this.getWorker();if(!i)throw new Error("Worker not available");let r=new MediaStreamTrackProcessor({track:e});i.postMessage({type:"addTrack",trackId:e.id,timeout:t,readable:r.readable},[r.readable])}catch(i){this._log.warn("check error:",i),this.stop(e.id)}}stop(e){if(e){this.worker&&this.worker.postMessage({type:"removeTrack",trackId:e}),this.callbacks.delete(e),delete this.sleep[e];let t=this.heartbeatListenerCleaner.get(e);t&&t(),this.heartbeatListenerCleaner.delete(e),this.userIdMap.delete(e)}}destroy(){this.callbacks.forEach((e,t)=>this.stop(t)),this.worker&&(this.worker.terminate(),this.worker=null)}},Qp=class extends WN{constructor(e){super(xe(ve({},e),{isUplink:!0})),m(this,"localMainAudioTrack",null),m(this,"localMainVideoTrack",null),m(this,"localAuxAudioTrack",null),m(this,"localAuxVideoTrack",null),m(this,"_isPublishingAux",!1),m(this,"_publishingLocalAudioTrack"),m(this,"_publishingLocalVideoTrack"),m(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,videoDecCodec:"",audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),m(this,"_flag",0),m(this,"_checkPublishStateTimeoutId",-1),this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:i,smallVideoSsrc:r,smallVideoRtxSsrc:n,auxVideoSsrc:s,auxVideoRtxSsrc:o}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:i||0,small:r||0,smallRtx:n||0,auxiliary:s||0,auxiliaryRtx:o||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];try{if(!e&&this._checkPublishStateTimeoutId>0)return;let{serverPublishState:t}=this,{publishState:i}=this._room,r=Object.keys(i).filter(n=>{if(i[n]!==t[n]&&i[n])switch(n){case"audio":return!(!this.localMainAudioTrack||!this.localMainAudioTrack.isMediaTrackActive);case"bigVideo":case"smallVideo":return!(!this.localMainVideoTrack||!this.localMainVideoTrack.isMediaTrackActive);case"auxVideo":return!(!this.localAuxVideoTrack||!this.localAuxVideoTrack.isMediaTrackActive)}return!1});if(r.length>0){if(!e)return void(this._checkPublishStateTimeoutId=ft.run("timeout",()=>this.checkPublishState(!0),{delay:1e4,count:1}));ce.addCount({key:521e3}),r.forEach(n=>{this._log.warn("".concat(n," publish failed during call ").concat(xo()," ").concat(Lo())),ce.addEnum({key:521719,value:jN[n]})}),ft.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}}catch(t){this._log.warn("checkPublishState failed",t)}}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get serverPublishState(){return{audio:!!(this.flag&dc),bigVideo:!!(this.flag&uc),smallVideo:!!(this.flag&n0),auxVideo:!!(this.flag&Ah)}}initialize(){this.installEvents()}close(e){var t;let i=((t=this._peerConnection)==null?void 0:t.getSenders())||[];for(let r of i)r.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var i,r,n;let s=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((i=this.localMainVideoTrack)==null||i.emit("connection-state-changed",{prevState:s,state:e}),(r=this.localAuxVideoTrack)==null||r.emit("connection-state-changed",{prevState:s,state:e}),(n=this._publishingLocalVideoTrack)==null||n.emit("connection-state-changed",{prevState:s,state:e}))),o}onVideoEncodeFailed(e){return P(this,null,function*(){if(!e||!e.isMediaTrackActive)return;let{videoCodec:t,singlePC:i}=this;if(!i)return;let r={h265:{supported:i.isH264EncodeSupported,target:"h264",log:"h265 encoder not working"},h264:{supported:i.isVP8EncodeSupported,target:"vp8",log:"h264 encoder not working"},vp8:{supported:!1,target:"vp8",log:"vp8 encoder not working, no fallback available"}};if(t==="vp9"||t==="av1")return;let n=r[t];this._log.warn(n.log),n!=null&&n.supported&&(yield i.switchVideoEncoder(n.target))})}publish(e){return P(this,arguments,function(t){var i=this;let{localAudioTrack:r,localVideoTrack:n,isAuxiliary:s}=t;return(function*(){var o,l,c,h,_,f,T;if(!i.singlePC)return;if(i.installEvents(),i.installTrackMuteEvents(r,n),n&&(n.retryEncodeFailed=i.onVideoEncodeFailed.bind(i)),yield i.singlePC.waitForPeerConnectionConnected(),r&&(i._publishingLocalAudioTrack=r),n){if(!i.singlePC.isH264EncodeSupported&&!i.singlePC.isVP8EncodeSupported)throw new me({code:te.NOT_SUPPORTED_H264,message:He({key:Fe.NOT_SUPPORTED_H264ENCODE})});i.singlePC.isUsingH264&&!i.singlePC.isH264EncodeSupported&&i.singlePC.isVP8EncodeSupported&&(i._log.warn("h264 encoder not supported"),yield i.singlePC.switchVideoEncoder("vp8")),Vt&&Zh()===115&&n.profile.width*n.profile.height<=230400&&(i._log.warn("fallback video to defaultBigVideoProfile: ".concat(JSON.stringify(cc))),n.setProfile(cc),yield n.applyProfile()),i._publishingLocalVideoTrack=n}let b;if(i._isPublishingAux=s,n&&!s&&n.small&&(b=i._room.videoManager.smallTrack),yield i._signalChannel.sendWaitForResponseWithRetry({command:yN,responseCommand:Ge.SPC_PUBLISH_RESULT,data:xe(ve({},i.singlePC.uplinkSSRC),{state:i._room.publishState,muteState:i._room.muteState}),retries:3}),n&&(yield i.checkHighProfile({streamType:n.streamType,newWidth:n.settings.width,newHeight:n.settings.height})),yield i.publishByTransceiver({localAudioTrack:r,localVideoTrack:n,smallTrack:b,isAuxiliary:s}),i._publishingLocalAudioTrack=null,i._publishingLocalVideoTrack=null,i._isPublishingAux=!1,n){i[s?"localAuxVideoTrack":"localMainVideoTrack"]=n,yield i.singlePC.setDegradationPreference(i._peerConnection.getSenders()[s?3:1],n.contentHint,n.streamType);let{scaleResolutionDownBy:x}=n;yield i.singlePC.setScaleResolutionDownBy(i._peerConnection.getSenders()[s?3:1],x,n.streamType)}r&&(i[s?"localAuxAudioTrack":"localMainAudioTrack"]=r),yield i.singlePC.setBandwidth({audio:((o=i.localMainAudioTrack)==null?void 0:o.profile.bitrate)||((l=i.localAuxAudioTrack)==null?void 0:l.profile.bitrate),bigVideo:(c=i.localMainVideoTrack)==null?void 0:c.profile.bitrate,smallVideo:(_=(h=i.localMainVideoTrack)==null?void 0:h.small)==null?void 0:_.bitrate,auxVideo:(f=i.localAuxVideoTrack)==null?void 0:f.profile.bitrate}),i.sendMediaSettings();let C=s?7:2;(i._room.preferHW||(T=i._room.scheduleResult.config)!=null&&T.preferHW)&&n&&n.profile.width*n.profile.height>=921600&&i.singlePC.useHWEncoder(!0,C)})()})}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:r,isAuxiliary:n}=e;if(!Rr())return;this._log.info("publish by transceiver");let s=i?.outMediaTrack,o=t?.outMediaTrack,l=this._peerConnection.getTransceivers(),c=[],h=[],_=(T,b,C)=>{var x;let B=l[b].sender.replaceTrack(C);h.push(b),(x=this.singlePC)!=null&&x.enableInsertableStreams&&B.then(()=>this.createEncodedStreams(l[b].sender,T)),this.initSenderTransform(l[b].sender,T),c.push(B)};o&&_(t.mediaType,0,o),s&&_(i.mediaType,n?3:1,s),i!=null&&i.small&&c.push(this.publishSmall(this._room.videoManager.smallMode,i));let f=this.singlePC.setTransceiverDirection(rt.SENDONLY,h);return c.push(f),Promise.all(c)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._room.localMainAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._room.localMainVideoTrack;case 2:return this.localAuxVideoTrack||this._room.localAuxVideoTrack;default:return null}}createEncodedStreams(e,t){var i,r;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let n=e.createEncodedStreams(),s=new AbortController;(i=this.singlePC)==null||i.addAbortController(e,s),((r=this.getTrackByMediaType(t))!=null&&r.enableEncodeFrame?n.readable.pipeThrough(new TransformStream({transform:(o,l)=>{var c,h;let _=this.getTrackByMediaType(t);if(!_||!_.encodeFrame)return l.enqueue(o);_.isAudio?l.enqueue(_.enableEncodeFrame?_.encodeFrame(o):o):l.enqueue((c=this.singlePC)!=null&&c.isUsingH264||(h=this.singlePC)!=null&&h.isUsingH265?_.encodeFrame(o,t===8):o)}}),s):n.readable).pipeTo(n.writable,s).catch(o=>{this._log.debug("encoded stream error",o),o!=="destroy"&&this._log.warn(o)})}initSenderTransform(e,t){if(!(this._peerConnection&&this.singlePC&&this.singlePC.scriptTransformWorker&&sp))return;let i=t!==2,r=t===8;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:i,isSmall:r}))}enableSmall(e){return P(this,null,function*(){e?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()})}publishSmall(e){return P(this,arguments,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.localMainVideoTrack;return(function*(){var n;if(!i.singlePC)return;if(t==="canvas"&&!vv())return void i._log.warn("canvas mode small stream is not supported");let s=i._peerConnection.getTransceivers(),{sender:o}=s[2],l=yield i.doPublishSmall(t,r),c=t==="canvas"?524700:524701;ce.addSuccessEvent({key:c}),l?((n=i.singlePC)!=null&&n.enableInsertableStreams&&i.createEncodedStreams(o,8),i.initSenderTransform(o,8),yield i.singlePC.setTransceiverDirection(rt.SENDONLY,[2]),i.updateMediaSettings(),yield i.doPublishChange(),o.track&&(i._blackSmallVideoDetectionId=Pa.start({track:o.track,room:i._room,isUplink:!0,userId:i.userId,onBlack:()=>{i._log.warn("small video is black");let h=t==="canvas"?524700:524701;ce.addFailedEvent({key:h,error:10002}),Pa.stop(i._blackSmallVideoDetectionId),i._blackSmallVideoDetectionId=void 0}}))):ce.addFailedEvent({key:c,error:10001})})()})}doPublishSmall(e){return P(this,arguments,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.localMainVideoTrack;return(function*(){if(!i.singlePC)return null;i._log.info("publish small",t);let n=i._peerConnection.getTransceivers(),{sender:s}=n[2];if(t==="canvas"&&i._room.videoManager.smallTrack)return yield s.replaceTrack(i._room.videoManager.smallTrack),"canvas";if(t==="api"&&r!=null&&r.outMediaTrack&&r!=null&&r.small){yield s.replaceTrack(r?.outMediaTrack);let o=s.getParameters(),l=Vh(r?.profile,r?.small);return i._log.info("small scaleResolutionDownBy",l),o.encodings[0].scaleResolutionDownBy=l,s.setParameters(o),"api"}return i._log.warn("small track can not be enabled, smallMode: ".concat(i._room.videoManager.smallMode,", smallTrack: ").concat(!!i._room.videoManager.smallTrack,", bigVideoTrack: ").concat(!(r==null||!r.outMediaTrack))),null})()})}unpublishSmall(){return P(this,null,function*(){this.singlePC&&(this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(rt.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),Pa.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)})}checkHighProfile(e){return P(this,null,function*(){var t,i;if((((t=this._room.scheduleResult.config)==null?void 0:t.profileLevelId)||{})[e.streamType==="main"?"big":"aux"]!=="high")return;let r=e.newWidth*e.newHeight>=921600&&!$2();try{yield(i=this.singlePC)==null?void 0:i.setH264ProfileLevelId(e.streamType,r)}catch(n){this._log.warn("setH264ProfileLevelId failed, ignore",n)}})}installTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach(r=>{r&&(r?.on("mute",this.sendMutedFlag,this),r?.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];t.forEach(r=>{r&&(r?.off("mute",this.sendMutedFlag,this),r?.off("unmute",this.sendMutedFlag,this))})}unpublish(e){return P(this,arguments,function(t){var i=this;let{localAudioTrack:r,localVideoTrack:n}=t;return(function*(){var s;yield(s=i.singlePC)==null?void 0:s.waitForPeerConnectionConnected();let o=n&&n===i.localAuxVideoTrack||r&&r===i.localAuxAudioTrack,l=n?.outMediaTrack,c=i._peerConnection.getSenders(),h=[];r&&(o?i.localAuxAudioTrack=null:i.localMainAudioTrack=null,!i.localMainAudioTrack&&!i.localAuxAudioTrack&&(yield c[0].replaceTrack(null),h.push(0))),l&&(o?(yield c[3].replaceTrack(null),i.localAuxVideoTrack=null,i._mediaSettings=xe(ve({},i._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),h.push(3)):(yield c[1].replaceTrack(null),yield c[2].replaceTrack(null),i.localMainVideoTrack=null,i._mediaSettings=xe(ve({},i._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),h.push(1,2))),i.isMainStreamPublished||i.isAuxStreamPublished?(yield i.singlePC.setTransceiverDirection(rt.INACTIVE,h),yield i.doPublishChange(!1)):yield i.doUnpublish(),i.uninstallTrackMuteEvents(r,n),n?.emit("connection-state-changed",{prevState:i._currentState,state:"DISCONNECTED"})})()})}doPublishChange(){let e=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return P(this,null,function*(){let t={state:this._room.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponseWithRetry({command:IE,data:t,responseCommand:Ge.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(i.data.code,i.data.message)})}doUnpublish(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this._signalChannel.sendWaitForResponse({command:jp,commandDesc:"unpublish",responseCommand:Ge.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===te.API_CALL_TIMEOUT||t.getCode()===te.API_CALL_ABORTED)return Promise.resolve();throw t})}updateMediaSettings(){var e,t;this._mediaSettings.videoCodec=((e=this.singlePC)==null?void 0:e.videoCodec)||"h264",this._mediaSettings.videoDecCodec=((t=this.singlePC)==null?void 0:t.downlinkVideoCodec)||"h264";let i=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:r,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:r=this._publishingLocalVideoTrack),Fo){if(i&&i.outMediaTrack){let s=i.outMediaTrack.getSettings();this._mediaSettings.audioChannel=s.channelCount||1,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=s.sampleRate||0}if(r&&r.outMediaTrack){let s=r.outMediaTrack.getSettings(),{scaleResolutionDownBy:o}=r;this._mediaSettings.videoWidth=(s.width||0)/o||0,this._mediaSettings.videoHeight=(s.height||0)/o||0,this._mediaSettings.videoFps=s.frameRate||0,this._mediaSettings.videoBps=1e3*r.profile.bitrate,r.small&&(this._mediaSettings.smallVideoWidth=r.small.width,this._mediaSettings.smallVideoHeight=r.small.height,this._mediaSettings.smallVideoFps=r.small.frameRate,this._mediaSettings.smallVideoBps=1e3*r.small.bitrate)}if(n&&n.outMediaTrack){let s=n.outMediaTrack.getSettings(),{scaleResolutionDownBy:o}=n;this._mediaSettings.auxVideoWidth=(s.width||0)/o||0,this._mediaSettings.auxVideoHeight=(s.height||0)/o||0,this._mediaSettings.auxVideoFps=s.frameRate||0,this._mediaSettings.auxVideoBps=1e3*n.profile.bitrate}}else i&&i.outMediaTrack&&(this._mediaSettings.audioChannel=i.profile.channelCount,this._mediaSettings.audioBps=1e3*i.profile.bitrate,this._mediaSettings.audioFs=i.profile.sampleRate),r&&r.outMediaTrack&&(this._mediaSettings.videoWidth=r.profile.width,this._mediaSettings.videoHeight=r.profile.height,this._mediaSettings.videoFps=r.profile.frameRate,this._mediaSettings.videoBps=1e3*r.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:bE,data:this._mediaSettings,responseCommand:Ge.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return P(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(t?D.AUXILIARY:D.MAIN," stream")),Vo()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return P(this,null,function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===D.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&(i=this.localMainVideoTrack)!=null&&i.small&&this._room.videoManager.smallTrack&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===rt.INACTIVE&&(yield this.singlePC.setTransceiverDirection(rt.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return P(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?D.AUXILIARY:D.MAIN," stream")),Vo()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return P(this,null,function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===D.AUDIO)yield i[0].sender.replaceTrack(null);else{let r=t?3:1;yield i[r].sender.replaceTrack(null),r===1&&this._room.videoManager.hasSmall&&(yield i[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(rt.INACTIVE,[r])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return P(this,null,function*(){var t;let i=(t=this._peerConnection)==null?void 0:t.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!i||i.length===0||!r||i.find(s=>s.track===r))return!1;let n=e.mediaType===2||e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(r.kind," track ").concat(r.id," ").concat(r.label," on ").concat(n?D.AUXILIARY:D.MAIN," stream")),r.kind===D.AUDIO&&i[0]&&(yield i[0].replaceTrack(r)),r.kind===D.VIDEO&&(!n&&i[1]&&(yield i[1].replaceTrack(r)),n&&i[3]&&(yield i[3].replaceTrack(r))),!0})}setBandwidth(e){return P(this,arguments,function(t){var i=this;let{bandwidth:r,type:n,videoType:s}=t;return(function*(){if(i.singlePC){let o={};n===D.AUDIO?o.audio=r:s==="big"?o.bigVideo=r:s==="small"?o.smallVideo=r:o.auxVideo=r,yield i.singlePC.setBandwidth(o)}})()})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this._room.muteState))),this._signalChannel.sendWaitForResponseWithRetry({command:gN,responseCommand:Ge.MUTE_RESULT,data:this._room.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&$.emit(ie.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:D.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===D.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===D.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===D.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===D.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===kh?(this._log.error(Ir.NOT_SUPPORTED_H264ENCODE),new me({code:te.NOT_SUPPORTED_H264,message:He({key:Fe.NOT_SUPPORTED_H264ENCODE})})):new me({code:te.UNKNOWN,message:He({key:Fe.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Ge.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return P(this,null,function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}};_e([Ta(e=>{let{localVideoTrack:t}=e;t==null||delete t.retryEncodeFailed})],Qp.prototype,"unpublish"),_e([GN({when(){return this.isDestroyed}})],Qp.prototype,"doPublishChange"),_e([GN({when(){return this.isDestroyed}})],Qp.prototype,"doUnpublish");var jN=(e=>(e[e.audio=1]="audio",e[e.bigVideo=2]="bigVideo",e[e.smallVideo=3]="smallVideo",e[e.auxVideo=4]="auxVideo",e))(jN||{}),zN=Qp;function KN(e){return Object.keys(e).filter(t=>e[t])}var Zp=class extends WN{constructor(e){super(xe(ve({},e),{isUplink:!1})),m(this,"_flag",0),m(this,"isRobot",!1),m(this,"role","anchor"),m(this,"fromType"),m(this,"remoteAudioTrack"),m(this,"remoteVideoTrack"),m(this,"remoteAuxiliaryTrack"),m(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),m(this,"jitterBufferTimeoutId",-1),m(this,"_videoCodec"),m(this,"avPlayerStateSyncManager"),m(this,"isDataChannelSubscribed",!1),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.fromType=e.fromType,this.remoteAudioTrack=new kp(this._room,this),this.remoteVideoTrack=new mu(this._room,this),this.remoteAuxiliaryTrack=new DD(this._room,this),this.avPlayerStateSyncManager=new dE({log:this._log,audioPlayer:this.remoteAudioTrack.player,videoPlayer:this.remoteVideoTrack.player}),this.initialize()}get videoCodec(){var e;return this._videoCodec||((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}set videoCodec(e){this._videoCodec=e}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing,datachannel:this.isDataChannelSubscribed}}get muteState(){return ca(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,i,r;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(i=this.remoteVideoTrack)==null||i.onFlagChanged(),(r=this.remoteAuxiliaryTrack)==null||r.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===D.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.avPlayerStateSyncManager.destroy(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.on("decode-failed",this.onDecodeFailed,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.off("decode-failed",this.onDecodeFailed,this))}emitConnectionStateChangedEvent(e){var t,i;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&((t=this.remoteVideoTrack)==null||t.emit("connection-state-changed",{prevState:r,state:e}),(i=this.remoteAuxiliaryTrack)==null||i.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){var t,i;let r=e.streams[0],{track:n,receiver:s}=e;if(!r.id.includes(this.tinyId))return;let o=r.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(o," ").concat(n.kind));let l=D.AUDIO;n.kind===D.VIDEO&&(l=o===D.MAIN?D.VIDEO:D.AUXILIARY);let c=this.remoteAudioTrack;l===D.VIDEO?c=this.remoteVideoTrack:l===D.AUXILIARY&&(c=this.remoteAuxiliaryTrack),(t=this.singlePC)==null||t.receiverRemoteTrackMap.set(s,c),(i=this.singlePC)!=null&&i.scriptTransformWorker&&this.initReceiverTransform(s,o,n.kind===D.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(s),c.setInputMediaStreamTrack(n)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),i=new AbortController,r={abortController:i,enqueue:n=>{var s,o,l;let c=(s=this.singlePC)==null?void 0:s.receiverRemoteTrackMap.get(e);return c&&(c.kind!=="video"||(o=this.singlePC)!=null&&o.isUsingH264||(l=this.singlePC)!=null&&l.isUsingH265)?c.decodeFrame(n):n}};t.readable.pipeThrough(new TransformStream({transform:(n,s)=>{let o=r.enqueue(n);o&&s.enqueue(o)}})).pipeTo(t.writable,i).catch(n=>{n!=="destroy"&&this._log.warn(n)}),this.singlePC.addAbortController(e,i)}}initReceiverTransform(e,t,i){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:i,userId:this.userId,streamType:t}))}subscribe(e,t){return P(this,null,function*(){var i,r;try{let n=!0;if(this._log.info("subscribe ".concat(t," ").concat(KN(e))),this.hasSSRC){let l="subscribe_change";Object.values(e).find(c=>c===!0)||(l="unsubscribe"),yield this.sendSubscription(l,e)}else{if(yield this._room.switchRoomSubedReq,(i=this.singlePC)!=null&&i.autoSubscribedUserMap.size){let l=this.singlePC.autoSubscribedUserMap.get(this.userId);if(l){this.singlePC.autoSubscribedUserMap.delete(this.userId);let c=(r=this.singlePC.autoSubscribedSsrcGroups.get(this._room.roomId))==null?void 0:r[l.groupIndex];c&&(this.ssrc={audio:c.audioSsrc,video:c.bigVideoSsrc,videoRtx:c.bigVideoRtxSsrc,auxiliary:c.auxVideoSsrc,auxiliaryRtx:c.auxVideoRtxSsrc},n=!1)}}yield this.doSubscribe(e,n),this.checkTrackEnded(e)}let{user:s,mediaTrack:o}=this.remoteVideoTrack;e.smallVideo&&o?(ce.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=Pa.start({track:o,isUplink:!1,room:this._room,userId:this.userId,onBlack:()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,s),ce.addFailedEvent({key:524702}),Pa.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}})):(Pa.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(n.message," ").concat(JSON.stringify(this.muteState))),new me({code:te.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):n}})}checkTrackEnded(e){var t,i,r;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((i=this.remoteVideoTrack.mediaTrack)==null?void 0:i.readyState)==="ended"||e.auxiliary&&((r=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:r.readyState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),or&&lr<92)return;this.singlePC.startReconnection()}}unsubscribe(e){return P(this,arguments,function(t){var i=this;let{remoteTracks:r,streamType:n}=t;return(function*(){var s;if(n==="main"&&!i.isMainStreamSubscribed||n==="auxiliary"&&!i.isAuxStreamSubscribed)return void i._log.info("".concat(n," stream already unsubscribed"));let o=ve({},i.subscribeState);r.forEach(c=>{switch(c.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1}});let l="subscribe_change";Object.values(o).find(c=>c===!0)||(l="unsubscribe"),i._log.info("".concat(l==="unsubscribe"?l:"subscribe"," ").concat(n," [").concat(KN(o),"]")),l==="unsubscribe"&&((s=i.singlePC)==null||s.removeDownlinkQueue.add(i.tinyId)),yield i.sendSubscription(l,o),n==="main"&&(Pa.stop(i._blackSmallVideoDetectionId),i._blackSmallVideoDetectionId=void 0),l==="unsubscribe"&&(yield i.removeDownlink())})()})}subscribeDataChannel(){return P(this,null,function*(){if(!this.singlePC)return;yield this.singlePC.waitForPeerConnectionConnected();let e=xe(ve({},this.subscribeState),{datachannel:!0});yield this.doSubscribe(e)})}unsubscribeDataChannel(){return P(this,null,function*(){let e=xe(ve({},this.subscribeState),{datachannel:!1});yield this.sendSubscription("unsubscribe",e),yield this.removeDownlink()})}sendSubscription(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscribeState,i={srcTinyId:this.tinyId,srcUserId:this.userId},r=RE,n=Ge.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(i={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:t.datachannel,srcTinyId:this.tinyId},r=AE,n=Ge.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:r,data:i,responseCommand:n,timeout:1e4,retries:3}).then(s=>{let{data:o}=s;if(o.code!==0){let l=new me({code:o.code,message:He({key:Fe.ERROR_MESSAGE,data:{type:e,message:o.message}})});throw this._log.error(l),l}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay(e){let{audioDelay:t,videoDelay:i}=e;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=i}onSinglePCReconnected(){return P(this,null,function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary||this.isDataChannelSubscribed)&&(this._log.warn("resubscribe ".concat(JSON.stringify(this.subscribeState))),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())})}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return P(this,arguments,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.subscribeState,i=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return(function*(){var r,n;if(e.singlePC){e.singlePC.addDownlinkQueue.add(e.tinyId),yield e.singlePC.waitForPeerConnectionConnected();try{if(i||!e.hasSSRC){let s={audioSsrc:Cr(),bigVideoSsrc:Cr(),bigVideoRtxSsrc:Cr(),auxVideoSsrc:Cr(),auxVideoRtxSsrc:Cr()},{audioSsrc:o,bigVideoSsrc:l,bigVideoRtxSsrc:c,auxVideoSsrc:h,auxVideoRtxSsrc:_}=s;e.ssrc={audio:o,video:l,videoRtx:c,auxiliary:h,auxiliaryRtx:_},e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc});try{let f=yield e._signalChannel.sendWaitForResponseWithRetry({command:TN,responseCommand:Ge.SPC_SUBSCRIBE_RESULT,data:{srcUserId:e.userId,srcTinyId:e.tinyId,audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:(r=t.datachannel)!=null&&r,ssrc:s},retries:3,retryTimeout:0});if(f.data.code!==0&&f.data.code!==-10036)throw new me({code:f.data.code,message:f.data.message});e.isDataChannelSubscribed=(n=t.datachannel)!=null&&n}catch(f){throw yield e.removeDownlink(),f}return}e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc})}finally{if((t.audio||t.video||t.smallVideo||t.auxiliary||!t.datachannel)&&ap){let{main:s,aux:o}=e._room.jitterBufferDelay||{},{jitterDelay:l=s,jitterDelayAux:c=o}=e._room.scheduleResult.config||{};(nt(l)||nt(c))&&e.setJitterBufferDelay({mainDelay:l,auxDelay:c})}}}})()})}removeDownlink(){return P(this,null,function*(){if(!this.singlePC)return;this.isDataChannelSubscribed=!1,this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;(e!=null&&e.jitterDelay||e!=null&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay(e){let{mainDelay:t,auxDelay:i}=e;if(!ap||!this.singlePC||!this._peerConnection||sr(t)&&sr(i))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i));let r=this.singlePC.getReceiversByUserId(this.userId);return nt(t)&&(this.remoteAudioTrack.jitterBufferDelay=t,this.remoteVideoTrack.jitterBufferDelay=t),nt(i)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=i,sr(t)&&(this.remoteAudioTrack.jitterBufferDelay=i)),new Promise(n=>{this.doSetJitterBufferDelay({mainDelay:t,auxDelay:i,receivers:r,resolve:n})})}doSetJitterBufferDelay(e){let{mainDelay:t,auxDelay:i,receivers:r,resolve:n}=e;try{if(t===0&&i===0)return r.forEach(s=>s.jitterBufferTarget=0),n();if(r.forEach(s=>{var o;let l=s.track===this.remoteAuxiliaryTrack.outMediaTrack||sr(t)&&s.track===this.remoteAudioTrack.outMediaTrack;if(l&&sr(i)||!l&&sr(t))return;let c=l?i||0:t,h=(s.jitterBufferTarget||0)+100;h>c||(s.jitterBufferTarget=h,this._log.debug("set ".concat(l?"aux ":"").concat((o=s?.track)==null?void 0:o.kind," jitterBuffer delay ").concat(h," -> ").concat(c)))}),!r.find(s=>{let o=s.track===this.remoteAuxiliaryTrack.outMediaTrack?i||0:t;return s.jitterBufferTarget<o}))return this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i," done")),n();this.jitterBufferTimeoutId=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:t,auxDelay:i,receivers:r,resolve:n})},1e3)}catch(s){this._log.warn("set jitterBuffer delay error: ".concat(s)),clearTimeout(this.jitterBufferTimeoutId),n()}}get audioReceiver(){var e;return((e=this.singlePC)==null?void 0:e.getReceiversByUserId(this.userId)[0])||null}onDecodeFailed(){this._room.downlinkVideoCodec==="h265"&&this._room.requestRemoteFallbackToH264()}};_e([ru(),_t(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return new Promise((n,s)=>{let o=l=>{this.off("closed",o),s(new me({code:te.API_CALL_ABORTED,message:He({key:Fe.CONNECTION_ABORTED,data:l})}))};this.on("closed",o),e.apply(this,i).then(n,s).finally(()=>{this.off("closed",o)})})})],Zp.prototype,"subscribe"),_e([ru()],Zp.prototype,"unsubscribe"),_e([ps(()=>"jitter")],Zp.prototype,"setJitterBufferDelay");var Ez=Zp,yz=ti(Ri()),JN=class cP extends yz.EventEmitter{constructor(t,i){super(),this.room=t,this.signalChannel=i,m(this,"log"),m(this,"cmdIdSeqMap",new Map),m(this,"messageMap",new Map),this.log=fe.createLogger({parent:t.getLogger(),id:"cmm",userId:t.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),i.on(Ge.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",r=>{let{userId:n}=r;[...this.messageMap.keys()].forEach(s=>{s.split("_").slice(0,-1).join("_")===n&&this.messageMap.delete(s)})})}send(t){let{cmdId:i,data:r}=t,n=this.cmdIdSeqMap.get(i)||Math.floor(16383*Math.random()),s={cmdId:i,msg:btoa(String.fromCharCode(...new Uint8Array(r))),ordered:!0,reliable:!0,streamSeq:n};this.cmdIdSeqMap.set(i,n+1),this.signalChannel.send(Fj,s),this.log.debug("send custom msg: ".concat(JSON.stringify(s)))}onReceiveMsg(t){let{data:i}=t.data,r=this.room.tinyIdToUserIdMap.get(i.srcTinyId);if(r){let n={userId:r,cmdId:i.cmdId,seq:i.streamSeq,data:Uint8Array.from(atob(i.msg),s=>s.charCodeAt(0)).buffer};if(i.ordered){let s="".concat(r,"_").concat(n.cmdId),o=this.messageMap.get(s);if(o&&o.lastSeq!==0)if(Math.abs(o.lastSeq-n.seq)>cP.SEQ_INTERVAL)this.messageMap.set(s,{lastSeq:n.seq,cachedMessageMap:new Map}),this.emitMessage(n);else if(n.seq>o.lastSeq){if(n.seq===o.lastSeq+1)this.emitMessage(n);else if(!o.cachedMessageMap.has(n.seq)){let l=setTimeout(()=>this.emitMessage(n,!0),5e3);o.cachedMessageMap.set(n.seq,{message:n,timeoutId:l})}}else this.log.debug("drop message ".concat(n.userId,"-").concat(n.cmdId,"-").concat(n.seq));else o||(o={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(s,o),setTimeout(()=>this.emitMessage(n,!0),100)),o.cachedMessageMap.set(n.seq,{message:n})}else this.emit("message",n)}else{this.log.warn("receive msg from unknown user, wait peer-join tinyId: ".concat(i.srcTinyId));let n=s=>{s.tinyId===i.srcTinyId&&(this.room.off("peer-join",n),this.onReceiveMsg(t))};this.room.on("peer-join",n),Br(2e3).then(()=>this.room.off("peer-join",n))}}emitMessage(t){let i=arguments.length>1&&arguments[1]!==void 0&&arguments[1];var r;let n=this.messageMap.get("".concat(t.userId,"_").concat(t.cmdId)),s=t;if(n){if(i){let l=[...n.cachedMessageMap.values()].sort((c,h)=>c.message.seq-h.message.seq);l[0]&&(s=l[0].message)}n.lastSeq!==0&&s.seq-n.lastSeq>1&&this.log.debug("msg lost userId: ".concat(s.userId," seq: ").concat(n.lastSeq," -> ").concat(s.seq)),n.lastSeq=s.seq,clearTimeout((r=n.cachedMessageMap.get(s.seq))==null?void 0:r.timeoutId),n.cachedMessageMap.delete(s.seq)}this.log.debug("receive custom msg: ".concat(JSON.stringify(s))),this.emit("message",s);let o=n?.cachedMessageMap.get(s.seq+1);o&&this.emitMessage(o.message)}};m(JN,"SEQ_INTERVAL",300);var Tz=JN,{isString:YN,isUndefined:Oa,getNetworkType:Sz,isEmpty:Iz}=Vr,Ts=class extends oz{constructor(e){super(e),m(this,"_businessInfo"),m(this,"userManager"),m(this,"_version"),m(this,"_heartbeat",-1),m(this,"_lastHeartBeatTime",-1),m(this,"_stats"),m(this,"_joinTimeout",-1),m(this,"_firstPublishedList",null),m(this,"_joinReject",null),m(this,"_isRelayChanged",!1),m(this,"sdpSemantics"),m(this,"signalChannel",null),m(this,"uplinkConnection",null),m(this,"singlePC",null),m(this,"enableSPC",Gc),m(this,"_changeBigSmallRecords",new Map),m(this,"networkQuality"),m(this,"_iceTransportPolicy"),m(this,"forceRelay",!1),m(this,"_turnServers",[]),m(this,"_iceServersFromJoin"),m(this,"_syncUserListInterval",-1),m(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160}),m(this,"enableSEI",!1),m(this,"_enableAudioVolumeEvaluation",!1),m(this,"_audioVolumeIntervalId",0),m(this,"_enableMultiAuxStream",!1),m(this,"_pureAudioPushMode",!1),m(this,"_customMessageManager"),m(this,"_enableDataChannel",!1),m(this,"preferHW",!1),m(this,"healthDetector"),m(this,"playoutDelay"),m(this,"jitterBufferDelay"),m(this,"_updateAudioLevelTaskId",-1),m(this,"switchRoomSubedReq"),m(this,"resolveSwitchRoomSubedReq"),m(this,"enableVolumeControlInIOS"),m(this,"capturedLocalMainAudioTrack"),m(this,"capturedLocalMainVideoTrack"),m(this,"capturedLocalAuxVideoTrack"),this._stats=new Kj(this,this._log),this.userManager=new jG(this.userId,this._log),this._version=yr,this.sdpSemantics=Ch,Oa(e.sdpSemantics)?Vc.isUnifiedPlanDefault()&&(this.sdpSemantics=hc):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(Sz())),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!Oa(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&Gc,!Oa(e.enableSPC)&&Gc&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this._initBusinessInfo(e),this.healthDetector=new pz(this)}get isMainStreamPublished(){var e;return!((e=this.uplinkConnection)==null||!e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!((e=this.uplinkConnection)==null||!e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!((e=this.uplinkConnection)==null||!e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(e=>e.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map(e=>[e.tinyId,e.userId]))}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get downlinkVideoCodec(){var e;return((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}join(e,t,i){return P(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",r=>{this.emit("peer-join",r)}),this.userManager.on("8",r=>{this.emit("asr-robot-peer-join",r)}),this.userManager.on("9",r=>{this.emit("asr-robot-peer-leave",r)}),this.userManager.on("2",r=>{let{userId:n,reason:s}=r;this.closeDownLinkConnection(n,"remote user exitRoom"),this.emit("peer-leave",{userId:n,reason:s})}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",r=>{var n=U1(r,[]);$.emit(ie.REMOTE_PUBLISH_STATE_CHANGED,ve({room:this},n)),this.emit("remote-publish-state-changed",ve({},n))}),this.joinParams=e,Rt(e.enableDataChannel)&&(this._enableDataChannel=e.enableDataChannel),new Promise((r,n)=>P(this,null,function*(){var s,o;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(c){if(!(c instanceof me&&c.code===te.SPC_INITIALIZED_FAILED))return n(c);(s=this.signalChannel)==null||s.destroy(),yield this.initialize()}let l=Ue();yield this.doJoin(e,(o=this.singlePC)==null?void 0:o.clientAbility),ce.addSuccessEvent({key:521708,cost:Ue()-l}),r(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(l){ce.addFailedEvent({key:521708,error:l}),n(l)}this._joinReject=null}))})}initSinglePC(){return P(this,null,function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new ys({signalChannel:this.signalChannel,room:this,enableDataChannel:this._enableDataChannel}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.on("dump",e=>this.emit("dump",e)),this.singlePC.once("error",()=>this.fallbackToMPC()),this.singlePC.on("data_channel_msg",e=>{let t=new TextDecoder().decode(e.data.data||e.data);try{this.emit("data-channel-message",{data:JSON.parse(t)})}catch{}});try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new me({code:te.SPC_INITIALIZED_FAILED,message:e?.message})}}})}doJoin(e,t){return new Promise((i,r)=>P(this,null,function*(){var n,s,o,l,c,h,_,f;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(Wp,C=>{this.clearJoinTimeout(),$.emit(ie.JOIN_SIGNAL_CONNECTION_END,{room:this,error:C}),r(C)}),Rt((s=(n=this.scheduleResult)==null?void 0:n.config)==null?void 0:s.singlePC)&&Gc&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),(!((l=(o=this.scheduleResult)==null?void 0:o.config)!=null&&l.jitterDelay)&&!((h=(c=this.scheduleResult)==null?void 0:c.config)!=null&&h.jitterDelayAux)||!ap)&&t&&this.playoutDelay&&(this._log.info("set playoutDelay",JSON.stringify(this.playoutDelay)),t.playoutDelay=this.playoutDelay);let T={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:ik(),netType:Ec(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0,isChorus:!!this.enableChorus,enableNtpAudioFrame:!!this.enableChorus&&ip(),transcription:this._enableDataChannel,downUseVp8:((_=this.scheduleResult.config)==null?void 0:_.downUseVp8)||!1};this._log.debug("join room signal data: ".concat(JSON.stringify(T)));let b=5e3;(f=this.scheduleResult.config)!=null&&f.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(b=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout(()=>{r(new me({code:te.JOIN_ROOM_FAILED,message:He({key:Fe.JOIN_ROOM_TIMEOUT})}))},b),$.emit(ie.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?xj:Tj,T),this.signalChannel.once(Ge.JOIN_ROOM_RESULT,C=>P(this,null,function*(){this.clearJoinTimeout();let{code:x,message:B,data:Y,tinyId:G}=C.data;$.emit(ie.JOIN_RECEIVED_CMD_RES,{room:this,code:x}),x===0?(this._log.info("Join room success, start heartbeat"),G&&(this.tinyId=G),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=Y.publishers,this._iceServersFromJoin=Y.iceServer?[Y.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var he;(he=this.singlePC)==null||he.connect(xe(ve({},Y.ability),{useVp8:Y.ability.useVp8||!!e.useVp8,useH265:Y.ability.useH265&&!!e.useH265})).catch(()=>{})}),i()):(this._log.error("Join room failed result: ".concat(x," error: ").concat(B)),r(new me({code:te.JOIN_ROOM_FAILED,extraCode:x,message:He({key:Fe.JOIN_ROOM_FAILED,data:{error:B,code:x}})})))}))}))}reJoin(){return P(this,null,function*(){if(this.isJoined)try{this._log.warn("reJoin pending: ".concat(this.joinParams.roomId));let e,t=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,t.push(this.initSinglePC().then(i=>(e=i,i)))),this.signalChannel&&(this.signalChannel.close(),t.push(this.signalChannel.connect())),yield Promise.all(t),yield this.doJoin(xe(ve({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),dt.logSuccessEvent({userId:this.userId,eventType:di.REJOIN}),this.singlePC){let i=r=>{var n;r.state==="CONNECTED"&&((n=this.singlePC)==null||n.off(Na.CONNECTION_STATE_CHANGED,i),this.uplinkConnection instanceof zN&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(s=>{s.installEvents(),s.onSinglePCReconnected()}))};this.singlePC.on(Na.CONNECTION_STATE_CHANGED,i),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof qp&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(e){this._log.warn("reJoin fail ".concat(e)),this.reset(),dt.logFailedEvent({userId:this.userId,eventType:di.REJOIN,error:e}),this.emit("error",new me({code:te.JOIN_ROOM_FAILED,message:He({key:Fe.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")})}initialize(){return P(this,null,function*(){let e,{mainUrl:t,backupUrl:i}=this.getSignalChannelUrl(),r=this.signalChannel||(function(s){return[...zp.values()].find(l=>l.room.userId===s&&!l.room.isJoined)||null})(this.userId),n=!!(r&&r.isConnected&&r.keepAlive&&r.userId===this.userId&&r.room===this);return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e=this.scheduleResult.domains[0]),this._log.info("".concat(n?"reuse":"setup"," signal channel")),n?(r.url=t,r.backupUrl=i,r.room=this,this.signalChannel=r):(r&&r.close(),this.signalChannel=new SN({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:t,backupUrl:i,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?e:void 0}),this._customMessageManager=new Tz(this,this.signalChannel),this._customMessageManager.on("message",s=>{this.emit("custom-message",s)})),this.networkQuality||(this.networkQuality=new CN({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(CN.EVENT_NETWORK_QUALITY,s=>{var o;this.emit("network-quality",s),(o=this.singlePC)==null||o.detectTCPAndUDP(s)})),Ar(this,this.signalChannel).add(SE,s=>{$.emit(ie.SIGNAL_CONNECTION_STATE_CHANGED,ve({room:this},s)),this.emit("signal-connection-state-changed",s)}).add(vj,s=>{this.reset(),this.emit("error",s)}).add(Ge.PEER_JOIN,s=>{let{srcTinyId:o,userId:l,role:c,fromType:h}=s.data.data;this.userManager.addUser({userId:l,tinyId:o,role:c,fromType:h})}).add(Ge.PEER_LEAVE,s=>{let{userId:o,reason:l=0}=s.data.data;this.userManager.deleteUser(o,l)}).add(Ge.UPDATE_REMOTE_MUTE_STAT,s=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(s.data)}).add(Ge.CLIENT_BANNED,s=>{let o=s.data.data,{reason:l}=o;if(dt.uploadEvent({log:"stat-banned:".concat(l),userId:this.userId}),l==="user_time_out")return this._log.warn("".concat(l," last heart beat time: ").concat(this._lastHeartBeatTime," interval: ").concat(Date.now()-this._lastHeartBeatTime,", visibility: ").concat(document.visibilityState)),void this.reJoin();this._log[l==="kick"?"error":"info"]("user was banned because of [".concat(l,"]")),this.reset(),this.emit("banned",{reason:l})}).add(Ge.SEND_SWITCH_ROOM_SUBED_REQ,s=>{if(!this.singlePC)return;let{subList:o}=s.data.data;this._log.info("auto subscribe ".concat(Tr(o,{keysToInclude:["userId"]}))),o.forEach(l=>{this.singlePC.autoSubscribedUserMap.set(l.userId,l)}),this.resolveSwitchRoomSubedReq()}).add(Ge.FALLBACK_CODEC,s=>P(this,null,function*(){var o,l,c,h,_;let f=s.data.data;((o=f.videoControlInfo)==null?void 0:o.enableH265Enc)===0&&((l=this.singlePC)==null?void 0:l.videoCodec)==="h265"&&(this._log.warn("fallback codec enableH265Enc: ".concat((c=f.videoControlInfo)==null?void 0:c.enableH265Enc)),ce.addCount({key:513e3}),yield(h=this.singlePC)==null?void 0:h.switchVideoEncoder("h264"),yield(_=this.uplinkConnection)==null?void 0:_.sendMediaSettings())})),this.signalChannel.once(mN,s=>{this.tinyId=s.signalInfo.tinyId,$.emit(ie.JOIN_SIGNAL_CONNECTION_END,{room:this})}),$.emit(ie.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),n&&$.emit(ie.JOIN_SIGNAL_CONNECTION_END,{room:this}),n})}setSignalChannel(e){this.signalChannel=e,e||bi(this)}leave(){return P(this,null,function*(){var e;try{yield this.doHeartbeat()}catch{}this._log.info("leave() => leaving room"),$.emit(ie.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(Sj),this.switchRoomSubedReq=void 0,this._changeBigSmallRecords.clear()})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=ft.run("ric",this.doHeartbeat.bind(this),{delay:2e3}),this.enableChorus&&this.startUpdateNTPTime())}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),ft.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return P(this,null,function*(){var e;let t=this.badCaseDetector.getMonitorFreeze(),i=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});this.badCaseDetector.resetMonitor();let r=(e=this.signalChannel)!=null&&e.isConnected?(function(s){if(jo.has(s)){let o=jo.get(s).map(l=>({uint32_event_id:l.eventId,uint64_date:l.timestamp,str_userid:l.remoteUserId,uint32_param1:l.param1,uint32_param2:l.param2,uint32_video_stream_type:l.streamType}));return jo.delete(s),o}return[]})(this.userId):[],n=xe(ve({str_sdk_version:Yg,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},i),{msg_device_info:ve({uint32_terminal_type:15,str_device_name:Lo(),str_os_version:"",uint32_net_type:Ec()},i.msg_device_info)});if(this.heartbeatReport=n,this.heartbeatCount++,$.emit(ie.HEARTBEAT_REPORT,{room:this,report:n}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(Ij,n);let s=Date.now();this._lastHeartBeatTime>0&&s-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(s-this._lastHeartBeatTime)),this._lastHeartBeatTime=s,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",xe(ve({},n),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=!1,i=e.data.userList||[],r=e.data.mixRobotList||[],n=[];for(let o of i){if(o.flag===e2)continue;let{userId:l,srcTinyId:c,flag:h,fromType:_}=o;l===this.userId&&(t=!0,this.uplinkConnection&&(this.uplinkConnection.flag=h),this.localPublishFlag!==h&&(this.localPublishFlag=h,this.emit("local-publish-flag-changed",h))),n.push({userId:l,tinyId:c,flag:h,fromType:_})}let s=[...r.map(o=>{let{userId:l,srcTinyId:c,flag:h,mixUserList:_,fromType:f}=o;return{userId:l,tinyId:c,flag:h,isRobot:!0,mixUserList:_,fromType:f}}),...n];s.forEach(o=>{let{userId:l}=o,c=this.remotePublishedUserMap.get(l);c&&this.checkSubscribeBigSmallVideo(c)}),e.data.fakeMixUser&&(e.data.fakeMixUser.tinyId=e.data.fakeMixUser.srcTinyId,s.push(e.data.fakeMixUser)),$.emit(ie.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:s}),t||(this.localPublishFlag=0,this.emit("local-publish-flag-changed",0)),this.userManager.setRemotePublishedUserList(s)}closeUplink(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"you unpublished";this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish().catch(()=>{}),this.uplinkConnection.close(e),e==="you exitRoom"&&(this.uplinkConnection.destroy(),this.uplinkConnection=null),this.uplinkConnection instanceof qp&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection(e){let{userId:t,tinyId:i,flag:r,isRobot:n,fromType:s}=e,o=new(this.singlePC?Ez:AN)({userId:t,tinyId:i,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:n,fromType:s});this.userManager.addRemotePublishedUser(o),this.installDownlinkEvents(o,t),this.emit("remote-published",o)}closeDownLinkConnection(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"remote user unpublished",i=this.remotePublishedUserMap.get(e);i&&(i.close(t),this.emit("remote-unpublished",i))}installDownlinkEvents(e,t){e.on("error",i=>{let r=i.getCode();r!==te.ICE_TRANSPORT_ERROR&&(r===te.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",i))}),e.on("connection-state-changed",i=>{this.emit("media-connection-state-changed",xe(ve({},i),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=ft.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){ft.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(e=this.signalChannel)!=null&&e.isConnected?this.signalChannel.sendWaitForResponse({command:Oj,responseCommand:Ge.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(t=>{let{data:i}=t,{code:r,message:n}=i;if(r===0)return(i.data&&i.data.userList||[]).map(s=>{let{userId:o,srcTinyId:l,role:c,fromType:h}=s;return{userId:o,tinyId:l,role:c,fromType:h}});throw He({key:Fe.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Ge.USER_LIST_RES,code:r,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||!IN)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?((e=this.singlePC.getPeerConnection())==null?void 0:e.connectionState)===Kt.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(t=>{if(t instanceof bn&&!t.getIsReconnecting()){let i=t.getPeerConnection();i&&i.connectionState===Kt.CLOSED&&(this._log.warn("[".concat(t.getUserId(),"] pc is closed but not reconnect")),t.startReconnection())}})}fallbackToMPC(){return P(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),dt.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin()),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new qp({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),t.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localMainAudioTrack,localVideoTrack:t.localMainVideoTrack,isAuxiliary:!1})),t.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localAuxAudioTrack,localVideoTrack:t.localAuxVideoTrack,isAuxiliary:!0})),t.close()}for(let t of[...this.remotePublishedUserMap.values()]){let i=new AN({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(i,t.userId),this.remotePublishedUserMap.set(t.userId,i),t.isMainStreamSubscribed&&(yield i.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield i.subscribe(t.subscribeState,"auxiliary"))}})}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new me({code:te.INVALID_OPERATION,message:He({key:Fe.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),ft.clearTask(this._audioVolumeIntervalId))}switchRole(e){return P(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))})}doSwitchRole(e){let t={command:Mj,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:Ge.SWITCH_ROLE_RES,retries:1};return this._log.info("switchRole signal data: ".concat(JSON.stringify(t.data))),this.signalChannel.sendWaitForResponseWithRetry(t).then(i=>{let{code:r,message:n}=i.data;if(r!==0)throw new me({code:te.SWITCH_ROLE_FAILED,message:He({key:Fe.SWITCH_ROLE_FAILED,data:{message:n,code:r}})});this.role=e}).catch(i=>{throw i instanceof me&&i.getCode()===te.API_CALL_TIMEOUT&&(i=new me({code:te.SWITCH_ROLE_FAILED,message:He({key:Fe.SWITCH_ROLE_TIMEOUT})})),this._log.error(i),i})}subscribeDataChannel(){return P(this,null,function*(){if(this.remotePublishedUserMap.size===0)return;let e=[...this.remotePublishedUserMap.values()].filter(t=>t.fromType===Nh);this._log.info("subscribeDataChannel",e.map(t=>t.userId)),yield Promise.all(e.map(t=>P(this,null,function*(){try{yield t.subscribe(xe(ve({},t.subscribeState),{datachannel:!0}),"main")}catch(i){this._log.error("subscribeDataChannel failed:",t.userId,i)}})))})}unsubscribeDataChannel(){return P(this,null,function*(){if(this.remotePublishedUserMap.size===0)return;let e=[...this.remotePublishedUserMap.values()].filter(t=>t.fromType===Nh);this._log.info("unsubscribeDataChannel",e.map(t=>t.userId)),yield Promise.all(e.map(t=>t.unsubscribeDataChannel()))})}_initUplinkConnection(){this.uplinkConnection=this.singlePC?new zN({userId:this.userId,tinyId:this.tinyId,room:this}):new qp({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",e=>{this.emit("media-connection-state-changed",xe(ve({},e),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",e=>{let t=e.getCode();t!==te.ICE_TRANSPORT_ERROR&&(t===te.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})}publish(e){return P(this,null,function*(){var t;this.uplinkConnection||this._initUplinkConnection();let i="".concat(e.streamType," ").concat(e.isAudio&&e.isScreen?"screen":"").concat(e.kind);this._log.info("publish() => ".concat(i)),yield(t=this.singlePC)==null?void 0:t.waitForPeerConnectionConnected(),yield this.uplinkConnection.publish({localAudioTrack:e instanceof Ia?e:null,localVideoTrack:e instanceof Rn?e:null,isAuxiliary:e.streamType==="auxiliary"})})}unpublish(e){return P(this,null,function*(){if((this.scene!=="live"||this.role==="anchor")&&(this.isMainStreamPublished||this.isAuxStreamPublished)&&this.uplinkConnection){try{let t="".concat(e.streamType," ").concat(e.isAudio&&e.isScreen?"screen":"").concat(e.kind);this._log.info("unpublish() => ".concat(t)),yield this.uplinkConnection.unpublish({localAudioTrack:e instanceof Ia?e:null,localVideoTrack:e instanceof Rn?e:null})}catch{}this.localTracks.size===0&&this.closeUplink("you unpublished")}})}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return this.uplinkConnection&&e.mediaTrack?(e.unpublish(),this.uplinkConnection.removeTrack(e)):Promise.resolve()}replaceTrack(e){return this.uplinkConnection&&e.mediaTrack&&dw()?this.uplinkConnection.replaceTrack(e).then(t=>{t&&$.emit(ie.LOCAL_TRACK_REPLACED,{track:e})}):Promise.resolve()}setBandWidth(e){return P(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return P(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:D.VIDEO,videoType:D.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return P(this,null,function*(){if(t=t.filter(o=>!o.isSubscribed),t.length===0)return;let{userId:r}=t[0],n=this.remotePublishedUserMap.get(r);if(!n)return;let s=t.find(o=>o.mediaType===2)?"auxiliary":"main";try{let o=ve({},n.subscribeState);t.forEach(c=>{switch(c.mediaType){case 1:o.audio=!0;break;case 4:o.video=!0;break;case 8:o.smallVideo=!0;break;case 2:o.auxiliary=!0}});let l=this._changeBigSmallRecords.get(r);l&&l.options.smallVideo&&n.muteState.hasSmall&&o.video&&(o.video=!1,o.smallVideo=!0),$.emit(ie.SUBSCRIBE_START,{room:this,streamType:s,remotePublishedUser:n,subscribeState:o}),this._log.info("subscribe() => ".concat(r," ").concat(s," ").concat(t.map(c=>c.strMediaType).join(",")," [").concat(wE(o),"] prev: [").concat(wE(n.subscribeState),"]")),yield n.subscribe(o,s),this._log.info("subscribe ".concat(r," ").concat(s," done"));for(let c of t)c.mediaTrack||(yield c.waitHasMediaTrack());$.emit(ie.SUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:n})}catch(o){let l=o instanceof me?o.getCode():te.UNKNOWN,c=o;throw o instanceof me?l===te.REMOTE_STREAM_NOT_EXIST&&(c=new me({code:te.API_CALL_ABORTED,message:He({key:Fe.API_CALL_ABORTED,data:{message:o.message,userId:r,streamType:s}})}),this._log.warn(c)):(c=new me({code:l,message:He({key:Fe.SUBSCRIBE_FAILED,data:{message:o.message,userId:r,streamType:s}})}),this._log.error(c)),c}})}unsubscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return P(this,null,function*(){let{userId:r}=t[0],n=this.remotePublishedUserMap.get(r);if(!n)return;let s=t.find(o=>o.mediaType===2)?"auxiliary":"main";this._log.info("unsubscribe() => ".concat(r," ").concat(s," ").concat(t.map(o=>o.strMediaType).join(",")));try{yield n.unsubscribe({remoteTracks:t,streamType:s})}catch(o){this._log.warn("unsubscribe() => failed ".concat(o))}t.forEach(o=>{o.unsubscribe(),o.mediaType===8&&o.setMediaType(4)}),$.emit(ie.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:n})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3,t=arguments.length>1?arguments[1]:void 0;if(e<=0)return this._enableAudioVolumeEvaluation=!1,void ft.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),$.emit(ie.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&ft.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=ft.run("intervalInWorker",()=>{var i;mp.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(i=this.remotePublishedUserMap)==null||i.forEach(n=>{if(n.muteState.hasAudio){!mp.isRunning&&n.muteState.audioAvailable&&n.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(n):n.remoteAudioTrack.volume=0;let s=Math.floor(100*n.remoteAudioTrack.getAudioLevel());r.push({userId:n.userId,volume:s,floatVolume:n.remoteAudioTrack.getInternalAudioLevel()})}}),this.emit("audio-volume",r)},{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return P(this,null,function*(){var i;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let r=(i=this.uplinkConnection.getPeerConnection())==null?void 0:i.getSenders()[0];if(!r)return;let n=Math.max(e,500);this._log.warn("updateAudioLevelFromSenderStat ".concat(n)),this._updateAudioLevelTaskId=ft.run("intervalInWorker",()=>P(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack)return void this.stopUpdateAudioLevelFromSenderStat();let s=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:o}=this.uplinkConnection;s.forEach(l=>{l.type==="media-source"&&l.audioLevel&&(o.volume=l.audioLevel)})}),{delay:n,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),ft.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(e=this.uplinkConnection)!=null&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var t;let{audioReceiver:i}=e;if(!hw||!i)return;let r=(t=i.getSynchronizationSources()[0])==null?void 0:t.audioLevel;nt(r)?e.remoteAudioTrack.volume=Math.min(2*r,1):i.getStats().then(n=>{n.forEach(s=>{s.type==="inbound-rtp"&&nt(s.audioLevel)&&(e.remoteAudioTrack.volume=s.audioLevel)})})}getLocalAudioStats(){return P(this,null,function*(){var e;let t={};return t[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(e=this.uplinkConnection)!=null&&e.localMainAudioTrack&&(t[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),t})}getLocalVideoStats(){return P(this,null,function*(){var e,t;let i={};return i[this.userId]=((t=(e=this.uplinkConnection)==null?void 0:e.localMainVideoTrack)==null?void 0:t.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},i})}getTransportStats(){return P(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 P(this,null,function*(){let t={};for(let[i,r]of this.remotePublishedUserMap)e==="main"&&r.muteState.hasVideo&&(t[i]=r.remoteVideoTrack.stat),e==="auxiliary"&&r.muteState.hasAuxiliary&&(t[i]=r.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return P(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(r=>i.push(Vr.getTurnServer(r))):Vr.isPlainObject(e)&&i.push(Vr.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:kj,data:e,timeout:5e3,responseCommand:Ge.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"}).catch(t=>{if(t.code!==te.API_CALL_ABORTED)throw t})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:wj,data:e,timeout:5e3,responseCommand:Ge.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"}).catch(t=>{if(t.code!==te.API_CALL_ABORTED)throw t})}sendStartPublishCDN(e){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?Rj:bj,data:e,timeout:5e3,responseCommand:t?Ge.START_PUBLISH_TENCENT_CDN_RES:Ge.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"}).catch(i=>{if(i.code!==te.API_CALL_ABORTED)throw i})}sendStopPublishCDN(e){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?Aj:Cj,data:e,timeout:5e3,responseCommand:t?Ge.STOP_PUBLISH_TENCENT_CDN_RES:Ge.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"}).catch(i=>{if(i.code!==te.API_CALL_ABORTED)throw i})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Dj,data:e,timeout:5e3,responseCommand:Ge.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"}).catch(t=>{if(t.code!==te.API_CALL_ABORTED)throw t})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Nj,data:e,timeout:5e3,responseCommand:Ge.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"}).catch(t=>{if(t.code!==te.API_CALL_ABORTED)throw t})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Pj,data:e,timeout:5e3,responseCommand:Ge.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"}).catch(t=>{if(t.code!==te.API_CALL_ABORTED)throw t})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:Uj,data:e,timeout:5e3,responseCommand:Ge.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(i=>{})}getIceServers(e){var t,i;return this._turnServers.length>0?this._turnServers:(t=this.scheduleResult.iceServers)!=null&&t.length?this.scheduleResult.iceServers:e!=null&&e.length?e:(i=this._iceServersFromJoin)!=null&&i.length?this._iceServersFromJoin:[]}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=Vr.getEnv();return t?(e.mainUrl="wss://".concat(Vr.getTestSignalDomain(t)),e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):this.proxy_unified?(e.mainUrl="wss://".concat(this.proxy_unified),e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl="wss://".concat(this.scheduleResult.domains[0]),e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl="wss://".concat(this.scheduleResult.domains[1]))),e}getSignalInfo(){var e;return((e=this.signalChannel)==null?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(e&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this.localPublishFlag=0,this.heartbeatCount=0,this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return P(this,null,function*(){let{subscribeState:t,userId:i,muteState:{hasSmall:r,hasVideo:n}}=e;if(!r&&!n||!t.video&&!t.smallVideo)return;let s=this._changeBigSmallRecords.get(i);if(!s||s.isSubscribing||s.reSubscribeCount<=0)return;let{options:o,reSubscribeCount:l}=s;if(o.video&&t.video||o.smallVideo&&t.smallVideo&&r)return;let c={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:o.video,smallVideo:o.smallVideo,datachannel:e.subscribeState.datachannel};try{if(!r&&c.smallVideo&&(c.video=!0,c.smallVideo=!1),c.smallVideo===t.smallVideo&&c.video===t.video)return;s.isSubscribing=!0,s.reSubscribeCount=l-1,yield e.subscribe(c,"main"),e.remoteVideoTrack.setMediaType(c.smallVideo?8:4),this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video successfully. count ").concat(mc-s.reSubscribeCount,".")),s.isSubscribing=!1,s.reSubscribeCount=mc}catch(h){this._log.info("change [".concat(i,"] to ").concat(c.smallVideo?"small":"big"," video failed. count ").concat(mc-s.reSubscribeCount,". reason: ").concat(h)),s.isSubscribing=!1,s.reSubscribeCount===0&&this._changeBigSmallRecords.delete(i)}})}changeType(e,t){let i={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:mc};this._changeBigSmallRecords.set(t.userId,i),this._log.info("set [".concat(t.userId,"] video prefer type: ").concat(e?"small":"big")),this.emit("subscribe-small-video-changed",{userId:t.userId,isSmall:e});let r=this.remotePublishedUserMap.get(t.userId);r&&this.checkSubscribeBigSmallVideo(r)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(YN(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!Oa(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new me({code:te.INVALID_PARAMETER,message:He({key:Fe.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(!Oa(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(i)===null)throw new me({code:te.INVALID_PARAMETER,message:He({key:Fe.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!Oa(e.userDefinePushArgs)){if(!(YN(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new me({code:te.INVALID_PARAMETER,message:He({key:Fe.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}Iz(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){return P(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&va)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()})}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new me({code:te.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return(e=this.singlePC)==null?void 0:e.scriptTransformWorker}switchRoom(e){return P(this,null,function*(){var t;if(!this.signalChannel||!this.singlePC)return;let{roomId:i,strRoomId:r,userSig:n,privateMapKey:s}=e,o=((t=this.scheduleResult.config)==null?void 0:t.autoSubscribeCount)||e?.autoSubscribeCount||1,l=String(this.useStringRoomId?r:i),c=[];for(let T=0;T<o;T++)c.push({audioSsrc:Cr(),bigVideoSsrc:Cr(),bigVideoRtxSsrc:Cr(),auxVideoSsrc:Cr(),auxVideoRtxSsrc:Cr()});let h={currRoomId:this.roomId,targetRoomId:l,useStringRoomId:this.useStringRoomId,ability:this.singlePC.clientAbility,userSig:n,privateMapKey:s??this.privateMapKey,subscribe:c};this.singlePC.autoSubscribedUserMap.clear(),this.singlePC.autoSubscribedSsrcGroups.clear(),this.singlePC.autoSubscribedSsrcGroups.set(l,c);let _,f=this.roomId;this.roomId=this.useStringRoomId?r:String(i),this.switchRoomSubedReq=new Promise(T=>{this.resolveSwitchRoomSubedReq=T,Br(5e3).then(T)}),$.emit(ie.SWITCH_ROOM_START,{room:this}),yield this.singlePC.waitForPeerConnectionConnected();try{this.userManager.clear(),_=yield this.signalChannel.sendWaitForResponse({command:Bj,responseCommand:Ge.SEND_SWITCH_ROOM_RES,data:h});let{code:T,message:b}=_.data;if(T!==0){this._log.error("switch room failed. result: ".concat(T," error: ").concat(b));let C=new me({code:te.SWITCH_ROOM_FAILED,extraCode:T,message:b});throw $.emit(ie.SWITCH_ROOM_FAILED,{room:this,error:C}),C}this.userSig=n,Oa(s)||(this.privateMapKey=s),$.emit(ie.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:f,targetRoomId:l})}catch(T){throw this.singlePC.autoSubscribedSsrcGroups.clear(),this.roomId=f,this.resolveSwitchRoomSubedReq(),T}})}isSwitchRoomSupported(){var e;let t="unable to use switchRoom API, fallback to exitRoom and enterRoom.";return((e=this.scheduleResult.config)==null?void 0:e.switchRoom)!==!0?(this._log.warn("".concat(t," Reason: this sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it.")),!1):this.scene!=="live"?(this._log.warn("".concat(t," Reason: the scene is not 'live'.")),!1):this.role!=="audience"?(this._log.warn("".concat(t," Reason: the role is not 'audience'.")),!1):!!this.singlePC||(this._log.warn("".concat(t," Reason: is not using single peerConnection.")),!1)}requestRemoteFallbackToH264(){var e;(e=this.singlePC)==null||e.requestRemoteFallbackToH264()}startUpdateNTPTime(){if(!this.signalChannel)return;let e=[];for(let t=0;t<5;t++)e.push(this.updateNTPTime());return Promise.all(e).then(t=>{var i;let r=t[0].offset,n=t[0].offset;t.forEach(l=>{r=Math.min(l.offset,r),n=Math.max(l.offset,n)});let s=Math.floor(t.reduce((l,c)=>l+c.rtt,0)/t.length),o=Math.floor(t.reduce((l,c)=>l+c.offset,0)/t.length);(n-r>30||s>50)&&setTimeout(()=>this.startUpdateNTPTime(),5e3),G1(o),(i=this.scriptTransformWorker)==null||i.postMessage({type:"ntp-offset",data:o}),this._log.debug("ntp updated offset: ".concat(o)),this.emit("ntp-time-updated")}).catch(t=>{this._log.warn("ntp updated failed: ".concat(t))})}updateNTPTime(){let e=Date.now();return this.signalChannel.sendWaitForResponse({command:Hj,responseCommand:Ge.UPDATE_NETWORK_TIME_RESULT,addReceiveTime:!0,data:{clientSendTime:String(e)},enableLog:!1}).then(t=>{let i=Number(t.data.data.serverSendTime),r=Number(t.data.data.serverRecvTime),n=t.data.receiveTime||Date.now();return{rtt:n-e-(r-i),offset:(r-e+(i-n))/2}})}};return _e([ni(["left",et.INIT],"joined"),hs({settings:{retries:1,timeout:0},onRetrying(e){this._log.warn("join retry ".concat(e))},onRetryFailed(e){this._log.error("join failed",e)},onError(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),Jr(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),_t(e=>{let t=new fj;return function(i,r,n){return P(this,null,function*(){let s=String(i.roomId||i.strRoomId);if(this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.userSig=i.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=r,i.privateMapKey=i.privateMapKey||"",this.isJoined)throw new me({code:te.INVALID_OPERATION,message:He({key:Fe.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new me({code:te.INVALID_OPERATION,message:He({key:Fe.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:s}),this.role=i.role===21?"audience":"anchor",this._log.info("Join() => joining room: ".concat(s," useStringRoomId: ").concat(this.useStringRoomId," scene: ").concat(this.scene," role: ").concat(this.role)),$.emit(ie.JOIN_START,{room:this,roomId:s,params:i});let o=Vr.getEnv();o||(o=sa.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(r0.OLD_CLOUD_LADDER)?o=sa.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(r0.WEBRTC)&&(o=sa.WEBRTC))),dt.setConfig({env:o,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),Vc.checkSystemRequirementsInternal(n).then(l=>{this.checkSystemResult=l,_j.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Vr.getEnv()&&(yield this.schedule(i,n));let l=yield e.call(this,i,r,n);return this.roomId=s,this._joinedTimestamp=Vr.performanceNow(),$.emit(ie.JOIN_SUCCESS,{room:this}),n===30&&!i.component&&dt.uploadEvent({log:"stat-conv-".concat(Number(fa),"-").concat(location.hostname),userId:this.userId}),l}catch(l){throw t.delete({room:this,roomId:s}),$.emit(ie.JOIN_FAILED,{room:this,error:l}),l}})}})],Ts.prototype,"join"),_e([ni("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),_t(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return P(this,null,function*(){$.emit(ie.LEAVE_START,{room:this}),yield e.call(this,...i),$.emit(ie.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})}),$w("leave room"),lp({fnName:"publish",validateArgs:!1}),lp({fnName:"unsubscribe",validateArgs:!1})],Ts.prototype,"leave"),_e([ps(e=>e.mediaType),_t(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return P(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(s=>s.outMediaTrack&&s.state==="ready"),!i.length))return;$.emit("61",{room:this});let n=e.apply(this,i);return Promise.all(i.map(s=>s.publish(this,n)))})}),hs({settings:{retries:Ro,timeout:e=>la(e)},onError(e,t,i,r){let[n]=r;var s;(s=e.message)!=null&&s.includes("timeout")?(this._log.warn("publish ".concat(n.strMediaType," timeout"),e),t()):(this._log.error("publish ".concat(n.strMediaType," failed: ").concat(e)),i(e),$.emit(ie.PUBLISH_FAILED,{room:this}))}})],Ts.prototype,"publish"),_e([lp({fnName:"publish"}),ps(e=>e.mediaType),_t(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];let n=e.apply(this,i);return i.forEach(s=>s.unpublish()),n}),Ta(function(){var e,t;this.localTracks.size===0&&Wc()&&((t=(e=this.singlePC)==null?void 0:e.getPeerConnection())==null||t.getSenders().forEach(i=>i.track&&i.replaceTrack(null)))})],Ts.prototype,"unpublish"),_e([Qw(e=>{if(e.code!==te.API_CALL_ABORTED)throw e}),ps(e=>e.userId)],Ts.prototype,"replaceTrack"),_e([ps(function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId},function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return"".concat(t[0].userId,"|sub")}),Cp(),_t(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];let n=e.apply(this,i);return i.forEach(s=>!s.isSubscribed&&s.subscribe(n)),n}),hs({settings:{retries:Ro,timeout:e=>la(e)},onError(e,t,i,r){if(e.message.includes("timeout"))this._log.warn("subscribe timeout"),t();else{let n=e?.code===te.API_CALL_ABORTED;this._log[n?"warn":"error"]("subscribe failed ".concat(r.map(s=>s.strMediaType).join(","),": ").concat(e)),i(e),$.emit(ie.SUBSCRIBE_FAILED,{room:this,remoteTracks:r})}}})],Ts.prototype,"subscribe"),_e([lp({fnName:"subscribe",callback(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.singlePC||t.forEach(r=>{let n=this.remotePublishedUserMap.get(r.userId);n&&!n.isMainStreamSubscribed&&!n.isAuxStreamSubscribed&&n.close("you unsubscribed")})}}),ps(function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return t[0].userId},function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return"".concat(t[0].userId,"|sub")})],Ts.prototype,"unsubscribe"),Hp.create=Hp._create.bind(Hp,Ts),yw(30),Hp})})(Ru)),Ru.exports}var pP=hP();const Ft=uP(pP);var La=typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{},kr=[],Ki=[],mP=typeof Uint8Array<"u"?Uint8Array:Array,em=!1;function VE(){em=!0;for(var a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",u=0,d=a.length;u<d;++u)kr[u]=a[u],Ki[a.charCodeAt(u)]=u;Ki[45]=62,Ki[95]=63}function fP(a,u,d){for(var p,v,g=[],y=u;y<d;y+=3)p=(a[y]<<16)+(a[y+1]<<8)+a[y+2],g.push(kr[(v=p)>>18&63]+kr[v>>12&63]+kr[v>>6&63]+kr[63&v]);return g.join("")}function FE(a){var u;em||VE();for(var d=a.length,p=d%3,v="",g=[],y=0,I=d-p;y<I;y+=16383)g.push(fP(a,y,y+16383>I?I:y+16383));return p===1?(u=a[d-1],v+=kr[u>>2],v+=kr[u<<4&63],v+="=="):p===2&&(u=(a[d-2]<<8)+a[d-1],v+=kr[u>>10],v+=kr[u>>4&63],v+=kr[u<<2&63],v+="="),g.push(v),g.join("")}function Au(a,u,d,p,v){var g,y,I=8*v-p-1,S=(1<<I)-1,E=S>>1,R=-7,k=d?v-1:0,N=d?-1:1,A=a[u+k];for(k+=N,g=A&(1<<-R)-1,A>>=-R,R+=I;R>0;g=256*g+a[u+k],k+=N,R-=8);for(y=g&(1<<-R)-1,g>>=-R,R+=p;R>0;y=256*y+a[u+k],k+=N,R-=8);if(g===0)g=1-E;else{if(g===S)return y?NaN:1/0*(A?-1:1);y+=Math.pow(2,p),g-=E}return(A?-1:1)*y*Math.pow(2,g-p)}function BE(a,u,d,p,v,g){var y,I,S,E=8*g-v-1,R=(1<<E)-1,k=R>>1,N=v===23?Math.pow(2,-24)-Math.pow(2,-77):0,A=p?0:g-1,O=p?1:-1,M=u<0||u===0&&1/u<0?1:0;for(u=Math.abs(u),isNaN(u)||u===1/0?(I=isNaN(u)?1:0,y=R):(y=Math.floor(Math.log(u)/Math.LN2),u*(S=Math.pow(2,-y))<1&&(y--,S*=2),(u+=y+k>=1?N/S:N*Math.pow(2,1-k))*S>=2&&(y++,S/=2),y+k>=R?(I=0,y=R):y+k>=1?(I=(u*S-1)*Math.pow(2,v),y+=k):(I=u*Math.pow(2,k-1)*Math.pow(2,v),y=0));v>=8;a[d+A]=255&I,A+=O,I/=256,v-=8);for(y=y<<v|I,E+=v;E>0;a[d+A]=255&y,A+=O,y/=256,E-=8);a[d+A-O]|=128*M}var _P={}.toString,HE=Array.isArray||function(a){return _P.call(a)=="[object Array]"};function tm(){return re.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function Yr(a,u){if(tm()<u)throw new RangeError("Invalid typed array length");return re.TYPED_ARRAY_SUPPORT?(a=new Uint8Array(u)).__proto__=re.prototype:(a===null&&(a=new re(u)),a.length=u),a}function re(a,u,d){if(!(re.TYPED_ARRAY_SUPPORT||this instanceof re))return new re(a,u,d);if(typeof a=="number"){if(typeof u=="string")throw new Error("If encoding is specified then the first argument must be a string");return im(this,a)}return WE(this,a,u,d)}function WE(a,u,d,p){if(typeof u=="number")throw new TypeError('"value" argument must not be a number');return typeof ArrayBuffer<"u"&&u instanceof ArrayBuffer?(function(v,g,y,I){if(g.byteLength,y<0||g.byteLength<y)throw new RangeError("'offset' is out of bounds");if(g.byteLength<y+(I||0))throw new RangeError("'length' is out of bounds");return g=y===void 0&&I===void 0?new Uint8Array(g):I===void 0?new Uint8Array(g,y):new Uint8Array(g,y,I),re.TYPED_ARRAY_SUPPORT?(v=g).__proto__=re.prototype:v=rm(v,g),v})(a,u,d,p):typeof u=="string"?(function(v,g,y){if(typeof y=="string"&&y!==""||(y="utf8"),!re.isEncoding(y))throw new TypeError('"encoding" must be a valid string encoding');var I=0|jE(g,y),S=(v=Yr(v,I)).write(g,y);return S!==I&&(v=v.slice(0,S)),v})(a,u,d):(function(v,g){if(wr(g)){var y=0|nm(g.length);return(v=Yr(v,y)).length===0||g.copy(v,0,0,y),v}if(g){if(typeof ArrayBuffer<"u"&&g.buffer instanceof ArrayBuffer||"length"in g)return typeof g.length!="number"||(I=g.length)!=I?Yr(v,0):rm(v,g);if(g.type==="Buffer"&&HE(g.data))return rm(v,g.data)}var I;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")})(a,u)}function GE(a){if(typeof a!="number")throw new TypeError('"size" argument must be a number');if(a<0)throw new RangeError('"size" argument must not be negative')}function im(a,u){if(GE(u),a=Yr(a,u<0?0:0|nm(u)),!re.TYPED_ARRAY_SUPPORT)for(var d=0;d<u;++d)a[d]=0;return a}function rm(a,u){var d=u.length<0?0:0|nm(u.length);a=Yr(a,d);for(var p=0;p<d;p+=1)a[p]=255&u[p];return a}function nm(a){if(a>=tm())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+tm().toString(16)+" bytes");return 0|a}function wr(a){return!(a==null||!a._isBuffer)}function jE(a,u){if(wr(a))return a.length;if(typeof ArrayBuffer<"u"&&typeof ArrayBuffer.isView=="function"&&(ArrayBuffer.isView(a)||a instanceof ArrayBuffer))return a.byteLength;typeof a!="string"&&(a=""+a);var d=a.length;if(d===0)return 0;for(var p=!1;;)switch(u){case"ascii":case"latin1":case"binary":return d;case"utf8":case"utf-8":case void 0:return ku(a).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*d;case"hex":return d>>>1;case"base64":return $E(a).length;default:if(p)return ku(a).length;u=(""+u).toLowerCase(),p=!0}}function gP(a,u,d){var p=!1;if((u===void 0||u<0)&&(u=0),u>this.length||((d===void 0||d>this.length)&&(d=this.length),d<=0)||(d>>>=0)<=(u>>>=0))return"";for(a||(a="utf8");;)switch(a){case"hex":return bP(this,u,d);case"utf8":case"utf-8":return YE(this,u,d);case"ascii":return RP(this,u,d);case"latin1":case"binary":return AP(this,u,d);case"base64":return IP(this,u,d);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return CP(this,u,d);default:if(p)throw new TypeError("Unknown encoding: "+a);a=(a+"").toLowerCase(),p=!0}}function Ss(a,u,d){var p=a[u];a[u]=a[d],a[d]=p}function zE(a,u,d,p,v){if(a.length===0)return-1;if(typeof d=="string"?(p=d,d=0):d>2147483647?d=2147483647:d<-2147483648&&(d=-2147483648),d=+d,isNaN(d)&&(d=v?0:a.length-1),d<0&&(d=a.length+d),d>=a.length){if(v)return-1;d=a.length-1}else if(d<0){if(!v)return-1;d=0}if(typeof u=="string"&&(u=re.from(u,p)),wr(u))return u.length===0?-1:KE(a,u,d,p,v);if(typeof u=="number")return u&=255,re.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf=="function"?v?Uint8Array.prototype.indexOf.call(a,u,d):Uint8Array.prototype.lastIndexOf.call(a,u,d):KE(a,[u],d,p,v);throw new TypeError("val must be string, number or Buffer")}function KE(a,u,d,p,v){var g,y=1,I=a.length,S=u.length;if(p!==void 0&&((p=String(p).toLowerCase())==="ucs2"||p==="ucs-2"||p==="utf16le"||p==="utf-16le")){if(a.length<2||u.length<2)return-1;y=2,I/=2,S/=2,d/=2}function E(A,O){return y===1?A[O]:A.readUInt16BE(O*y)}if(v){var R=-1;for(g=d;g<I;g++)if(E(a,g)===E(u,R===-1?0:g-R)){if(R===-1&&(R=g),g-R+1===S)return R*y}else R!==-1&&(g-=g-R),R=-1}else for(d+S>I&&(d=I-S),g=d;g>=0;g--){for(var k=!0,N=0;N<S;N++)if(E(a,g+N)!==E(u,N)){k=!1;break}if(k)return g}return-1}function vP(a,u,d,p){d=Number(d)||0;var v=a.length-d;p?(p=Number(p))>v&&(p=v):p=v;var g=u.length;if(g%2!=0)throw new TypeError("Invalid hex string");p>g/2&&(p=g/2);for(var y=0;y<p;++y){var I=parseInt(u.substr(2*y,2),16);if(isNaN(I))return y;a[d+y]=I}return y}function EP(a,u,d,p){return wu(ku(u,a.length-d),a,d,p)}function JE(a,u,d,p){return wu((function(v){for(var g=[],y=0;y<v.length;++y)g.push(255&v.charCodeAt(y));return g})(u),a,d,p)}function yP(a,u,d,p){return JE(a,u,d,p)}function TP(a,u,d,p){return wu($E(u),a,d,p)}function SP(a,u,d,p){return wu((function(v,g){for(var y,I,S,E=[],R=0;R<v.length&&!((g-=2)<0);++R)y=v.charCodeAt(R),I=y>>8,S=y%256,E.push(S),E.push(I);return E})(u,a.length-d),a,d,p)}function IP(a,u,d){return u===0&&d===a.length?FE(a):FE(a.slice(u,d))}function YE(a,u,d){d=Math.min(a.length,d);for(var p=[],v=u;v<d;){var g,y,I,S,E=a[v],R=null,k=E>239?4:E>223?3:E>191?2:1;if(v+k<=d)switch(k){case 1:E<128&&(R=E);break;case 2:(192&(g=a[v+1]))==128&&(S=(31&E)<<6|63&g)>127&&(R=S);break;case 3:g=a[v+1],y=a[v+2],(192&g)==128&&(192&y)==128&&(S=(15&E)<<12|(63&g)<<6|63&y)>2047&&(S<55296||S>57343)&&(R=S);break;case 4:g=a[v+1],y=a[v+2],I=a[v+3],(192&g)==128&&(192&y)==128&&(192&I)==128&&(S=(15&E)<<18|(63&g)<<12|(63&y)<<6|63&I)>65535&&S<1114112&&(R=S)}R===null?(R=65533,k=1):R>65535&&(R-=65536,p.push(R>>>10&1023|55296),R=56320|1023&R),p.push(R),v+=k}return(function(N){var A=N.length;if(A<=qE)return String.fromCharCode.apply(String,N);for(var O="",M=0;M<A;)O+=String.fromCharCode.apply(String,N.slice(M,M+=qE));return O})(p)}re.TYPED_ARRAY_SUPPORT=La.TYPED_ARRAY_SUPPORT===void 0||La.TYPED_ARRAY_SUPPORT,re.poolSize=8192,re._augment=function(a){return a.__proto__=re.prototype,a},re.from=function(a,u,d){return WE(null,a,u,d)},re.TYPED_ARRAY_SUPPORT&&(re.prototype.__proto__=Uint8Array.prototype,re.__proto__=Uint8Array),re.alloc=function(a,u,d){return(function(p,v,g,y){return GE(v),v<=0?Yr(p,v):g!==void 0?typeof y=="string"?Yr(p,v).fill(g,y):Yr(p,v).fill(g):Yr(p,v)})(null,a,u,d)},re.allocUnsafe=function(a){return im(null,a)},re.allocUnsafeSlow=function(a){return im(null,a)},re.isBuffer=el,re.compare=function(a,u){if(!wr(a)||!wr(u))throw new TypeError("Arguments must be Buffers");if(a===u)return 0;for(var d=a.length,p=u.length,v=0,g=Math.min(d,p);v<g;++v)if(a[v]!==u[v]){d=a[v],p=u[v];break}return d<p?-1:p<d?1:0},re.isEncoding=function(a){switch(String(a).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},re.concat=function(a,u){if(!HE(a))throw new TypeError('"list" argument must be an Array of Buffers');if(a.length===0)return re.alloc(0);var d;if(u===void 0)for(u=0,d=0;d<a.length;++d)u+=a[d].length;var p=re.allocUnsafe(u),v=0;for(d=0;d<a.length;++d){var g=a[d];if(!wr(g))throw new TypeError('"list" argument must be an Array of Buffers');g.copy(p,v),v+=g.length}return p},re.byteLength=jE,re.prototype._isBuffer=!0,re.prototype.swap16=function(){var a=this.length;if(a%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var u=0;u<a;u+=2)Ss(this,u,u+1);return this},re.prototype.swap32=function(){var a=this.length;if(a%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var u=0;u<a;u+=4)Ss(this,u,u+3),Ss(this,u+1,u+2);return this},re.prototype.swap64=function(){var a=this.length;if(a%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var u=0;u<a;u+=8)Ss(this,u,u+7),Ss(this,u+1,u+6),Ss(this,u+2,u+5),Ss(this,u+3,u+4);return this},re.prototype.toString=function(){var a=0|this.length;return a===0?"":arguments.length===0?YE(this,0,a):gP.apply(this,arguments)},re.prototype.equals=function(a){if(!wr(a))throw new TypeError("Argument must be a Buffer");return this===a||re.compare(this,a)===0},re.prototype.inspect=function(){var a="";return this.length>0&&(a=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(a+=" ... ")),"<Buffer "+a+">"},re.prototype.compare=function(a,u,d,p,v){if(!wr(a))throw new TypeError("Argument must be a Buffer");if(u===void 0&&(u=0),d===void 0&&(d=a?a.length:0),p===void 0&&(p=0),v===void 0&&(v=this.length),u<0||d>a.length||p<0||v>this.length)throw new RangeError("out of range index");if(p>=v&&u>=d)return 0;if(p>=v)return-1;if(u>=d)return 1;if(this===a)return 0;for(var g=(v>>>=0)-(p>>>=0),y=(d>>>=0)-(u>>>=0),I=Math.min(g,y),S=this.slice(p,v),E=a.slice(u,d),R=0;R<I;++R)if(S[R]!==E[R]){g=S[R],y=E[R];break}return g<y?-1:y<g?1:0},re.prototype.includes=function(a,u,d){return this.indexOf(a,u,d)!==-1},re.prototype.indexOf=function(a,u,d){return zE(this,a,u,d,!0)},re.prototype.lastIndexOf=function(a,u,d){return zE(this,a,u,d,!1)},re.prototype.write=function(a,u,d,p){if(u===void 0)p="utf8",d=this.length,u=0;else if(d===void 0&&typeof u=="string")p=u,d=this.length,u=0;else{if(!isFinite(u))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");u|=0,isFinite(d)?(d|=0,p===void 0&&(p="utf8")):(p=d,d=void 0)}var v=this.length-u;if((d===void 0||d>v)&&(d=v),a.length>0&&(d<0||u<0)||u>this.length)throw new RangeError("Attempt to write outside buffer bounds");p||(p="utf8");for(var g=!1;;)switch(p){case"hex":return vP(this,a,u,d);case"utf8":case"utf-8":return EP(this,a,u,d);case"ascii":return JE(this,a,u,d);case"latin1":case"binary":return yP(this,a,u,d);case"base64":return TP(this,a,u,d);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return SP(this,a,u,d);default:if(g)throw new TypeError("Unknown encoding: "+p);p=(""+p).toLowerCase(),g=!0}},re.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var qE=4096;function RP(a,u,d){var p="";d=Math.min(a.length,d);for(var v=u;v<d;++v)p+=String.fromCharCode(127&a[v]);return p}function AP(a,u,d){var p="";d=Math.min(a.length,d);for(var v=u;v<d;++v)p+=String.fromCharCode(a[v]);return p}function bP(a,u,d){var p=a.length;(!u||u<0)&&(u=0),(!d||d<0||d>p)&&(d=p);for(var v="",g=u;g<d;++g)v+=wP(a[g]);return v}function CP(a,u,d){for(var p=a.slice(u,d),v="",g=0;g<p.length;g+=2)v+=String.fromCharCode(p[g]+256*p[g+1]);return v}function Zt(a,u,d){if(a%1!=0||a<0)throw new RangeError("offset is not uint");if(a+u>d)throw new RangeError("Trying to access beyond buffer length")}function wi(a,u,d,p,v,g){if(!wr(a))throw new TypeError('"buffer" argument must be a Buffer instance');if(u>v||u<g)throw new RangeError('"value" argument is out of bounds');if(d+p>a.length)throw new RangeError("Index out of range")}function bu(a,u,d,p){u<0&&(u=65535+u+1);for(var v=0,g=Math.min(a.length-d,2);v<g;++v)a[d+v]=(u&255<<8*(p?v:1-v))>>>8*(p?v:1-v)}function Cu(a,u,d,p){u<0&&(u=4294967295+u+1);for(var v=0,g=Math.min(a.length-d,4);v<g;++v)a[d+v]=u>>>8*(p?v:3-v)&255}function XE(a,u,d,p,v,g){if(d+p>a.length)throw new RangeError("Index out of range");if(d<0)throw new RangeError("Index out of range")}function QE(a,u,d,p,v){return v||XE(a,0,d,4),BE(a,u,d,p,23,4),d+4}function ZE(a,u,d,p,v){return v||XE(a,0,d,8),BE(a,u,d,p,52,8),d+8}re.prototype.slice=function(a,u){var d,p=this.length;if((a=~~a)<0?(a+=p)<0&&(a=0):a>p&&(a=p),(u=u===void 0?p:~~u)<0?(u+=p)<0&&(u=0):u>p&&(u=p),u<a&&(u=a),re.TYPED_ARRAY_SUPPORT)(d=this.subarray(a,u)).__proto__=re.prototype;else{var v=u-a;d=new re(v,void 0);for(var g=0;g<v;++g)d[g]=this[g+a]}return d},re.prototype.readUIntLE=function(a,u,d){a|=0,u|=0,d||Zt(a,u,this.length);for(var p=this[a],v=1,g=0;++g<u&&(v*=256);)p+=this[a+g]*v;return p},re.prototype.readUIntBE=function(a,u,d){a|=0,u|=0,d||Zt(a,u,this.length);for(var p=this[a+--u],v=1;u>0&&(v*=256);)p+=this[a+--u]*v;return p},re.prototype.readUInt8=function(a,u){return u||Zt(a,1,this.length),this[a]},re.prototype.readUInt16LE=function(a,u){return u||Zt(a,2,this.length),this[a]|this[a+1]<<8},re.prototype.readUInt16BE=function(a,u){return u||Zt(a,2,this.length),this[a]<<8|this[a+1]},re.prototype.readUInt32LE=function(a,u){return u||Zt(a,4,this.length),(this[a]|this[a+1]<<8|this[a+2]<<16)+16777216*this[a+3]},re.prototype.readUInt32BE=function(a,u){return u||Zt(a,4,this.length),16777216*this[a]+(this[a+1]<<16|this[a+2]<<8|this[a+3])},re.prototype.readIntLE=function(a,u,d){a|=0,u|=0,d||Zt(a,u,this.length);for(var p=this[a],v=1,g=0;++g<u&&(v*=256);)p+=this[a+g]*v;return p>=(v*=128)&&(p-=Math.pow(2,8*u)),p},re.prototype.readIntBE=function(a,u,d){a|=0,u|=0,d||Zt(a,u,this.length);for(var p=u,v=1,g=this[a+--p];p>0&&(v*=256);)g+=this[a+--p]*v;return g>=(v*=128)&&(g-=Math.pow(2,8*u)),g},re.prototype.readInt8=function(a,u){return u||Zt(a,1,this.length),128&this[a]?-1*(255-this[a]+1):this[a]},re.prototype.readInt16LE=function(a,u){u||Zt(a,2,this.length);var d=this[a]|this[a+1]<<8;return 32768&d?4294901760|d:d},re.prototype.readInt16BE=function(a,u){u||Zt(a,2,this.length);var d=this[a+1]|this[a]<<8;return 32768&d?4294901760|d:d},re.prototype.readInt32LE=function(a,u){return u||Zt(a,4,this.length),this[a]|this[a+1]<<8|this[a+2]<<16|this[a+3]<<24},re.prototype.readInt32BE=function(a,u){return u||Zt(a,4,this.length),this[a]<<24|this[a+1]<<16|this[a+2]<<8|this[a+3]},re.prototype.readFloatLE=function(a,u){return u||Zt(a,4,this.length),Au(this,a,!0,23,4)},re.prototype.readFloatBE=function(a,u){return u||Zt(a,4,this.length),Au(this,a,!1,23,4)},re.prototype.readDoubleLE=function(a,u){return u||Zt(a,8,this.length),Au(this,a,!0,52,8)},re.prototype.readDoubleBE=function(a,u){return u||Zt(a,8,this.length),Au(this,a,!1,52,8)},re.prototype.writeUIntLE=function(a,u,d,p){a=+a,u|=0,d|=0,p||wi(this,a,u,d,Math.pow(2,8*d)-1,0);var v=1,g=0;for(this[u]=255&a;++g<d&&(v*=256);)this[u+g]=a/v&255;return u+d},re.prototype.writeUIntBE=function(a,u,d,p){a=+a,u|=0,d|=0,p||wi(this,a,u,d,Math.pow(2,8*d)-1,0);var v=d-1,g=1;for(this[u+v]=255&a;--v>=0&&(g*=256);)this[u+v]=a/g&255;return u+d},re.prototype.writeUInt8=function(a,u,d){return a=+a,u|=0,d||wi(this,a,u,1,255,0),re.TYPED_ARRAY_SUPPORT||(a=Math.floor(a)),this[u]=255&a,u+1},re.prototype.writeUInt16LE=function(a,u,d){return a=+a,u|=0,d||wi(this,a,u,2,65535,0),re.TYPED_ARRAY_SUPPORT?(this[u]=255&a,this[u+1]=a>>>8):bu(this,a,u,!0),u+2},re.prototype.writeUInt16BE=function(a,u,d){return a=+a,u|=0,d||wi(this,a,u,2,65535,0),re.TYPED_ARRAY_SUPPORT?(this[u]=a>>>8,this[u+1]=255&a):bu(this,a,u,!1),u+2},re.prototype.writeUInt32LE=function(a,u,d){return a=+a,u|=0,d||wi(this,a,u,4,4294967295,0),re.TYPED_ARRAY_SUPPORT?(this[u+3]=a>>>24,this[u+2]=a>>>16,this[u+1]=a>>>8,this[u]=255&a):Cu(this,a,u,!0),u+4},re.prototype.writeUInt32BE=function(a,u,d){return a=+a,u|=0,d||wi(this,a,u,4,4294967295,0),re.TYPED_ARRAY_SUPPORT?(this[u]=a>>>24,this[u+1]=a>>>16,this[u+2]=a>>>8,this[u+3]=255&a):Cu(this,a,u,!1),u+4},re.prototype.writeIntLE=function(a,u,d,p){if(a=+a,u|=0,!p){var v=Math.pow(2,8*d-1);wi(this,a,u,d,v-1,-v)}var g=0,y=1,I=0;for(this[u]=255&a;++g<d&&(y*=256);)a<0&&I===0&&this[u+g-1]!==0&&(I=1),this[u+g]=(a/y>>0)-I&255;return u+d},re.prototype.writeIntBE=function(a,u,d,p){if(a=+a,u|=0,!p){var v=Math.pow(2,8*d-1);wi(this,a,u,d,v-1,-v)}var g=d-1,y=1,I=0;for(this[u+g]=255&a;--g>=0&&(y*=256);)a<0&&I===0&&this[u+g+1]!==0&&(I=1),this[u+g]=(a/y>>0)-I&255;return u+d},re.prototype.writeInt8=function(a,u,d){return a=+a,u|=0,d||wi(this,a,u,1,127,-128),re.TYPED_ARRAY_SUPPORT||(a=Math.floor(a)),a<0&&(a=255+a+1),this[u]=255&a,u+1},re.prototype.writeInt16LE=function(a,u,d){return a=+a,u|=0,d||wi(this,a,u,2,32767,-32768),re.TYPED_ARRAY_SUPPORT?(this[u]=255&a,this[u+1]=a>>>8):bu(this,a,u,!0),u+2},re.prototype.writeInt16BE=function(a,u,d){return a=+a,u|=0,d||wi(this,a,u,2,32767,-32768),re.TYPED_ARRAY_SUPPORT?(this[u]=a>>>8,this[u+1]=255&a):bu(this,a,u,!1),u+2},re.prototype.writeInt32LE=function(a,u,d){return a=+a,u|=0,d||wi(this,a,u,4,2147483647,-2147483648),re.TYPED_ARRAY_SUPPORT?(this[u]=255&a,this[u+1]=a>>>8,this[u+2]=a>>>16,this[u+3]=a>>>24):Cu(this,a,u,!0),u+4},re.prototype.writeInt32BE=function(a,u,d){return a=+a,u|=0,d||wi(this,a,u,4,2147483647,-2147483648),a<0&&(a=4294967295+a+1),re.TYPED_ARRAY_SUPPORT?(this[u]=a>>>24,this[u+1]=a>>>16,this[u+2]=a>>>8,this[u+3]=255&a):Cu(this,a,u,!1),u+4},re.prototype.writeFloatLE=function(a,u,d){return QE(this,a,u,!0,d)},re.prototype.writeFloatBE=function(a,u,d){return QE(this,a,u,!1,d)},re.prototype.writeDoubleLE=function(a,u,d){return ZE(this,a,u,!0,d)},re.prototype.writeDoubleBE=function(a,u,d){return ZE(this,a,u,!1,d)},re.prototype.copy=function(a,u,d,p){if(d||(d=0),p||p===0||(p=this.length),u>=a.length&&(u=a.length),u||(u=0),p>0&&p<d&&(p=d),p===d||a.length===0||this.length===0)return 0;if(u<0)throw new RangeError("targetStart out of bounds");if(d<0||d>=this.length)throw new RangeError("sourceStart out of bounds");if(p<0)throw new RangeError("sourceEnd out of bounds");p>this.length&&(p=this.length),a.length-u<p-d&&(p=a.length-u+d);var v,g=p-d;if(this===a&&d<u&&u<p)for(v=g-1;v>=0;--v)a[v+u]=this[v+d];else if(g<1e3||!re.TYPED_ARRAY_SUPPORT)for(v=0;v<g;++v)a[v+u]=this[v+d];else Uint8Array.prototype.set.call(a,this.subarray(d,d+g),u);return g},re.prototype.fill=function(a,u,d,p){if(typeof a=="string"){if(typeof u=="string"?(p=u,u=0,d=this.length):typeof d=="string"&&(p=d,d=this.length),a.length===1){var v=a.charCodeAt(0);v<256&&(a=v)}if(p!==void 0&&typeof p!="string")throw new TypeError("encoding must be a string");if(typeof p=="string"&&!re.isEncoding(p))throw new TypeError("Unknown encoding: "+p)}else typeof a=="number"&&(a&=255);if(u<0||this.length<u||this.length<d)throw new RangeError("Out of range index");if(d<=u)return this;var g;if(u>>>=0,d=d===void 0?this.length:d>>>0,a||(a=0),typeof a=="number")for(g=u;g<d;++g)this[g]=a;else{var y=wr(a)?a:ku(new re(a,p).toString()),I=y.length;for(g=0;g<d-u;++g)this[g+u]=y[g%I]}return this};var kP=/[^+\/0-9A-Za-z-_]/g;function wP(a){return a<16?"0"+a.toString(16):a.toString(16)}function ku(a,u){var d;u=u||1/0;for(var p=a.length,v=null,g=[],y=0;y<p;++y){if((d=a.charCodeAt(y))>55295&&d<57344){if(!v){if(d>56319){(u-=3)>-1&&g.push(239,191,189);continue}if(y+1===p){(u-=3)>-1&&g.push(239,191,189);continue}v=d;continue}if(d<56320){(u-=3)>-1&&g.push(239,191,189),v=d;continue}d=65536+(v-55296<<10|d-56320)}else v&&(u-=3)>-1&&g.push(239,191,189);if(v=null,d<128){if((u-=1)<0)break;g.push(d)}else if(d<2048){if((u-=2)<0)break;g.push(d>>6|192,63&d|128)}else if(d<65536){if((u-=3)<0)break;g.push(d>>12|224,d>>6&63|128,63&d|128)}else{if(!(d<1114112))throw new Error("Invalid code point");if((u-=4)<0)break;g.push(d>>18|240,d>>12&63|128,d>>6&63|128,63&d|128)}}return g}function $E(a){return(function(u){var d,p,v,g,y,I;em||VE();var S=u.length;if(S%4>0)throw new Error("Invalid string. Length must be a multiple of 4");y=u[S-2]==="="?2:u[S-1]==="="?1:0,I=new mP(3*S/4-y),v=y>0?S-4:S;var E=0;for(d=0,p=0;d<v;d+=4,p+=3)g=Ki[u.charCodeAt(d)]<<18|Ki[u.charCodeAt(d+1)]<<12|Ki[u.charCodeAt(d+2)]<<6|Ki[u.charCodeAt(d+3)],I[E++]=g>>16&255,I[E++]=g>>8&255,I[E++]=255&g;return y===2?(g=Ki[u.charCodeAt(d)]<<2|Ki[u.charCodeAt(d+1)]>>4,I[E++]=255&g):y===1&&(g=Ki[u.charCodeAt(d)]<<10|Ki[u.charCodeAt(d+1)]<<4|Ki[u.charCodeAt(d+2)]>>2,I[E++]=g>>8&255,I[E++]=255&g),I})((function(u){if((u=(function(d){return d.trim?d.trim():d.replace(/^\s+|\s+$/g,"")})(u).replace(kP,"")).length<2)return"";for(;u.length%4!=0;)u+="=";return u})(a))}function wu(a,u,d,p){for(var v=0;v<p&&!(v+d>=u.length||v>=a.length);++v)u[v+d]=a[v];return v}function el(a){return a!=null&&(!!a._isBuffer||ey(a)||(function(u){return typeof u.readFloatLE=="function"&&typeof u.slice=="function"&&ey(u.slice(0,0))})(a))}function ey(a){return!!a.constructor&&typeof a.constructor.isBuffer=="function"&&a.constructor.isBuffer(a)}function ot(a,u){return a(u={exports:{}},u.exports),u.exports}var ct=ot(function(a,u){var d;a.exports=(d=d||(function(p,v){var g=Object.create||(function(){function w(){}return function(U){var L;return w.prototype=U,L=new w,w.prototype=null,L}})(),y={},I=y.lib={},S=I.Base={extend:function(w){var U=g(this);return w&&U.mixIn(w),U.hasOwnProperty("init")&&this.init!==U.init||(U.init=function(){U.$super.init.apply(this,arguments)}),U.init.prototype=U,U.$super=this,U},create:function(){var w=this.extend();return w.init.apply(w,arguments),w},init:function(){},mixIn:function(w){for(var U in w)w.hasOwnProperty(U)&&(this[U]=w[U]);w.hasOwnProperty("toString")&&(this.toString=w.toString)},clone:function(){return this.init.prototype.extend(this)}},E=I.WordArray=S.extend({init:function(w,U){w=this.words=w||[],this.sigBytes=U??4*w.length},toString:function(w){return(w||k).stringify(this)},concat:function(w){var U=this.words,L=w.words,V=this.sigBytes,F=w.sigBytes;if(this.clamp(),V%4)for(var q=0;q<F;q++){var K=L[q>>>2]>>>24-q%4*8&255;U[V+q>>>2]|=K<<24-(V+q)%4*8}else for(var q=0;q<F;q+=4)U[V+q>>>2]=L[q>>>2];return this.sigBytes+=F,this},clamp:function(){var w=this.words,U=this.sigBytes;w[U>>>2]&=4294967295<<32-U%4*8,w.length=p.ceil(U/4)},clone:function(){var w=S.clone.call(this);return w.words=this.words.slice(0),w},random:function(w){for(var U,L=[],V=function(z){var z=z,J=987654321,X=4294967295;return function(){var W=((J=36969*(65535&J)+(J>>16)&X)<<16)+(z=18e3*(65535&z)+(z>>16)&X)&X;return W/=4294967296,(W+=.5)*(p.random()>.5?1:-1)}},F=0;F<w;F+=4){var q=V(4294967296*(U||p.random()));U=987654071*q(),L.push(4294967296*q()|0)}return new E.init(L,w)}}),R=y.enc={},k=R.Hex={stringify:function(w){for(var U=w.words,L=w.sigBytes,V=[],F=0;F<L;F++){var q=U[F>>>2]>>>24-F%4*8&255;V.push((q>>>4).toString(16)),V.push((15&q).toString(16))}return V.join("")},parse:function(w){for(var U=w.length,L=[],V=0;V<U;V+=2)L[V>>>3]|=parseInt(w.substr(V,2),16)<<24-V%8*4;return new E.init(L,U/2)}},N=R.Latin1={stringify:function(w){for(var U=w.words,L=w.sigBytes,V=[],F=0;F<L;F++){var q=U[F>>>2]>>>24-F%4*8&255;V.push(String.fromCharCode(q))}return V.join("")},parse:function(w){for(var U=w.length,L=[],V=0;V<U;V++)L[V>>>2]|=(255&w.charCodeAt(V))<<24-V%4*8;return new E.init(L,U)}},A=R.Utf8={stringify:function(w){try{return decodeURIComponent(escape(N.stringify(w)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(w){return N.parse(unescape(encodeURIComponent(w)))}},O=I.BufferedBlockAlgorithm=S.extend({reset:function(){this._data=new E.init,this._nDataBytes=0},_append:function(w){typeof w=="string"&&(w=A.parse(w)),this._data.concat(w),this._nDataBytes+=w.sigBytes},_process:function(w){var U=this._data,L=U.words,V=U.sigBytes,F=this.blockSize,q=4*F,K=V/q,z=(K=w?p.ceil(K):p.max((0|K)-this._minBufferSize,0))*F,J=p.min(4*z,V);if(z){for(var X=0;X<z;X+=F)this._doProcessBlock(L,X);var W=L.splice(0,z);U.sigBytes-=J}return new E.init(W,J)},clone:function(){var w=S.clone.call(this);return w._data=this._data.clone(),w},_minBufferSize:0}),M=(I.Hasher=O.extend({cfg:S.extend(),init:function(w){this.cfg=this.cfg.extend(w),this.reset()},reset:function(){O.reset.call(this),this._doReset()},update:function(w){return this._append(w),this._process(),this},finalize:function(w){w&&this._append(w);var U=this._doFinalize();return U},blockSize:16,_createHelper:function(w){return function(U,L){return new w.init(L).finalize(U)}},_createHmacHelper:function(w){return function(U,L){return new M.HMAC.init(w,L).finalize(U)}}}),y.algo={});return y})(Math),d)}),ty=(ot(function(a,u){var d,p,v,g,y,I;a.exports=(v=(p=d=ct).lib,g=v.Base,y=v.WordArray,(I=p.x64={}).Word=g.extend({init:function(S,E){this.high=S,this.low=E}}),I.WordArray=g.extend({init:function(S,E){S=this.words=S||[],this.sigBytes=E??8*S.length},toX32:function(){for(var S=this.words,E=S.length,R=[],k=0;k<E;k++){var N=S[k];R.push(N.high),R.push(N.low)}return y.create(R,this.sigBytes)},clone:function(){for(var S=g.clone.call(this),E=S.words=this.words.slice(0),R=E.length,k=0;k<R;k++)E[k]=E[k].clone();return S}}),d)}),ot(function(a,u){var d;a.exports=(d=ct,(function(){if(typeof ArrayBuffer=="function"){var p=d.lib.WordArray,v=p.init;(p.init=function(g){if(g instanceof ArrayBuffer&&(g=new Uint8Array(g)),(g instanceof Int8Array||typeof Uint8ClampedArray<"u"&&g instanceof Uint8ClampedArray||g instanceof Int16Array||g instanceof Uint16Array||g instanceof Int32Array||g instanceof Uint32Array||g instanceof Float32Array||g instanceof Float64Array)&&(g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength)),g instanceof Uint8Array){for(var y=g.byteLength,I=[],S=0;S<y;S++)I[S>>>2]|=g[S]<<24-S%4*8;v.call(this,I,y)}else v.apply(this,arguments)}).prototype=p}})(),d.lib.WordArray)}),ot(function(a,u){var d;a.exports=(d=ct,(function(){var p=d,v=p.lib.WordArray,g=p.enc;function y(I){return I<<8&4278255360|I>>>8&16711935}g.Utf16=g.Utf16BE={stringify:function(I){for(var S=I.words,E=I.sigBytes,R=[],k=0;k<E;k+=2){var N=S[k>>>2]>>>16-k%4*8&65535;R.push(String.fromCharCode(N))}return R.join("")},parse:function(I){for(var S=I.length,E=[],R=0;R<S;R++)E[R>>>1]|=I.charCodeAt(R)<<16-R%2*16;return v.create(E,2*S)}},g.Utf16LE={stringify:function(I){for(var S=I.words,E=I.sigBytes,R=[],k=0;k<E;k+=2){var N=y(S[k>>>2]>>>16-k%4*8&65535);R.push(String.fromCharCode(N))}return R.join("")},parse:function(I){for(var S=I.length,E=[],R=0;R<S;R++)E[R>>>1]|=y(I.charCodeAt(R)<<16-R%2*16);return v.create(E,2*S)}}})(),d.enc.Utf16)}),ot(function(a,u){var d,p,v;a.exports=(v=(p=d=ct).lib.WordArray,p.enc.Base64={stringify:function(g){var y=g.words,I=g.sigBytes,S=this._map;g.clamp();for(var E=[],R=0;R<I;R+=3)for(var k=(y[R>>>2]>>>24-R%4*8&255)<<16|(y[R+1>>>2]>>>24-(R+1)%4*8&255)<<8|y[R+2>>>2]>>>24-(R+2)%4*8&255,N=0;N<4&&R+.75*N<I;N++)E.push(S.charAt(k>>>6*(3-N)&63));var A=S.charAt(64);if(A)for(;E.length%4;)E.push(A);return E.join("")},parse:function(g){var y=g.length,I=this._map,S=this._reverseMap;if(!S){S=this._reverseMap=[];for(var E=0;E<I.length;E++)S[I.charCodeAt(E)]=E}var R=I.charAt(64);if(R){var k=g.indexOf(R);k!==-1&&(y=k)}return(function(N,A,O){for(var M=[],w=0,U=0;U<A;U++)if(U%4){var L=O[N.charCodeAt(U-1)]<<U%4*2,V=O[N.charCodeAt(U)]>>>6-U%4*2;M[w>>>2]|=(L|V)<<24-w%4*8,w++}return v.create(M,w)})(g,y,S)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},d.enc.Base64)}),ot(function(a,u){var d;a.exports=(d=ct,(function(p){var v=d,g=v.lib,y=g.WordArray,I=g.Hasher,S=v.algo,E=[];(function(){for(var M=0;M<64;M++)E[M]=4294967296*p.abs(p.sin(M+1))|0})();var R=S.MD5=I.extend({_doReset:function(){this._hash=new y.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(M,w){for(var U=0;U<16;U++){var L=w+U,V=M[L];M[L]=16711935&(V<<8|V>>>24)|4278255360&(V<<24|V>>>8)}var F=this._hash.words,q=M[w+0],K=M[w+1],z=M[w+2],J=M[w+3],X=M[w+4],W=M[w+5],Q=M[w+6],ge=M[w+7],ne=M[w+8],Te=M[w+9],ke=M[w+10],Ve=M[w+11],We=M[w+12],we=M[w+13],tt=M[w+14],Nt=M[w+15],le=F[0],se=F[1],oe=F[2],ue=F[3];le=k(le,se,oe,ue,q,7,E[0]),ue=k(ue,le,se,oe,K,12,E[1]),oe=k(oe,ue,le,se,z,17,E[2]),se=k(se,oe,ue,le,J,22,E[3]),le=k(le,se,oe,ue,X,7,E[4]),ue=k(ue,le,se,oe,W,12,E[5]),oe=k(oe,ue,le,se,Q,17,E[6]),se=k(se,oe,ue,le,ge,22,E[7]),le=k(le,se,oe,ue,ne,7,E[8]),ue=k(ue,le,se,oe,Te,12,E[9]),oe=k(oe,ue,le,se,ke,17,E[10]),se=k(se,oe,ue,le,Ve,22,E[11]),le=k(le,se,oe,ue,We,7,E[12]),ue=k(ue,le,se,oe,we,12,E[13]),oe=k(oe,ue,le,se,tt,17,E[14]),le=N(le,se=k(se,oe,ue,le,Nt,22,E[15]),oe,ue,K,5,E[16]),ue=N(ue,le,se,oe,Q,9,E[17]),oe=N(oe,ue,le,se,Ve,14,E[18]),se=N(se,oe,ue,le,q,20,E[19]),le=N(le,se,oe,ue,W,5,E[20]),ue=N(ue,le,se,oe,ke,9,E[21]),oe=N(oe,ue,le,se,Nt,14,E[22]),se=N(se,oe,ue,le,X,20,E[23]),le=N(le,se,oe,ue,Te,5,E[24]),ue=N(ue,le,se,oe,tt,9,E[25]),oe=N(oe,ue,le,se,J,14,E[26]),se=N(se,oe,ue,le,ne,20,E[27]),le=N(le,se,oe,ue,we,5,E[28]),ue=N(ue,le,se,oe,z,9,E[29]),oe=N(oe,ue,le,se,ge,14,E[30]),le=A(le,se=N(se,oe,ue,le,We,20,E[31]),oe,ue,W,4,E[32]),ue=A(ue,le,se,oe,ne,11,E[33]),oe=A(oe,ue,le,se,Ve,16,E[34]),se=A(se,oe,ue,le,tt,23,E[35]),le=A(le,se,oe,ue,K,4,E[36]),ue=A(ue,le,se,oe,X,11,E[37]),oe=A(oe,ue,le,se,ge,16,E[38]),se=A(se,oe,ue,le,ke,23,E[39]),le=A(le,se,oe,ue,we,4,E[40]),ue=A(ue,le,se,oe,q,11,E[41]),oe=A(oe,ue,le,se,J,16,E[42]),se=A(se,oe,ue,le,Q,23,E[43]),le=A(le,se,oe,ue,Te,4,E[44]),ue=A(ue,le,se,oe,We,11,E[45]),oe=A(oe,ue,le,se,Nt,16,E[46]),le=O(le,se=A(se,oe,ue,le,z,23,E[47]),oe,ue,q,6,E[48]),ue=O(ue,le,se,oe,ge,10,E[49]),oe=O(oe,ue,le,se,tt,15,E[50]),se=O(se,oe,ue,le,W,21,E[51]),le=O(le,se,oe,ue,We,6,E[52]),ue=O(ue,le,se,oe,J,10,E[53]),oe=O(oe,ue,le,se,ke,15,E[54]),se=O(se,oe,ue,le,K,21,E[55]),le=O(le,se,oe,ue,ne,6,E[56]),ue=O(ue,le,se,oe,Nt,10,E[57]),oe=O(oe,ue,le,se,Q,15,E[58]),se=O(se,oe,ue,le,we,21,E[59]),le=O(le,se,oe,ue,X,6,E[60]),ue=O(ue,le,se,oe,Ve,10,E[61]),oe=O(oe,ue,le,se,z,15,E[62]),se=O(se,oe,ue,le,Te,21,E[63]),F[0]=F[0]+le|0,F[1]=F[1]+se|0,F[2]=F[2]+oe|0,F[3]=F[3]+ue|0},_doFinalize:function(){var M=this._data,w=M.words,U=8*this._nDataBytes,L=8*M.sigBytes;w[L>>>5]|=128<<24-L%32;var V=p.floor(U/4294967296),F=U;w[15+(L+64>>>9<<4)]=16711935&(V<<8|V>>>24)|4278255360&(V<<24|V>>>8),w[14+(L+64>>>9<<4)]=16711935&(F<<8|F>>>24)|4278255360&(F<<24|F>>>8),M.sigBytes=4*(w.length+1),this._process();for(var q=this._hash,K=q.words,z=0;z<4;z++){var J=K[z];K[z]=16711935&(J<<8|J>>>24)|4278255360&(J<<24|J>>>8)}return q},clone:function(){var M=I.clone.call(this);return M._hash=this._hash.clone(),M}});function k(M,w,U,L,V,F,q){var K=M+(w&U|~w&L)+V+q;return(K<<F|K>>>32-F)+w}function N(M,w,U,L,V,F,q){var K=M+(w&L|U&~L)+V+q;return(K<<F|K>>>32-F)+w}function A(M,w,U,L,V,F,q){var K=M+(w^U^L)+V+q;return(K<<F|K>>>32-F)+w}function O(M,w,U,L,V,F,q){var K=M+(U^(w|~L))+V+q;return(K<<F|K>>>32-F)+w}v.MD5=I._createHelper(R),v.HmacMD5=I._createHmacHelper(R)})(Math),d.MD5)}),ot(function(a,u){var d,p,v,g,y,I,S,E;a.exports=(v=(p=d=ct).lib,g=v.WordArray,y=v.Hasher,I=p.algo,S=[],E=I.SHA1=y.extend({_doReset:function(){this._hash=new g.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(R,k){for(var N=this._hash.words,A=N[0],O=N[1],M=N[2],w=N[3],U=N[4],L=0;L<80;L++){if(L<16)S[L]=0|R[k+L];else{var V=S[L-3]^S[L-8]^S[L-14]^S[L-16];S[L]=V<<1|V>>>31}var F=(A<<5|A>>>27)+U+S[L];F+=L<20?1518500249+(O&M|~O&w):L<40?1859775393+(O^M^w):L<60?(O&M|O&w|M&w)-1894007588:(O^M^w)-899497514,U=w,w=M,M=O<<30|O>>>2,O=A,A=F}N[0]=N[0]+A|0,N[1]=N[1]+O|0,N[2]=N[2]+M|0,N[3]=N[3]+w|0,N[4]=N[4]+U|0},_doFinalize:function(){var R=this._data,k=R.words,N=8*this._nDataBytes,A=8*R.sigBytes;return k[A>>>5]|=128<<24-A%32,k[14+(A+64>>>9<<4)]=Math.floor(N/4294967296),k[15+(A+64>>>9<<4)]=N,R.sigBytes=4*k.length,this._process(),this._hash},clone:function(){var R=y.clone.call(this);return R._hash=this._hash.clone(),R}}),p.SHA1=y._createHelper(E),p.HmacSHA1=y._createHmacHelper(E),d.SHA1)}),ot(function(a,u){var d;a.exports=(d=ct,(function(p){var v=d,g=v.lib,y=g.WordArray,I=g.Hasher,S=v.algo,E=[],R=[];(function(){function A(U){for(var L=p.sqrt(U),V=2;V<=L;V++)if(!(U%V))return!1;return!0}function O(U){return 4294967296*(U-(0|U))|0}for(var M=2,w=0;w<64;)A(M)&&(w<8&&(E[w]=O(p.pow(M,.5))),R[w]=O(p.pow(M,1/3)),w++),M++})();var k=[],N=S.SHA256=I.extend({_doReset:function(){this._hash=new y.init(E.slice(0))},_doProcessBlock:function(A,O){for(var M=this._hash.words,w=M[0],U=M[1],L=M[2],V=M[3],F=M[4],q=M[5],K=M[6],z=M[7],J=0;J<64;J++){if(J<16)k[J]=0|A[O+J];else{var X=k[J-15],W=(X<<25|X>>>7)^(X<<14|X>>>18)^X>>>3,Q=k[J-2],ge=(Q<<15|Q>>>17)^(Q<<13|Q>>>19)^Q>>>10;k[J]=W+k[J-7]+ge+k[J-16]}var ne=w&U^w&L^U&L,Te=(w<<30|w>>>2)^(w<<19|w>>>13)^(w<<10|w>>>22),ke=z+((F<<26|F>>>6)^(F<<21|F>>>11)^(F<<7|F>>>25))+(F&q^~F&K)+R[J]+k[J];z=K,K=q,q=F,F=V+ke|0,V=L,L=U,U=w,w=ke+(Te+ne)|0}M[0]=M[0]+w|0,M[1]=M[1]+U|0,M[2]=M[2]+L|0,M[3]=M[3]+V|0,M[4]=M[4]+F|0,M[5]=M[5]+q|0,M[6]=M[6]+K|0,M[7]=M[7]+z|0},_doFinalize:function(){var A=this._data,O=A.words,M=8*this._nDataBytes,w=8*A.sigBytes;return O[w>>>5]|=128<<24-w%32,O[14+(w+64>>>9<<4)]=p.floor(M/4294967296),O[15+(w+64>>>9<<4)]=M,A.sigBytes=4*O.length,this._process(),this._hash},clone:function(){var A=I.clone.call(this);return A._hash=this._hash.clone(),A}});v.SHA256=I._createHelper(N),v.HmacSHA256=I._createHmacHelper(N)})(Math),d.SHA256)}),ot(function(a,u){var d,p,v,g,y,I;a.exports=(v=(p=d=ct).lib.WordArray,g=p.algo,y=g.SHA256,I=g.SHA224=y.extend({_doReset:function(){this._hash=new v.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var S=y._doFinalize.call(this);return S.sigBytes-=4,S}}),p.SHA224=y._createHelper(I),p.HmacSHA224=y._createHmacHelper(I),d.SHA224)}),ot(function(a,u){var d;a.exports=(d=ct,(function(){var p=d,v=p.lib.Hasher,g=p.x64,y=g.Word,I=g.WordArray,S=p.algo;function E(){return y.create.apply(y,arguments)}var R=[E(1116352408,3609767458),E(1899447441,602891725),E(3049323471,3964484399),E(3921009573,2173295548),E(961987163,4081628472),E(1508970993,3053834265),E(2453635748,2937671579),E(2870763221,3664609560),E(3624381080,2734883394),E(310598401,1164996542),E(607225278,1323610764),E(1426881987,3590304994),E(1925078388,4068182383),E(2162078206,991336113),E(2614888103,633803317),E(3248222580,3479774868),E(3835390401,2666613458),E(4022224774,944711139),E(264347078,2341262773),E(604807628,2007800933),E(770255983,1495990901),E(1249150122,1856431235),E(1555081692,3175218132),E(1996064986,2198950837),E(2554220882,3999719339),E(2821834349,766784016),E(2952996808,2566594879),E(3210313671,3203337956),E(3336571891,1034457026),E(3584528711,2466948901),E(113926993,3758326383),E(338241895,168717936),E(666307205,1188179964),E(773529912,1546045734),E(1294757372,1522805485),E(1396182291,2643833823),E(1695183700,2343527390),E(1986661051,1014477480),E(2177026350,1206759142),E(2456956037,344077627),E(2730485921,1290863460),E(2820302411,3158454273),E(3259730800,3505952657),E(3345764771,106217008),E(3516065817,3606008344),E(3600352804,1432725776),E(4094571909,1467031594),E(275423344,851169720),E(430227734,3100823752),E(506948616,1363258195),E(659060556,3750685593),E(883997877,3785050280),E(958139571,3318307427),E(1322822218,3812723403),E(1537002063,2003034995),E(1747873779,3602036899),E(1955562222,1575990012),E(2024104815,1125592928),E(2227730452,2716904306),E(2361852424,442776044),E(2428436474,593698344),E(2756734187,3733110249),E(3204031479,2999351573),E(3329325298,3815920427),E(3391569614,3928383900),E(3515267271,566280711),E(3940187606,3454069534),E(4118630271,4000239992),E(116418474,1914138554),E(174292421,2731055270),E(289380356,3203993006),E(460393269,320620315),E(685471733,587496836),E(852142971,1086792851),E(1017036298,365543100),E(1126000580,2618297676),E(1288033470,3409855158),E(1501505948,4234509866),E(1607167915,987167468),E(1816402316,1246189591)],k=[];(function(){for(var A=0;A<80;A++)k[A]=E()})();var N=S.SHA512=v.extend({_doReset:function(){this._hash=new I.init([new y.init(1779033703,4089235720),new y.init(3144134277,2227873595),new y.init(1013904242,4271175723),new y.init(2773480762,1595750129),new y.init(1359893119,2917565137),new y.init(2600822924,725511199),new y.init(528734635,4215389547),new y.init(1541459225,327033209)])},_doProcessBlock:function(A,O){for(var M=this._hash.words,w=M[0],U=M[1],L=M[2],V=M[3],F=M[4],q=M[5],K=M[6],z=M[7],J=w.high,X=w.low,W=U.high,Q=U.low,ge=L.high,ne=L.low,Te=V.high,ke=V.low,Ve=F.high,We=F.low,we=q.high,tt=q.low,Nt=K.high,le=K.low,se=z.high,oe=z.low,ue=J,bt=X,ci=W,$e=Q,Pi=ge,Et=ne,en=Te,Fi=ke,Mt=Ve,Lt=We,tn=we,Or=tt,ae=Nt,ye=le,ze=se,Qe=oe,Le=0;Le<80;Le++){var Yt=k[Le];if(Le<16)var Hn=Yt.high=0|A[O+2*Le],Ei=Yt.low=0|A[O+2*Le+1];else{var vl=k[Le-15],Wn=vl.high,Hs=vl.low,Xu=(Wn>>>1|Hs<<31)^(Wn>>>8|Hs<<24)^Wn>>>7,El=(Hs>>>1|Wn<<31)^(Hs>>>8|Wn<<24)^(Hs>>>7|Wn<<25),Qu=k[Le-2],Gn=Qu.high,Ws=Qu.low,jm=(Gn>>>19|Ws<<13)^(Gn<<3|Ws>>>29)^Gn>>>6,ja=(Ws>>>19|Gn<<13)^(Ws<<3|Gn>>>29)^(Ws>>>6|Gn<<26),Zu=k[Le-7],jn=Zu.high,zm=Zu.low,$u=k[Le-16],Km=$u.high,Oi=$u.low;Hn=(Hn=(Hn=Xu+jn+((Ei=El+zm)>>>0<El>>>0?1:0))+jm+((Ei+=ja)>>>0<ja>>>0?1:0))+Km+((Ei+=Oi)>>>0<Oi>>>0?1:0),Yt.high=Hn,Yt.low=Ei}var rn,Jm=Mt&tn^~Mt&ae,zn=Lt&Or^~Lt&ye,yl=ue&ci^ue&Pi^ci&Pi,Tl=bt&$e^bt&Et^$e&Et,Sl=(ue>>>28|bt<<4)^(ue<<30|bt>>>2)^(ue<<25|bt>>>7),ed=(bt>>>28|ue<<4)^(bt<<30|ue>>>2)^(bt<<25|ue>>>7),td=(Mt>>>14|Lt<<18)^(Mt>>>18|Lt<<14)^(Mt<<23|Lt>>>9),id=(Lt>>>14|Mt<<18)^(Lt>>>18|Mt<<14)^(Lt<<23|Mt>>>9),rd=R[Le],Il=rd.high,nd=rd.low,Gs=ze+td+((rn=Qe+id)>>>0<Qe>>>0?1:0),Rl=ed+Tl;ze=ae,Qe=ye,ae=tn,ye=Or,tn=Mt,Or=Lt,Mt=en+(Gs=(Gs=(Gs=Gs+Jm+((rn+=zn)>>>0<zn>>>0?1:0))+Il+((rn+=nd)>>>0<nd>>>0?1:0))+Hn+((rn+=Ei)>>>0<Ei>>>0?1:0))+((Lt=Fi+rn|0)>>>0<Fi>>>0?1:0)|0,en=Pi,Fi=Et,Pi=ci,Et=$e,ci=ue,$e=bt,ue=Gs+(Sl+yl+(Rl>>>0<ed>>>0?1:0))+((bt=rn+Rl|0)>>>0<rn>>>0?1:0)|0}X=w.low=X+bt,w.high=J+ue+(X>>>0<bt>>>0?1:0),Q=U.low=Q+$e,U.high=W+ci+(Q>>>0<$e>>>0?1:0),ne=L.low=ne+Et,L.high=ge+Pi+(ne>>>0<Et>>>0?1:0),ke=V.low=ke+Fi,V.high=Te+en+(ke>>>0<Fi>>>0?1:0),We=F.low=We+Lt,F.high=Ve+Mt+(We>>>0<Lt>>>0?1:0),tt=q.low=tt+Or,q.high=we+tn+(tt>>>0<Or>>>0?1:0),le=K.low=le+ye,K.high=Nt+ae+(le>>>0<ye>>>0?1:0),oe=z.low=oe+Qe,z.high=se+ze+(oe>>>0<Qe>>>0?1:0)},_doFinalize:function(){var A=this._data,O=A.words,M=8*this._nDataBytes,w=8*A.sigBytes;return O[w>>>5]|=128<<24-w%32,O[30+(w+128>>>10<<5)]=Math.floor(M/4294967296),O[31+(w+128>>>10<<5)]=M,A.sigBytes=4*O.length,this._process(),this._hash.toX32()},clone:function(){var A=v.clone.call(this);return A._hash=this._hash.clone(),A},blockSize:32});p.SHA512=v._createHelper(N),p.HmacSHA512=v._createHmacHelper(N)})(),d.SHA512)}),ot(function(a,u){var d,p,v,g,y,I,S,E;a.exports=(v=(p=d=ct).x64,g=v.Word,y=v.WordArray,I=p.algo,S=I.SHA512,E=I.SHA384=S.extend({_doReset:function(){this._hash=new y.init([new g.init(3418070365,3238371032),new g.init(1654270250,914150663),new g.init(2438529370,812702999),new g.init(355462360,4144912697),new g.init(1731405415,4290775857),new g.init(2394180231,1750603025),new g.init(3675008525,1694076839),new g.init(1203062813,3204075428)])},_doFinalize:function(){var R=S._doFinalize.call(this);return R.sigBytes-=16,R}}),p.SHA384=S._createHelper(E),p.HmacSHA384=S._createHmacHelper(E),d.SHA384)}),ot(function(a,u){var d;a.exports=(d=ct,(function(p){var v=d,g=v.lib,y=g.WordArray,I=g.Hasher,S=v.x64.Word,E=v.algo,R=[],k=[],N=[];(function(){for(var M=1,w=0,U=0;U<24;U++){R[M+5*w]=(U+1)*(U+2)/2%64;var L=(2*M+3*w)%5;M=w%5,w=L}for(M=0;M<5;M++)for(w=0;w<5;w++)k[M+5*w]=w+(2*M+3*w)%5*5;for(var V=1,F=0;F<24;F++){for(var q=0,K=0,z=0;z<7;z++){if(1&V){var J=(1<<z)-1;J<32?K^=1<<J:q^=1<<J-32}128&V?V=V<<1^113:V<<=1}N[F]=S.create(q,K)}})();var A=[];(function(){for(var M=0;M<25;M++)A[M]=S.create()})();var O=E.SHA3=I.extend({cfg:I.cfg.extend({outputLength:512}),_doReset:function(){for(var M=this._state=[],w=0;w<25;w++)M[w]=new S.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(M,w){for(var U=this._state,L=this.blockSize/2,V=0;V<L;V++){var F=M[w+2*V],q=M[w+2*V+1];F=16711935&(F<<8|F>>>24)|4278255360&(F<<24|F>>>8),q=16711935&(q<<8|q>>>24)|4278255360&(q<<24|q>>>8),(oe=U[V]).high^=q,oe.low^=F}for(var K=0;K<24;K++){for(var z=0;z<5;z++){for(var J=0,X=0,W=0;W<5;W++)J^=(oe=U[z+5*W]).high,X^=oe.low;var Q=A[z];Q.high=J,Q.low=X}for(z=0;z<5;z++){var ge=A[(z+4)%5],ne=A[(z+1)%5],Te=ne.high,ke=ne.low;for(J=ge.high^(Te<<1|ke>>>31),X=ge.low^(ke<<1|Te>>>31),W=0;W<5;W++)(oe=U[z+5*W]).high^=J,oe.low^=X}for(var Ve=1;Ve<25;Ve++){var We=(oe=U[Ve]).high,we=oe.low,tt=R[Ve];tt<32?(J=We<<tt|we>>>32-tt,X=we<<tt|We>>>32-tt):(J=we<<tt-32|We>>>64-tt,X=We<<tt-32|we>>>64-tt);var Nt=A[k[Ve]];Nt.high=J,Nt.low=X}var le=A[0],se=U[0];for(le.high=se.high,le.low=se.low,z=0;z<5;z++)for(W=0;W<5;W++){var oe=U[Ve=z+5*W],ue=A[Ve],bt=A[(z+1)%5+5*W],ci=A[(z+2)%5+5*W];oe.high=ue.high^~bt.high&ci.high,oe.low=ue.low^~bt.low&ci.low}oe=U[0];var $e=N[K];oe.high^=$e.high,oe.low^=$e.low}},_doFinalize:function(){var M=this._data,w=M.words,U=(this._nDataBytes,8*M.sigBytes),L=32*this.blockSize;w[U>>>5]|=1<<24-U%32,w[(p.ceil((U+1)/L)*L>>>5)-1]|=128,M.sigBytes=4*w.length,this._process();for(var V=this._state,F=this.cfg.outputLength/8,q=F/8,K=[],z=0;z<q;z++){var J=V[z],X=J.high,W=J.low;X=16711935&(X<<8|X>>>24)|4278255360&(X<<24|X>>>8),W=16711935&(W<<8|W>>>24)|4278255360&(W<<24|W>>>8),K.push(W),K.push(X)}return new y.init(K,F)},clone:function(){for(var M=I.clone.call(this),w=M._state=this._state.slice(0),U=0;U<25;U++)w[U]=w[U].clone();return M}});v.SHA3=I._createHelper(O),v.HmacSHA3=I._createHmacHelper(O)})(Math),d.SHA3)}),ot(function(a,u){var d;a.exports=(d=ct,(function(p){var v=d,g=v.lib,y=g.WordArray,I=g.Hasher,S=v.algo,E=y.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),R=y.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),k=y.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),N=y.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),A=y.create([0,1518500249,1859775393,2400959708,2840853838]),O=y.create([1352829926,1548603684,1836072691,2053994217,0]),M=S.RIPEMD160=I.extend({_doReset:function(){this._hash=y.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(K,z){for(var J=0;J<16;J++){var X=z+J,W=K[X];K[X]=16711935&(W<<8|W>>>24)|4278255360&(W<<24|W>>>8)}var Q,ge,ne,Te,ke,Ve,We,we,tt,Nt,le,se=this._hash.words,oe=A.words,ue=O.words,bt=E.words,ci=R.words,$e=k.words,Pi=N.words;for(Ve=Q=se[0],We=ge=se[1],we=ne=se[2],tt=Te=se[3],Nt=ke=se[4],J=0;J<80;J+=1)le=Q+K[z+bt[J]]|0,le+=J<16?w(ge,ne,Te)+oe[0]:J<32?U(ge,ne,Te)+oe[1]:J<48?L(ge,ne,Te)+oe[2]:J<64?V(ge,ne,Te)+oe[3]:F(ge,ne,Te)+oe[4],le=(le=q(le|=0,$e[J]))+ke|0,Q=ke,ke=Te,Te=q(ne,10),ne=ge,ge=le,le=Ve+K[z+ci[J]]|0,le+=J<16?F(We,we,tt)+ue[0]:J<32?V(We,we,tt)+ue[1]:J<48?L(We,we,tt)+ue[2]:J<64?U(We,we,tt)+ue[3]:w(We,we,tt)+ue[4],le=(le=q(le|=0,Pi[J]))+Nt|0,Ve=Nt,Nt=tt,tt=q(we,10),we=We,We=le;le=se[1]+ne+tt|0,se[1]=se[2]+Te+Nt|0,se[2]=se[3]+ke+Ve|0,se[3]=se[4]+Q+We|0,se[4]=se[0]+ge+we|0,se[0]=le},_doFinalize:function(){var K=this._data,z=K.words,J=8*this._nDataBytes,X=8*K.sigBytes;z[X>>>5]|=128<<24-X%32,z[14+(X+64>>>9<<4)]=16711935&(J<<8|J>>>24)|4278255360&(J<<24|J>>>8),K.sigBytes=4*(z.length+1),this._process();for(var W=this._hash,Q=W.words,ge=0;ge<5;ge++){var ne=Q[ge];Q[ge]=16711935&(ne<<8|ne>>>24)|4278255360&(ne<<24|ne>>>8)}return W},clone:function(){var K=I.clone.call(this);return K._hash=this._hash.clone(),K}});function w(K,z,J){return K^z^J}function U(K,z,J){return K&z|~K&J}function L(K,z,J){return(K|~z)^J}function V(K,z,J){return K&J|z&~J}function F(K,z,J){return K^(z|~J)}function q(K,z){return K<<z|K>>>32-z}v.RIPEMD160=I._createHelper(M),v.HmacRIPEMD160=I._createHmacHelper(M)})(),d.RIPEMD160)}),ot(function(a,u){var d,p,v,g,y,I;a.exports=(p=(d=ct).lib,v=p.Base,g=d.enc,y=g.Utf8,I=d.algo,void(I.HMAC=v.extend({init:function(S,E){S=this._hasher=new S.init,typeof E=="string"&&(E=y.parse(E));var R=S.blockSize,k=4*R;E.sigBytes>k&&(E=S.finalize(E)),E.clamp();for(var N=this._oKey=E.clone(),A=this._iKey=E.clone(),O=N.words,M=A.words,w=0;w<R;w++)O[w]^=1549556828,M[w]^=909522486;N.sigBytes=A.sigBytes=k,this.reset()},reset:function(){var S=this._hasher;S.reset(),S.update(this._iKey)},update:function(S){return this._hasher.update(S),this},finalize:function(S){var E=this._hasher,R=E.finalize(S);E.reset();var k=E.finalize(this._oKey.clone().concat(R));return k}})))}),ot(function(a,u){var d,p,v,g,y,I,S,E,R;a.exports=(v=(p=d=ct).lib,g=v.Base,y=v.WordArray,I=p.algo,S=I.SHA1,E=I.HMAC,R=I.PBKDF2=g.extend({cfg:g.extend({keySize:4,hasher:S,iterations:1}),init:function(k){this.cfg=this.cfg.extend(k)},compute:function(k,N){for(var A=this.cfg,O=E.create(A.hasher,k),M=y.create(),w=y.create([1]),U=M.words,L=w.words,V=A.keySize,F=A.iterations;U.length<V;){var q=O.update(N).finalize(w);O.reset();for(var K=q.words,z=K.length,J=q,X=1;X<F;X++){J=O.finalize(J),O.reset();for(var W=J.words,Q=0;Q<z;Q++)K[Q]^=W[Q]}M.concat(q),L[0]++}return M.sigBytes=4*V,M}}),p.PBKDF2=function(k,N,A){return R.create(A).compute(k,N)},d.PBKDF2)}),ot(function(a,u){var d,p,v,g,y,I,S,E;a.exports=(v=(p=d=ct).lib,g=v.Base,y=v.WordArray,I=p.algo,S=I.MD5,E=I.EvpKDF=g.extend({cfg:g.extend({keySize:4,hasher:S,iterations:1}),init:function(R){this.cfg=this.cfg.extend(R)},compute:function(R,k){for(var N=this.cfg,A=N.hasher.create(),O=y.create(),M=O.words,w=N.keySize,U=N.iterations;M.length<w;){L&&A.update(L);var L=A.update(R).finalize(k);A.reset();for(var V=1;V<U;V++)L=A.finalize(L),A.reset();O.concat(L)}return O.sigBytes=4*w,O}}),p.EvpKDF=function(R,k,N){return E.create(N).compute(R,k)},d.EvpKDF)}),ot(function(a,u){var d,p,v,g,y,I,S,E,R,k,N,A,O,M,w,U,L,V,F,q,K,z,J,X;a.exports=void((d=ct).lib.Cipher||(v=d,g=v.lib,y=g.Base,I=g.WordArray,S=g.BufferedBlockAlgorithm,E=v.enc,E.Utf8,R=E.Base64,k=v.algo,N=k.EvpKDF,A=g.Cipher=S.extend({cfg:y.extend(),createEncryptor:function(W,Q){return this.create(this._ENC_XFORM_MODE,W,Q)},createDecryptor:function(W,Q){return this.create(this._DEC_XFORM_MODE,W,Q)},init:function(W,Q,ge){this.cfg=this.cfg.extend(ge),this._xformMode=W,this._key=Q,this.reset()},reset:function(){S.reset.call(this),this._doReset()},process:function(W){return this._append(W),this._process()},finalize:function(W){W&&this._append(W);var Q=this._doFinalize();return Q},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:(function(){function W(Q){return typeof Q=="string"?X:K}return function(Q){return{encrypt:function(ge,ne,Te){return W(ne).encrypt(Q,ge,ne,Te)},decrypt:function(ge,ne,Te){return W(ne).decrypt(Q,ge,ne,Te)}}}})()}),g.StreamCipher=A.extend({_doFinalize:function(){var W=this._process(!0);return W},blockSize:1}),O=v.mode={},M=g.BlockCipherMode=y.extend({createEncryptor:function(W,Q){return this.Encryptor.create(W,Q)},createDecryptor:function(W,Q){return this.Decryptor.create(W,Q)},init:function(W,Q){this._cipher=W,this._iv=Q}}),w=O.CBC=(function(){var W=M.extend();function Q(ge,ne,Te){var ke=this._iv;if(ke){var Ve=ke;this._iv=p}else var Ve=this._prevBlock;for(var We=0;We<Te;We++)ge[ne+We]^=Ve[We]}return W.Encryptor=W.extend({processBlock:function(ge,ne){var Te=this._cipher,ke=Te.blockSize;Q.call(this,ge,ne,ke),Te.encryptBlock(ge,ne),this._prevBlock=ge.slice(ne,ne+ke)}}),W.Decryptor=W.extend({processBlock:function(ge,ne){var Te=this._cipher,ke=Te.blockSize,Ve=ge.slice(ne,ne+ke);Te.decryptBlock(ge,ne),Q.call(this,ge,ne,ke),this._prevBlock=Ve}}),W})(),U=v.pad={},L=U.Pkcs7={pad:function(W,Q){for(var ge=4*Q,ne=ge-W.sigBytes%ge,Te=ne<<24|ne<<16|ne<<8|ne,ke=[],Ve=0;Ve<ne;Ve+=4)ke.push(Te);var We=I.create(ke,ne);W.concat(We)},unpad:function(W){var Q=255&W.words[W.sigBytes-1>>>2];W.sigBytes-=Q}},g.BlockCipher=A.extend({cfg:A.cfg.extend({mode:w,padding:L}),reset:function(){A.reset.call(this);var W=this.cfg,Q=W.iv,ge=W.mode;if(this._xformMode==this._ENC_XFORM_MODE)var ne=ge.createEncryptor;else{var ne=ge.createDecryptor;this._minBufferSize=1}this._mode&&this._mode.__creator==ne?this._mode.init(this,Q&&Q.words):(this._mode=ne.call(ge,this,Q&&Q.words),this._mode.__creator=ne)},_doProcessBlock:function(W,Q){this._mode.processBlock(W,Q)},_doFinalize:function(){var W=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){W.pad(this._data,this.blockSize);var Q=this._process(!0)}else{var Q=this._process(!0);W.unpad(Q)}return Q},blockSize:4}),V=g.CipherParams=y.extend({init:function(W){this.mixIn(W)},toString:function(W){return(W||this.formatter).stringify(this)}}),F=v.format={},q=F.OpenSSL={stringify:function(W){var Q=W.ciphertext,ge=W.salt;if(ge)var ne=I.create([1398893684,1701076831]).concat(ge).concat(Q);else var ne=Q;return ne.toString(R)},parse:function(W){var Q=R.parse(W),ge=Q.words;if(ge[0]==1398893684&&ge[1]==1701076831){var ne=I.create(ge.slice(2,4));ge.splice(0,4),Q.sigBytes-=16}return V.create({ciphertext:Q,salt:ne})}},K=g.SerializableCipher=y.extend({cfg:y.extend({format:q}),encrypt:function(W,Q,ge,ne){ne=this.cfg.extend(ne);var Te=W.createEncryptor(ge,ne),ke=Te.finalize(Q),Ve=Te.cfg;return V.create({ciphertext:ke,key:ge,iv:Ve.iv,algorithm:W,mode:Ve.mode,padding:Ve.padding,blockSize:W.blockSize,formatter:ne.format})},decrypt:function(W,Q,ge,ne){ne=this.cfg.extend(ne),Q=this._parse(Q,ne.format);var Te=W.createDecryptor(ge,ne).finalize(Q.ciphertext);return Te},_parse:function(W,Q){return typeof W=="string"?Q.parse(W,this):W}}),z=v.kdf={},J=z.OpenSSL={execute:function(W,Q,ge,ne){ne||(ne=I.random(8));var Te=N.create({keySize:Q+ge}).compute(W,ne),ke=I.create(Te.words.slice(Q),4*ge);return Te.sigBytes=4*Q,V.create({key:Te,iv:ke,salt:ne})}},X=g.PasswordBasedCipher=K.extend({cfg:K.cfg.extend({kdf:J}),encrypt:function(W,Q,ge,ne){var Te=(ne=this.cfg.extend(ne)).kdf.execute(ge,W.keySize,W.ivSize);ne.iv=Te.iv;var ke=K.encrypt.call(this,W,Q,Te.key,ne);return ke.mixIn(Te),ke},decrypt:function(W,Q,ge,ne){ne=this.cfg.extend(ne),Q=this._parse(Q,ne.format);var Te=ne.kdf.execute(ge,W.keySize,W.ivSize,Q.salt);ne.iv=Te.iv;var ke=K.decrypt.call(this,W,Q,Te.key,ne);return ke}})))}),ot(function(a,u){var d;a.exports=((d=ct).mode.CFB=(function(){var p=d.lib.BlockCipherMode.extend();function v(g,y,I,S){var E=this._iv;if(E){var R=E.slice(0);this._iv=void 0}else R=this._prevBlock;S.encryptBlock(R,0);for(var k=0;k<I;k++)g[y+k]^=R[k]}return p.Encryptor=p.extend({processBlock:function(g,y){var I=this._cipher,S=I.blockSize;v.call(this,g,y,S,I),this._prevBlock=g.slice(y,y+S)}}),p.Decryptor=p.extend({processBlock:function(g,y){var I=this._cipher,S=I.blockSize,E=g.slice(y,y+S);v.call(this,g,y,S,I),this._prevBlock=E}}),p})(),d.mode.CFB)}),ot(function(a,u){var d,p,v;a.exports=((d=ct).mode.CTR=(p=d.lib.BlockCipherMode.extend(),v=p.Encryptor=p.extend({processBlock:function(g,y){var I=this._cipher,S=I.blockSize,E=this._iv,R=this._counter;E&&(R=this._counter=E.slice(0),this._iv=void 0);var k=R.slice(0);I.encryptBlock(k,0),R[S-1]=R[S-1]+1|0;for(var N=0;N<S;N++)g[y+N]^=k[N]}}),p.Decryptor=v,p),d.mode.CTR)}),ot(function(a,u){var d;a.exports=((d=ct).mode.CTRGladman=(function(){var p=d.lib.BlockCipherMode.extend();function v(y){if((y>>24&255)==255){var I=y>>16&255,S=y>>8&255,E=255&y;I===255?(I=0,S===255?(S=0,E===255?E=0:++E):++S):++I,y=0,y+=I<<16,y+=S<<8,y+=E}else y+=1<<24;return y}var g=p.Encryptor=p.extend({processBlock:function(y,I){var S=this._cipher,E=S.blockSize,R=this._iv,k=this._counter;R&&(k=this._counter=R.slice(0),this._iv=void 0),(function(O){(O[0]=v(O[0]))===0&&(O[1]=v(O[1]))})(k);var N=k.slice(0);S.encryptBlock(N,0);for(var A=0;A<E;A++)y[I+A]^=N[A]}});return p.Decryptor=g,p})(),d.mode.CTRGladman)}),ot(function(a,u){var d,p,v;a.exports=((d=ct).mode.OFB=(p=d.lib.BlockCipherMode.extend(),v=p.Encryptor=p.extend({processBlock:function(g,y){var I=this._cipher,S=I.blockSize,E=this._iv,R=this._keystream;E&&(R=this._keystream=E.slice(0),this._iv=void 0),I.encryptBlock(R,0);for(var k=0;k<S;k++)g[y+k]^=R[k]}}),p.Decryptor=v,p),d.mode.OFB)}),ot(function(a,u){var d,p;a.exports=((d=ct).mode.ECB=((p=d.lib.BlockCipherMode.extend()).Encryptor=p.extend({processBlock:function(v,g){this._cipher.encryptBlock(v,g)}}),p.Decryptor=p.extend({processBlock:function(v,g){this._cipher.decryptBlock(v,g)}}),p),d.mode.ECB)}),ot(function(a,u){var d;a.exports=((d=ct).pad.AnsiX923={pad:function(p,v){var g=p.sigBytes,y=4*v,I=y-g%y,S=g+I-1;p.clamp(),p.words[S>>>2]|=I<<24-S%4*8,p.sigBytes+=I},unpad:function(p){var v=255&p.words[p.sigBytes-1>>>2];p.sigBytes-=v}},d.pad.Ansix923)}),ot(function(a,u){var d;a.exports=((d=ct).pad.Iso10126={pad:function(p,v){var g=4*v,y=g-p.sigBytes%g;p.concat(d.lib.WordArray.random(y-1)).concat(d.lib.WordArray.create([y<<24],1))},unpad:function(p){var v=255&p.words[p.sigBytes-1>>>2];p.sigBytes-=v}},d.pad.Iso10126)}),ot(function(a,u){var d;a.exports=((d=ct).pad.Iso97971={pad:function(p,v){p.concat(d.lib.WordArray.create([2147483648],1)),d.pad.ZeroPadding.pad(p,v)},unpad:function(p){d.pad.ZeroPadding.unpad(p),p.sigBytes--}},d.pad.Iso97971)}),ot(function(a,u){var d;a.exports=((d=ct).pad.ZeroPadding={pad:function(p,v){var g=4*v;p.clamp(),p.sigBytes+=g-(p.sigBytes%g||g)},unpad:function(p){for(var v=p.words,g=p.sigBytes-1;!(v[g>>>2]>>>24-g%4*8&255);)g--;p.sigBytes=g+1}},d.pad.ZeroPadding)}),ot(function(a,u){var d;a.exports=((d=ct).pad.NoPadding={pad:function(){},unpad:function(){}},d.pad.NoPadding)}),ot(function(a,u){var d,p,v,g;a.exports=(v=(p=d=ct).lib.CipherParams,g=p.enc.Hex,p.format.Hex={stringify:function(y){return y.ciphertext.toString(g)},parse:function(y){var I=g.parse(y);return v.create({ciphertext:I})}},d.format.Hex)}),ot(function(a,u){var d;a.exports=(d=ct,(function(){var p=d,v=p.lib.BlockCipher,g=p.algo,y=[],I=[],S=[],E=[],R=[],k=[],N=[],A=[],O=[],M=[];(function(){for(var L=[],V=0;V<256;V++)L[V]=V<128?V<<1:V<<1^283;var F=0,q=0;for(V=0;V<256;V++){var K=q^q<<1^q<<2^q<<3^q<<4;K=K>>>8^255&K^99,y[F]=K,I[K]=F;var z=L[F],J=L[z],X=L[J],W=257*L[K]^16843008*K;S[F]=W<<24|W>>>8,E[F]=W<<16|W>>>16,R[F]=W<<8|W>>>24,k[F]=W,W=16843009*X^65537*J^257*z^16843008*F,N[K]=W<<24|W>>>8,A[K]=W<<16|W>>>16,O[K]=W<<8|W>>>24,M[K]=W,F?(F=z^L[L[L[X^z]]],q^=L[L[q]]):F=q=1}})();var w=[0,1,2,4,8,16,32,64,128,27,54],U=g.AES=v.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var L=this._keyPriorReset=this._key,V=L.words,F=L.sigBytes/4,q=4*((this._nRounds=F+6)+1),K=this._keySchedule=[],z=0;z<q;z++)if(z<F)K[z]=V[z];else{var J=K[z-1];z%F?F>6&&z%F==4&&(J=y[J>>>24]<<24|y[J>>>16&255]<<16|y[J>>>8&255]<<8|y[255&J]):(J=y[(J=J<<8|J>>>24)>>>24]<<24|y[J>>>16&255]<<16|y[J>>>8&255]<<8|y[255&J],J^=w[z/F|0]<<24),K[z]=K[z-F]^J}for(var X=this._invKeySchedule=[],W=0;W<q;W++)z=q-W,J=W%4?K[z]:K[z-4],X[W]=W<4||z<=4?J:N[y[J>>>24]]^A[y[J>>>16&255]]^O[y[J>>>8&255]]^M[y[255&J]]}},encryptBlock:function(L,V){this._doCryptBlock(L,V,this._keySchedule,S,E,R,k,y)},decryptBlock:function(L,V){var F=L[V+1];L[V+1]=L[V+3],L[V+3]=F,this._doCryptBlock(L,V,this._invKeySchedule,N,A,O,M,I),F=L[V+1],L[V+1]=L[V+3],L[V+3]=F},_doCryptBlock:function(L,V,F,q,K,z,J,X){for(var W=this._nRounds,Q=L[V]^F[0],ge=L[V+1]^F[1],ne=L[V+2]^F[2],Te=L[V+3]^F[3],ke=4,Ve=1;Ve<W;Ve++){var We=q[Q>>>24]^K[ge>>>16&255]^z[ne>>>8&255]^J[255&Te]^F[ke++],we=q[ge>>>24]^K[ne>>>16&255]^z[Te>>>8&255]^J[255&Q]^F[ke++],tt=q[ne>>>24]^K[Te>>>16&255]^z[Q>>>8&255]^J[255&ge]^F[ke++],Nt=q[Te>>>24]^K[Q>>>16&255]^z[ge>>>8&255]^J[255&ne]^F[ke++];Q=We,ge=we,ne=tt,Te=Nt}We=(X[Q>>>24]<<24|X[ge>>>16&255]<<16|X[ne>>>8&255]<<8|X[255&Te])^F[ke++],we=(X[ge>>>24]<<24|X[ne>>>16&255]<<16|X[Te>>>8&255]<<8|X[255&Q])^F[ke++],tt=(X[ne>>>24]<<24|X[Te>>>16&255]<<16|X[Q>>>8&255]<<8|X[255&ge])^F[ke++],Nt=(X[Te>>>24]<<24|X[Q>>>16&255]<<16|X[ge>>>8&255]<<8|X[255&ne])^F[ke++],L[V]=We,L[V+1]=we,L[V+2]=tt,L[V+3]=Nt},keySize:8});p.AES=v._createHelper(U)})(),d.AES)}),ot(function(a,u){var d;a.exports=(d=ct,(function(){var p=d,v=p.lib,g=v.WordArray,y=v.BlockCipher,I=p.algo,S=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],E=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],R=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],k=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],N=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],A=I.DES=y.extend({_doReset:function(){for(var U=this._key.words,L=[],V=0;V<56;V++){var F=S[V]-1;L[V]=U[F>>>5]>>>31-F%32&1}for(var q=this._subKeys=[],K=0;K<16;K++){var z=q[K]=[],J=R[K];for(V=0;V<24;V++)z[V/6|0]|=L[(E[V]-1+J)%28]<<31-V%6,z[4+(V/6|0)]|=L[28+(E[V+24]-1+J)%28]<<31-V%6;for(z[0]=z[0]<<1|z[0]>>>31,V=1;V<7;V++)z[V]=z[V]>>>4*(V-1)+3;z[7]=z[7]<<5|z[7]>>>27}var X=this._invSubKeys=[];for(V=0;V<16;V++)X[V]=q[15-V]},encryptBlock:function(U,L){this._doCryptBlock(U,L,this._subKeys)},decryptBlock:function(U,L){this._doCryptBlock(U,L,this._invSubKeys)},_doCryptBlock:function(U,L,V){this._lBlock=U[L],this._rBlock=U[L+1],O.call(this,4,252645135),O.call(this,16,65535),M.call(this,2,858993459),M.call(this,8,16711935),O.call(this,1,1431655765);for(var F=0;F<16;F++){for(var q=V[F],K=this._lBlock,z=this._rBlock,J=0,X=0;X<8;X++)J|=k[X][((z^q[X])&N[X])>>>0];this._lBlock=z,this._rBlock=K^J}var W=this._lBlock;this._lBlock=this._rBlock,this._rBlock=W,O.call(this,1,1431655765),M.call(this,8,16711935),M.call(this,2,858993459),O.call(this,16,65535),O.call(this,4,252645135),U[L]=this._lBlock,U[L+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});function O(U,L){var V=(this._lBlock>>>U^this._rBlock)&L;this._rBlock^=V,this._lBlock^=V<<U}function M(U,L){var V=(this._rBlock>>>U^this._lBlock)&L;this._lBlock^=V,this._rBlock^=V<<U}p.DES=y._createHelper(A);var w=I.TripleDES=y.extend({_doReset:function(){var U=this._key.words;this._des1=A.createEncryptor(g.create(U.slice(0,2))),this._des2=A.createEncryptor(g.create(U.slice(2,4))),this._des3=A.createEncryptor(g.create(U.slice(4,6)))},encryptBlock:function(U,L){this._des1.encryptBlock(U,L),this._des2.decryptBlock(U,L),this._des3.encryptBlock(U,L)},decryptBlock:function(U,L){this._des3.decryptBlock(U,L),this._des2.encryptBlock(U,L),this._des1.decryptBlock(U,L)},keySize:6,ivSize:2,blockSize:2});p.TripleDES=y._createHelper(w)})(),d.TripleDES)}),ot(function(a,u){var d;a.exports=(d=ct,(function(){var p=d,v=p.lib.StreamCipher,g=p.algo,y=g.RC4=v.extend({_doReset:function(){for(var E=this._key,R=E.words,k=E.sigBytes,N=this._S=[],A=0;A<256;A++)N[A]=A;A=0;for(var O=0;A<256;A++){var M=A%k,w=R[M>>>2]>>>24-M%4*8&255;O=(O+N[A]+w)%256;var U=N[A];N[A]=N[O],N[O]=U}this._i=this._j=0},_doProcessBlock:function(E,R){E[R]^=I.call(this)},keySize:8,ivSize:0});function I(){for(var E=this._S,R=this._i,k=this._j,N=0,A=0;A<4;A++){k=(k+E[R=(R+1)%256])%256;var O=E[R];E[R]=E[k],E[k]=O,N|=E[(E[R]+E[k])%256]<<24-8*A}return this._i=R,this._j=k,N}p.RC4=v._createHelper(y);var S=g.RC4Drop=y.extend({cfg:y.cfg.extend({drop:192}),_doReset:function(){y._doReset.call(this);for(var E=this.cfg.drop;E>0;E--)I.call(this)}});p.RC4Drop=v._createHelper(S)})(),d.RC4)}),ot(function(a,u){var d;a.exports=(d=ct,(function(){var p=d,v=p.lib.StreamCipher,g=p.algo,y=[],I=[],S=[],E=g.Rabbit=v.extend({_doReset:function(){for(var k=this._key.words,N=this.cfg.iv,A=0;A<4;A++)k[A]=16711935&(k[A]<<8|k[A]>>>24)|4278255360&(k[A]<<24|k[A]>>>8);var O=this._X=[k[0],k[3]<<16|k[2]>>>16,k[1],k[0]<<16|k[3]>>>16,k[2],k[1]<<16|k[0]>>>16,k[3],k[2]<<16|k[1]>>>16],M=this._C=[k[2]<<16|k[2]>>>16,4294901760&k[0]|65535&k[1],k[3]<<16|k[3]>>>16,4294901760&k[1]|65535&k[2],k[0]<<16|k[0]>>>16,4294901760&k[2]|65535&k[3],k[1]<<16|k[1]>>>16,4294901760&k[3]|65535&k[0]];for(this._b=0,A=0;A<4;A++)R.call(this);for(A=0;A<8;A++)M[A]^=O[A+4&7];if(N){var w=N.words,U=w[0],L=w[1],V=16711935&(U<<8|U>>>24)|4278255360&(U<<24|U>>>8),F=16711935&(L<<8|L>>>24)|4278255360&(L<<24|L>>>8),q=V>>>16|4294901760&F,K=F<<16|65535&V;for(M[0]^=V,M[1]^=q,M[2]^=F,M[3]^=K,M[4]^=V,M[5]^=q,M[6]^=F,M[7]^=K,A=0;A<4;A++)R.call(this)}},_doProcessBlock:function(k,N){var A=this._X;R.call(this),y[0]=A[0]^A[5]>>>16^A[3]<<16,y[1]=A[2]^A[7]>>>16^A[5]<<16,y[2]=A[4]^A[1]>>>16^A[7]<<16,y[3]=A[6]^A[3]>>>16^A[1]<<16;for(var O=0;O<4;O++)y[O]=16711935&(y[O]<<8|y[O]>>>24)|4278255360&(y[O]<<24|y[O]>>>8),k[N+O]^=y[O]},blockSize:4,ivSize:2});function R(){for(var k=this._X,N=this._C,A=0;A<8;A++)I[A]=N[A];for(N[0]=N[0]+1295307597+this._b|0,N[1]=N[1]+3545052371+(N[0]>>>0<I[0]>>>0?1:0)|0,N[2]=N[2]+886263092+(N[1]>>>0<I[1]>>>0?1:0)|0,N[3]=N[3]+1295307597+(N[2]>>>0<I[2]>>>0?1:0)|0,N[4]=N[4]+3545052371+(N[3]>>>0<I[3]>>>0?1:0)|0,N[5]=N[5]+886263092+(N[4]>>>0<I[4]>>>0?1:0)|0,N[6]=N[6]+1295307597+(N[5]>>>0<I[5]>>>0?1:0)|0,N[7]=N[7]+3545052371+(N[6]>>>0<I[6]>>>0?1:0)|0,this._b=N[7]>>>0<I[7]>>>0?1:0,A=0;A<8;A++){var O=k[A]+N[A],M=65535&O,w=O>>>16,U=((M*M>>>17)+M*w>>>15)+w*w,L=((4294901760&O)*O|0)+((65535&O)*O|0);S[A]=U^L}k[0]=S[0]+(S[7]<<16|S[7]>>>16)+(S[6]<<16|S[6]>>>16)|0,k[1]=S[1]+(S[0]<<8|S[0]>>>24)+S[7]|0,k[2]=S[2]+(S[1]<<16|S[1]>>>16)+(S[0]<<16|S[0]>>>16)|0,k[3]=S[3]+(S[2]<<8|S[2]>>>24)+S[1]|0,k[4]=S[4]+(S[3]<<16|S[3]>>>16)+(S[2]<<16|S[2]>>>16)|0,k[5]=S[5]+(S[4]<<8|S[4]>>>24)+S[3]|0,k[6]=S[6]+(S[5]<<16|S[5]>>>16)+(S[4]<<16|S[4]>>>16)|0,k[7]=S[7]+(S[6]<<8|S[6]>>>24)+S[5]|0}p.Rabbit=v._createHelper(E)})(),d.Rabbit)}),ot(function(a,u){var d;a.exports=(d=ct,(function(){var p=d,v=p.lib.StreamCipher,g=p.algo,y=[],I=[],S=[],E=g.RabbitLegacy=v.extend({_doReset:function(){var k=this._key.words,N=this.cfg.iv,A=this._X=[k[0],k[3]<<16|k[2]>>>16,k[1],k[0]<<16|k[3]>>>16,k[2],k[1]<<16|k[0]>>>16,k[3],k[2]<<16|k[1]>>>16],O=this._C=[k[2]<<16|k[2]>>>16,4294901760&k[0]|65535&k[1],k[3]<<16|k[3]>>>16,4294901760&k[1]|65535&k[2],k[0]<<16|k[0]>>>16,4294901760&k[2]|65535&k[3],k[1]<<16|k[1]>>>16,4294901760&k[3]|65535&k[0]];this._b=0;for(var M=0;M<4;M++)R.call(this);for(M=0;M<8;M++)O[M]^=A[M+4&7];if(N){var w=N.words,U=w[0],L=w[1],V=16711935&(U<<8|U>>>24)|4278255360&(U<<24|U>>>8),F=16711935&(L<<8|L>>>24)|4278255360&(L<<24|L>>>8),q=V>>>16|4294901760&F,K=F<<16|65535&V;for(O[0]^=V,O[1]^=q,O[2]^=F,O[3]^=K,O[4]^=V,O[5]^=q,O[6]^=F,O[7]^=K,M=0;M<4;M++)R.call(this)}},_doProcessBlock:function(k,N){var A=this._X;R.call(this),y[0]=A[0]^A[5]>>>16^A[3]<<16,y[1]=A[2]^A[7]>>>16^A[5]<<16,y[2]=A[4]^A[1]>>>16^A[7]<<16,y[3]=A[6]^A[3]>>>16^A[1]<<16;for(var O=0;O<4;O++)y[O]=16711935&(y[O]<<8|y[O]>>>24)|4278255360&(y[O]<<24|y[O]>>>8),k[N+O]^=y[O]},blockSize:4,ivSize:2});function R(){for(var k=this._X,N=this._C,A=0;A<8;A++)I[A]=N[A];for(N[0]=N[0]+1295307597+this._b|0,N[1]=N[1]+3545052371+(N[0]>>>0<I[0]>>>0?1:0)|0,N[2]=N[2]+886263092+(N[1]>>>0<I[1]>>>0?1:0)|0,N[3]=N[3]+1295307597+(N[2]>>>0<I[2]>>>0?1:0)|0,N[4]=N[4]+3545052371+(N[3]>>>0<I[3]>>>0?1:0)|0,N[5]=N[5]+886263092+(N[4]>>>0<I[4]>>>0?1:0)|0,N[6]=N[6]+1295307597+(N[5]>>>0<I[5]>>>0?1:0)|0,N[7]=N[7]+3545052371+(N[6]>>>0<I[6]>>>0?1:0)|0,this._b=N[7]>>>0<I[7]>>>0?1:0,A=0;A<8;A++){var O=k[A]+N[A],M=65535&O,w=O>>>16,U=((M*M>>>17)+M*w>>>15)+w*w,L=((4294901760&O)*O|0)+((65535&O)*O|0);S[A]=U^L}k[0]=S[0]+(S[7]<<16|S[7]>>>16)+(S[6]<<16|S[6]>>>16)|0,k[1]=S[1]+(S[0]<<8|S[0]>>>24)+S[7]|0,k[2]=S[2]+(S[1]<<16|S[1]>>>16)+(S[0]<<16|S[0]>>>16)|0,k[3]=S[3]+(S[2]<<8|S[2]>>>24)+S[1]|0,k[4]=S[4]+(S[3]<<16|S[3]>>>16)+(S[2]<<16|S[2]>>>16)|0,k[5]=S[5]+(S[4]<<8|S[4]>>>24)+S[3]|0,k[6]=S[6]+(S[5]<<16|S[5]>>>16)+(S[4]<<16|S[4]>>>16)|0,k[7]=S[7]+(S[6]<<8|S[6]>>>24)+S[5]|0}p.RabbitLegacy=v._createHelper(E)})(),d.RabbitLegacy)}),ot(function(a,u){a.exports=ct}));function iy(){throw new Error("setTimeout has not been defined")}function ry(){throw new Error("clearTimeout has not been defined")}var Dn=iy,Nn=ry;function ny(a){if(Dn===setTimeout)return setTimeout(a,0);if((Dn===iy||!Dn)&&setTimeout)return Dn=setTimeout,setTimeout(a,0);try{return Dn(a,0)}catch{try{return Dn.call(null,a,0)}catch{return Dn.call(this,a,0)}}}typeof La.setTimeout=="function"&&(Dn=setTimeout),typeof La.clearTimeout=="function"&&(Nn=clearTimeout);var Is,qr=[],xa=!1,Du=-1;function DP(){xa&&Is&&(xa=!1,Is.length?qr=Is.concat(qr):Du=-1,qr.length&&sy())}function sy(){if(!xa){var a=ny(DP);xa=!0;for(var u=qr.length;u;){for(Is=qr,qr=[];++Du<u;)Is&&Is[Du].run();Du=-1,u=qr.length}Is=null,xa=!1,(function(d){if(Nn===clearTimeout)return clearTimeout(d);if((Nn===ry||!Nn)&&clearTimeout)return Nn=clearTimeout,clearTimeout(d);try{Nn(d)}catch{try{return Nn.call(null,d)}catch{return Nn.call(this,d)}}})(a)}}function oi(a){var u=new Array(arguments.length-1);if(arguments.length>1)for(var d=1;d<arguments.length;d++)u[d-1]=arguments[d];qr.push(new ay(a,u)),qr.length!==1||xa||ny(sy)}function ay(a,u){this.fun=a,this.array=u}ay.prototype.run=function(){this.fun.apply(null,this.array)};var tl=La.performance||{};tl.now||tl.mozNow||tl.msNow||tl.oNow||tl.webkitNow;function Pn(){}function lt(){lt.init.call(this)}function oy(a){return a._maxListeners===void 0?lt.defaultMaxListeners:a._maxListeners}function NP(a,u,d){if(u)a.call(d);else for(var p=a.length,v=il(a,p),g=0;g<p;++g)v[g].call(d)}function PP(a,u,d,p){if(u)a.call(d,p);else for(var v=a.length,g=il(a,v),y=0;y<v;++y)g[y].call(d,p)}function OP(a,u,d,p,v){if(u)a.call(d,p,v);else for(var g=a.length,y=il(a,g),I=0;I<g;++I)y[I].call(d,p,v)}function MP(a,u,d,p,v,g){if(u)a.call(d,p,v,g);else for(var y=a.length,I=il(a,y),S=0;S<y;++S)I[S].call(d,p,v,g)}function LP(a,u,d,p){if(u)a.apply(d,p);else for(var v=a.length,g=il(a,v),y=0;y<v;++y)g[y].apply(d,p)}function ly(a,u,d,p){var v,g,y,I;if(typeof d!="function")throw new TypeError('"listener" argument must be a function');if((g=a._events)?(g.newListener&&(a.emit("newListener",u,d.listener?d.listener:d),g=a._events),y=g[u]):(g=a._events=new Pn,a._eventsCount=0),y){if(typeof y=="function"?y=g[u]=p?[d,y]:[y,d]:p?y.unshift(d):y.push(d),!y.warned&&(v=oy(a))&&v>0&&y.length>v){y.warned=!0;var S=new Error("Possible EventEmitter memory leak detected. "+y.length+" "+u+" listeners added. Use emitter.setMaxListeners() to increase limit");S.name="MaxListenersExceededWarning",S.emitter=a,S.type=u,S.count=y.length,I=S,typeof console.warn=="function"?console.warn(I):console.log(I)}}else y=g[u]=d,++a._eventsCount;return a}function cy(a,u,d){var p=!1;function v(){a.removeListener(u,v),p||(p=!0,d.apply(a,arguments))}return v.listener=d,v}function uy(a){var u=this._events;if(u){var d=u[a];if(typeof d=="function")return 1;if(d)return d.length}return 0}function il(a,u){for(var d=new Array(u);u--;)d[u]=a[u];return d}Pn.prototype=Object.create(null),lt.EventEmitter=lt,lt.usingDomains=!1,lt.prototype.domain=void 0,lt.prototype._events=void 0,lt.prototype._maxListeners=void 0,lt.defaultMaxListeners=10,lt.init=function(){this.domain=null,lt.usingDomains&&(void 0).active&&(void 0).Domain,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new Pn,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},lt.prototype.setMaxListeners=function(a){if(typeof a!="number"||a<0||isNaN(a))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=a,this},lt.prototype.getMaxListeners=function(){return oy(this)},lt.prototype.emit=function(a){var u,d,p,v,g,y,I,S=a==="error";if(y=this._events)S=S&&y.error==null;else if(!S)return!1;if(I=this.domain,S){if(u=arguments[1],!I){if(u instanceof Error)throw u;var E=new Error('Uncaught, unspecified "error" event. ('+u+")");throw E.context=u,E}return u||(u=new Error('Uncaught, unspecified "error" event')),u.domainEmitter=this,u.domain=I,u.domainThrown=!1,I.emit("error",u),!1}if(!(d=y[a]))return!1;var R=typeof d=="function";switch(p=arguments.length){case 1:NP(d,R,this);break;case 2:PP(d,R,this,arguments[1]);break;case 3:OP(d,R,this,arguments[1],arguments[2]);break;case 4:MP(d,R,this,arguments[1],arguments[2],arguments[3]);break;default:for(v=new Array(p-1),g=1;g<p;g++)v[g-1]=arguments[g];LP(d,R,this,v)}return!0},lt.prototype.addListener=function(a,u){return ly(this,a,u,!1)},lt.prototype.on=lt.prototype.addListener,lt.prototype.prependListener=function(a,u){return ly(this,a,u,!0)},lt.prototype.once=function(a,u){if(typeof u!="function")throw new TypeError('"listener" argument must be a function');return this.on(a,cy(this,a,u)),this},lt.prototype.prependOnceListener=function(a,u){if(typeof u!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(a,cy(this,a,u)),this},lt.prototype.removeListener=function(a,u){var d,p,v,g,y;if(typeof u!="function")throw new TypeError('"listener" argument must be a function');if(!(p=this._events))return this;if(!(d=p[a]))return this;if(d===u||d.listener&&d.listener===u)--this._eventsCount==0?this._events=new Pn:(delete p[a],p.removeListener&&this.emit("removeListener",a,d.listener||u));else if(typeof d!="function"){for(v=-1,g=d.length;g-- >0;)if(d[g]===u||d[g].listener&&d[g].listener===u){y=d[g].listener,v=g;break}if(v<0)return this;if(d.length===1){if(d[0]=void 0,--this._eventsCount==0)return this._events=new Pn,this;delete p[a]}else(function(I,S){for(var E=S,R=E+1,k=I.length;R<k;E+=1,R+=1)I[E]=I[R];I.pop()})(d,v);p.removeListener&&this.emit("removeListener",a,y||u)}return this},lt.prototype.removeAllListeners=function(a){var u,d;if(!(d=this._events))return this;if(!d.removeListener)return arguments.length===0?(this._events=new Pn,this._eventsCount=0):d[a]&&(--this._eventsCount==0?this._events=new Pn:delete d[a]),this;if(arguments.length===0){for(var p,v=Object.keys(d),g=0;g<v.length;++g)(p=v[g])!=="removeListener"&&this.removeAllListeners(p);return this.removeAllListeners("removeListener"),this._events=new Pn,this._eventsCount=0,this}if(typeof(u=d[a])=="function")this.removeListener(a,u);else if(u)do this.removeListener(a,u[u.length-1]);while(u[0]);return this},lt.prototype.listeners=function(a){var u,d=this._events;return d&&(u=d[a])?typeof u=="function"?[u.listener||u]:(function(p){for(var v=new Array(p.length),g=0;g<v.length;++g)v[g]=p[g].listener||p[g];return v})(u):[]},lt.listenerCount=function(a,u){return typeof a.listenerCount=="function"?a.listenerCount(u):uy.call(a,u)},lt.prototype.listenerCount=uy,lt.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};var Di=typeof Object.create=="function"?function(a,u){a.super_=u,a.prototype=Object.create(u.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}})}:function(a,u){a.super_=u;var d=function(){};d.prototype=u.prototype,a.prototype=new d,a.prototype.constructor=a},xP=/%[sdj%]/g;function UP(a){if(!cm(a)){for(var u=[],d=0;d<arguments.length;d++)u.push(On(arguments[d]));return u.join(" ")}d=1;for(var p=arguments,v=p.length,g=String(a).replace(xP,function(I){if(I==="%%")return"%";if(d>=v)return I;switch(I){case"%s":return String(p[d++]);case"%d":return Number(p[d++]);case"%j":try{return JSON.stringify(p[d++])}catch{return"[Circular]"}default:return I}}),y=p[d];d<v;y=p[++d])lm(y)||!rl(y)?g+=" "+y:g+=" "+On(y);return g}function dy(a,u){if(Mn(La.process))return function(){return dy(a,u).apply(this,arguments)};var d=!1;return function(){return d||(console.error(u),d=!0),a.apply(this,arguments)}}var sm,Nu={};function On(a,u){var d={seen:[],stylize:FP};return arguments.length>=3&&(d.depth=arguments[2]),arguments.length>=4&&(d.colors=arguments[3]),hy(u)?d.showHidden=u:u&&(function(p,v){if(!v||!rl(v))return p;for(var g=Object.keys(v),y=g.length;y--;)p[g[y]]=v[g[y]]})(d,u),Mn(d.showHidden)&&(d.showHidden=!1),Mn(d.depth)&&(d.depth=2),Mn(d.colors)&&(d.colors=!1),Mn(d.customInspect)&&(d.customInspect=!0),d.colors&&(d.stylize=VP),Pu(d,a,d.depth)}function VP(a,u){var d=On.styles[u];return d?"\x1B["+On.colors[d][0]+"m"+a+"\x1B["+On.colors[d][1]+"m":a}function FP(a,u){return a}function Pu(a,u,d){if(a.customInspect&&u&&hm(u.inspect)&&u.inspect!==On&&(!u.constructor||u.constructor.prototype!==u)){var p=u.inspect(d,a);return cm(p)||(p=Pu(a,p,d)),p}var v=(function(A,O){if(Mn(O))return A.stylize("undefined","undefined");if(cm(O)){var M="'"+JSON.stringify(O).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return A.stylize(M,"string")}if(w=O,typeof w=="number")return A.stylize(""+O,"number");var w;if(hy(O))return A.stylize(""+O,"boolean");if(lm(O))return A.stylize("null","null")})(a,u);if(v)return v;var g=Object.keys(u),y=(function(A){var O={};return A.forEach(function(M,w){O[M]=!0}),O})(g);if(a.showHidden&&(g=Object.getOwnPropertyNames(u)),dm(u)&&(g.indexOf("message")>=0||g.indexOf("description")>=0))return am(u);if(g.length===0){if(hm(u)){var I=u.name?": "+u.name:"";return a.stylize("[Function"+I+"]","special")}if(um(u))return a.stylize(RegExp.prototype.toString.call(u),"regexp");if(py(u))return a.stylize(Date.prototype.toString.call(u),"date");if(dm(u))return am(u)}var S,E,R="",k=!1,N=["{","}"];return S=u,Array.isArray(S)&&(k=!0,N=["[","]"]),hm(u)&&(R=" [Function"+(u.name?": "+u.name:"")+"]"),um(u)&&(R=" "+RegExp.prototype.toString.call(u)),py(u)&&(R=" "+Date.prototype.toUTCString.call(u)),dm(u)&&(R=" "+am(u)),g.length!==0||k&&u.length!=0?d<0?um(u)?a.stylize(RegExp.prototype.toString.call(u),"regexp"):a.stylize("[Object]","special"):(a.seen.push(u),E=k?(function(A,O,M,w,U){for(var L=[],V=0,F=O.length;V<F;++V)my(O,String(V))?L.push(om(A,O,M,w,String(V),!0)):L.push("");return U.forEach(function(q){q.match(/^\d+$/)||L.push(om(A,O,M,w,q,!0))}),L})(a,u,d,y,g):g.map(function(A){return om(a,u,d,y,A,k)}),a.seen.pop(),(function(A,O,M){return A.reduce(function(w,U){return U.indexOf(`
156
+ `),w+U.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?M[0]+(O===""?"":O+`
157
+ `)+" "+A.join(`,
158
+ `)+" "+M[1]:M[0]+O+" "+A.join(", ")+" "+M[1]})(E,R,N)):N[0]+R+N[1]}function am(a){return"["+Error.prototype.toString.call(a)+"]"}function om(a,u,d,p,v,g){var y,I,S;if((S=Object.getOwnPropertyDescriptor(u,v)||{value:u[v]}).get?I=S.set?a.stylize("[Getter/Setter]","special"):a.stylize("[Getter]","special"):S.set&&(I=a.stylize("[Setter]","special")),my(p,v)||(y="["+v+"]"),I||(a.seen.indexOf(S.value)<0?(I=lm(d)?Pu(a,S.value,null):Pu(a,S.value,d-1)).indexOf(`
159
+ `)>-1&&(I=g?I.split(`
160
+ `).map(function(E){return" "+E}).join(`
161
+ `).substr(2):`
162
+ `+I.split(`
163
+ `).map(function(E){return" "+E}).join(`
164
+ `)):I=a.stylize("[Circular]","special")),Mn(y)){if(g&&v.match(/^\d+$/))return I;(y=JSON.stringify(""+v)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(y=y.substr(1,y.length-2),y=a.stylize(y,"name")):(y=y.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),y=a.stylize(y,"string"))}return y+": "+I}function hy(a){return typeof a=="boolean"}function lm(a){return a===null}function cm(a){return typeof a=="string"}function Mn(a){return a===void 0}function um(a){return rl(a)&&pm(a)==="[object RegExp]"}function rl(a){return typeof a=="object"&&a!==null}function py(a){return rl(a)&&pm(a)==="[object Date]"}function dm(a){return rl(a)&&(pm(a)==="[object Error]"||a instanceof Error)}function hm(a){return typeof a=="function"}function pm(a){return Object.prototype.toString.call(a)}function my(a,u){return Object.prototype.hasOwnProperty.call(a,u)}function Rs(){this.head=null,this.tail=null,this.length=0}On.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},On.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},Rs.prototype.push=function(a){var u={data:a,next:null};this.length>0?this.tail.next=u:this.head=u,this.tail=u,++this.length},Rs.prototype.unshift=function(a){var u={data:a,next:this.head};this.length===0&&(this.tail=u),this.head=u,++this.length},Rs.prototype.shift=function(){if(this.length!==0){var a=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,a}},Rs.prototype.clear=function(){this.head=this.tail=null,this.length=0},Rs.prototype.join=function(a){if(this.length===0)return"";for(var u=this.head,d=""+u.data;u=u.next;)d+=a+u.data;return d},Rs.prototype.concat=function(a){if(this.length===0)return re.alloc(0);if(this.length===1)return this.head.data;for(var u=re.allocUnsafe(a>>>0),d=this.head,p=0;d;)d.data.copy(u,p),p+=d.data.length,d=d.next;return u};var BP=re.isEncoding||function(a){switch(a&&a.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function nl(a){switch(this.encoding=(a||"utf8").toLowerCase().replace(/[-_]/,""),(function(u){if(u&&!BP(u))throw new Error("Unknown encoding: "+u)})(a),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=WP;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=GP;break;default:return void(this.write=HP)}this.charBuffer=new re(6),this.charReceived=0,this.charLength=0}function HP(a){return a.toString(this.encoding)}function WP(a){this.charReceived=a.length%2,this.charLength=this.charReceived?2:0}function GP(a){this.charReceived=a.length%3,this.charLength=this.charReceived?3:0}nl.prototype.write=function(a){for(var u="";this.charLength;){var d=a.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:a.length;if(a.copy(this.charBuffer,this.charReceived,0,d),this.charReceived+=d,this.charReceived<this.charLength)return"";if(a=a.slice(d,a.length),!((v=(u=this.charBuffer.slice(0,this.charLength).toString(this.encoding)).charCodeAt(u.length-1))>=55296&&v<=56319)){if(this.charReceived=this.charLength=0,a.length===0)return u;break}this.charLength+=this.surrogateSize,u=""}this.detectIncompleteChar(a);var p=a.length;this.charLength&&(a.copy(this.charBuffer,0,a.length-this.charReceived,p),p-=this.charReceived);var v;if(p=(u+=a.toString(this.encoding,0,p)).length-1,(v=u.charCodeAt(p))>=55296&&v<=56319){var g=this.surrogateSize;return this.charLength+=g,this.charReceived+=g,this.charBuffer.copy(this.charBuffer,g,0,g),a.copy(this.charBuffer,0,0,g),u.substring(0,p)}return u},nl.prototype.detectIncompleteChar=function(a){for(var u=a.length>=3?3:a.length;u>0;u--){var d=a[a.length-u];if(u==1&&d>>5==6){this.charLength=2;break}if(u<=2&&d>>4==14){this.charLength=3;break}if(u<=3&&d>>3==30){this.charLength=4;break}}this.charReceived=u},nl.prototype.end=function(a){var u="";if(a&&a.length&&(u=this.write(a)),this.charReceived){var d=this.charReceived,p=this.charBuffer,v=this.encoding;u+=p.slice(0,d).toString(v)}return u},Bt.ReadableState=fy;var vt=(function(a){return Mn(sm)&&(sm=""),a=a.toUpperCase(),Nu[a]||(new RegExp("\\b"+a+"\\b","i").test(sm)?Nu[a]=function(){var u=UP.apply(null,arguments);console.error("%s %d: %s",a,0,u)}:Nu[a]=function(){}),Nu[a]})("stream");function fy(a,u){a=a||{},this.objectMode=!!a.objectMode,u instanceof Ji&&(this.objectMode=this.objectMode||!!a.readableObjectMode);var d=a.highWaterMark,p=this.objectMode?16:16384;this.highWaterMark=d||d===0?d:p,this.highWaterMark=~~this.highWaterMark,this.buffer=new Rs,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=a.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,a.encoding&&(this.decoder=new nl(a.encoding),this.encoding=a.encoding)}function Bt(a){if(!(this instanceof Bt))return new Bt(a);this._readableState=new fy(a,this),this.readable=!0,a&&typeof a.read=="function"&&(this._read=a.read),lt.call(this)}function _y(a,u,d,p,v){var g=(function(E,R){var k=null;return el(R)||typeof R=="string"||R==null||E.objectMode||(k=new TypeError("Invalid non-string/buffer chunk")),k})(u,d);if(g)a.emit("error",g);else if(d===null)u.reading=!1,(function(E,R){if(!R.ended){if(R.decoder){var k=R.decoder.end();k&&k.length&&(R.buffer.push(k),R.length+=R.objectMode?1:k.length)}R.ended=!0,Ou(E)}})(a,u);else if(u.objectMode||d&&d.length>0)if(u.ended&&!v){var y=new Error("stream.push() after EOF");a.emit("error",y)}else if(u.endEmitted&&v){var I=new Error("stream.unshift() after end event");a.emit("error",I)}else{var S;!u.decoder||v||p||(d=u.decoder.write(d),S=!u.objectMode&&d.length===0),v||(u.reading=!1),S||(u.flowing&&u.length===0&&!u.sync?(a.emit("data",d),a.read(0)):(u.length+=u.objectMode?1:d.length,v?u.buffer.unshift(d):u.buffer.push(d),u.needReadable&&Ou(a))),(function(E,R){R.readingMore||(R.readingMore=!0,oi(jP,E,R))})(a,u)}else v||(u.reading=!1);return(function(E){return!E.ended&&(E.needReadable||E.length<E.highWaterMark||E.length===0)})(u)}Di(Bt,lt),Bt.prototype.push=function(a,u){var d=this._readableState;return d.objectMode||typeof a!="string"||(u=u||d.defaultEncoding)!==d.encoding&&(a=re.from(a,u),u=""),_y(this,d,a,u,!1)},Bt.prototype.unshift=function(a){return _y(this,this._readableState,a,"",!0)},Bt.prototype.isPaused=function(){return this._readableState.flowing===!1},Bt.prototype.setEncoding=function(a){return this._readableState.decoder=new nl(a),this._readableState.encoding=a,this};var gy=8388608;function vy(a,u){return a<=0||u.length===0&&u.ended?0:u.objectMode?1:a!=a?u.flowing&&u.length?u.buffer.head.data.length:u.length:(a>u.highWaterMark&&(u.highWaterMark=(function(d){return d>=gy?d=gy:(d--,d|=d>>>1,d|=d>>>2,d|=d>>>4,d|=d>>>8,d|=d>>>16,d++),d})(a)),a<=u.length?a:u.ended?u.length:(u.needReadable=!0,0))}function Ou(a){var u=a._readableState;u.needReadable=!1,u.emittedReadable||(vt("emitReadable",u.flowing),u.emittedReadable=!0,u.sync?oi(Ey,a):Ey(a))}function Ey(a){vt("emit readable"),a.emit("readable"),mm(a)}function jP(a,u){for(var d=u.length;!u.reading&&!u.flowing&&!u.ended&&u.length<u.highWaterMark&&(vt("maybeReadMore read 0"),a.read(0),d!==u.length);)d=u.length;u.readingMore=!1}function zP(a){vt("readable nexttick read 0"),a.read(0)}function KP(a,u){u.reading||(vt("resume read 0"),a.read(0)),u.resumeScheduled=!1,u.awaitDrain=0,a.emit("resume"),mm(a),u.flowing&&!u.reading&&a.read(0)}function mm(a){var u=a._readableState;for(vt("flow",u.flowing);u.flowing&&a.read()!==null;);}function yy(a,u){return u.length===0?null:(u.objectMode?d=u.buffer.shift():!a||a>=u.length?(d=u.decoder?u.buffer.join(""):u.buffer.length===1?u.buffer.head.data:u.buffer.concat(u.length),u.buffer.clear()):d=(function(p,v,g){var y;return p<v.head.data.length?(y=v.head.data.slice(0,p),v.head.data=v.head.data.slice(p)):y=p===v.head.data.length?v.shift():g?(function(I,S){var E=S.head,R=1,k=E.data;for(I-=k.length;E=E.next;){var N=E.data,A=I>N.length?N.length:I;if(A===N.length?k+=N:k+=N.slice(0,I),(I-=A)===0){A===N.length?(++R,E.next?S.head=E.next:S.head=S.tail=null):(S.head=E,E.data=N.slice(A));break}++R}return S.length-=R,k})(p,v):(function(I,S){var E=re.allocUnsafe(I),R=S.head,k=1;for(R.data.copy(E),I-=R.data.length;R=R.next;){var N=R.data,A=I>N.length?N.length:I;if(N.copy(E,E.length-I,0,A),(I-=A)===0){A===N.length?(++k,R.next?S.head=R.next:S.head=S.tail=null):(S.head=R,R.data=N.slice(A));break}++k}return S.length-=k,E})(p,v),y})(a,u.buffer,u.decoder),d);var d}function fm(a){var u=a._readableState;if(u.length>0)throw new Error('"endReadable()" called on non-empty stream');u.endEmitted||(u.ended=!0,oi(JP,u,a))}function JP(a,u){a.endEmitted||a.length!==0||(a.endEmitted=!0,u.readable=!1,u.emit("end"))}function Ty(a,u){for(var d=0,p=a.length;d<p;d++)if(a[d]===u)return d;return-1}function YP(){}function qP(a,u,d){this.chunk=a,this.encoding=u,this.callback=d,this.next=null}function _m(a,u){Object.defineProperty(this,"buffer",{get:dy(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")}),a=a||{},this.objectMode=!!a.objectMode,u instanceof Ji&&(this.objectMode=this.objectMode||!!a.writableObjectMode);var d=a.highWaterMark,p=this.objectMode?16:16384;this.highWaterMark=d||d===0?d:p,this.highWaterMark=~~this.highWaterMark,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1;var v=a.decodeStrings===!1;this.decodeStrings=!v,this.defaultEncoding=a.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(g){(function(y,I){var S=y._writableState,E=S.sync,R=S.writecb;if((function(N){N.writing=!1,N.writecb=null,N.length-=N.writelen,N.writelen=0})(S),I)(function(N,A,O,M,w){--A.pendingcb,O?oi(w,M):w(M),N._writableState.errorEmitted=!0,N.emit("error",M)})(y,S,E,I,R);else{var k=Ry(S);k||S.corked||S.bufferProcessing||!S.bufferedRequest||Iy(y,S),E?oi(Sy,y,S,k,R):Sy(y,S,k,R)}})(u,g)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new Cy(this)}function mi(a){if(!(this instanceof mi||this instanceof Ji))return new mi(a);this._writableState=new _m(a,this),this.writable=!0,a&&(typeof a.write=="function"&&(this._write=a.write),typeof a.writev=="function"&&(this._writev=a.writev)),lt.call(this)}function gm(a,u,d,p,v,g,y){u.writelen=p,u.writecb=y,u.writing=!0,u.sync=!0,d?a._writev(v,u.onwrite):a._write(v,g,u.onwrite),u.sync=!1}function Sy(a,u,d,p){d||(function(v,g){g.length===0&&g.needDrain&&(g.needDrain=!1,v.emit("drain"))})(a,u),u.pendingcb--,p(),by(a,u)}function Iy(a,u){u.bufferProcessing=!0;var d=u.bufferedRequest;if(a._writev&&d&&d.next){var p=u.bufferedRequestCount,v=new Array(p),g=u.corkedRequestsFree;g.entry=d;for(var y=0;d;)v[y]=d,d=d.next,y+=1;gm(a,u,!0,u.length,v,"",g.finish),u.pendingcb++,u.lastBufferedRequest=null,g.next?(u.corkedRequestsFree=g.next,g.next=null):u.corkedRequestsFree=new Cy(u)}else{for(;d;){var I=d.chunk,S=d.encoding,E=d.callback;if(gm(a,u,!1,u.objectMode?1:I.length,I,S,E),d=d.next,u.writing)break}d===null&&(u.lastBufferedRequest=null)}u.bufferedRequestCount=0,u.bufferedRequest=d,u.bufferProcessing=!1}function Ry(a){return a.ending&&a.length===0&&a.bufferedRequest===null&&!a.finished&&!a.writing}function Ay(a,u){u.prefinished||(u.prefinished=!0,a.emit("prefinish"))}function by(a,u){var d=Ry(u);return d&&(u.pendingcb===0?(Ay(a,u),u.finished=!0,a.emit("finish")):Ay(a,u)),d}function Cy(a){var u=this;this.next=null,this.entry=null,this.finish=function(d){var p=u.entry;for(u.entry=null;p;){var v=p.callback;a.pendingcb--,v(d),p=p.next}a.corkedRequestsFree?a.corkedRequestsFree.next=u:a.corkedRequestsFree=u}}Bt.prototype.read=function(a){vt("read",a),a=parseInt(a,10);var u=this._readableState,d=a;if(a!==0&&(u.emittedReadable=!1),a===0&&u.needReadable&&(u.length>=u.highWaterMark||u.ended))return vt("read: emitReadable",u.length,u.ended),u.length===0&&u.ended?fm(this):Ou(this),null;if((a=vy(a,u))===0&&u.ended)return u.length===0&&fm(this),null;var p,v=u.needReadable;return vt("need readable",v),(u.length===0||u.length-a<u.highWaterMark)&&vt("length less than watermark",v=!0),u.ended||u.reading?vt("reading or ended",v=!1):v&&(vt("do read"),u.reading=!0,u.sync=!0,u.length===0&&(u.needReadable=!0),this._read(u.highWaterMark),u.sync=!1,u.reading||(a=vy(d,u))),(p=a>0?yy(a,u):null)===null?(u.needReadable=!0,a=0):u.length-=a,u.length===0&&(u.ended||(u.needReadable=!0),d!==a&&u.ended&&fm(this)),p!==null&&this.emit("data",p),p},Bt.prototype._read=function(a){this.emit("error",new Error("not implemented"))},Bt.prototype.pipe=function(a,u){var d=this,p=this._readableState;switch(p.pipesCount){case 0:p.pipes=a;break;case 1:p.pipes=[p.pipes,a];break;default:p.pipes.push(a)}p.pipesCount+=1,vt("pipe count=%d opts=%j",p.pipesCount,u);var v=!u||u.end!==!1?y:E;function g(w){vt("onunpipe"),w===d&&E()}function y(){vt("onend"),a.end()}p.endEmitted?oi(v):d.once("end",v),a.on("unpipe",g);var I=(function(w){return function(){var U=w._readableState;vt("pipeOnDrain",U.awaitDrain),U.awaitDrain&&U.awaitDrain--,U.awaitDrain===0&&w.listeners("data").length&&(U.flowing=!0,mm(w))}})(d);a.on("drain",I);var S=!1;function E(){vt("cleanup"),a.removeListener("close",A),a.removeListener("finish",O),a.removeListener("drain",I),a.removeListener("error",N),a.removeListener("unpipe",g),d.removeListener("end",y),d.removeListener("end",E),d.removeListener("data",k),S=!0,!p.awaitDrain||a._writableState&&!a._writableState.needDrain||I()}var R=!1;function k(w){vt("ondata"),R=!1,a.write(w)!==!1||R||((p.pipesCount===1&&p.pipes===a||p.pipesCount>1&&Ty(p.pipes,a)!==-1)&&!S&&(vt("false write response, pause",d._readableState.awaitDrain),d._readableState.awaitDrain++,R=!0),d.pause())}function N(w){var U;vt("onerror",w),M(),a.removeListener("error",N),U="error",a.listeners(U).length===0&&a.emit("error",w)}function A(){a.removeListener("finish",O),M()}function O(){vt("onfinish"),a.removeListener("close",A),M()}function M(){vt("unpipe"),d.unpipe(a)}return d.on("data",k),(function(w,U,L){if(typeof w.prependListener=="function")return w.prependListener(U,L);w._events&&w._events[U]?Array.isArray(w._events[U])?w._events[U].unshift(L):w._events[U]=[L,w._events[U]]:w.on(U,L)})(a,"error",N),a.once("close",A),a.once("finish",O),a.emit("pipe",d),p.flowing||(vt("pipe resume"),d.resume()),a},Bt.prototype.unpipe=function(a){var u=this._readableState;if(u.pipesCount===0)return this;if(u.pipesCount===1)return a&&a!==u.pipes?this:(a||(a=u.pipes),u.pipes=null,u.pipesCount=0,u.flowing=!1,a&&a.emit("unpipe",this),this);if(!a){var d=u.pipes,p=u.pipesCount;u.pipes=null,u.pipesCount=0,u.flowing=!1;for(var v=0;v<p;v++)d[v].emit("unpipe",this);return this}var g=Ty(u.pipes,a);return g===-1?this:(u.pipes.splice(g,1),u.pipesCount-=1,u.pipesCount===1&&(u.pipes=u.pipes[0]),a.emit("unpipe",this),this)},Bt.prototype.on=function(a,u){var d=lt.prototype.on.call(this,a,u);if(a==="data")this._readableState.flowing!==!1&&this.resume();else if(a==="readable"){var p=this._readableState;p.endEmitted||p.readableListening||(p.readableListening=p.needReadable=!0,p.emittedReadable=!1,p.reading?p.length&&Ou(this):oi(zP,this))}return d},Bt.prototype.addListener=Bt.prototype.on,Bt.prototype.resume=function(){var a=this._readableState;return a.flowing||(vt("resume"),a.flowing=!0,(function(u,d){d.resumeScheduled||(d.resumeScheduled=!0,oi(KP,u,d))})(this,a)),this},Bt.prototype.pause=function(){return vt("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(vt("pause"),this._readableState.flowing=!1,this.emit("pause")),this},Bt.prototype.wrap=function(a){var u=this._readableState,d=!1,p=this;for(var v in a.on("end",function(){if(vt("wrapped end"),u.decoder&&!u.ended){var g=u.decoder.end();g&&g.length&&p.push(g)}p.push(null)}),a.on("data",function(g){vt("wrapped data"),u.decoder&&(g=u.decoder.write(g)),u.objectMode&&g==null||(u.objectMode||g&&g.length)&&(p.push(g)||(d=!0,a.pause()))}),a)this[v]===void 0&&typeof a[v]=="function"&&(this[v]=(function(g){return function(){return a[g].apply(a,arguments)}})(v));return(function(g,y){for(var I=0,S=g.length;I<S;I++)y(g[I],I)})(["error","close","destroy","pause","resume"],function(g){a.on(g,p.emit.bind(p,g))}),p._read=function(g){vt("wrapped _read",g),d&&(d=!1,a.resume())},p},Bt._fromList=yy,mi.WritableState=_m,Di(mi,lt),_m.prototype.getBuffer=function(){for(var a=this.bufferedRequest,u=[];a;)u.push(a),a=a.next;return u},mi.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},mi.prototype.write=function(a,u,d){var p=this._writableState,v=!1;return typeof u=="function"&&(d=u,u=null),re.isBuffer(a)?u="buffer":u||(u=p.defaultEncoding),typeof d!="function"&&(d=YP),p.ended?(function(g,y){var I=new Error("write after end");g.emit("error",I),oi(y,I)})(this,d):(function(g,y,I,S){var E=!0,R=!1;return I===null?R=new TypeError("May not write null values to stream"):re.isBuffer(I)||typeof I=="string"||I===void 0||y.objectMode||(R=new TypeError("Invalid non-string/buffer chunk")),R&&(g.emit("error",R),oi(S,R),E=!1),E})(this,p,a,d)&&(p.pendingcb++,v=(function(g,y,I,S,E){I=(function(A,O,M){return A.objectMode||A.decodeStrings===!1||typeof O!="string"||(O=re.from(O,M)),O})(y,I,S),re.isBuffer(I)&&(S="buffer");var R=y.objectMode?1:I.length;y.length+=R;var k=y.length<y.highWaterMark;if(k||(y.needDrain=!0),y.writing||y.corked){var N=y.lastBufferedRequest;y.lastBufferedRequest=new qP(I,S,E),N?N.next=y.lastBufferedRequest:y.bufferedRequest=y.lastBufferedRequest,y.bufferedRequestCount+=1}else gm(g,y,!1,R,I,S,E);return k})(this,p,a,u,d)),v},mi.prototype.cork=function(){this._writableState.corked++},mi.prototype.uncork=function(){var a=this._writableState;a.corked&&(a.corked--,a.writing||a.corked||a.finished||a.bufferProcessing||!a.bufferedRequest||Iy(this,a))},mi.prototype.setDefaultEncoding=function(a){if(typeof a=="string"&&(a=a.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((a+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+a);return this._writableState.defaultEncoding=a,this},mi.prototype._write=function(a,u,d){d(new Error("not implemented"))},mi.prototype._writev=null,mi.prototype.end=function(a,u,d){var p=this._writableState;typeof a=="function"?(d=a,a=null,u=null):typeof u=="function"&&(d=u,u=null),a!=null&&this.write(a,u),p.corked&&(p.corked=1,this.uncork()),p.ending||p.finished||(function(v,g,y){g.ending=!0,by(v,g),y&&(g.finished?oi(y):v.once("finish",y)),g.ended=!0,v.writable=!1})(this,p,d)},Di(Ji,Bt);for(var ky=Object.keys(mi.prototype),vm=0;vm<ky.length;vm++){var Em=ky[vm];Ji.prototype[Em]||(Ji.prototype[Em]=mi.prototype[Em])}function Ji(a){if(!(this instanceof Ji))return new Ji(a);Bt.call(this,a),mi.call(this,a),a&&a.readable===!1&&(this.readable=!1),a&&a.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,a&&a.allowHalfOpen===!1&&(this.allowHalfOpen=!1),this.once("end",XP)}function XP(){this.allowHalfOpen||this._writableState.ended||oi(QP,this)}function QP(a){a.end()}function ZP(a){this.afterTransform=function(u,d){return(function(p,v,g){var y=p._transformState;y.transforming=!1;var I=y.writecb;if(!I)return p.emit("error",new Error("no writecb in Transform class"));y.writechunk=null,y.writecb=null,g!=null&&p.push(g),I(v);var S=p._readableState;S.reading=!1,(S.needReadable||S.length<S.highWaterMark)&&p._read(S.highWaterMark)})(a,u,d)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null,this.writeencoding=null}function Yi(a){if(!(this instanceof Yi))return new Yi(a);Ji.call(this,a),this._transformState=new ZP(this);var u=this;this._readableState.needReadable=!0,this._readableState.sync=!1,a&&(typeof a.transform=="function"&&(this._transform=a.transform),typeof a.flush=="function"&&(this._flush=a.flush)),this.once("prefinish",function(){typeof this._flush=="function"?this._flush(function(d){wy(u,d)}):wy(u)})}function wy(a,u){if(u)return a.emit("error",u);var d=a._writableState,p=a._transformState;if(d.length)throw new Error("Calling transform done when ws.length != 0");if(p.transforming)throw new Error("Calling transform done when still transforming");return a.push(null)}function sl(a){if(!(this instanceof sl))return new sl(a);Yi.call(this,a)}function Xr(){lt.call(this)}Di(Yi,Ji),Yi.prototype.push=function(a,u){return this._transformState.needTransform=!1,Ji.prototype.push.call(this,a,u)},Yi.prototype._transform=function(a,u,d){throw new Error("Not implemented")},Yi.prototype._write=function(a,u,d){var p=this._transformState;if(p.writecb=d,p.writechunk=a,p.writeencoding=u,!p.transforming){var v=this._readableState;(p.needTransform||v.needReadable||v.length<v.highWaterMark)&&this._read(v.highWaterMark)}},Yi.prototype._read=function(a){var u=this._transformState;u.writechunk!==null&&u.writecb&&!u.transforming?(u.transforming=!0,this._transform(u.writechunk,u.writeencoding,u.afterTransform)):u.needTransform=!0},Di(sl,Yi),sl.prototype._transform=function(a,u,d){d(null,a)},Di(Xr,lt),Xr.Readable=Bt,Xr.Writable=mi,Xr.Duplex=Ji,Xr.Transform=Yi,Xr.PassThrough=sl,Xr.Stream=Xr,Xr.prototype.pipe=function(a,u){var d=this;function p(R){a.writable&&a.write(R)===!1&&d.pause&&d.pause()}function v(){d.readable&&d.resume&&d.resume()}d.on("data",p),a.on("drain",v),a._isStdio||u&&u.end===!1||(d.on("end",y),d.on("close",I));var g=!1;function y(){g||(g=!0,a.end())}function I(){g||(g=!0,typeof a.destroy=="function"&&a.destroy())}function S(R){if(E(),lt.listenerCount(this,"error")===0)throw R}function E(){d.removeListener("data",p),a.removeListener("drain",v),d.removeListener("end",y),d.removeListener("close",I),d.removeListener("error",S),a.removeListener("error",S),d.removeListener("end",E),d.removeListener("close",E),a.removeListener("close",E)}return d.on("error",S),a.on("error",S),d.on("end",E),d.on("close",E),a.on("close",E),a.emit("pipe",d),a};var Dy={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"};function $P(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}function Qr(a,u,d,p,v){if(u.subarray&&a.subarray)a.set(u.subarray(d,d+p),v);else for(var g=0;g<p;g++)a[v+g]=u[d+g]}var Mu=Uint8Array,qi=Uint16Array,Lu=Int32Array,eO=4,Ny=0,Py=1,tO=2;function Ua(a){for(var u=a.length;--u>=0;)a[u]=0}var iO=0,Oy=1,rO=2,ym=29,al=256,ol=al+1+ym,Va=30,Tm=19,My=2*ol+1,As=15,Sm=16,nO=7,Im=256,Ly=16,xy=17,Uy=18,Rm=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],xu=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],sO=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],Vy=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Zr=new Array(2*(ol+2));Ua(Zr);var ll=new Array(2*Va);Ua(ll);var cl=new Array(512);Ua(cl);var ul=new Array(256);Ua(ul);var Am=new Array(ym);Ua(Am);var Fy,By,Hy,Uu=new Array(Va);function bm(a,u,d,p,v){this.static_tree=a,this.extra_bits=u,this.extra_base=d,this.elems=p,this.max_length=v,this.has_stree=a&&a.length}function Cm(a,u){this.dyn_tree=a,this.max_code=0,this.stat_desc=u}function Wy(a){return a<256?cl[a]:cl[256+(a>>>7)]}function dl(a,u){a.pending_buf[a.pending++]=255&u,a.pending_buf[a.pending++]=u>>>8&255}function Ni(a,u,d){a.bi_valid>Sm-d?(a.bi_buf|=u<<a.bi_valid&65535,dl(a,a.bi_buf),a.bi_buf=u>>Sm-a.bi_valid,a.bi_valid+=d-Sm):(a.bi_buf|=u<<a.bi_valid&65535,a.bi_valid+=d)}function Dr(a,u,d){Ni(a,d[2*u],d[2*u+1])}function Gy(a,u){var d=0;do d|=1&a,a>>>=1,d<<=1;while(--u>0);return d>>>1}function jy(a,u,d){var p,v,g=new Array(As+1),y=0;for(p=1;p<=As;p++)g[p]=y=y+d[p-1]<<1;for(v=0;v<=u;v++){var I=a[2*v+1];I!==0&&(a[2*v]=Gy(g[I]++,I))}}function zy(a){var u;for(u=0;u<ol;u++)a.dyn_ltree[2*u]=0;for(u=0;u<Va;u++)a.dyn_dtree[2*u]=0;for(u=0;u<Tm;u++)a.bl_tree[2*u]=0;a.dyn_ltree[2*Im]=1,a.opt_len=a.static_len=0,a.last_lit=a.matches=0}function Ky(a){a.bi_valid>8?dl(a,a.bi_buf):a.bi_valid>0&&(a.pending_buf[a.pending++]=a.bi_buf),a.bi_buf=0,a.bi_valid=0}function Jy(a,u,d,p){var v=2*u,g=2*d;return a[v]<a[g]||a[v]===a[g]&&p[u]<=p[d]}function km(a,u,d){for(var p=a.heap[d],v=d<<1;v<=a.heap_len&&(v<a.heap_len&&Jy(u,a.heap[v+1],a.heap[v],a.depth)&&v++,!Jy(u,p,a.heap[v],a.depth));)a.heap[d]=a.heap[v],d=v,v<<=1;a.heap[d]=p}function Yy(a,u,d){var p,v,g,y,I=0;if(a.last_lit!==0)do p=a.pending_buf[a.d_buf+2*I]<<8|a.pending_buf[a.d_buf+2*I+1],v=a.pending_buf[a.l_buf+I],I++,p===0?Dr(a,v,u):(Dr(a,(g=ul[v])+al+1,u),(y=Rm[g])!==0&&Ni(a,v-=Am[g],y),Dr(a,g=Wy(--p),d),(y=xu[g])!==0&&Ni(a,p-=Uu[g],y));while(I<a.last_lit);Dr(a,Im,u)}function wm(a,u){var d,p,v,g=u.dyn_tree,y=u.stat_desc.static_tree,I=u.stat_desc.has_stree,S=u.stat_desc.elems,E=-1;for(a.heap_len=0,a.heap_max=My,d=0;d<S;d++)g[2*d]!==0?(a.heap[++a.heap_len]=E=d,a.depth[d]=0):g[2*d+1]=0;for(;a.heap_len<2;)g[2*(v=a.heap[++a.heap_len]=E<2?++E:0)]=1,a.depth[v]=0,a.opt_len--,I&&(a.static_len-=y[2*v+1]);for(u.max_code=E,d=a.heap_len>>1;d>=1;d--)km(a,g,d);v=S;do d=a.heap[1],a.heap[1]=a.heap[a.heap_len--],km(a,g,1),p=a.heap[1],a.heap[--a.heap_max]=d,a.heap[--a.heap_max]=p,g[2*v]=g[2*d]+g[2*p],a.depth[v]=(a.depth[d]>=a.depth[p]?a.depth[d]:a.depth[p])+1,g[2*d+1]=g[2*p+1]=v,a.heap[1]=v++,km(a,g,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],(function(R,k){var N,A,O,M,w,U,L=k.dyn_tree,V=k.max_code,F=k.stat_desc.static_tree,q=k.stat_desc.has_stree,K=k.stat_desc.extra_bits,z=k.stat_desc.extra_base,J=k.stat_desc.max_length,X=0;for(M=0;M<=As;M++)R.bl_count[M]=0;for(L[2*R.heap[R.heap_max]+1]=0,N=R.heap_max+1;N<My;N++)(M=L[2*L[2*(A=R.heap[N])+1]+1]+1)>J&&(M=J,X++),L[2*A+1]=M,A>V||(R.bl_count[M]++,w=0,A>=z&&(w=K[A-z]),U=L[2*A],R.opt_len+=U*(M+w),q&&(R.static_len+=U*(F[2*A+1]+w)));if(X!==0){do{for(M=J-1;R.bl_count[M]===0;)M--;R.bl_count[M]--,R.bl_count[M+1]+=2,R.bl_count[J]--,X-=2}while(X>0);for(M=J;M!==0;M--)for(A=R.bl_count[M];A!==0;)(O=R.heap[--N])>V||(L[2*O+1]!==M&&(R.opt_len+=(M-L[2*O+1])*L[2*O],L[2*O+1]=M),A--)}})(a,u),jy(g,E,a.bl_count)}function qy(a,u,d){var p,v,g=-1,y=u[1],I=0,S=7,E=4;for(y===0&&(S=138,E=3),u[2*(d+1)+1]=65535,p=0;p<=d;p++)v=y,y=u[2*(p+1)+1],++I<S&&v===y||(I<E?a.bl_tree[2*v]+=I:v!==0?(v!==g&&a.bl_tree[2*v]++,a.bl_tree[2*Ly]++):I<=10?a.bl_tree[2*xy]++:a.bl_tree[2*Uy]++,I=0,g=v,y===0?(S=138,E=3):v===y?(S=6,E=3):(S=7,E=4))}function Xy(a,u,d){var p,v,g=-1,y=u[1],I=0,S=7,E=4;for(y===0&&(S=138,E=3),p=0;p<=d;p++)if(v=y,y=u[2*(p+1)+1],!(++I<S&&v===y)){if(I<E)do Dr(a,v,a.bl_tree);while(--I!=0);else v!==0?(v!==g&&(Dr(a,v,a.bl_tree),I--),Dr(a,Ly,a.bl_tree),Ni(a,I-3,2)):I<=10?(Dr(a,xy,a.bl_tree),Ni(a,I-3,3)):(Dr(a,Uy,a.bl_tree),Ni(a,I-11,7));I=0,g=v,y===0?(S=138,E=3):v===y?(S=6,E=3):(S=7,E=4)}}Ua(Uu);var Qy=!1;function aO(a){Qy||((function(){var u,d,p,v,g,y=new Array(As+1);for(p=0,v=0;v<ym-1;v++)for(Am[v]=p,u=0;u<1<<Rm[v];u++)ul[p++]=v;for(ul[p-1]=v,g=0,v=0;v<16;v++)for(Uu[v]=g,u=0;u<1<<xu[v];u++)cl[g++]=v;for(g>>=7;v<Va;v++)for(Uu[v]=g<<7,u=0;u<1<<xu[v]-7;u++)cl[256+g++]=v;for(d=0;d<=As;d++)y[d]=0;for(u=0;u<=143;)Zr[2*u+1]=8,u++,y[8]++;for(;u<=255;)Zr[2*u+1]=9,u++,y[9]++;for(;u<=279;)Zr[2*u+1]=7,u++,y[7]++;for(;u<=287;)Zr[2*u+1]=8,u++,y[8]++;for(jy(Zr,ol+1,y),u=0;u<Va;u++)ll[2*u+1]=5,ll[2*u]=Gy(u,5);Fy=new bm(Zr,Rm,al+1,ol,As),By=new bm(ll,xu,0,Va,As),Hy=new bm(new Array(0),sO,0,Tm,nO)})(),Qy=!0),a.l_desc=new Cm(a.dyn_ltree,Fy),a.d_desc=new Cm(a.dyn_dtree,By),a.bl_desc=new Cm(a.bl_tree,Hy),a.bi_buf=0,a.bi_valid=0,zy(a)}function Zy(a,u,d,p){Ni(a,(iO<<1)+(p?1:0),3),(function(v,g,y,I){Ky(v),dl(v,y),dl(v,~y),Qr(v.pending_buf,v.window,g,y,v.pending),v.pending+=y})(a,u,d)}function oO(a){Ni(a,Oy<<1,3),Dr(a,Im,Zr),(function(u){u.bi_valid===16?(dl(u,u.bi_buf),u.bi_buf=0,u.bi_valid=0):u.bi_valid>=8&&(u.pending_buf[u.pending++]=255&u.bi_buf,u.bi_buf>>=8,u.bi_valid-=8)})(a)}function lO(a,u,d,p){var v,g,y=0;a.level>0?(a.strm.data_type===tO&&(a.strm.data_type=(function(I){var S,E=4093624447;for(S=0;S<=31;S++,E>>>=1)if(1&E&&I.dyn_ltree[2*S]!==0)return Ny;if(I.dyn_ltree[18]!==0||I.dyn_ltree[20]!==0||I.dyn_ltree[26]!==0)return Py;for(S=32;S<al;S++)if(I.dyn_ltree[2*S]!==0)return Py;return Ny})(a)),wm(a,a.l_desc),wm(a,a.d_desc),y=(function(I){var S;for(qy(I,I.dyn_ltree,I.l_desc.max_code),qy(I,I.dyn_dtree,I.d_desc.max_code),wm(I,I.bl_desc),S=Tm-1;S>=3&&I.bl_tree[2*Vy[S]+1]===0;S--);return I.opt_len+=3*(S+1)+5+5+4,S})(a),v=a.opt_len+3+7>>>3,(g=a.static_len+3+7>>>3)<=v&&(v=g)):v=g=d+5,d+4<=v&&u!==-1?Zy(a,u,d,p):a.strategy===eO||g===v?(Ni(a,(Oy<<1)+(p?1:0),3),Yy(a,Zr,ll)):(Ni(a,(rO<<1)+(p?1:0),3),(function(I,S,E,R){var k;for(Ni(I,S-257,5),Ni(I,E-1,5),Ni(I,R-4,4),k=0;k<R;k++)Ni(I,I.bl_tree[2*Vy[k]+1],3);Xy(I,I.dyn_ltree,S-1),Xy(I,I.dyn_dtree,E-1)})(a,a.l_desc.max_code+1,a.d_desc.max_code+1,y+1),Yy(a,a.dyn_ltree,a.dyn_dtree)),zy(a),p&&Ky(a)}function Ln(a,u,d){return a.pending_buf[a.d_buf+2*a.last_lit]=u>>>8&255,a.pending_buf[a.d_buf+2*a.last_lit+1]=255&u,a.pending_buf[a.l_buf+a.last_lit]=255&d,a.last_lit++,u===0?a.dyn_ltree[2*d]++:(a.matches++,u--,a.dyn_ltree[2*(ul[d]+al+1)]++,a.dyn_dtree[2*Wy(u)]++),a.last_lit===a.lit_bufsize-1}function Dm(a,u,d,p){for(var v=65535&a|0,g=a>>>16&65535|0,y=0;d!==0;){d-=y=d>2e3?2e3:d;do g=g+(v=v+u[p++]|0)|0;while(--y);v%=65521,g%=65521}return v|g<<16|0}var cO=(function(){for(var a,u=[],d=0;d<256;d++){a=d;for(var p=0;p<8;p++)a=1&a?3988292384^a>>>1:a>>>1;u[d]=a}return u})();function $t(a,u,d,p){var v=cO,g=p+d;a^=-1;for(var y=p;y<g;y++)a=a>>>8^v[255&(a^u[y])];return-1^a}var Fa,bs=0,uO=1,dO=3,xn=4,$y=5,Cs=0,eT=1,ks=-2,hO=-3,Nm=-5,pO=-1,mO=1,Vu=2,fO=3,_O=4,gO=2,Pm=8,vO=9,Om=286,EO=30,yO=19,TO=2*Om+1,SO=15,mt=3,Un=258,hr=Un+mt+1,IO=32,Mm=42,Lm=69,Fu=73,Bu=91,Hu=103,ws=113,hl=666,ei=1,pl=2,Ds=3,Ba=4,RO=3;function Vn(a,u){return a.msg=Dy[u],u}function tT(a){return(a<<1)-(a>4?9:0)}function Ns(a){for(var u=a.length;--u>=0;)a[u]=0}function Fn(a){var u=a.state,d=u.pending;d>a.avail_out&&(d=a.avail_out),d!==0&&(Qr(a.output,u.pending_buf,u.pending_out,d,a.next_out),a.next_out+=d,u.pending_out+=d,a.total_out+=d,a.avail_out-=d,u.pending-=d,u.pending===0&&(u.pending_out=0))}function li(a,u){lO(a,a.block_start>=0?a.block_start:-1,a.strstart-a.block_start,u),a.block_start=a.strstart,Fn(a.strm)}function ht(a,u){a.pending_buf[a.pending++]=u}function ml(a,u){a.pending_buf[a.pending++]=u>>>8&255,a.pending_buf[a.pending++]=255&u}function iT(a,u){var d,p,v=a.max_chain_length,g=a.strstart,y=a.prev_length,I=a.nice_match,S=a.strstart>a.w_size-hr?a.strstart-(a.w_size-hr):0,E=a.window,R=a.w_mask,k=a.prev,N=a.strstart+Un,A=E[g+y-1],O=E[g+y];a.prev_length>=a.good_match&&(v>>=2),I>a.lookahead&&(I=a.lookahead);do if(E[(d=u)+y]===O&&E[d+y-1]===A&&E[d]===E[g]&&E[++d]===E[g+1]){g+=2,d++;do;while(E[++g]===E[++d]&&E[++g]===E[++d]&&E[++g]===E[++d]&&E[++g]===E[++d]&&E[++g]===E[++d]&&E[++g]===E[++d]&&E[++g]===E[++d]&&E[++g]===E[++d]&&g<N);if(p=Un-(N-g),g=N-Un,p>y){if(a.match_start=u,y=p,p>=I)break;A=E[g+y-1],O=E[g+y]}}while((u=k[u&R])>S&&--v!=0);return y<=a.lookahead?y:a.lookahead}function fl(a){var u,d,p,v,g,y,I,S,E,R,k=a.w_size;do{if(v=a.window_size-a.lookahead-a.strstart,a.strstart>=k+(k-hr)){Qr(a.window,a.window,k,k,0),a.match_start-=k,a.strstart-=k,a.block_start-=k,u=d=a.hash_size;do p=a.head[--u],a.head[u]=p>=k?p-k:0;while(--d);u=d=k;do p=a.prev[--u],a.prev[u]=p>=k?p-k:0;while(--d);v+=k}if(a.strm.avail_in===0)break;if(y=a.strm,I=a.window,S=a.strstart+a.lookahead,E=v,R=void 0,(R=y.avail_in)>E&&(R=E),d=R===0?0:(y.avail_in-=R,Qr(I,y.input,y.next_in,R,S),y.state.wrap===1?y.adler=Dm(y.adler,I,R,S):y.state.wrap===2&&(y.adler=$t(y.adler,I,R,S)),y.next_in+=R,y.total_in+=R,R),a.lookahead+=d,a.lookahead+a.insert>=mt)for(g=a.strstart-a.insert,a.ins_h=a.window[g],a.ins_h=(a.ins_h<<a.hash_shift^a.window[g+1])&a.hash_mask;a.insert&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[g+mt-1])&a.hash_mask,a.prev[g&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=g,g++,a.insert--,!(a.lookahead+a.insert<mt)););}while(a.lookahead<hr&&a.strm.avail_in!==0)}function xm(a,u){for(var d,p;;){if(a.lookahead<hr){if(fl(a),a.lookahead<hr&&u===bs)return ei;if(a.lookahead===0)break}if(d=0,a.lookahead>=mt&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+mt-1])&a.hash_mask,d=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),d!==0&&a.strstart-d<=a.w_size-hr&&(a.match_length=iT(a,d)),a.match_length>=mt)if(p=Ln(a,a.strstart-a.match_start,a.match_length-mt),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=mt){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+mt-1])&a.hash_mask,d=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart;while(--a.match_length!=0);a.strstart++}else a.strstart+=a.match_length,a.match_length=0,a.ins_h=a.window[a.strstart],a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+1])&a.hash_mask;else p=Ln(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++;if(p&&(li(a,!1),a.strm.avail_out===0))return ei}return a.insert=a.strstart<mt-1?a.strstart:mt-1,u===xn?(li(a,!0),a.strm.avail_out===0?Ds:Ba):a.last_lit&&(li(a,!1),a.strm.avail_out===0)?ei:pl}function Ha(a,u){for(var d,p,v;;){if(a.lookahead<hr){if(fl(a),a.lookahead<hr&&u===bs)return ei;if(a.lookahead===0)break}if(d=0,a.lookahead>=mt&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+mt-1])&a.hash_mask,d=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),a.prev_length=a.match_length,a.prev_match=a.match_start,a.match_length=mt-1,d!==0&&a.prev_length<a.max_lazy_match&&a.strstart-d<=a.w_size-hr&&(a.match_length=iT(a,d),a.match_length<=5&&(a.strategy===mO||a.match_length===mt&&a.strstart-a.match_start>4096)&&(a.match_length=mt-1)),a.prev_length>=mt&&a.match_length<=a.prev_length){v=a.strstart+a.lookahead-mt,p=Ln(a,a.strstart-1-a.prev_match,a.prev_length-mt),a.lookahead-=a.prev_length-1,a.prev_length-=2;do++a.strstart<=v&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+mt-1])&a.hash_mask,d=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart);while(--a.prev_length!=0);if(a.match_available=0,a.match_length=mt-1,a.strstart++,p&&(li(a,!1),a.strm.avail_out===0))return ei}else if(a.match_available){if((p=Ln(a,0,a.window[a.strstart-1]))&&li(a,!1),a.strstart++,a.lookahead--,a.strm.avail_out===0)return ei}else a.match_available=1,a.strstart++,a.lookahead--}return a.match_available&&(p=Ln(a,0,a.window[a.strstart-1]),a.match_available=0),a.insert=a.strstart<mt-1?a.strstart:mt-1,u===xn?(li(a,!0),a.strm.avail_out===0?Ds:Ba):a.last_lit&&(li(a,!1),a.strm.avail_out===0)?ei:pl}function Nr(a,u,d,p,v){this.good_length=a,this.max_lazy=u,this.nice_length=d,this.max_chain=p,this.func=v}function AO(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Pm,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new qi(2*TO),this.dyn_dtree=new qi(2*(2*EO+1)),this.bl_tree=new qi(2*(2*yO+1)),Ns(this.dyn_ltree),Ns(this.dyn_dtree),Ns(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new qi(SO+1),this.heap=new qi(2*Om+1),Ns(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new qi(2*Om+1),Ns(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function rT(a){var u,d=(function(p){var v;return p&&p.state?(p.total_in=p.total_out=0,p.data_type=gO,(v=p.state).pending=0,v.pending_out=0,v.wrap<0&&(v.wrap=-v.wrap),v.status=v.wrap?Mm:ws,p.adler=v.wrap===2?0:1,v.last_flush=bs,aO(v),Cs):Vn(p,ks)})(a);return d===Cs&&((u=a.state).window_size=2*u.w_size,Ns(u.head),u.max_lazy_match=Fa[u.level].max_lazy,u.good_match=Fa[u.level].good_length,u.nice_match=Fa[u.level].nice_length,u.max_chain_length=Fa[u.level].max_chain,u.strstart=0,u.block_start=0,u.lookahead=0,u.insert=0,u.match_length=u.prev_length=mt-1,u.match_available=0,u.ins_h=0),d}function bO(a,u){var d,p,v,g;if(!a||!a.state||u>$y||u<0)return a?Vn(a,ks):ks;if(p=a.state,!a.output||!a.input&&a.avail_in!==0||p.status===hl&&u!==xn)return Vn(a,a.avail_out===0?Nm:ks);if(p.strm=a,d=p.last_flush,p.last_flush=u,p.status===Mm)if(p.wrap===2)a.adler=0,ht(p,31),ht(p,139),ht(p,8),p.gzhead?(ht(p,(p.gzhead.text?1:0)+(p.gzhead.hcrc?2:0)+(p.gzhead.extra?4:0)+(p.gzhead.name?8:0)+(p.gzhead.comment?16:0)),ht(p,255&p.gzhead.time),ht(p,p.gzhead.time>>8&255),ht(p,p.gzhead.time>>16&255),ht(p,p.gzhead.time>>24&255),ht(p,p.level===9?2:p.strategy>=Vu||p.level<2?4:0),ht(p,255&p.gzhead.os),p.gzhead.extra&&p.gzhead.extra.length&&(ht(p,255&p.gzhead.extra.length),ht(p,p.gzhead.extra.length>>8&255)),p.gzhead.hcrc&&(a.adler=$t(a.adler,p.pending_buf,p.pending,0)),p.gzindex=0,p.status=Lm):(ht(p,0),ht(p,0),ht(p,0),ht(p,0),ht(p,0),ht(p,p.level===9?2:p.strategy>=Vu||p.level<2?4:0),ht(p,RO),p.status=ws);else{var y=Pm+(p.w_bits-8<<4)<<8;y|=(p.strategy>=Vu||p.level<2?0:p.level<6?1:p.level===6?2:3)<<6,p.strstart!==0&&(y|=IO),y+=31-y%31,p.status=ws,ml(p,y),p.strstart!==0&&(ml(p,a.adler>>>16),ml(p,65535&a.adler)),a.adler=1}if(p.status===Lm)if(p.gzhead.extra){for(v=p.pending;p.gzindex<(65535&p.gzhead.extra.length)&&(p.pending!==p.pending_buf_size||(p.gzhead.hcrc&&p.pending>v&&(a.adler=$t(a.adler,p.pending_buf,p.pending-v,v)),Fn(a),v=p.pending,p.pending!==p.pending_buf_size));)ht(p,255&p.gzhead.extra[p.gzindex]),p.gzindex++;p.gzhead.hcrc&&p.pending>v&&(a.adler=$t(a.adler,p.pending_buf,p.pending-v,v)),p.gzindex===p.gzhead.extra.length&&(p.gzindex=0,p.status=Fu)}else p.status=Fu;if(p.status===Fu)if(p.gzhead.name){v=p.pending;do{if(p.pending===p.pending_buf_size&&(p.gzhead.hcrc&&p.pending>v&&(a.adler=$t(a.adler,p.pending_buf,p.pending-v,v)),Fn(a),v=p.pending,p.pending===p.pending_buf_size)){g=1;break}g=p.gzindex<p.gzhead.name.length?255&p.gzhead.name.charCodeAt(p.gzindex++):0,ht(p,g)}while(g!==0);p.gzhead.hcrc&&p.pending>v&&(a.adler=$t(a.adler,p.pending_buf,p.pending-v,v)),g===0&&(p.gzindex=0,p.status=Bu)}else p.status=Bu;if(p.status===Bu)if(p.gzhead.comment){v=p.pending;do{if(p.pending===p.pending_buf_size&&(p.gzhead.hcrc&&p.pending>v&&(a.adler=$t(a.adler,p.pending_buf,p.pending-v,v)),Fn(a),v=p.pending,p.pending===p.pending_buf_size)){g=1;break}g=p.gzindex<p.gzhead.comment.length?255&p.gzhead.comment.charCodeAt(p.gzindex++):0,ht(p,g)}while(g!==0);p.gzhead.hcrc&&p.pending>v&&(a.adler=$t(a.adler,p.pending_buf,p.pending-v,v)),g===0&&(p.status=Hu)}else p.status=Hu;if(p.status===Hu&&(p.gzhead.hcrc?(p.pending+2>p.pending_buf_size&&Fn(a),p.pending+2<=p.pending_buf_size&&(ht(p,255&a.adler),ht(p,a.adler>>8&255),a.adler=0,p.status=ws)):p.status=ws),p.pending!==0){if(Fn(a),a.avail_out===0)return p.last_flush=-1,Cs}else if(a.avail_in===0&&tT(u)<=tT(d)&&u!==xn)return Vn(a,Nm);if(p.status===hl&&a.avail_in!==0)return Vn(a,Nm);if(a.avail_in!==0||p.lookahead!==0||u!==bs&&p.status!==hl){var I=p.strategy===Vu?(function(S,E){for(var R;;){if(S.lookahead===0&&(fl(S),S.lookahead===0)){if(E===bs)return ei;break}if(S.match_length=0,R=Ln(S,0,S.window[S.strstart]),S.lookahead--,S.strstart++,R&&(li(S,!1),S.strm.avail_out===0))return ei}return S.insert=0,E===xn?(li(S,!0),S.strm.avail_out===0?Ds:Ba):S.last_lit&&(li(S,!1),S.strm.avail_out===0)?ei:pl})(p,u):p.strategy===fO?(function(S,E){for(var R,k,N,A,O=S.window;;){if(S.lookahead<=Un){if(fl(S),S.lookahead<=Un&&E===bs)return ei;if(S.lookahead===0)break}if(S.match_length=0,S.lookahead>=mt&&S.strstart>0&&(k=O[N=S.strstart-1])===O[++N]&&k===O[++N]&&k===O[++N]){A=S.strstart+Un;do;while(k===O[++N]&&k===O[++N]&&k===O[++N]&&k===O[++N]&&k===O[++N]&&k===O[++N]&&k===O[++N]&&k===O[++N]&&N<A);S.match_length=Un-(A-N),S.match_length>S.lookahead&&(S.match_length=S.lookahead)}if(S.match_length>=mt?(R=Ln(S,1,S.match_length-mt),S.lookahead-=S.match_length,S.strstart+=S.match_length,S.match_length=0):(R=Ln(S,0,S.window[S.strstart]),S.lookahead--,S.strstart++),R&&(li(S,!1),S.strm.avail_out===0))return ei}return S.insert=0,E===xn?(li(S,!0),S.strm.avail_out===0?Ds:Ba):S.last_lit&&(li(S,!1),S.strm.avail_out===0)?ei:pl})(p,u):Fa[p.level].func(p,u);if(I!==Ds&&I!==Ba||(p.status=hl),I===ei||I===Ds)return a.avail_out===0&&(p.last_flush=-1),Cs;if(I===pl&&(u===uO?oO(p):u!==$y&&(Zy(p,0,0,!1),u===dO&&(Ns(p.head),p.lookahead===0&&(p.strstart=0,p.block_start=0,p.insert=0))),Fn(a),a.avail_out===0))return p.last_flush=-1,Cs}return u!==xn?Cs:p.wrap<=0?eT:(p.wrap===2?(ht(p,255&a.adler),ht(p,a.adler>>8&255),ht(p,a.adler>>16&255),ht(p,a.adler>>24&255),ht(p,255&a.total_in),ht(p,a.total_in>>8&255),ht(p,a.total_in>>16&255),ht(p,a.total_in>>24&255)):(ml(p,a.adler>>>16),ml(p,65535&a.adler)),Fn(a),p.wrap>0&&(p.wrap=-p.wrap),p.pending!==0?Cs:eT)}Fa=[new Nr(0,0,0,0,function(a,u){var d=65535;for(d>a.pending_buf_size-5&&(d=a.pending_buf_size-5);;){if(a.lookahead<=1){if(fl(a),a.lookahead===0&&u===bs)return ei;if(a.lookahead===0)break}a.strstart+=a.lookahead,a.lookahead=0;var p=a.block_start+d;if((a.strstart===0||a.strstart>=p)&&(a.lookahead=a.strstart-p,a.strstart=p,li(a,!1),a.strm.avail_out===0)||a.strstart-a.block_start>=a.w_size-hr&&(li(a,!1),a.strm.avail_out===0))return ei}return a.insert=0,u===xn?(li(a,!0),a.strm.avail_out===0?Ds:Ba):(a.strstart>a.block_start&&(li(a,!1),a.strm.avail_out),ei)}),new Nr(4,4,8,4,xm),new Nr(4,5,16,8,xm),new Nr(4,6,32,32,xm),new Nr(4,4,16,16,Ha),new Nr(8,16,32,32,Ha),new Nr(8,16,128,128,Ha),new Nr(8,32,128,256,Ha),new Nr(32,128,258,1024,Ha),new Nr(32,258,258,4096,Ha)];var Wu=30,CO=12;function kO(a,u){var d,p,v,g,y,I,S,E,R,k,N,A,O,M,w,U,L,V,F,q,K,z,J,X,W;d=a.state,p=a.next_in,X=a.input,v=p+(a.avail_in-5),g=a.next_out,W=a.output,y=g-(u-a.avail_out),I=g+(a.avail_out-257),S=d.dmax,E=d.wsize,R=d.whave,k=d.wnext,N=d.window,A=d.hold,O=d.bits,M=d.lencode,w=d.distcode,U=(1<<d.lenbits)-1,L=(1<<d.distbits)-1;e:do{O<15&&(A+=X[p++]<<O,O+=8,A+=X[p++]<<O,O+=8),V=M[A&U];t:for(;;){if(A>>>=F=V>>>24,O-=F,(F=V>>>16&255)===0)W[g++]=65535&V;else{if(!(16&F)){if((64&F)==0){V=M[(65535&V)+(A&(1<<F)-1)];continue t}if(32&F){d.mode=CO;break e}a.msg="invalid literal/length code",d.mode=Wu;break e}q=65535&V,(F&=15)&&(O<F&&(A+=X[p++]<<O,O+=8),q+=A&(1<<F)-1,A>>>=F,O-=F),O<15&&(A+=X[p++]<<O,O+=8,A+=X[p++]<<O,O+=8),V=w[A&L];i:for(;;){if(A>>>=F=V>>>24,O-=F,!(16&(F=V>>>16&255))){if((64&F)==0){V=w[(65535&V)+(A&(1<<F)-1)];continue i}a.msg="invalid distance code",d.mode=Wu;break e}if(K=65535&V,O<(F&=15)&&(A+=X[p++]<<O,(O+=8)<F&&(A+=X[p++]<<O,O+=8)),(K+=A&(1<<F)-1)>S){a.msg="invalid distance too far back",d.mode=Wu;break e}if(A>>>=F,O-=F,K>(F=g-y)){if((F=K-F)>R&&d.sane){a.msg="invalid distance too far back",d.mode=Wu;break e}if(z=0,J=N,k===0){if(z+=E-F,F<q){q-=F;do W[g++]=N[z++];while(--F);z=g-K,J=W}}else if(k<F){if(z+=E+k-F,(F-=k)<q){q-=F;do W[g++]=N[z++];while(--F);if(z=0,k<q){q-=F=k;do W[g++]=N[z++];while(--F);z=g-K,J=W}}}else if(z+=k-F,F<q){q-=F;do W[g++]=N[z++];while(--F);z=g-K,J=W}for(;q>2;)W[g++]=J[z++],W[g++]=J[z++],W[g++]=J[z++],q-=3;q&&(W[g++]=J[z++],q>1&&(W[g++]=J[z++]))}else{z=g-K;do W[g++]=W[z++],W[g++]=W[z++],W[g++]=W[z++],q-=3;while(q>2);q&&(W[g++]=W[z++],q>1&&(W[g++]=W[z++]))}break}}break}}while(p<v&&g<I);p-=q=O>>3,A&=(1<<(O-=q<<3))-1,a.next_in=p,a.next_out=g,a.avail_in=p<v?v-p+5:5-(p-v),a.avail_out=g<I?I-g+257:257-(g-I),d.hold=A,d.bits=O}var Wa=15,nT=852,sT=592,aT=0,Um=1,oT=2,wO=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],DO=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],NO=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],PO=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];function _l(a,u,d,p,v,g,y,I){var S,E,R,k,N,A,O,M,w,U=I.bits,L=0,V=0,F=0,q=0,K=0,z=0,J=0,X=0,W=0,Q=0,ge=null,ne=0,Te=new qi(Wa+1),ke=new qi(Wa+1),Ve=null,We=0;for(L=0;L<=Wa;L++)Te[L]=0;for(V=0;V<p;V++)Te[u[d+V]]++;for(K=U,q=Wa;q>=1&&Te[q]===0;q--);if(K>q&&(K=q),q===0)return v[g++]=20971520,v[g++]=20971520,I.bits=1,0;for(F=1;F<q&&Te[F]===0;F++);for(K<F&&(K=F),X=1,L=1;L<=Wa;L++)if(X<<=1,(X-=Te[L])<0)return-1;if(X>0&&(a===aT||q!==1))return-1;for(ke[1]=0,L=1;L<Wa;L++)ke[L+1]=ke[L]+Te[L];for(V=0;V<p;V++)u[d+V]!==0&&(y[ke[u[d+V]]++]=V);if(a===aT?(ge=Ve=y,A=19):a===Um?(ge=wO,ne-=257,Ve=DO,We-=257,A=256):(ge=NO,Ve=PO,A=-1),Q=0,V=0,L=F,N=g,z=K,J=0,R=-1,k=(W=1<<K)-1,a===Um&&W>nT||a===oT&&W>sT)return 1;for(;;){O=L-J,y[V]<A?(M=0,w=y[V]):y[V]>A?(M=Ve[We+y[V]],w=ge[ne+y[V]]):(M=96,w=0),S=1<<L-J,F=E=1<<z;do v[N+(Q>>J)+(E-=S)]=O<<24|M<<16|w|0;while(E!==0);for(S=1<<L-1;Q&S;)S>>=1;if(S!==0?(Q&=S-1,Q+=S):Q=0,V++,--Te[L]==0){if(L===q)break;L=u[d+y[V]]}if(L>K&&(Q&k)!==R){for(J===0&&(J=K),N+=F,X=1<<(z=L-J);z+J<q&&!((X-=Te[z+J])<=0);)z++,X<<=1;if(W+=1<<z,a===Um&&W>nT||a===oT&&W>sT)return 1;v[R=Q&k]=K<<24|z<<16|N-g|0}}return Q!==0&&(v[N+Q]=L-J<<24|64<<16|0),I.bits=K,0}var OO=0,lT=1,cT=2,uT=4,MO=5,Gu=6,ju=0,LO=1,xO=2,Bn=-2,UO=-3,VO=-4,FO=-5,dT=8,hT=1,pT=2,mT=3,fT=4,_T=5,gT=6,vT=7,ET=8,yT=9,TT=10,ST=11,$r=12,Vm=13,IT=14,Fm=15,RT=16,AT=17,bT=18,CT=19,zu=20,Ku=21,kT=22,wT=23,DT=24,NT=25,PT=26,Bm=27,OT=28,MT=29,Dt=30,BO=31,HO=32,WO=852,GO=592;function LT(a){return(a>>>24&255)+(a>>>8&65280)+((65280&a)<<8)+((255&a)<<24)}function jO(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new qi(320),this.work=new qi(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function xT(a){var u;return a&&a.state?((u=a.state).wsize=0,u.whave=0,u.wnext=0,(function(d){var p;return d&&d.state?(p=d.state,d.total_in=d.total_out=p.total=0,d.msg="",p.wrap&&(d.adler=1&p.wrap),p.mode=hT,p.last=0,p.havedict=0,p.dmax=32768,p.head=null,p.hold=0,p.bits=0,p.lencode=p.lendyn=new Lu(WO),p.distcode=p.distdyn=new Lu(GO),p.sane=1,p.back=-1,ju):Bn})(a)):Bn}function zO(a,u){var d,p;return a?(p=new jO,a.state=p,p.window=null,(d=(function(v,g){var y,I;return v&&v.state?(I=v.state,g<0?(y=0,g=-g):(y=1+(g>>4),g<48&&(g&=15)),g&&(g<8||g>15)?Bn:(I.window!==null&&I.wbits!==g&&(I.window=null),I.wrap=y,I.wbits=g,xT(v))):Bn})(a,u))!==ju&&(a.state=null),d):Bn}var Hm,Wm,UT=!0;function KO(a){if(UT){var u;for(Hm=new Lu(512),Wm=new Lu(32),u=0;u<144;)a.lens[u++]=8;for(;u<256;)a.lens[u++]=9;for(;u<280;)a.lens[u++]=7;for(;u<288;)a.lens[u++]=8;for(_l(lT,a.lens,0,288,Hm,0,a.work,{bits:9}),u=0;u<32;)a.lens[u++]=5;_l(cT,a.lens,0,32,Wm,0,a.work,{bits:5}),UT=!1}a.lencode=Hm,a.lenbits=9,a.distcode=Wm,a.distbits=5}function JO(a,u){var d,p,v,g,y,I,S,E,R,k,N,A,O,M,w,U,L,V,F,q,K,z,J,X,W=0,Q=new Mu(4),ge=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!a||!a.state||!a.output||!a.input&&a.avail_in!==0)return Bn;(d=a.state).mode===$r&&(d.mode=Vm),y=a.next_out,v=a.output,S=a.avail_out,g=a.next_in,p=a.input,I=a.avail_in,E=d.hold,R=d.bits,k=I,N=S,z=ju;e:for(;;)switch(d.mode){case hT:if(d.wrap===0){d.mode=Vm;break}for(;R<16;){if(I===0)break e;I--,E+=p[g++]<<R,R+=8}if(2&d.wrap&&E===35615){d.check=0,Q[0]=255&E,Q[1]=E>>>8&255,d.check=$t(d.check,Q,2,0),E=0,R=0,d.mode=pT;break}if(d.flags=0,d.head&&(d.head.done=!1),!(1&d.wrap)||(((255&E)<<8)+(E>>8))%31){a.msg="incorrect header check",d.mode=Dt;break}if((15&E)!==dT){a.msg="unknown compression method",d.mode=Dt;break}if(R-=4,K=8+(15&(E>>>=4)),d.wbits===0)d.wbits=K;else if(K>d.wbits){a.msg="invalid window size",d.mode=Dt;break}d.dmax=1<<K,a.adler=d.check=1,d.mode=512&E?TT:$r,E=0,R=0;break;case pT:for(;R<16;){if(I===0)break e;I--,E+=p[g++]<<R,R+=8}if(d.flags=E,(255&d.flags)!==dT){a.msg="unknown compression method",d.mode=Dt;break}if(57344&d.flags){a.msg="unknown header flags set",d.mode=Dt;break}d.head&&(d.head.text=E>>8&1),512&d.flags&&(Q[0]=255&E,Q[1]=E>>>8&255,d.check=$t(d.check,Q,2,0)),E=0,R=0,d.mode=mT;case mT:for(;R<32;){if(I===0)break e;I--,E+=p[g++]<<R,R+=8}d.head&&(d.head.time=E),512&d.flags&&(Q[0]=255&E,Q[1]=E>>>8&255,Q[2]=E>>>16&255,Q[3]=E>>>24&255,d.check=$t(d.check,Q,4,0)),E=0,R=0,d.mode=fT;case fT:for(;R<16;){if(I===0)break e;I--,E+=p[g++]<<R,R+=8}d.head&&(d.head.xflags=255&E,d.head.os=E>>8),512&d.flags&&(Q[0]=255&E,Q[1]=E>>>8&255,d.check=$t(d.check,Q,2,0)),E=0,R=0,d.mode=_T;case _T:if(1024&d.flags){for(;R<16;){if(I===0)break e;I--,E+=p[g++]<<R,R+=8}d.length=E,d.head&&(d.head.extra_len=E),512&d.flags&&(Q[0]=255&E,Q[1]=E>>>8&255,d.check=$t(d.check,Q,2,0)),E=0,R=0}else d.head&&(d.head.extra=null);d.mode=gT;case gT:if(1024&d.flags&&((A=d.length)>I&&(A=I),A&&(d.head&&(K=d.head.extra_len-d.length,d.head.extra||(d.head.extra=new Array(d.head.extra_len)),Qr(d.head.extra,p,g,A,K)),512&d.flags&&(d.check=$t(d.check,p,A,g)),I-=A,g+=A,d.length-=A),d.length))break e;d.length=0,d.mode=vT;case vT:if(2048&d.flags){if(I===0)break e;A=0;do K=p[g+A++],d.head&&K&&d.length<65536&&(d.head.name+=String.fromCharCode(K));while(K&&A<I);if(512&d.flags&&(d.check=$t(d.check,p,A,g)),I-=A,g+=A,K)break e}else d.head&&(d.head.name=null);d.length=0,d.mode=ET;case ET:if(4096&d.flags){if(I===0)break e;A=0;do K=p[g+A++],d.head&&K&&d.length<65536&&(d.head.comment+=String.fromCharCode(K));while(K&&A<I);if(512&d.flags&&(d.check=$t(d.check,p,A,g)),I-=A,g+=A,K)break e}else d.head&&(d.head.comment=null);d.mode=yT;case yT:if(512&d.flags){for(;R<16;){if(I===0)break e;I--,E+=p[g++]<<R,R+=8}if(E!==(65535&d.check)){a.msg="header crc mismatch",d.mode=Dt;break}E=0,R=0}d.head&&(d.head.hcrc=d.flags>>9&1,d.head.done=!0),a.adler=d.check=0,d.mode=$r;break;case TT:for(;R<32;){if(I===0)break e;I--,E+=p[g++]<<R,R+=8}a.adler=d.check=LT(E),E=0,R=0,d.mode=ST;case ST:if(d.havedict===0)return a.next_out=y,a.avail_out=S,a.next_in=g,a.avail_in=I,d.hold=E,d.bits=R,xO;a.adler=d.check=1,d.mode=$r;case $r:if(u===MO||u===Gu)break e;case Vm:if(d.last){E>>>=7&R,R-=7&R,d.mode=Bm;break}for(;R<3;){if(I===0)break e;I--,E+=p[g++]<<R,R+=8}switch(d.last=1&E,R-=1,3&(E>>>=1)){case 0:d.mode=IT;break;case 1:if(KO(d),d.mode=zu,u===Gu){E>>>=2,R-=2;break e}break;case 2:d.mode=AT;break;case 3:a.msg="invalid block type",d.mode=Dt}E>>>=2,R-=2;break;case IT:for(E>>>=7&R,R-=7&R;R<32;){if(I===0)break e;I--,E+=p[g++]<<R,R+=8}if((65535&E)!=(E>>>16^65535)){a.msg="invalid stored block lengths",d.mode=Dt;break}if(d.length=65535&E,E=0,R=0,d.mode=Fm,u===Gu)break e;case Fm:d.mode=RT;case RT:if(A=d.length){if(A>I&&(A=I),A>S&&(A=S),A===0)break e;Qr(v,p,g,A,y),I-=A,g+=A,S-=A,y+=A,d.length-=A;break}d.mode=$r;break;case AT:for(;R<14;){if(I===0)break e;I--,E+=p[g++]<<R,R+=8}if(d.nlen=257+(31&E),E>>>=5,R-=5,d.ndist=1+(31&E),E>>>=5,R-=5,d.ncode=4+(15&E),E>>>=4,R-=4,d.nlen>286||d.ndist>30){a.msg="too many length or distance symbols",d.mode=Dt;break}d.have=0,d.mode=bT;case bT:for(;d.have<d.ncode;){for(;R<3;){if(I===0)break e;I--,E+=p[g++]<<R,R+=8}d.lens[ge[d.have++]]=7&E,E>>>=3,R-=3}for(;d.have<19;)d.lens[ge[d.have++]]=0;if(d.lencode=d.lendyn,d.lenbits=7,J={bits:d.lenbits},z=_l(OO,d.lens,0,19,d.lencode,0,d.work,J),d.lenbits=J.bits,z){a.msg="invalid code lengths set",d.mode=Dt;break}d.have=0,d.mode=CT;case CT:for(;d.have<d.nlen+d.ndist;){for(;U=(W=d.lencode[E&(1<<d.lenbits)-1])>>>16&255,L=65535&W,!((w=W>>>24)<=R);){if(I===0)break e;I--,E+=p[g++]<<R,R+=8}if(L<16)E>>>=w,R-=w,d.lens[d.have++]=L;else{if(L===16){for(X=w+2;R<X;){if(I===0)break e;I--,E+=p[g++]<<R,R+=8}if(E>>>=w,R-=w,d.have===0){a.msg="invalid bit length repeat",d.mode=Dt;break}K=d.lens[d.have-1],A=3+(3&E),E>>>=2,R-=2}else if(L===17){for(X=w+3;R<X;){if(I===0)break e;I--,E+=p[g++]<<R,R+=8}R-=w,K=0,A=3+(7&(E>>>=w)),E>>>=3,R-=3}else{for(X=w+7;R<X;){if(I===0)break e;I--,E+=p[g++]<<R,R+=8}R-=w,K=0,A=11+(127&(E>>>=w)),E>>>=7,R-=7}if(d.have+A>d.nlen+d.ndist){a.msg="invalid bit length repeat",d.mode=Dt;break}for(;A--;)d.lens[d.have++]=K}}if(d.mode===Dt)break;if(d.lens[256]===0){a.msg="invalid code -- missing end-of-block",d.mode=Dt;break}if(d.lenbits=9,J={bits:d.lenbits},z=_l(lT,d.lens,0,d.nlen,d.lencode,0,d.work,J),d.lenbits=J.bits,z){a.msg="invalid literal/lengths set",d.mode=Dt;break}if(d.distbits=6,d.distcode=d.distdyn,J={bits:d.distbits},z=_l(cT,d.lens,d.nlen,d.ndist,d.distcode,0,d.work,J),d.distbits=J.bits,z){a.msg="invalid distances set",d.mode=Dt;break}if(d.mode=zu,u===Gu)break e;case zu:d.mode=Ku;case Ku:if(I>=6&&S>=258){a.next_out=y,a.avail_out=S,a.next_in=g,a.avail_in=I,d.hold=E,d.bits=R,kO(a,N),y=a.next_out,v=a.output,S=a.avail_out,g=a.next_in,p=a.input,I=a.avail_in,E=d.hold,R=d.bits,d.mode===$r&&(d.back=-1);break}for(d.back=0;U=(W=d.lencode[E&(1<<d.lenbits)-1])>>>16&255,L=65535&W,!((w=W>>>24)<=R);){if(I===0)break e;I--,E+=p[g++]<<R,R+=8}if(U&&(240&U)==0){for(V=w,F=U,q=L;U=(W=d.lencode[q+((E&(1<<V+F)-1)>>V)])>>>16&255,L=65535&W,!(V+(w=W>>>24)<=R);){if(I===0)break e;I--,E+=p[g++]<<R,R+=8}E>>>=V,R-=V,d.back+=V}if(E>>>=w,R-=w,d.back+=w,d.length=L,U===0){d.mode=PT;break}if(32&U){d.back=-1,d.mode=$r;break}if(64&U){a.msg="invalid literal/length code",d.mode=Dt;break}d.extra=15&U,d.mode=kT;case kT:if(d.extra){for(X=d.extra;R<X;){if(I===0)break e;I--,E+=p[g++]<<R,R+=8}d.length+=E&(1<<d.extra)-1,E>>>=d.extra,R-=d.extra,d.back+=d.extra}d.was=d.length,d.mode=wT;case wT:for(;U=(W=d.distcode[E&(1<<d.distbits)-1])>>>16&255,L=65535&W,!((w=W>>>24)<=R);){if(I===0)break e;I--,E+=p[g++]<<R,R+=8}if((240&U)==0){for(V=w,F=U,q=L;U=(W=d.distcode[q+((E&(1<<V+F)-1)>>V)])>>>16&255,L=65535&W,!(V+(w=W>>>24)<=R);){if(I===0)break e;I--,E+=p[g++]<<R,R+=8}E>>>=V,R-=V,d.back+=V}if(E>>>=w,R-=w,d.back+=w,64&U){a.msg="invalid distance code",d.mode=Dt;break}d.offset=L,d.extra=15&U,d.mode=DT;case DT:if(d.extra){for(X=d.extra;R<X;){if(I===0)break e;I--,E+=p[g++]<<R,R+=8}d.offset+=E&(1<<d.extra)-1,E>>>=d.extra,R-=d.extra,d.back+=d.extra}if(d.offset>d.dmax){a.msg="invalid distance too far back",d.mode=Dt;break}d.mode=NT;case NT:if(S===0)break e;if(A=N-S,d.offset>A){if((A=d.offset-A)>d.whave&&d.sane){a.msg="invalid distance too far back",d.mode=Dt;break}A>d.wnext?(A-=d.wnext,O=d.wsize-A):O=d.wnext-A,A>d.length&&(A=d.length),M=d.window}else M=v,O=y-d.offset,A=d.length;A>S&&(A=S),S-=A,d.length-=A;do v[y++]=M[O++];while(--A);d.length===0&&(d.mode=Ku);break;case PT:if(S===0)break e;v[y++]=d.length,S--,d.mode=Ku;break;case Bm:if(d.wrap){for(;R<32;){if(I===0)break e;I--,E|=p[g++]<<R,R+=8}if(N-=S,a.total_out+=N,d.total+=N,N&&(a.adler=d.check=d.flags?$t(d.check,v,N,y-N):Dm(d.check,v,N,y-N)),N=S,(d.flags?E:LT(E))!==d.check){a.msg="incorrect data check",d.mode=Dt;break}E=0,R=0}d.mode=OT;case OT:if(d.wrap&&d.flags){for(;R<32;){if(I===0)break e;I--,E+=p[g++]<<R,R+=8}if(E!==(4294967295&d.total)){a.msg="incorrect length check",d.mode=Dt;break}E=0,R=0}d.mode=MT;case MT:z=LO;break e;case Dt:z=UO;break e;case BO:return VO;case HO:default:return Bn}return a.next_out=y,a.avail_out=S,a.next_in=g,a.avail_in=I,d.hold=E,d.bits=R,(d.wsize||N!==a.avail_out&&d.mode<Dt&&(d.mode<Bm||u!==uT))&&(function(ne,Te,ke,Ve){var We,we=ne.state;we.window===null&&(we.wsize=1<<we.wbits,we.wnext=0,we.whave=0,we.window=new Mu(we.wsize)),Ve>=we.wsize?(Qr(we.window,Te,ke-we.wsize,we.wsize,0),we.wnext=0,we.whave=we.wsize):((We=we.wsize-we.wnext)>Ve&&(We=Ve),Qr(we.window,Te,ke-Ve,We,we.wnext),(Ve-=We)?(Qr(we.window,Te,ke-Ve,Ve,0),we.wnext=Ve,we.whave=we.wsize):(we.wnext+=We,we.wnext===we.wsize&&(we.wnext=0),we.whave<we.wsize&&(we.whave+=We)))})(a,a.output,a.next_out,N-a.avail_out),k-=a.avail_in,N-=a.avail_out,a.total_in+=k,a.total_out+=N,d.total+=N,d.wrap&&N&&(a.adler=d.check=d.flags?$t(d.check,v,N,a.next_out-N):Dm(d.check,v,N,a.next_out-N)),a.data_type=d.bits+(d.last?64:0)+(d.mode===$r?128:0)+(d.mode===zu||d.mode===Fm?256:0),(k===0&&N===0||u===uT)&&z===ju&&(z=FO),z}var Ju,Ga=1,gl=7;function Pr(a){if(a<Ga||a>gl)throw new TypeError("Bad argument");this.mode=a,this.init_done=!1,this.write_in_progress=!1,this.pending_close=!1,this.windowBits=0,this.level=0,this.memLevel=0,this.strategy=0,this.dictionary=null}function YO(a,u){for(var d=0;d<a.length;d++)this[u+d]=a[d]}Pr.prototype.init=function(a,u,d,p,v){var g;switch(this.windowBits=a,this.level=u,this.memLevel=d,this.strategy=p,this.mode!==3&&this.mode!==4||(this.windowBits+=16),this.mode===gl&&(this.windowBits+=32),this.mode!==5&&this.mode!==6||(this.windowBits=-this.windowBits),this.strm=new $P,this.mode){case Ga:case 3:case 5:g=(function(y,I,S,E,R,k){if(!y)return ks;var N=1;if(I===pO&&(I=6),E<0?(N=0,E=-E):E>15&&(N=2,E-=16),R<1||R>vO||S!==Pm||E<8||E>15||I<0||I>9||k<0||k>_O)return Vn(y,ks);E===8&&(E=9);var A=new AO;return y.state=A,A.strm=y,A.wrap=N,A.gzhead=null,A.w_bits=E,A.w_size=1<<A.w_bits,A.w_mask=A.w_size-1,A.hash_bits=R+7,A.hash_size=1<<A.hash_bits,A.hash_mask=A.hash_size-1,A.hash_shift=~~((A.hash_bits+mt-1)/mt),A.window=new Mu(2*A.w_size),A.head=new qi(A.hash_size),A.prev=new qi(A.w_size),A.lit_bufsize=1<<R+6,A.pending_buf_size=4*A.lit_bufsize,A.pending_buf=new Mu(A.pending_buf_size),A.d_buf=1*A.lit_bufsize,A.l_buf=3*A.lit_bufsize,A.level=I,A.strategy=k,A.method=S,rT(y)})(this.strm,this.level,8,this.windowBits,this.memLevel,this.strategy);break;case 2:case 4:case 6:case gl:g=zO(this.strm,this.windowBits);break;default:throw new Error("Unknown mode "+this.mode)}g===0?(this.write_in_progress=!1,this.init_done=!0):this._error(g)},Pr.prototype.params=function(){throw new Error("deflateParams Not supported")},Pr.prototype._writeCheck=function(){if(!this.init_done)throw new Error("write before init");if(this.mode===0)throw new Error("already finalized");if(this.write_in_progress)throw new Error("write already in progress");if(this.pending_close)throw new Error("close is pending")},Pr.prototype.write=function(a,u,d,p,v,g,y){this._writeCheck(),this.write_in_progress=!0;var I=this;return oi(function(){I.write_in_progress=!1;var S=I._write(a,u,d,p,v,g,y);I.callback(S[0],S[1]),I.pending_close&&I.close()}),this},Pr.prototype.writeSync=function(a,u,d,p,v,g,y){return this._writeCheck(),this._write(a,u,d,p,v,g,y)},Pr.prototype._write=function(a,u,d,p,v,g,y){if(this.write_in_progress=!0,a!==0&&a!==1&&a!==2&&a!==3&&a!==4&&a!==5)throw new Error("Invalid flush value");u==null&&(u=new re(0),p=0,d=0),v._set?v.set=v._set:v.set=YO;var I,S=this.strm;switch(S.avail_in=p,S.input=u,S.next_in=d,S.avail_out=y,S.output=v,S.next_out=g,this.mode){case Ga:case 3:case 5:I=bO(S,a);break;case gl:case 2:case 4:case 6:I=JO(S,a);break;default:throw new Error("Unknown mode "+this.mode)}return I!==1&&I!==0&&this._error(I),this.write_in_progress=!1,[S.avail_in,S.avail_out]},Pr.prototype.close=function(){this.write_in_progress?this.pending_close=!0:(this.pending_close=!1,this.mode===Ga||this.mode===3||this.mode===5?(function(a){var u;a&&a.state&&((u=a.state.status)!==Mm&&u!==Lm&&u!==Fu&&u!==Bu&&u!==Hu&&u!==ws&&u!==hl?Vn(a,ks):(a.state=null,u===ws&&Vn(a,hO)))})(this.strm):(function(a){if(!a||!a.state)return Bn;var u=a.state;u.window&&(u.window=null),a.state=null})(this.strm),this.mode=0)},Pr.prototype.reset=function(){switch(this.mode){case Ga:case 5:Ju=rT(this.strm);break;case 2:case 6:Ju=xT(this.strm)}Ju!==0&&this._error(Ju)},Pr.prototype._error=function(a){this.onerror(Dy[a]+": "+this.strm.msg,a),this.write_in_progress=!1,this.pending_close&&this.close()};var VT=Object.freeze({NONE:0,DEFLATE:Ga,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:gl,Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8,Zlib:Pr}),Re={};Object.keys(VT).forEach(function(a){Re[a]=VT[a]}),Re.Z_MIN_WINDOWBITS=8,Re.Z_MAX_WINDOWBITS=15,Re.Z_DEFAULT_WINDOWBITS=15,Re.Z_MIN_CHUNK=64,Re.Z_MAX_CHUNK=1/0,Re.Z_DEFAULT_CHUNK=16384,Re.Z_MIN_MEMLEVEL=1,Re.Z_MAX_MEMLEVEL=9,Re.Z_DEFAULT_MEMLEVEL=8,Re.Z_MIN_LEVEL=-1,Re.Z_MAX_LEVEL=9,Re.Z_DEFAULT_LEVEL=Re.Z_DEFAULT_COMPRESSION;var Yu={Z_OK:Re.Z_OK,Z_STREAM_END:Re.Z_STREAM_END,Z_NEED_DICT:Re.Z_NEED_DICT,Z_ERRNO:Re.Z_ERRNO,Z_STREAM_ERROR:Re.Z_STREAM_ERROR,Z_DATA_ERROR:Re.Z_DATA_ERROR,Z_MEM_ERROR:Re.Z_MEM_ERROR,Z_BUF_ERROR:Re.Z_BUF_ERROR,Z_VERSION_ERROR:Re.Z_VERSION_ERROR};function Ps(a,u,d){var p=[],v=0;function g(){for(var I;(I=a.read())!==null;)p.push(I),v+=I.length;a.once("readable",g)}function y(){var I=re.concat(p,v);p=[],d(null,I),a.close()}a.on("error",function(I){a.removeListener("end",y),a.removeListener("readable",g),d(I)}),a.on("end",y),a.end(u),g()}function Os(a,u){if(typeof u=="string"&&(u=new re(u)),!el(u))throw new TypeError("Not a string or buffer");var d=Re.Z_FINISH;return a._processChunk(u,d)}function Ms(a){if(!(this instanceof Ms))return new Ms(a);Ot.call(this,a,Re.DEFLATE)}function Ls(a){if(!(this instanceof Ls))return new Ls(a);Ot.call(this,a,Re.INFLATE)}function xs(a){if(!(this instanceof xs))return new xs(a);Ot.call(this,a,Re.GZIP)}function Us(a){if(!(this instanceof Us))return new Us(a);Ot.call(this,a,Re.GUNZIP)}function Vs(a){if(!(this instanceof Vs))return new Vs(a);Ot.call(this,a,Re.DEFLATERAW)}function Fs(a){if(!(this instanceof Fs))return new Fs(a);Ot.call(this,a,Re.INFLATERAW)}function Bs(a){if(!(this instanceof Bs))return new Bs(a);Ot.call(this,a,Re.UNZIP)}function Ot(a,u){if(this._opts=a=a||{},this._chunkSize=a.chunkSize||Re.Z_DEFAULT_CHUNK,Yi.call(this,a),a.flush&&a.flush!==Re.Z_NO_FLUSH&&a.flush!==Re.Z_PARTIAL_FLUSH&&a.flush!==Re.Z_SYNC_FLUSH&&a.flush!==Re.Z_FULL_FLUSH&&a.flush!==Re.Z_FINISH&&a.flush!==Re.Z_BLOCK)throw new Error("Invalid flush flag: "+a.flush);if(this._flushFlag=a.flush||Re.Z_NO_FLUSH,a.chunkSize&&(a.chunkSize<Re.Z_MIN_CHUNK||a.chunkSize>Re.Z_MAX_CHUNK))throw new Error("Invalid chunk size: "+a.chunkSize);if(a.windowBits&&(a.windowBits<Re.Z_MIN_WINDOWBITS||a.windowBits>Re.Z_MAX_WINDOWBITS))throw new Error("Invalid windowBits: "+a.windowBits);if(a.level&&(a.level<Re.Z_MIN_LEVEL||a.level>Re.Z_MAX_LEVEL))throw new Error("Invalid compression level: "+a.level);if(a.memLevel&&(a.memLevel<Re.Z_MIN_MEMLEVEL||a.memLevel>Re.Z_MAX_MEMLEVEL))throw new Error("Invalid memLevel: "+a.memLevel);if(a.strategy&&a.strategy!=Re.Z_FILTERED&&a.strategy!=Re.Z_HUFFMAN_ONLY&&a.strategy!=Re.Z_RLE&&a.strategy!=Re.Z_FIXED&&a.strategy!=Re.Z_DEFAULT_STRATEGY)throw new Error("Invalid strategy: "+a.strategy);if(a.dictionary&&!el(a.dictionary))throw new Error("Invalid dictionary: it should be a Buffer instance");this._binding=new Re.Zlib(u);var d=this;this._hadError=!1,this._binding.onerror=function(g,y){d._binding=null,d._hadError=!0;var I=new Error(g);I.errno=y,I.code=Re.codes[y],d.emit("error",I)};var p=Re.Z_DEFAULT_COMPRESSION;typeof a.level=="number"&&(p=a.level);var v=Re.Z_DEFAULT_STRATEGY;typeof a.strategy=="number"&&(v=a.strategy),this._binding.init(a.windowBits||Re.Z_DEFAULT_WINDOWBITS,p,a.memLevel||Re.Z_DEFAULT_MEMLEVEL,v,a.dictionary),this._buffer=new re(this._chunkSize),this._offset=0,this._closed=!1,this._level=p,this._strategy=v,this.once("end",this.close)}Object.keys(Yu).forEach(function(a){Yu[Yu[a]]=a}),Di(Ot,Yi),Ot.prototype.params=function(a,u,d){if(a<Re.Z_MIN_LEVEL||a>Re.Z_MAX_LEVEL)throw new RangeError("Invalid compression level: "+a);if(u!=Re.Z_FILTERED&&u!=Re.Z_HUFFMAN_ONLY&&u!=Re.Z_RLE&&u!=Re.Z_FIXED&&u!=Re.Z_DEFAULT_STRATEGY)throw new TypeError("Invalid strategy: "+u);if(this._level!==a||this._strategy!==u){var p=this;this.flush(Re.Z_SYNC_FLUSH,function(){p._binding.params(a,u),p._hadError||(p._level=a,p._strategy=u,d&&d())})}else oi(d)},Ot.prototype.reset=function(){return this._binding.reset()},Ot.prototype._flush=function(a){this._transform(new re(0),"",a)},Ot.prototype.flush=function(a,u){var d=this._writableState;if((typeof a=="function"||a===void 0&&!u)&&(u=a,a=Re.Z_FULL_FLUSH),d.ended)u&&oi(u);else if(d.ending)u&&this.once("end",u);else if(d.needDrain){var p=this;this.once("drain",function(){p.flush(u)})}else this._flushFlag=a,this.write(new re(0),"",u)},Ot.prototype.close=function(a){if(a&&oi(a),!this._closed){this._closed=!0,this._binding.close();var u=this;oi(function(){u.emit("close")})}},Ot.prototype._transform=function(a,u,d){var p,v=this._writableState,g=(v.ending||v.ended)&&(!a||v.length===a.length);if(!a===null&&!el(a))return d(new Error("invalid input"));g?p=Re.Z_FINISH:(p=this._flushFlag,a.length>=v.length&&(this._flushFlag=this._opts.flush||Re.Z_NO_FLUSH)),this._processChunk(a,p,d)},Ot.prototype._processChunk=function(a,u,d){var p=a&&a.length,v=this._chunkSize-this._offset,g=0,y=this,I=typeof d=="function";if(!I){var S,E=[],R=0;this.on("error",function(M){S=M});do var k=this._binding.writeSync(u,a,g,p,this._buffer,this._offset,v);while(!this._hadError&&O(k[0],k[1]));if(this._hadError)throw S;var N=re.concat(E,R);return this.close(),N}var A=this._binding.write(u,a,g,p,this._buffer,this._offset,v);function O(M,w){if(!y._hadError){var U=v-w;if((function(F,q){if(!F)throw new Error(q)})(U>=0,"have should not go down"),U>0){var L=y._buffer.slice(y._offset,y._offset+U);y._offset+=U,I?y.push(L):(E.push(L),R+=L.length)}if((w===0||y._offset>=y._chunkSize)&&(v=y._chunkSize,y._offset=0,y._buffer=new re(y._chunkSize)),w===0){if(g+=p-M,p=M,!I)return!0;var V=y._binding.write(u,a,g,p,y._buffer,y._offset,y._chunkSize);return V.callback=O,void(V.buffer=a)}if(!I)return!1;d()}}A.buffer=a,A.callback=O},Di(Ms,Ot),Di(Ls,Ot),Di(xs,Ot),Di(Us,Ot),Di(Vs,Ot),Di(Fs,Ot),Di(Bs,Ot);var FT={codes:Yu,createDeflate:function(a){return new Ms(a)},createInflate:function(a){return new Ls(a)},createDeflateRaw:function(a){return new Vs(a)},createInflateRaw:function(a){return new Fs(a)},createGzip:function(a){return new xs(a)},createGunzip:function(a){return new Us(a)},createUnzip:function(a){return new Bs(a)},deflate:function(a,u,d){return typeof u=="function"&&(d=u,u={}),Ps(new Ms(u),a,d)},deflateSync:function(a,u){return Os(new Ms(u),a)},gzip:function(a,u,d){return typeof u=="function"&&(d=u,u={}),Ps(new xs(u),a,d)},gzipSync:function(a,u){return Os(new xs(u),a)},deflateRaw:function(a,u,d){return typeof u=="function"&&(d=u,u={}),Ps(new Vs(u),a,d)},deflateRawSync:function(a,u){return Os(new Vs(u),a)},unzip:function(a,u,d){return typeof u=="function"&&(d=u,u={}),Ps(new Bs(u),a,d)},unzipSync:function(a,u){return Os(new Bs(u),a)},inflate:function(a,u,d){return typeof u=="function"&&(d=u,u={}),Ps(new Ls(u),a,d)},inflateSync:function(a,u){return Os(new Ls(u),a)},gunzip:function(a,u,d){return typeof u=="function"&&(d=u,u={}),Ps(new Us(u),a,d)},gunzipSync:function(a,u){return Os(new Us(u),a)},inflateRaw:function(a,u,d){return typeof u=="function"&&(d=u,u={}),Ps(new Fs(u),a,d)},inflateRawSync:function(a,u){return Os(new Fs(u),a)},Deflate:Ms,Inflate:Ls,Gzip:xs,Gunzip:Us,DeflateRaw:Vs,InflateRaw:Fs,Unzip:Bs,Zlib:Ot};class qO{constructor(u,d,p){this.SDKAPPID=u,this.EXPIRETIME=p,this.PRIVATEKEY=d}genTestUserSig(u){return this._isNumber(this.SDKAPPID)?this._isString(this.PRIVATEKEY)?this._isString(u)?this._isNumber(this.EXPIRETIME)?(console.log("sdkAppID="+this.SDKAPPID+" key="+this.PRIVATEKEY+" userID="+u+" expire="+this.EXPIRETIME),this.genSigWithUserbuf(u,this.EXPIRETIME,null)):(console.error("expireTime must be a number"),""):(console.error("userID must be a string"),""):(console.error("privateKey must be a string"),""):(console.error("sdkAppID must be a number"),"")}newBuffer(u,d){return re.from?re.from(u,d):new re(u,d)}unescape(u){return u.replace(/_/g,"=").replace(/\-/g,"/").replace(/\*/g,"+")}escape(u){return u.replace(/\+/g,"*").replace(/\//g,"-").replace(/=/g,"_")}encode(u){return this.escape(this.newBuffer(u).toString("base64"))}decode(u){return this.newBuffer(this.unescape(u),"base64")}base64encode(u){return this.newBuffer(u).toString("base64")}base64decode(u){return this.newBuffer(u,"base64").toString()}_hmacsha256(u,d,p,v){let g="TLS.identifier:"+u+`
165
+ `;g+="TLS.sdkappid:"+this.SDKAPPID+`
166
+ `,g+="TLS.time:"+d+`
167
+ `,g+="TLS.expire:"+p+`
168
+ `,v!=null&&(g+="TLS.userbuf:"+v+`
169
+ `);let y=ty.HmacSHA256(g,this.PRIVATEKEY);return ty.enc.Base64.stringify(y)}_utc(){return Math.round(Date.now()/1e3)}_isNumber(u){return u!==null&&(typeof u=="number"&&!isNaN(u-0)||typeof u=="object"&&u.constructor===Number)}_isString(u){return typeof u=="string"}genSigWithUserbuf(u,d,p){let v=this._utc(),g={"TLS.ver":"2.0","TLS.identifier":u,"TLS.sdkappid":this.SDKAPPID,"TLS.time":v,"TLS.expire":d},y="";if(p!=null){let R=this.base64encode(p);g["TLS.userbuf"]=R,y=this._hmacsha256(u,v,d,R)}else y=this._hmacsha256(u,v,d,null);g["TLS.sig"]=y;let I=JSON.stringify(g),S=FT.deflateSync(this.newBuffer(I)).toString("base64"),E=this.escape(S);return console.log("ret="+E),E}validate(u){let d=this.decode(u),p=FT.inflateSync(d);console.log("validate ret="+p)}}let qu=window.SDKAppID;console.log("🚀 ~GGG SDKAPPID:",qu);let Gm=window.SDKSecretKey;console.log("🚀 ~GGG SECRETKEY:",Gm);const XO=604800;function QO({userID:a,SDKAppID:u,SecretKey:d}){u&&(qu=u),d&&(Gm=d);const v=new qO(qu,Gm,XO).genTestUserSig(a);return{SDKAppID:qu,userSig:v}}const ZO="data:image/svg+xml,%3c?xml%20version='1.0'%20standalone='no'?%3e%3c!DOCTYPE%20svg%20PUBLIC%20'-//W3C//DTD%20SVG%201.1//EN'%20'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3e%3csvg%20t='1768359133902'%20class='icon'%20viewBox='0%200%201024%201024'%20version='1.1'%20xmlns='http://www.w3.org/2000/svg'%20p-id='12117'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='200'%20height='200'%3e%3cpath%20d='M17.516667%20500.983333c0%2055.033333%202.054167%2078.5875%2014.325%20132.345834%204.270833%2018.7%2014.745833%2048.591667%2021.870833%2066.466666%2017.0125%2042.6875%2048.295833%2096.245833%2077.591667%20129.0875%2029.6375%2033.2375%2040.495833%2045.695833%2075.304166%2073.045834%2048.570833%2038.158333%2096.041667%2062.558333%20154.916667%2081.779166%2020.004167%206.525%2052.5%2014.7125%2071.345833%2017%2022.9%202.779167%2040.520833%204.5%2056.5125%205.275h38.279167c16.5-0.783333%2034.504167-2.520833%2058.183333-5.120833%2015.904167-1.75%2033.991667-6.65%2049.720834-10.295833%2023.7125-5.491667%2065.575-21.241667%2086.541666-31.808334%206.816667-3.433333%2012.629167-6.158333%2018.9125-9.429166l19.304167-10.7c28.1-17%2044.783333-30.3125%2069.995833-50.016667l39.791667-38.55c28.733333-34.370833%2043.470833-48.891667%2067.520833-90.825%2011.525-20.0875%2019.495833-37.758333%2028.879167-59.4625%2051.383333-118.845833%2047.283333-280.908333-9.35-393.25-7.1375-14.15-13.129167-25.816667-20.55-39.458333-24.404167-44.895833-71.704167-100.0375-110.358333-131.329167-43.05-34.845833-62.083333-45.495833-111.354167-70.333333-60.920833-30.708333-143.316667-44.433333-212.279167-44.433334-104.808333%200-207.425%2038.2-290.058333%20100-38.145833%2028.533333-76.254167%2068.5875-104.320833%20107.366667C57.291667%20298.758333%2017.516667%20404.133333%2017.516667%20500.983333z'%20fill='%2314B400'%20p-id='12118'%3e%3c/path%3e%3cpath%20d='M401.0875%20150.3875c-90.966667%2016.291667-107.383333%20115.995833-88.566667%20212.3875%2019.2375%2098.554167%2089.308333%20242.670833%20150.279167%20319.683333%2023.741667%2029.991667%2030.2625%2037.158333%2055.091667%2061.583334l20.454166%2019.583333c40.208333%2037.041667%20152.145833%20115.054167%20217.9%2047.6%2010.195833-10.4625%2024.6-30.533333%2027.758334-50.491667%205.091667-32.220833-25.4625-49.9125-46.4375-69.7l-62.375-55.979166c-9.208333-9.379167-12.4875-4.5375-26.516667%200.304166-10.158333%203.5125-19.695833%206.958333-29.591667%2010.408334-41.625%2014.5-32.258333%2017.1125-54.270833-0.316667-61.595833-48.7875-107.7625-105.891667-126.308333-187.154167-2.345833-10.266667-11.1625-59.129167-8.441667-68.341666%202.15-7.279167%2058.345833-50.216667%2059.970833-56.291667%201.4125-5.2875-8.016667-98.666667-8.975-107.670833-2.379167-22.383333-3.391667-49.958333-16.391666-62.0875-14.179167-13.229167-39.808333-17.775-63.579167-13.516667z'%20fill='%23FEFDFC'%20p-id='12119'%3e%3c/path%3e%3c/svg%3e",BT="data:image/svg+xml,%3c?xml%20version='1.0'%20standalone='no'?%3e%3c!DOCTYPE%20svg%20PUBLIC%20'-//W3C//DTD%20SVG%201.1//EN'%20'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3e%3csvg%20t='1768382101596'%20class='icon'%20viewBox='0%200%201024%201024'%20version='1.1'%20xmlns='http://www.w3.org/2000/svg'%20p-id='8216'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='200'%20height='200'%3e%3cpath%20d='M510.82885015%20513.55777368m358.46705228-358.46705229a506.948967%20506.948967%200%201%200-716.93410456%20716.93410457%20506.948967%20506.948967%200%201%200%20716.93410456-716.93410457Z'%20fill='%23ea331b'%20p-id='8217'%3e%3c/path%3e%3cpath%20d='M511.23865671%20491.7945444c-41.24543107%200-82.50977582%207.84936752-119.82737014%2025.5340869l-7.84306295%2066.7921271c-0.01260984%203.92153148-2.96321511%206.87213675-7.86197665%207.86197664l-112.94262426%2024.55055158c-14.72150427%202.94430142-30.4580674-4.9239805-33.39606355-19.65179004a10.824279%2010.824279%200%200%201-0.01260913-7.85567209l0.99614446-63.84152111c0.97723076-18.66825471%209.82274203-35.35682893%2024.55055087-46.163107%2075.62502924-50.09094233%20165.98417187-77.57949006%20256.34962119-79.55286528%2090.35283807-1.96076538%20179.72844609%2022.60239532%20256.33700994%2071.69719391%2014.72780884%2010.80627807%2023.56701625%2027.50115756%2024.55685614%2046.16941085l-0.98353533%2065.79598264c0%2015.72395329-11.78350812%2027.50746142-27.51376598%2027.51376598-2.93799615%200.97092549-5.88860143%200-7.84936751-0.00630456l-112.96153866-22.58978619c-3.92153077%200-6.86583219-2.94430142-7.85567209-7.85567208l-5.90121055-66.7921271c-37.31128975-15.71134416-77.56057636-22.57087179-117.8413858-21.60625015z%20m0%200'%20fill='%23ffffff'%20p-id='8218'%20data-spm-anchor-id='a313x.search_index.0.i3.5a6e3a81TURsDW'%20class='selected'%3e%3c/path%3e%3c/svg%3e",$O="data:image/svg+xml,%3c?xml%20version='1.0'%20standalone='no'?%3e%3c!DOCTYPE%20svg%20PUBLIC%20'-//W3C//DTD%20SVG%201.1//EN'%20'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3e%3csvg%20t='1768358629006'%20class='icon'%20viewBox='0%200%201024%201024'%20version='1.1'%20xmlns='http://www.w3.org/2000/svg'%20p-id='6156'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='200'%20height='200'%3e%3cpath%20d='M512%20637.1c106.5%200%20193.7-87.2%20193.7-193.7V257.7C705.7%20151.2%20618.5%2064%20512%2064c-106.6%200-193.7%2087.2-193.7%20193.7v185.7c0%20106.5%2087.1%20193.7%20193.7%20193.7z'%20p-id='6157'%20fill='%232c2c2c'%3e%3c/path%3e%3cpath%20d='M834.9%20403c-22.3%200-40.4%2018.1-40.4%2040.4%200%20155.8-126.7%20282.5-282.5%20282.5S229.5%20599.2%20229.5%20443.4c0-22.3-18.1-40.4-40.4-40.4s-40.4%2018.1-40.4%2040.4c0%20183.9%20137.3%20336.1%20314.8%20359.9v108.3c0%2026.6%2021.8%2048.4%2048.4%2048.4%2026.6%200%2048.4-21.8%2048.4-48.4V803.3c177.5-23.8%20314.8-176.1%20314.8-359.9%200.1-22.3-17.9-40.4-40.2-40.4z'%20p-id='6158'%20fill='%232c2c2c'%3e%3c/path%3e%3c/svg%3e",eM="data:image/svg+xml,%3c?xml%20version='1.0'%20standalone='no'?%3e%3c!DOCTYPE%20svg%20PUBLIC%20'-//W3C//DTD%20SVG%201.1//EN'%20'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3e%3csvg%20t='1768358648084'%20class='icon'%20viewBox='0%200%201024%201024'%20version='1.1'%20xmlns='http://www.w3.org/2000/svg'%20p-id='6380'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='200'%20height='200'%3e%3cpath%20d='M556.4%20631.7L318.3%20291.6v151.8c0%20106.6%2087.2%20193.7%20193.7%20193.7%2015.3%200%2030.1-2%2044.4-5.4z'%20p-id='6381'%20fill='%23ffffff'%3e%3c/path%3e%3cpath%20d='M512%20725.9c-155.8%200-282.5-126.7-282.5-282.5%200-22.3-18.1-40.4-40.4-40.4s-40.4%2018.1-40.4%2040.4c0%20183.9%20137.3%20336.1%20314.8%20359.9v108.3c0%2026.6%2021.8%2048.4%2048.4%2048.4%2026.6%200%2048.4-21.8%2048.4-48.4V803.3c34.1-4.6%2066.6-13.9%2097-27.3l-47.6-67.9c-30.4%2011.3-63.3%2017.8-97.7%2017.8zM760.9%20707.3c70.3-66.2%20114.4-160%20114.4-264%200-22.3-18.1-40.4-40.4-40.4s-40.4%2018.1-40.4%2040.4c0%2076.6-30.8%20146.1-80.5%20197l-52.5-74.9c27.4-33.4%2044.2-75.8%2044.2-122.1V257.7C705.7%20151.2%20618.5%2064%20512%2064c-60.8%200-115.1%2028.5-150.7%2072.8l-35.7-51c-10.2-14.5-30.4-18.1-45-7.9-14.5%2010.2-18.1%2030.4-7.9%2045l494.7%20706.6c10.2%2014.5%2030.4%2018.1%2045%207.9%2014.5-10.2%2018.1-30.4%207.9-45l-59.4-85.1z'%20p-id='6382'%20fill='%23ffffff'%3e%3c/path%3e%3c/svg%3e",tM="data:image/svg+xml,%3c?xml%20version='1.0'%20standalone='no'?%3e%3c!DOCTYPE%20svg%20PUBLIC%20'-//W3C//DTD%20SVG%201.1//EN'%20'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3e%3csvg%20t='1768358681920'%20class='icon'%20viewBox='0%200%201024%201024'%20version='1.1'%20xmlns='http://www.w3.org/2000/svg'%20p-id='7461'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='200'%20height='200'%3e%3cpath%20d='M868.032%20287.808a64%2064%200%200%201%20101.056%2051.648l2.624%20302.592a64%2064%200%200%201-102.752%2051.456l-206.912-157.536a64%2064%200%200%201%201.728-103.104l204.256-145.056z'%20fill='%232c2c2c'%20p-id='7462'%3e%3c/path%3e%3cpath%20d='M144%20192h456.32a96%2096%200%200%201%2096%2096v417.376a96%2096%200%200%201-96%2096H144a96%2096%200%200%201-96-96V288a96%2096%200%200%201%2096-96z'%20fill='%232c2c2c'%20p-id='7463'%3e%3c/path%3e%3c/svg%3e",iM="data:image/svg+xml,%3c?xml%20version='1.0'%20standalone='no'?%3e%3c!DOCTYPE%20svg%20PUBLIC%20'-//W3C//DTD%20SVG%201.1//EN'%20'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3e%3csvg%20t='1768358492097'%20class='icon'%20viewBox='0%200%201024%201024'%20version='1.1'%20xmlns='http://www.w3.org/2000/svg'%20p-id='4839'%20id='mx_n_1768358492097'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='200'%20height='200'%3e%3cpath%20d='M106.912%20152.096A32%2032%200%201%201%20149.12%20103.904l768%20672a32%2032%200%200%201-42.176%2048.192l-768-672z'%20fill='%23ffffff'%20p-id='4840'%3e%3c/path%3e%3cpath%20d='M732.672%20462.4l-37.056-52.16%20172.416-122.432a64%2064%200%200%201%20101.056%2051.648l2.624%20302.592a63.904%2063.904%200%200%201-20.16%2047.2l-43.84-46.656-2.624-302.592-172.416%20122.432z%20m-34.72-54.016l35.616%2053.184c-10.752%207.2-24.32%2012.16-37.216%2012.16a64%2064%200%200%201-64-64V288a32%2032%200%200%200-32-32h-205.952V192h205.952a96%2096%200%200%201%2096%2096v121.28c0.416-0.224%201.088-0.544%201.6-0.896zM632.32%20608h64v97.376a96%2096%200%200%201-96%2096H144a96%2096%200%200%201-96-96V288a96%2096%200%200%201%2096-96h96v64h-96a32%2032%200%200%200-32%2032v417.376a32%2032%200%200%200%2032%2032h456.32a32%2032%200%200%200%2032-32V608z'%20fill='%23ffffff'%20p-id='4841'%3e%3c/path%3e%3c/svg%3e",rM=(a,u)=>{const d=a.__vccOpts||a;for(const[p,v]of u)d[p]=v;return d},nM={key:0,class:"callkit-wrapper"},sM={class:"call-label"},aM=["id"],oM={class:"bottom-controls"},lM={key:0,class:"operation-btn"},cM=["src"],uM={class:"operation-btn"},dM=["src"],hM=["src"],pM={class:"operation-btn"},mM=["src"],fM=["src"],HT=rM({__name:"CallKit",emits:["notify","remote-user-status-change"],setup(a,{expose:u,emit:d}){const p=Ie.ref(""),v=Ie.ref(null),g=Ie.ref(null),y=Ie.ref([]),I=Ie.ref([]),S=Ie.reactive({}),E=Ie.ref(!1),R=Ie.ref(!1),k=Ie.ref(""),N=Ie.ref(""),A=Ie.ref(null),O=Ft.create(),M=d;function w(ae,ye){try{M("notify",{type:ae,text:ye})}catch(ze){console.warn("emit notify failed",ze)}}const U=Ie.reactive({audio:!0,video:!0}),L=Ie.ref(!1),V=Ie.ref("1440p");let F=null;async function q(){if(!v.value||!g.value){w("error","缺少 sdkAppId 或 sdkSecretKey");return}try{const{userSig:ae}=QO({userID:p.value,SDKAppID:v.value,SecretKey:g.value});console.log("🚀 ~ 当前用户:",p.value),await O.enterRoom({sdkAppId:v.value,userId:p.value,userSig:ae,roomId:8888}),tt(),await we(),ke(),w("info","进入房间成功")}catch(ae){w("error","进入房间失败: "+ae)}}async function K({userId:ae,sdkAppId:ye,sdkSecretKey:ze}={}){p.value=ae||`user_${Math.floor(Math.random()*900+100)}`,v.value=ye||v.value,g.value=ze||g.value,await q()}function z(){E.value=!0}function J(){E.value=!1,R.value=!1,A.value=null,k.value="",N.value=""}async function X(){try{await O.exitRoom(),console.log("🚀 ~ 退出房间成功"),await Q(),await We(),Nt(),Ve()}catch(ae){w("error","退出房间失败: "+ae)}}async function W(){console.log("🚀 ~ 打开麦克风");try{await O.startLocalAudio(),U.audio=!0}catch(ae){U.audio=!1,w("error","启动麦克风失败: "+ae)}}async function Q(){console.log("🚀 ~ 关闭麦克风"),await O.stopLocalAudio();try{await O.stopLocalAudio(),U.audio=!1}catch(ae){w("error","关闭麦克风失败: "+ae)}}async function ge(){console.log("🚀 ~ 打开摄像头");try{const ae="local-video",ye=await Ft.getCameraList();await O.startLocalVideo({view:ae,option:{profile:V.value}}),ye[1]&&await O.updateLocalVideo({option:{cameraId:ye[1].deviceId}}),U.video=!0}catch(ae){U.video=!1,w("error","打开摄像头失败: "+ae)}}async function ne(ae){if(!(!ae||V.value===ae))try{try{await O.stopLocalVideo()}catch{}await O.startLocalVideo({view:"local-video",option:{profile:ae}}),V.value=ae,U.video=!0,w("info",`已将视频质量调整为 ${ae}`)}catch(ye){U.video=!1,w("error","调整视频质量失败:"+ye)}}async function Te(){try{let ae=null;typeof O.getLocalStats=="function"&&(ae=await O.getLocalStats());let ye=!1,ze="";if(ae){const Qe=ae.uplinkKbps??ae.sendKbps??ae.txKbps??null,Le=ae.uplinkPacketLostRate??ae.packetLostRate??ae.sendPacketLostRate??null;ze=`uplink:${Qe??"n/a"}kbps loss:${Le??"n/a"}`,(Qe!==null&&Qe<300||Le!==null&&Le>.05)&&(ye=!0)}else if(typeof O.getNetworkQuality=="function"){const Qe=await O.getNetworkQuality(),Le=Qe.uplinkQuality??Qe.upQuality??null;ze=`uplinkQuality:${Le??"n/a"}`,Le!==null&&Le>=4&&(ye=!0)}else return;ye&&!L.value?(L.value=!0,w("warn",`网络不稳定:${ze},已切换到低清 360p`),await ne("360p")):!ye&&L.value&&(L.value=!1,w("info",`网络已恢复:${ze},恢复到高清`),await ne("1440p"))}catch(ae){console.warn("checkNetworkQuality error",ae)}}function ke(){Ve(),F=setInterval(()=>{Te()},5e3)}function Ve(){F&&(clearInterval(F),F=null)}async function We(){console.log("🚀 ~ 关闭摄像头");try{await O.stopLocalVideo(),U.video=!1}catch(ae){w("error","关闭摄像头失败: "+ae)}}async function we(){console.log("🚀 ~ 打开扬声器");try{await O.setCurrentSpeaker(Ft.TYPE.SPEAKER)}catch(ae){w("error","打开扬声器失败:"+ae)}}function tt(){O.on(Ft.EVENT.ERROR,le),O.on(Ft.EVENT.REMOTE_VIDEO_AVAILABLE,oe),O.on(Ft.EVENT.REMOTE_VIDEO_UNAVAILABLE,ue),O.on(Ft.EVENT.VIDEO_SIZE_CHANGED,se),O.on(Ft.EVENT.REMOTE_AUDIO_AVAILABLE,bt),O.on(Ft.EVENT.REMOTE_USER_ENTER,ci),O.on(Ft.EVENT.REMOTE_USER_EXIT,$e),O.on(Ft.EVENT.CUSTOM_MESSAGE,Et)}function Nt(){O.off(Ft.EVENT.ERROR,le),O.off(Ft.EVENT.REMOTE_VIDEO_AVAILABLE,oe),O.off(Ft.EVENT.REMOTE_VIDEO_UNAVAILABLE,ue),O.off(Ft.EVENT.VIDEO_SIZE_CHANGED,se),O.off(Ft.EVENT.REMOTE_AUDIO_AVAILABLE,bt),O.off(Ft.EVENT.REMOTE_USER_ENTER,ci),O.off(Ft.EVENT.REMOTE_USER_EXIT,$e),O.off(Ft.EVENT.CUSTOM_MESSAGE,Et)}function le(ae){console.error("🚀 ~ 错误 ~ error:",ae),w("error","TRTC 错误:"+(ae&&ae.message?ae.message:JSON.stringify(ae)))}function se(ae){console.log("🚀 ~ 远端视频尺寸变化 ~ event:",ae);const{userId:ye,streamType:ze,newHeight:Qe,newWidth:Le}=ae,Yt=`${ye}_${ze}`;Qe>0&&Le>0&&(S[Yt]=Le/Qe)}async function oe(ae){console.log("🚀 ~ 远端用户发布了视频 ~ event:",ae);const{userId:ye,streamType:ze}=ae,Qe=`${ye}_${ze}`;try{if(ze===Ft.TYPE.STREAM_TYPE_MAIN){y.value.push(Qe),await Ie.nextTick(),await O.startRemoteVideo({userId:ye,streamType:ze,view:Qe});try{await O.startRemoteAudio({userId:ye})}catch{}await we()}else{y.value.push(Qe),await Ie.nextTick(),O.startRemoteVideo({userId:ye,streamType:ze,view:Qe});try{await O.startRemoteAudio({userId:ye})}catch{}}setTimeout(()=>{try{const Le=document.getElementById(Qe);if(Le){const Yt=Le.querySelector("video");Yt&&Yt.videoWidth>0&&Yt.videoHeight>0&&(S[Qe]=Yt.videoWidth/Yt.videoHeight)}}catch(Le){console.warn("Failed to get video element:",Le)}},1e3)}catch(Le){console.log("🚀 ~ handleRemoteVideoAvailable ~ error:",Le),w("error","远端视频订阅失败:"+Le)}}async function ue(ae){console.log("🚀 ~ 远端用户停止发布视频 ~ event:",ae);const{userId:ye,streamType:ze}=ae,Qe=`${ye}_${ze}`;try{await O.stopRemoteVideo({userId:ye,streamType:ze})}catch{}const Le=y.value.indexOf(Qe);Le!==-1&&y.value.splice(Le,1),delete S[Qe]}async function bt(ae){console.log("🚀 ~ 异步订阅音频 ~ event:",ae);const{userId:ye}=ae;try{await O.startRemoteAudio({userId:ye})}catch(ze){console.warn("startRemoteAudio fail",ze)}}function ci(ae){const{userId:ye}=ae;if(console.log("🚀 ~ 远端用户进入/退出",ye),!I.value.includes(ye)){I.value.push(ye),w("info",`用户 ${ye} 进入房间`);try{M("remote-user-status-change",{userId:ye,action:"enter",userList:[...I.value]})}catch(ze){console.warn("emit remote-user-status-change failed",ze)}}}async function $e(ae){const{userId:ye}=ae;console.log("🚀 ~ 远端用户退出房间",ye);try{await O.stopRemoteAudio({userId:ye})}catch{}try{await O.stopRemoteVideo({userId:ye,streamType:Ft.TYPE.STREAM_TYPE_MAIN})}catch{}try{await O.stopRemoteVideo({userId:ye,streamType:Ft.TYPE.STREAM_TYPE_SUB})}catch{}["main","screen","sub"].forEach(Qe=>{const Le=`${ye}_${Qe}`,Yt=y.value.indexOf(Le);Yt!==-1&&y.value.splice(Yt,1),delete S[Le]});const ze=I.value.indexOf(ye);ze!==-1&&I.value.splice(ze,1),w("info",`用户 ${ye} 离开房间`);try{M("remote-user-status-change",{userId:ye,action:"exit",userList:[...I.value]})}catch(Qe){console.warn("emit remote-user-status-change failed",Qe)}try{const Qe=I.value.length;R.value&&Qe===0&&k.value===ye&&(w("info","对方已离开,正在自动结束本地通话"),await Fi())}catch(Qe){console.warn("auto hangup on remote exit failed",Qe)}}async function Pi(ae,ye=1){console.log("🚀 ~ 发送自定义信令(广播) ~ payload, cmdId:",ae,ye);try{const Qe=new TextEncoder().encode(JSON.stringify(ae)).buffer;await O.sendCustomMessage({cmdId:ye,data:Qe})}catch(ze){console.warn("发送自定义信令(广播)",ze),w("error","发送信令失败:"+ze)}}async function Et(ae){console.log("🚀 ~ 收到自定义消息",ae);let ye=null;if(ae.data instanceof ArrayBuffer?(ye=ae.data,ae.userId||ae.from):ae.message&&ae.message.data?(ye=ae.message.data,ae.userId||ae.message.userId):(ae.userId&&ae.cmdId&&ae.data||ae.userId&&ae.data instanceof ArrayBuffer)&&(ye=ae.data,ae.userId),!!ye)try{const Qe=new TextDecoder().decode(new Uint8Array(ye)),Le=JSON.parse(Qe);if(console.log("🚀 ~ 收到自定义消息内容",Le),!Le||!Le.type)return;Le.type==="incoming_call"&&Le.to===p.value?(A.value={from:Le.from,callId:Le.callId},E.value=!0,N.value=Le.from):Le.type==="call_response"&&Le.to===p.value?Le.accept?(w("info",`用户 ${Le.from} 接听了呼叫`),await W(),await ge(),R.value=!0,N.value=Le.from):(w("info",`用户 ${Le.from} 拒绝了呼叫`),J()):Le.type==="hangup_call"&&Le.to===p.value&&(await Fi(),w("info",`用户 ${Le.from} 已挂断通话`))}catch(ze){console.warn("parse custom message fail",ze),w("error","接收广播消息异常: "+ze.message)}}async function en(ae){console.log("🚀 ~ 发起呼叫");const ye=ae&&String(ae).trim();if(!ye){w("error","缺少呼叫目标,请传入目标用户ID");return}if(!I.value.includes(ye)){w("error","用户不在线或未加入房间");return}E.value=!0,k.value=ye,N.value=ye;const ze=`call_${Date.now()}_${Math.floor(Math.random()*1e4)}`,Qe={type:"incoming_call",from:p.value,to:ye,callId:ze};await Pi(Qe,1),w("info",`已向 ${ye} 发起呼叫,等待应答`)}async function Fi(){try{await Q(),await We();const ae=`call_${Date.now()}_${Math.floor(Math.random()*1e4)}`,ye={type:"hangup_call",from:p.value,to:k.value,callId:ae};await Pi(ye,3),J(),w("info","已挂断")}catch(ae){console.warn("hangup fail",ae),w("error","挂断失败:"+ae)}}async function Mt(){if(console.log("🚀 ~ 接听来电"),!A.value)return;const ae={type:"call_response",from:p.value,to:A.value.from,callId:A.value.callId,accept:!0};await Pi(ae,2),await W(),await ge(),R.value=!0,k.value=A.value.from,N.value=A.value.from,A.value=null}async function Lt(){if(console.log("🚀 ~ 拒绝来电"),A.value){const ae={type:"call_response",from:p.value,to:A.value.from,callId:A.value.callId,accept:!1};await Pi(ae,2),A.value=null,J();return}else Fi()}function tn(){U.audio?Q():W()}function Or(){U.video?We():ge()}return u({handleCall:en,init:K,show:z,hide:J,hangup:Fi}),Ie.onUnmounted(()=>{X()}),(ae,ye)=>(Ie.openBlock(),Ie.createBlock(Ie.Transition,{name:"callkit"},{default:Ie.withCtx(()=>[E.value?(Ie.openBlock(),Ie.createElementBlock("div",nM,[Ie.createElementVNode("div",sM,Ie.toDisplayString(N.value),1),ye[3]||(ye[3]=Ie.createElementVNode("div",{class:"local-video",id:"local-video"},null,-1)),Ie.createElementVNode("div",{class:Ie.normalizeClass(["player-container",{single:y.value.length===1}])},[(Ie.openBlock(!0),Ie.createElementBlock(Ie.Fragment,null,Ie.renderList(y.value,ze=>(Ie.openBlock(),Ie.createElementBlock("div",{key:ze,class:"remote",id:ze,style:Ie.normalizeStyle({aspectRatio:S[ze]||"16/9"})},null,12,aM))),128))],2),Ie.createElementVNode("div",oM,[R.value?(Ie.openBlock(),Ie.createElementBlock(Ie.Fragment,{key:1},[Ie.createElementVNode("div",{class:Ie.normalizeClass(["equipment-btn operation-btn",U.audio?"equipment-btn--open":"equipment-btn--close"])},[Ie.createElementVNode("img",{src:U.audio?Ie.unref($O):Ie.unref(eM),onClick:tn},null,8,hM),Ie.createElementVNode("div",null,Ie.toDisplayString(U.audio?"麦克风已开":"麦克风已关"),1)],2),Ie.createElementVNode("div",pM,[Ie.createElementVNode("img",{src:Ie.unref(BT),onClick:Fi},null,8,mM),ye[2]||(ye[2]=Ie.createElementVNode("div",null,"挂断",-1))]),Ie.createElementVNode("div",{class:Ie.normalizeClass(["equipment-btn operation-btn",U.video?"equipment-btn--open":"equipment-btn--close"])},[Ie.createElementVNode("img",{src:U.video?Ie.unref(tM):Ie.unref(iM),onClick:Or},null,8,fM),Ie.createElementVNode("div",null,Ie.toDisplayString(U.video?"摄像头已开":"摄像头已关"),1)],2)],64)):(Ie.openBlock(),Ie.createElementBlock(Ie.Fragment,{key:0},[A.value?(Ie.openBlock(),Ie.createElementBlock("div",lM,[Ie.createElementVNode("img",{src:Ie.unref(ZO),onClick:Mt},null,8,cM),ye[0]||(ye[0]=Ie.createElementVNode("div",null,"接听",-1))])):Ie.createCommentVNode("",!0),Ie.createElementVNode("div",uM,[Ie.createElementVNode("img",{src:Ie.unref(BT),onClick:Lt},null,8,dM),ye[1]||(ye[1]=Ie.createElementVNode("div",null,"挂断",-1))])],64))])])):Ie.createCommentVNode("",!0)]),_:1}))}},[["__scopeId","data-v-989115b9"]]);wn.CallKit=HT,wn.default=HT,Object.defineProperties(wn,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));