160 lines
939 KiB
JavaScript
160 lines
939 KiB
JavaScript
import{c as fk,a as yW}from"./lodash-D3kF6u-c.js";var Gu={exports:{}},SW=Gu.exports,_k;function IW(){return _k||(_k=1,(function(kk,RW){(function(B_,An){kk.exports=An()})(SW,function(){function B_(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 An=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof fk<"u"?fk:typeof self<"u"?self:{};function Dk(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ms=function(e){return e&&e.Math===Math&&e},se=Ms(typeof globalThis=="object"&&globalThis)||Ms(typeof window=="object"&&window)||Ms(typeof self=="object"&&self)||Ms(typeof An=="object"&&An)||Ms(typeof An=="object"&&An)||(function(){return this})()||Function("return this")(),Fo={},de=function(e){try{return!!e()}catch{return!0}},Me=!de(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),Bo=!de(function(){var e=(function(){}).bind();return typeof e!="function"||e.hasOwnProperty("prototype")}),wk=Bo,Ho=Function.prototype.call,De=wk?Ho.bind(Ho):function(){return Ho.apply(Ho,arguments)},zu={},H_={}.propertyIsEnumerable,W_=Object.getOwnPropertyDescriptor,Nk=W_&&!H_.call({1:2},1);zu.f=Nk?function(e){var t=W_(this,e);return!!t&&t.enumerable}:H_;var Xi,Wo,Rn=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},G_=Bo,j_=Function.prototype,Ju=j_.call,Pk=G_&&j_.bind.bind(Ju,Ju),pe=G_?Pk:function(e){return function(){return Ju.apply(e,arguments)}},z_=pe,Ok=z_({}.toString),Mk=z_("".slice),Dr=function(e){return Mk(Ok(e),8,-1)},Lk=de,xk=Dr,Ku=Object,Uk=pe("".split),Go=Lk(function(){return!Ku("z").propertyIsEnumerable(0)})?function(e){return xk(e)==="String"?Uk(e,""):Ku(e)}:Ku,jo=function(e){return e==null},Vk=jo,Fk=TypeError,vi=function(e){if(Vk(e))throw new Fk("Can't call method on "+e);return e},Bk=Go,Hk=vi,Ls=function(e){return Bk(Hk(e))},qu=typeof document=="object"&&document.all,Te=qu===void 0&&qu!==void 0?function(e){return typeof e=="function"||e===qu}:function(e){return typeof e=="function"},Wk=Te,We=function(e){return typeof e=="object"?e!==null:Wk(e)},Yu=se,Gk=Te,yi=function(e,t){return arguments.length<2?(i=Yu[e],Gk(i)?i:void 0):Yu[e]&&Yu[e][t];var i},Qi=pe({}.isPrototypeOf),J_=se.navigator,K_=J_&&J_.userAgent,oi=K_?String(K_):"",q_=se,Xu=oi,Y_=q_.process,X_=q_.Deno,Q_=Y_&&Y_.versions||X_&&X_.version,Z_=Q_&&Q_.v8;Z_&&(Wo=(Xi=Z_.split("."))[0]>0&&Xi[0]<4?1:+(Xi[0]+Xi[1])),!Wo&&Xu&&(!(Xi=Xu.match(/Edge\/(\d+)/))||Xi[1]>=74)&&(Xi=Xu.match(/Chrome\/(\d+)/))&&(Wo=+Xi[1]);var Zi=Wo,$_=Zi,jk=de,zk=se.String,eg=!!Object.getOwnPropertySymbols&&!jk(function(){var e=Symbol("symbol detection");return!zk(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&$_&&$_<41}),tg=eg&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Jk=yi,Kk=Te,qk=Qi,Yk=Object,Qu=tg?function(e){return typeof e=="symbol"}:function(e){var t=Jk("Symbol");return Kk(t)&&qk(t.prototype,Yk(e))},Xk=String,Cn=function(e){try{return Xk(e)}catch{return"Object"}},Qk=Te,Zk=Cn,$k=TypeError,zt=function(e){if(Qk(e))return e;throw new $k(Zk(e)+" is not a function")},eD=zt,tD=jo,xs=function(e,t){var i=e[t];return tD(i)?void 0:eD(i)},Zu=De,$u=Te,ed=We,iD=TypeError,ig={exports:{}},rg=se,rD=Object.defineProperty,td=function(e,t){try{rD(rg,e,{value:t,configurable:!0,writable:!0})}catch{rg[e]=t}return t},nD=se,sD=td,ng="__core-js_shared__",sg=ig.exports=nD[ng]||sD(ng,{});(sg.versions||(sg.versions=[])).push({version:"3.48.0",mode:"global",copyright:"© 2013–2025 Denis Pushkarev (zloirock.ru), 2025–2026 CoreJS Company (core-js.io). All rights reserved.",license:"https://github.com/zloirock/core-js/blob/v3.48.0/LICENSE",source:"https://github.com/zloirock/core-js"});var id=ig.exports,ag=id,rd=function(e,t){return ag[e]||(ag[e]=t||{})},aD=vi,oD=Object,Jt=function(e){return oD(aD(e))},lD=Jt,cD=pe({}.hasOwnProperty),Xe=Object.hasOwn||function(e,t){return cD(lD(e),t)},uD=pe,dD=0,hD=Math.random(),mD=uD(1.1.toString),nd=function(e){return"Symbol("+(e===void 0?"":e)+")_"+mD(++dD+hD,36)},pD=rd,og=Xe,fD=nd,_D=eg,gD=tg,bn=se.Symbol,sd=pD("wks"),TD=gD?bn.for||bn:bn&&bn.withoutSetter||fD,Ne=function(e){return og(sd,e)||(sd[e]=_D&&og(bn,e)?bn[e]:TD("Symbol."+e)),sd[e]},ED=De,lg=We,cg=Qu,vD=xs,yD=function(e,t){var i,r;if(t==="string"&&$u(i=e.toString)&&!ed(r=Zu(i,e))||$u(i=e.valueOf)&&!ed(r=Zu(i,e))||t!=="string"&&$u(i=e.toString)&&!ed(r=Zu(i,e)))return r;throw new iD("Can't convert object to primitive value")},SD=TypeError,ID=Ne("toPrimitive"),ug=function(e,t){if(!lg(e)||cg(e))return e;var i,r=vD(e,ID);if(r){if(t===void 0&&(t="default"),i=ED(r,e,t),!lg(i)||cg(i))return i;throw new SD("Can't convert object to primitive value")}return t===void 0&&(t="number"),yD(e,t)},AD=ug,RD=Qu,ad=function(e){var t=AD(e,"string");return RD(t)?t:t+""},dg=We,od=se.document,CD=dg(od)&&dg(od.createElement),zo=function(e){return CD?od.createElement(e):{}},bD=zo,hg=!Me&&!de(function(){return Object.defineProperty(bD("div"),"a",{get:function(){return 7}}).a!==7}),kD=Me,DD=De,wD=zu,ND=Rn,PD=Ls,OD=ad,MD=Xe,LD=hg,mg=Object.getOwnPropertyDescriptor;Fo.f=kD?mg:function(e,t){if(e=PD(e),t=OD(t),LD)try{return mg(e,t)}catch{}if(MD(e,t))return ND(!DD(wD.f,e,t),e[t])};var Dt={},pg=Me&&de(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),xD=We,UD=String,VD=TypeError,lt=function(e){if(xD(e))return e;throw new VD(UD(e)+" is not an object")},FD=Me,BD=hg,HD=pg,Jo=lt,fg=ad,WD=TypeError,ld=Object.defineProperty,GD=Object.getOwnPropertyDescriptor,cd="enumerable",ud="configurable",dd="writable";Dt.f=FD?HD?function(e,t,i){if(Jo(e),t=fg(t),Jo(i),typeof e=="function"&&t==="prototype"&&"value"in i&&dd in i&&!i[dd]){var r=GD(e,t);r&&r[dd]&&(e[t]=i.value,i={configurable:ud in i?i[ud]:r[ud],enumerable:cd in i?i[cd]:r[cd],writable:!1})}return ld(e,t,i)}:ld:function(e,t,i){if(Jo(e),t=fg(t),Jo(i),BD)try{return ld(e,t,i)}catch{}if("get"in i||"set"in i)throw new WD("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var jD=Dt,zD=Rn,Si=Me?function(e,t,i){return jD.f(e,t,zD(1,i))}:function(e,t,i){return e[t]=i,e},_g={exports:{}},hd=Me,JD=Xe,gg=Function.prototype,KD=hd&&Object.getOwnPropertyDescriptor,Tg=JD(gg,"name"),kn={PROPER:Tg&&(function(){}).name==="something",CONFIGURABLE:Tg&&(!hd||hd&&KD(gg,"name").configurable)},qD=Te,md=id,YD=pe(Function.toString);qD(md.inspectSource)||(md.inspectSource=function(e){return YD(e)});var Ko,Us,qo,pd=md.inspectSource,XD=Te,Eg=se.WeakMap,QD=XD(Eg)&&/native code/.test(String(Eg)),ZD=nd,vg=rd("keys"),fd=function(e){return vg[e]||(vg[e]=ZD(e))},_d={},$D=QD,yg=se,ew=We,tw=Si,gd=Xe,Td=id,iw=fd,rw=_d,Sg="Object already initialized",Ed=yg.TypeError,nw=yg.WeakMap;if($D||Td.state){var li=Td.state||(Td.state=new nw);li.get=li.get,li.has=li.has,li.set=li.set,Ko=function(e,t){if(li.has(e))throw new Ed(Sg);return t.facade=e,li.set(e,t),t},Us=function(e){return li.get(e)||{}},qo=function(e){return li.has(e)}}else{var Dn=iw("state");rw[Dn]=!0,Ko=function(e,t){if(gd(e,Dn))throw new Ed(Sg);return t.facade=e,tw(e,Dn,t),t},Us=function(e){return gd(e,Dn)?e[Dn]:{}},qo=function(e){return gd(e,Dn)}}var gt={set:Ko,get:Us,has:qo,enforce:function(e){return qo(e)?Us(e):Ko(e,{})},getterFor:function(e){return function(t){var i;if(!ew(t)||(i=Us(t)).type!==e)throw new Ed("Incompatible receiver, "+e+" required");return i}}},vd=pe,sw=de,aw=Te,Yo=Xe,yd=Me,ow=kn.CONFIGURABLE,lw=pd,cw=gt.enforce,uw=gt.get,Ig=String,Xo=Object.defineProperty,dw=vd("".slice),hw=vd("".replace),mw=vd([].join),pw=yd&&!sw(function(){return Xo(function(){},"length",{value:8}).length!==8}),fw=String(String).split("String"),_w=_g.exports=function(e,t,i){dw(Ig(t),0,7)==="Symbol("&&(t="["+hw(Ig(t),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!Yo(e,"name")||ow&&e.name!==t)&&(yd?Xo(e,"name",{value:t,configurable:!0}):e.name=t),pw&&i&&Yo(i,"arity")&&e.length!==i.arity&&Xo(e,"length",{value:i.arity});try{i&&Yo(i,"constructor")&&i.constructor?yd&&Xo(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch{}var r=cw(e);return Yo(r,"source")||(r.source=mw(fw,typeof t=="string"?t:"")),e};Function.prototype.toString=_w(function(){return aw(this)&&uw(this).source||lw(this)},"toString");var Ag=_g.exports,gw=Te,Tw=Dt,Ew=Ag,vw=td,wt=function(e,t,i,r){r||(r={});var n=r.enumerable,s=r.name!==void 0?r.name:t;if(gw(i)&&Ew(i,s,r),r.global)n?e[t]=i:vw(t,i);else{try{r.unsafe?e[t]&&(n=!0):delete e[t]}catch{}n?e[t]=i:Tw.f(e,t,{value:i,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},Qo={},yw=Math.ceil,Sw=Math.floor,Iw=Math.trunc||function(e){var t=+e;return(t>0?Sw:yw)(t)},Aw=Iw,$i=function(e){var t=+e;return t!=t||t===0?0:Aw(t)},Rw=$i,Cw=Math.max,bw=Math.min,Zo=function(e,t){var i=Rw(e);return i<0?Cw(i+t,0):bw(i,t)},kw=$i,Dw=Math.min,wr=function(e){var t=kw(e);return t>0?Dw(t,9007199254740991):0},ww=wr,ci=function(e){return ww(e.length)},Nw=Ls,Pw=Zo,Ow=ci,Rg=function(e){return function(t,i,r){var n=Nw(t),s=Ow(n);if(s===0)return!e&&-1;var a,o=Pw(r,s);if(e&&i!=i){for(;s>o;)if((a=n[o++])!=a)return!0}else for(;s>o;o++)if((e||o in n)&&n[o]===i)return e||o||0;return!e&&-1}},Cg={includes:Rg(!0),indexOf:Rg(!1)},Sd=Xe,Mw=Ls,Lw=Cg.indexOf,xw=_d,bg=pe([].push),kg=function(e,t){var i,r=Mw(e),n=0,s=[];for(i in r)!Sd(xw,i)&&Sd(r,i)&&bg(s,i);for(;t.length>n;)Sd(r,i=t[n++])&&(~Lw(s,i)||bg(s,i));return s},Id=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Uw=kg,Vw=Id.concat("length","prototype");Qo.f=Object.getOwnPropertyNames||function(e){return Uw(e,Vw)};var Ad={};Ad.f=Object.getOwnPropertySymbols;var Fw=yi,Bw=Qo,Hw=Ad,Ww=lt,Gw=pe([].concat),jw=Fw("Reflect","ownKeys")||function(e){var t=Bw.f(Ww(e)),i=Hw.f;return i?Gw(t,i(e)):t},Dg=Xe,zw=jw,Jw=Fo,Kw=Dt,Rd=function(e,t,i){for(var r=zw(t),n=Kw.f,s=Jw.f,a=0;a<r.length;a++){var o=r[a];Dg(e,o)||i&&Dg(i,o)||n(e,o,s(t,o))}},qw=de,Yw=Te,Xw=/#|\.prototype\./,Vs=function(e,t){var i=Zw[Qw(e)];return i===eN||i!==$w&&(Yw(t)?qw(t):!!t)},Qw=Vs.normalize=function(e){return String(e).replace(Xw,".").toLowerCase()},Zw=Vs.data={},$w=Vs.NATIVE="N",eN=Vs.POLYFILL="P",Cd=Vs,$o=se,tN=Fo.f,iN=Si,rN=wt,nN=td,sN=Rd,aN=Cd,Ee=function(e,t){var i,r,n,s,a,o=e.target,l=e.global,c=e.stat;if(i=l?$o:c?$o[o]||nN(o,{}):$o[o]&&$o[o].prototype)for(r in t){if(s=t[r],n=e.dontCallGetSet?(a=tN(i,r))&&a.value:i[r],!aN(l?r:o+(c?".":"#")+r,e.forced)&&n!==void 0){if(typeof s==typeof n)continue;sN(s,n)}(e.sham||n&&n.sham)&&iN(s,"sham",!0),rN(i,r,s,e)}},wg={};wg[Ne("toStringTag")]="z";var oN=String(wg)==="[object z]",lN=Te,el=Dr,cN=Ne("toStringTag"),uN=Object,dN=el((function(){return arguments})())==="Arguments",er=oN?el: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=uN(e),cN))=="string"?i:dN?el(t):(r=el(t))==="Object"&&lN(t.callee)?"Arguments":r},hN=er,mN=String,St=function(e){if(hN(e)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return mN(e)},Ng=Ag,pN=Dt,Nr=function(e,t,i){return i.get&&Ng(i.get,t,{getter:!0}),i.set&&Ng(i.set,t,{setter:!0}),pN.f(e,t,i)},fN=Ee,_N=Me,tl=pe,gN=Xe,TN=Te,EN=Qi,vN=St,yN=Nr,SN=Rd,Ii=se.Symbol,Pr=Ii&&Ii.prototype;if(_N&&TN(Ii)&&(!("description"in Pr)||Ii().description!==void 0)){var Pg={},il=function(){var e=arguments.length<1||arguments[0]===void 0?void 0:vN(arguments[0]),t=EN(Pr,this)?new Ii(e):e===void 0?Ii():Ii(e);return e===""&&(Pg[t]=!0),t};SN(il,Ii),il.prototype=Pr,Pr.constructor=il;var IN=String(Ii("description detection"))==="Symbol(description detection)",AN=tl(Pr.valueOf),RN=tl(Pr.toString),CN=/^Symbol\((.*)\)[^)]+$/,bN=tl("".replace),kN=tl("".slice);yN(Pr,"description",{configurable:!0,get:function(){var e=AN(this);if(gN(Pg,e))return"";var t=RN(e),i=IN?kN(t,7,-1):bN(t,CN,"$1");return i===""?void 0:i}}),fN({global:!0,constructor:!0,forced:!0},{Symbol:il})}var Og={},DN=kg,wN=Id,Mg=Object.keys||function(e){return DN(e,wN)},NN=Me,PN=pg,ON=Dt,MN=lt,LN=Ls,xN=Mg;Og.f=NN&&!PN?Object.defineProperties:function(e,t){MN(e);for(var i,r=LN(t),n=xN(t),s=n.length,a=0;s>a;)ON.f(e,i=n[a++],r[i]);return e};var rl,Lg=yi("document","documentElement"),UN=lt,VN=Og,xg=Id,FN=_d,BN=Lg,HN=zo,bd="prototype",kd="script",Ug=fd("IE_PROTO"),Dd=function(){},Vg=function(e){return"<"+kd+">"+e+"</"+kd+">"},Fg=function(e){e.write(Vg("")),e.close();var t=e.parentWindow.Object;return e=null,t},nl=function(){try{rl=new ActiveXObject("htmlfile")}catch{}nl=typeof document<"u"?document.domain&&rl?Fg(rl):(function(){var t,i=HN("iframe"),r="java"+kd+":";return i.style.display="none",BN.appendChild(i),i.src=String(r),(t=i.contentWindow.document).open(),t.write(Vg("document.F=Object")),t.close(),t.F})():Fg(rl);for(var e=xg.length;e--;)delete nl[bd][xg[e]];return nl()};FN[Ug]=!0;var wn=Object.create||function(e,t){var i;return e!==null?(Dd[bd]=UN(e),i=new Dd,Dd[bd]=null,i[Ug]=e):i=nl(),t===void 0?i:VN.f(i,t)},WN=Ne,GN=wn,jN=Dt.f,wd=WN("unscopables"),Nd=Array.prototype;Nd[wd]===void 0&&jN(Nd,wd,{configurable:!0,value:GN(null)});var Bg=function(e){Nd[wd][e]=!0},zN=Cg.includes,JN=Bg;Ee({target:"Array",proto:!0,forced:de(function(){return!Array(1).includes()})},{includes:function(e){return zN(this,e,arguments.length>1?arguments[1]:void 0)}}),JN("includes");var Or,Hg,Wg,Fs={},KN=!de(function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}),qN=Xe,YN=Te,XN=Jt,QN=KN,Gg=fd("IE_PROTO"),Pd=Object,ZN=Pd.prototype,sl=QN?Pd.getPrototypeOf:function(e){var t=XN(e);if(qN(t,Gg))return t[Gg];var i=t.constructor;return YN(i)&&t instanceof i?i.prototype:t instanceof Pd?ZN:null},$N=de,eP=Te,tP=We,jg=sl,iP=wt,Od=Ne("iterator"),zg=!1;[].keys&&("next"in(Wg=[].keys())?(Hg=jg(jg(Wg)))!==Object.prototype&&(Or=Hg):zg=!0);var rP=!tP(Or)||$N(function(){var e={};return Or[Od].call(e)!==e});rP&&(Or={}),eP(Or[Od])||iP(Or,Od,function(){return this});var Md={IteratorPrototype:Or,BUGGY_SAFARI_ITERATORS:zg},nP=Dt.f,sP=Xe,Jg=Ne("toStringTag"),Mr=function(e,t,i){e&&!i&&(e=e.prototype),e&&!sP(e,Jg)&&nP(e,Jg,{configurable:!0,value:t})},aP=Md.IteratorPrototype,oP=wn,lP=Rn,cP=Mr,uP=Fs,dP=function(){return this},Kg=function(e,t,i,r){var n=t+" Iterator";return e.prototype=oP(aP,{next:lP(+!r,i)}),cP(e,n,!1),uP[n]=dP,e},hP=pe,mP=zt,pP=We,fP=function(e){return pP(e)||e===null},_P=String,gP=TypeError,TP=function(e,t,i){try{return hP(mP(Object.getOwnPropertyDescriptor(e,t)[i]))}catch{}},EP=We,vP=vi,yP=function(e){if(fP(e))return e;throw new gP("Can't set "+_P(e)+" as a prototype")},Nn=Object.setPrototypeOf||("__proto__"in{}?(function(){var e,t=!1,i={};try{(e=TP(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch{}return function(r,n){return vP(r),yP(n),EP(r)&&(t?e(r,n):r.__proto__=n),r}})():void 0),SP=Ee,IP=De,AP=Te,RP=Kg,qg=sl,Yg=Nn,CP=Mr,bP=Si,Ld=wt,kP=Fs,DP=kn.PROPER,wP=kn.CONFIGURABLE,Xg=Md.IteratorPrototype,al=Md.BUGGY_SAFARI_ITERATORS,Bs=Ne("iterator"),Qg="keys",Hs="values",Zg="entries",NP=function(){return this},$g=function(e,t,i,r,n,s,a){RP(i,t,r);var o,l,c,d=function(v){if(v===n&&T)return T;if(!al&&v&&v in p)return p[v];switch(v){case Qg:case Hs:case Zg:return function(){return new i(this,v)}}return function(){return new i(this)}},h=t+" Iterator",m=!1,p=e.prototype,f=p[Bs]||p["@@iterator"]||n&&p[n],T=!al&&f||d(n),E=t==="Array"&&p.entries||f;if(E&&(o=qg(E.call(new e)))!==Object.prototype&&o.next&&(qg(o)!==Xg&&(Yg?Yg(o,Xg):AP(o[Bs])||Ld(o,Bs,NP)),CP(o,h,!0)),DP&&n===Hs&&f&&f.name!==Hs&&(wP?bP(p,"name",Hs):(m=!0,T=function(){return IP(f,this)})),n)if(l={values:d(Hs),keys:s?T:d(Qg),entries:d(Zg)},a)for(c in l)(al||m||!(c in p))&&Ld(p,c,l[c]);else SP({target:t,proto:!0,forced:al||m},l);return p[Bs]!==T&&Ld(p,Bs,T,{name:n}),kP[t]=T,l},xd=function(e,t){return{value:e,done:t}},PP=Ls,Ud=Bg,eT=Fs,tT=gt,OP=Dt.f,MP=$g,ol=xd,LP=Me,iT="Array Iterator",xP=tT.set,UP=tT.getterFor(iT),VP=MP(Array,"Array",function(e,t){xP(this,{type:iT,target:PP(e),index:0,kind:t})},function(){var e=UP(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,ol(void 0,!0);switch(e.kind){case"keys":return ol(i,!1);case"values":return ol(t[i],!1)}return ol([i,t[i]],!1)},"values"),rT=eT.Arguments=eT.Array;if(Ud("keys"),Ud("values"),Ud("entries"),LP&&rT.name!=="values")try{OP(rT,"name",{value:"values"})}catch{}var FP=zt,BP=Jt,HP=Go,WP=ci,nT=TypeError,sT="Reduce of empty array with no initial value",aT=function(e){return function(t,i,r,n){var s=BP(t),a=HP(s),o=WP(s);if(FP(i),o===0&&r<2)throw new nT(sT);var l=e?o-1:0,c=e?-1:1;if(r<2)for(;;){if(l in a){n=a[l],l+=c;break}if(l+=c,e?l<0:o<=l)throw new nT(sT)}for(;e?l>=0:o>l;l+=c)l in a&&(n=i(n,a[l],l,s));return n}},oT={left:aT(!1),right:aT(!0)},GP=de,ll=function(e,t){var i=[][e];return!!i&&GP(function(){i.call(null,t||function(){return 1},1)})},Ws=se,jP=oi,zP=Dr,cl=function(e){return jP.slice(0,e.length)===e},Vd=cl("Bun/")?"BUN":cl("Cloudflare-Workers")?"CLOUDFLARE":cl("Deno/")?"DENO":cl("Node.js/")?"NODE":Ws.Bun&&typeof Bun.version=="string"?"BUN":Ws.Deno&&typeof Deno.version=="object"?"DENO":zP(Ws.process)==="process"?"NODE":Ws.window&&Ws.document?"BROWSER":"REST",Gs=Vd==="NODE",JP=oT.left;Ee({target:"Array",proto:!0,forced:!Gs&&Zi>79&&Zi<83||!ll("reduce")},{reduce:function(e){var t=arguments.length;return JP(this,e,t,t>1?arguments[1]:void 0)}});var KP=oT.right;Ee({target:"Array",proto:!0,forced:!Gs&&Zi>79&&Zi<83||!ll("reduceRight")},{reduceRight:function(e){return KP(this,e,arguments.length,arguments.length>1?arguments[1]:void 0)}});var qP=Dr,Fd=Array.isArray||function(e){return qP(e)==="Array"},YP=Ee,XP=Fd,QP=pe([].reverse),lT=[1,2];YP({target:"Array",proto:!0,forced:String(lT)===String(lT.reverse())},{reverse:function(){return XP(this)&&(this.length=this.length),QP(this)}});var cT=Cn,ZP=TypeError,js=pe([].slice),uT=js,$P=Math.floor,Bd=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 a=$P(i/2),o=Bd(uT(e,0,a),t),l=Bd(uT(e,a),t),c=o.length,d=l.length,h=0,m=0;h<c||m<d;)e[h+m]=h<c&&m<d?t(o[h],l[m])<=0?o[h++]:l[m++]:h<c?o[h++]:l[m++];return e},Hd=Bd,dT=oi.match(/firefox\/(\d+)/i),hT=!!dT&&+dT[1],mT=/MSIE|Trident/.test(oi),pT=oi.match(/AppleWebKit\/(\d+)\./),fT=!!pT&&+pT[1],eO=Ee,_T=pe,tO=zt,iO=Jt,gT=ci,rO=function(e,t){if(!delete e[t])throw new ZP("Cannot delete property "+cT(t)+" of "+cT(e))},TT=St,Wd=de,nO=Hd,sO=ll,ET=hT,aO=mT,vT=Zi,yT=fT,tr=[],ST=_T(tr.sort),oO=_T(tr.push),lO=Wd(function(){tr.sort(void 0)}),cO=Wd(function(){tr.sort(null)}),uO=sO("sort"),IT=!Wd(function(){if(vT)return vT<70;if(!(ET&&ET>3)){if(aO)return!0;if(yT)return yT<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++)tr.push({k:t+r,v:i})}for(tr.sort(function(s,a){return a.v-s.v}),r=0;r<tr.length;r++)t=tr[r].k.charAt(0),n.charAt(n.length-1)!==t&&(n+=t);return n!=="DGBEFHACIJK"}});eO({target:"Array",proto:!0,forced:lO||!cO||!uO||!IT},{sort:function(e){e!==void 0&&tO(e);var t=iO(this);if(IT)return e===void 0?ST(t):ST(t,e);var i,r,n=[],s=gT(t);for(r=0;r<s;r++)r in t&&oO(n,t[r]);for(nO(n,(function(a){return function(o,l){return l===void 0?-1:o===void 0?1:a!==void 0?+a(o,l)||0:TT(o)>TT(l)?1:-1}})(e)),i=gT(n),r=0;r<i;)t[r]=n[r++];for(;r<s;)rO(t,r++);return t}});var AT=typeof ArrayBuffer<"u"&&typeof DataView<"u",dO=wt,RT=function(e,t,i){for(var r in t)dO(e,r,t[r],i);return e},hO=Qi,mO=TypeError,zs=function(e,t){if(hO(t,e))return e;throw new mO("Incorrect invocation")},pO=$i,fO=wr,_O=RangeError,CT=function(e){if(e===void 0)return 0;var t=pO(e),i=fO(t);if(t!==i)throw new _O("Wrong length or index");return i},gO=Math.sign||function(e){var t=+e;return t===0||t!=t?t:t<0?-1:1},bT=4503599627370496,TO=gO,EO=function(e){return e+bT-bT},vO=Math.abs,yO=function(e,t,i,r){var n=+e,s=vO(n),a=TO(n);if(s<r)return a*EO(s/r/t)*r*t;var o=(1+t/2220446049250313e-31)*s,l=o-(o-s);return l>i||l!=l?1/0*a:a*l},SO=Math.fround||function(e){return yO(e,11920928955078125e-23,34028234663852886e22,11754943508222875e-54)},IO=Array,AO=Math.abs,Ai=Math.pow,RO=Math.floor,CO=Math.log,bO=Math.LN2,kO={pack:function(e,t,i){var r,n,s,a=IO(i),o=8*i-t-1,l=(1<<o)-1,c=l>>1,d=t===23?Ai(2,-24)-Ai(2,-77):0,h=e<0||e===0&&1/e<0?1:0,m=0;for((e=AO(e))!=e||e===1/0?(n=e!=e?1:0,r=l):(r=RO(CO(e)/bO),e*(s=Ai(2,-r))<1&&(r--,s*=2),(e+=r+c>=1?d/s:d*Ai(2,1-c))*s>=2&&(r++,s/=2),r+c>=l?(n=0,r=l):r+c>=1?(n=(e*s-1)*Ai(2,t),r+=c):(n=e*Ai(2,c-1)*Ai(2,t),r=0));t>=8;)a[m++]=255&n,n/=256,t-=8;for(r=r<<t|n,o+=t;o>0;)a[m++]=255&r,r/=256,o-=8;return a[m-1]|=128*h,a},unpack:function(e,t){var i,r=e.length,n=8*r-t-1,s=(1<<n)-1,a=s>>1,o=n-7,l=r-1,c=e[l--],d=127&c;for(c>>=7;o>0;)d=256*d+e[l--],o-=8;for(i=d&(1<<-o)-1,d>>=-o,o+=t;o>0;)i=256*i+e[l--],o-=8;if(d===0)d=1-a;else{if(d===s)return i?NaN:c?-1/0:1/0;i+=Ai(2,t),d-=a}return(c?-1:1)*i*Ai(2,d-t)}},DO=Jt,kT=Zo,wO=ci,DT=function(e){for(var t=DO(this),i=wO(t),r=arguments.length,n=kT(r>1?arguments[1]:void 0,i),s=r>2?arguments[2]:void 0,a=s===void 0?i:kT(s,i);a>n;)t[n++]=e;return t},NO=Te,PO=We,wT=Nn,Gd=function(e,t,i){var r,n;return wT&&NO(r=t.constructor)&&r!==i&&PO(n=r.prototype)&&n!==i.prototype&&wT(e,n),e},ul=se,jd=pe,zd=Me,OO=AT,MO=Si,LO=Nr,NT=RT,Jd=de,dl=zs,xO=$i,UO=wr,hl=CT,VO=SO,PT=kO,FO=sl,OT=Nn,BO=DT,HO=js,WO=Gd,GO=Rd,MT=Mr,Kd=gt,jO=kn.PROPER,LT=kn.CONFIGURABLE,Pn="ArrayBuffer",ml="DataView",On="prototype",xT="Wrong index",UT=Kd.getterFor(Pn),Js=Kd.getterFor(ml),VT=Kd.set,Kt=ul[Pn],qt=Kt,Mn=qt&&qt[On],Ri=ul[ml],Lr=Ri&&Ri[On],FT=Object.prototype,zO=ul.Array,pl=ul.RangeError,JO=jd(BO),KO=jd([].reverse),BT=PT.pack,HT=PT.unpack,WT=function(e){return[255&e]},GT=function(e){return[255&e,e>>8&255]},jT=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},zT=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},qO=function(e){return BT(VO(e),23,4)},YO=function(e){return BT(e,52,8)},fl=function(e,t,i){LO(e[On],t,{configurable:!0,get:function(){return i(this)[t]}})},ir=function(e,t,i,r){var n=Js(e),s=hl(i),a=!!r;if(s+t>n.byteLength)throw new pl(xT);var o=n.bytes,l=s+n.byteOffset,c=HO(o,l,l+t);return a?c:KO(c)},rr=function(e,t,i,r,n,s){var a=Js(e),o=hl(i),l=r(+n),c=!!s;if(o+t>a.byteLength)throw new pl(xT);for(var d=a.bytes,h=o+a.byteOffset,m=0;m<t;m++)d[h+m]=l[c?m:t-m-1]};if(OO){var JT=jO&&Kt.name!==Pn;Jd(function(){Kt(1)})&&Jd(function(){new Kt(-1)})&&!Jd(function(){return new Kt,new Kt(1.5),new Kt(NaN),Kt.length!==1||JT&&!LT})?JT&<&&MO(Kt,"name",Pn):((qt=function(e){return dl(this,Mn),WO(new Kt(hl(e)),this,qt)})[On]=Mn,Mn.constructor=qt,GO(qt,Kt)),OT&&FO(Lr)!==FT&&OT(Lr,FT);var _l=new Ri(new qt(2)),KT=jd(Lr.setInt8);_l.setInt8(0,2147483648),_l.setInt8(1,2147483649),!_l.getInt8(0)&&_l.getInt8(1)||NT(Lr,{setInt8:function(e,t){KT(this,e,t<<24>>24)},setUint8:function(e,t){KT(this,e,t<<24>>24)}},{unsafe:!0})}else Mn=(qt=function(e){dl(this,Mn);var t=hl(e);VT(this,{type:Pn,bytes:JO(zO(t),0),byteLength:t}),zd||(this.byteLength=t,this.detached=!1)})[On],Lr=(Ri=function(e,t,i){dl(this,Lr),dl(e,Mn);var r=UT(e),n=r.byteLength,s=xO(t);if(s<0||s>n)throw new pl("Wrong offset");if(s+(i=i===void 0?n-s:UO(i))>n)throw new pl("Wrong length");VT(this,{type:ml,buffer:e,byteLength:i,byteOffset:s,bytes:r.bytes}),zd||(this.buffer=e,this.byteLength=i,this.byteOffset=s)})[On],zd&&(fl(qt,"byteLength",UT),fl(Ri,"buffer",Js),fl(Ri,"byteLength",Js),fl(Ri,"byteOffset",Js)),NT(Lr,{getInt8:function(e){return ir(this,1,e)[0]<<24>>24},getUint8:function(e){return ir(this,1,e)[0]},getInt16:function(e){var t=ir(this,2,e,arguments.length>1&&arguments[1]);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=ir(this,2,e,arguments.length>1&&arguments[1]);return t[1]<<8|t[0]},getInt32:function(e){return zT(ir(this,4,e,arguments.length>1&&arguments[1]))},getUint32:function(e){return zT(ir(this,4,e,arguments.length>1&&arguments[1]))>>>0},getFloat32:function(e){return HT(ir(this,4,e,arguments.length>1&&arguments[1]),23)},getFloat64:function(e){return HT(ir(this,8,e,arguments.length>1&&arguments[1]),52)},setInt8:function(e,t){rr(this,1,e,WT,t)},setUint8:function(e,t){rr(this,1,e,WT,t)},setInt16:function(e,t){rr(this,2,e,GT,t,arguments.length>2&&arguments[2])},setUint16:function(e,t){rr(this,2,e,GT,t,arguments.length>2&&arguments[2])},setInt32:function(e,t){rr(this,4,e,jT,t,arguments.length>2&&arguments[2])},setUint32:function(e,t){rr(this,4,e,jT,t,arguments.length>2&&arguments[2])},setFloat32:function(e,t){rr(this,4,e,qO,t,arguments.length>2&&arguments[2])},setFloat64:function(e,t){rr(this,8,e,YO,t,arguments.length>2&&arguments[2])}});MT(qt,Pn),MT(Ri,ml);var gl={ArrayBuffer:qt,DataView:Ri},XO=yi,QO=Nr,ZO=Me,qT=Ne("species"),Tl=function(e){var t=XO(e);ZO&&t&&!t[qT]&&QO(t,qT,{configurable:!0,get:function(){return this}})},$O=Tl,qd="ArrayBuffer",YT=gl[qd];Ee({global:!0,constructor:!0,forced:se[qd]!==YT},{ArrayBuffer:YT}),$O(qd);var eM=Dr,tM=pe,El=function(e){if(eM(e)==="Function")return tM(e)},iM=Ee,Yd=El,rM=de,XT=lt,QT=Zo,nM=wr,Xd=gl.ArrayBuffer,Qd=gl.DataView,ZT=Qd.prototype,$T=Yd(Xd.prototype.slice),sM=Yd(ZT.getUint8),aM=Yd(ZT.setUint8);iM({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:rM(function(){return!new Xd(2).slice(1,void 0).byteLength})},{slice:function(e,t){if($T&&t===void 0)return $T(XT(this),e);for(var i=XT(this).byteLength,r=QT(e,i),n=QT(t===void 0?i:t,i),s=new Xd(nM(n-r)),a=new Qd(this),o=new Qd(s),l=0;r<n;)aM(o,l++,sM(a,r++));return s}});var oM=se,lM=pe,cM=de,eE=Te,uM=er,dM=pd,tE=function(){},iE=yi("Reflect","construct"),Zd=/^\s*(?:class|function)\b/,hM=lM(Zd.exec),mM=!Zd.test(tE),Ks=function(e){if(!eE(e))return!1;try{return iE(tE,[],e),!0}catch{return!1}},rE=function(e){if(!eE(e))return!1;switch(uM(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return mM||!!hM(Zd,dM(e))}catch{return!0}};rE.sham=!0;var qs,Ln,nE,$d,eh=!iE||cM(function(){var e;return Ks(Ks.call)||!Ks(Object)||!Ks(function(){e=!0})||e})?rE:Ks,pM=eh,fM=Cn,_M=TypeError,sE=function(e){if(pM(e))return e;throw new _M(fM(e)+" is not a constructor")},aE=lt,gM=sE,TM=jo,EM=Ne("species"),oE=function(e,t){var i,r=aE(e).constructor;return r===void 0||TM(i=aE(r)[EM])?t:gM(i)},vM=Bo,lE=Function.prototype,cE=lE.apply,uE=lE.call,th=typeof Reflect=="object"&&Reflect.apply||(vM?uE.bind(cE):function(){return uE.apply(cE,arguments)}),yM=zt,SM=Bo,IM=El(El.bind),nr=function(e,t){return yM(e),t===void 0?e:SM?IM(e,t):function(){return e.apply(t,arguments)}},AM=TypeError,vl=function(e,t){if(e<t)throw new AM("Not enough arguments");return e},dE=/(?:ipad|iphone|ipod).*applewebkit/i.test(oi),It=se,RM=th,CM=nr,hE=Te,bM=Xe,mE=de,pE=Lg,kM=js,fE=zo,DM=vl,wM=dE,NM=Gs,ih=It.setImmediate,rh=It.clearImmediate,PM=It.process,nh=It.Dispatch,OM=It.Function,_E=It.MessageChannel,MM=It.String,sh=0,Ys={},gE="onreadystatechange";mE(function(){qs=It.location});var ah=function(e){if(bM(Ys,e)){var t=Ys[e];delete Ys[e],t()}},oh=function(e){return function(){ah(e)}},TE=function(e){ah(e.data)},EE=function(e){It.postMessage(MM(e),qs.protocol+"//"+qs.host)};ih&&rh||(ih=function(e){DM(arguments.length,1);var t=hE(e)?e:OM(e),i=kM(arguments,1);return Ys[++sh]=function(){RM(t,void 0,i)},Ln(sh),sh},rh=function(e){delete Ys[e]},NM?Ln=function(e){PM.nextTick(oh(e))}:nh&&nh.now?Ln=function(e){nh.now(oh(e))}:_E&&!wM?($d=(nE=new _E).port2,nE.port1.onmessage=TE,Ln=CM($d.postMessage,$d)):It.addEventListener&&hE(It.postMessage)&&!It.importScripts&&qs&&qs.protocol!=="file:"&&!mE(EE)?(Ln=EE,It.addEventListener("message",TE,!1)):Ln=gE in fE("script")?function(e){pE.appendChild(fE("script"))[gE]=function(){pE.removeChild(this),ah(e)}}:function(e){setTimeout(oh(e),0)});var yl={set:ih,clear:rh},vE=se,LM=Me,xM=Object.getOwnPropertyDescriptor,yE=function(e){if(!LM)return vE[e];var t=xM(vE,e);return t&&t.value},SE=function(){this.head=null,this.tail=null};SE.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 xn,lh,ch,uh,IE,AE=SE,UM=/ipad|iphone|ipod/i.test(oi)&&typeof Pebble<"u",VM=/web0s(?!.*chrome)/i.test(oi),Un=se,FM=yE,RE=nr,dh=yl.set,BM=AE,HM=dE,WM=UM,GM=VM,hh=Gs,CE=Un.MutationObserver||Un.WebKitMutationObserver,bE=Un.document,kE=Un.process,Sl=Un.Promise,mh=FM("queueMicrotask");if(!mh){var Il=new BM,Al=function(){var e,t;for(hh&&(e=kE.domain)&&e.exit();t=Il.get();)try{t()}catch(i){throw Il.head&&xn(),i}e&&e.enter()};HM||hh||GM||!CE||!bE?!WM&&Sl&&Sl.resolve?((uh=Sl.resolve(void 0)).constructor=Sl,IE=RE(uh.then,uh),xn=function(){IE(Al)}):hh?xn=function(){kE.nextTick(Al)}:(dh=RE(dh,Un),xn=function(){dh(Al)}):(lh=!0,ch=bE.createTextNode(""),new CE(Al).observe(ch,{characterData:!0}),xn=function(){ch.data=lh=!lh}),mh=function(e){Il.head||xn(),Il.add(e)}}var jM=mh,ph=function(e){try{return{error:!1,value:e()}}catch(t){return{error:!0,value:t}}},Xs=se.Promise,zM=se,Qs=Xs,JM=Te,KM=Cd,qM=pd,YM=Ne,DE=Vd,fh=Zi;Qs&&Qs.prototype;var XM=YM("species"),wE=!1,NE=JM(zM.PromiseRejectionEvent),QM=KM("Promise",function(){var e=qM(Qs),t=e!==String(Qs);if(!t&&fh===66)return!0;if(!fh||fh<51||!/native code/.test(e)){var i=new Qs(function(n){n(1)}),r=function(n){n(function(){},function(){})};if((i.constructor={})[XM]=r,!(wE=i.then(function(){})instanceof r))return!0}return!(t||DE!=="BROWSER"&&DE!=="DENO"||NE)}),xr={CONSTRUCTOR:QM,REJECTION_EVENT:NE,SUBCLASSING:wE},Vn={},PE=zt,ZM=TypeError,$M=function(e){var t,i;this.promise=new e(function(r,n){if(t!==void 0||i!==void 0)throw new ZM("Bad Promise constructor");t=r,i=n}),this.resolve=PE(t),this.reject=PE(i)};Vn.f=function(e){return new $M(e)};var _h,OE,ME,LE,eL=Ee,Rl=Gs,sr=se,tL=oM,Fn=De,xE=wt,UE=Nn,iL=Mr,rL=Tl,nL=zt,Cl=Te,sL=We,aL=zs,oL=oE,VE=yl.set,gh=jM,lL=function(e,t){try{arguments.length===1?console.error(e):console.error(e,t)}catch{}},cL=ph,uL=AE,FE=gt,bl=Xs,BE=Vn,kl="Promise",HE=xr.CONSTRUCTOR,dL=xr.REJECTION_EVENT,hL=xr.SUBCLASSING,Th=FE.getterFor(kl),mL=FE.set,Bn=bl&&bl.prototype,Hn=bl,Dl=Bn,WE=sr.TypeError,Eh=sr.document,vh=sr.process,yh=BE.f,pL=yh,fL=!!(Eh&&Eh.createEvent&&sr.dispatchEvent),GE="unhandledrejection",jE=function(e){var t;return!(!sL(e)||!Cl(t=e.then))&&t},zE=function(e,t){var i,r,n,s=t.value,a=t.state===1,o=a?e.ok:e.fail,l=e.resolve,c=e.reject,d=e.domain;try{o?(a||(t.rejection===2&&gL(t),t.rejection=1),o===!0?i=s:(d&&d.enter(),i=o(s),d&&(d.exit(),n=!0)),i===e.promise?c(new WE("Promise-chain cycle")):(r=jE(i))?Fn(r,i,l,c):l(i)):c(s)}catch(h){d&&!n&&d.exit(),c(h)}},JE=function(e,t){e.notified||(e.notified=!0,gh(function(){for(var i,r=e.reactions;i=r.get();)zE(i,e);e.notified=!1,t&&!e.rejection&&_L(e)}))},KE=function(e,t,i){var r,n;fL?((r=Eh.createEvent("Event")).promise=t,r.reason=i,r.initEvent(e,!1,!0),sr.dispatchEvent(r)):r={promise:t,reason:i},!dL&&(n=sr["on"+e])?n(r):e===GE&&lL("Unhandled promise rejection",i)},_L=function(e){Fn(VE,sr,function(){var t,i=e.facade,r=e.value;if(qE(e)&&(t=cL(function(){Rl?vh.emit("unhandledRejection",r,i):KE(GE,i,r)}),e.rejection=Rl||qE(e)?2:1,t.error))throw t.value})},qE=function(e){return e.rejection!==1&&!e.parent},gL=function(e){Fn(VE,sr,function(){var t=e.facade;Rl?vh.emit("rejectionHandled",t):KE("rejectionhandled",t,e.value)})},Wn=function(e,t,i){return function(r){e(t,r,i)}},Gn=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,JE(e,!0))},Sh=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw new WE("Promise can't be resolved itself");var r=jE(t);r?gh(function(){var n={done:!1};try{Fn(r,t,Wn(Sh,n,e),Wn(Gn,n,e))}catch(s){Gn(n,s,e)}}):(e.value=t,e.state=1,JE(e,!1))}catch(n){Gn({done:!1},n,e)}}};if(HE&&(Dl=(Hn=function(e){aL(this,Dl),nL(e),Fn(_h,this);var t=Th(this);try{e(Wn(Sh,t),Wn(Gn,t))}catch(i){Gn(t,i)}}).prototype,(_h=function(e){mL(this,{type:kl,done:!1,notified:!1,parent:!1,reactions:new uL,rejection:!1,state:0,value:null})}).prototype=xE(Dl,"then",function(e,t){var i=Th(this),r=yh(oL(this,Hn));return i.parent=!0,r.ok=!Cl(e)||e,r.fail=Cl(t)&&t,r.domain=Rl?vh.domain:void 0,i.state===0?i.reactions.add(r):gh(function(){zE(r,i)}),r.promise}),OE=function(){var e=new _h,t=Th(e);this.promise=e,this.resolve=Wn(Sh,t),this.reject=Wn(Gn,t)},BE.f=yh=function(e){return e===Hn||e===ME?new OE(e):pL(e)},Cl(bl)&&Bn!==Object.prototype)){LE=Bn.then,hL||xE(Bn,"then",function(e,t){var i=this;return new Hn(function(r,n){Fn(LE,i,r,n)}).then(e,t)},{unsafe:!0});try{delete Bn.constructor}catch{}UE&&UE(Bn,Dl)}eL({global:!0,constructor:!0,wrap:!0,forced:HE},{Promise:Hn}),ME=tL.Promise,iL(Hn,kl,!1),rL(kl);var TL=Fs,EL=Ne("iterator"),vL=Array.prototype,Ih=function(e){return e!==void 0&&(TL.Array===e||vL[EL]===e)},yL=er,YE=xs,SL=jo,IL=Fs,AL=Ne("iterator"),Zs=function(e){if(!SL(e))return YE(e,AL)||YE(e,"@@iterator")||IL[yL(e)]},RL=De,CL=zt,bL=lt,kL=Cn,DL=Zs,wL=TypeError,wl=function(e,t){var i=arguments.length<2?DL(e):t;if(CL(i))return bL(RL(i,e));throw new wL(kL(e)+" is not iterable")},NL=De,XE=lt,PL=xs,QE=function(e,t,i){var r,n;XE(e);try{if(!(r=PL(e,"return"))){if(t==="throw")throw i;return i}r=NL(r,e)}catch(s){n=!0,r=s}if(t==="throw")throw i;if(n)throw r;return XE(r),i},OL=nr,ML=De,LL=lt,xL=Cn,UL=Ih,VL=ci,ZE=Qi,FL=wl,BL=Zs,$E=QE,HL=TypeError,Nl=function(e,t){this.stopped=e,this.result=t},ev=Nl.prototype,tv=function(e,t,i){var r,n,s,a,o,l,c,d=i&&i.that,h=!(!i||!i.AS_ENTRIES),m=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),f=!(!i||!i.INTERRUPTED),T=OL(t,d),E=function(y){return r&&$E(r,"normal"),new Nl(!0,y)},v=function(y){return h?(LL(y),f?T(y[0],y[1],E):T(y[0],y[1])):f?T(y,E):T(y)};if(m)r=e.iterator;else if(p)r=e;else{if(!(n=BL(e)))throw new HL(xL(e)+" is not iterable");if(UL(n)){for(s=0,a=VL(e);a>s;s++)if((o=v(e[s]))&&ZE(ev,o))return o;return new Nl(!1)}r=FL(e,n)}for(l=m?e.next:r.next;!(c=ML(l,r)).done;){try{o=v(c.value)}catch(y){$E(r,"throw",y)}if(typeof o=="object"&&o&&ZE(ev,o))return o}return new Nl(!1)},iv=Ne("iterator"),rv=!1;try{var WL=0,nv={next:function(){return{done:!!WL++}},return:function(){rv=!0}};nv[iv]=function(){return this},Array.from(nv,function(){throw 2})}catch{}var sv=function(e,t){try{if(!t&&!rv)return!1}catch{return!1}var i=!1;try{var r={};r[iv]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch{}return i},GL=Xs,av=xr.CONSTRUCTOR||!sv(function(e){GL.all(e).then(void 0,function(){})}),jL=De,zL=zt,JL=Vn,KL=ph,qL=tv;Ee({target:"Promise",stat:!0,forced:av},{all:function(e){var t=this,i=JL.f(t),r=i.resolve,n=i.reject,s=KL(function(){var a=zL(t.resolve),o=[],l=0,c=1;qL(e,function(d){var h=l++,m=!1;c++,jL(a,t,d).then(function(p){m||(m=!0,o[h]=p,--c||r(o))},n)}),--c||r(o)});return s.error&&n(s.value),i.promise}});var YL=Ee,XL=xr.CONSTRUCTOR,Ah=Xs,QL=yi,ZL=Te,$L=wt,ov=Ah&&Ah.prototype;if(YL({target:"Promise",proto:!0,forced:XL,real:!0},{catch:function(e){return this.then(void 0,e)}}),ZL(Ah)){var lv=QL("Promise").prototype.catch;ov.catch!==lv&&$L(ov,"catch",lv,{unsafe:!0})}var ex=De,tx=zt,ix=Vn,rx=ph,nx=tv;Ee({target:"Promise",stat:!0,forced:av},{race:function(e){var t=this,i=ix.f(t),r=i.reject,n=rx(function(){var s=tx(t.resolve);nx(e,function(a){ex(s,t,a).then(i.resolve,r)})});return n.error&&r(n.value),i.promise}});var sx=Vn;Ee({target:"Promise",stat:!0,forced:xr.CONSTRUCTOR},{reject:function(e){var t=sx.f(this);return(0,t.reject)(e),t.promise}});var ax=lt,ox=We,lx=Vn,cv=function(e,t){if(ax(e),ox(t)&&t.constructor===e)return t;var i=lx.f(e);return(0,i.resolve)(t),i.promise},cx=Ee,ux=xr.CONSTRUCTOR,dx=cv;yi("Promise"),cx({target:"Promise",stat:!0,forced:ux},{resolve:function(e){return dx(this,e)}});var hx=Ee,Pl=Xs,mx=de,uv=yi,dv=Te,px=oE,hv=cv,fx=wt,Rh=Pl&&Pl.prototype;if(hx({target:"Promise",proto:!0,real:!0,forced:!!Pl&&mx(function(){Rh.finally.call({then:function(){}},function(){})})},{finally:function(e){var t=px(this,uv("Promise")),i=dv(e);return this.then(i?function(r){return hv(t,e()).then(function(){return r})}:e,i?function(r){return hv(t,e()).then(function(){throw r})}:e)}}),dv(Pl)){var mv=uv("Promise").prototype.finally;Rh.finally!==mv&&fx(Rh,"finally",mv,{unsafe:!0})}var _x=We,gx=Dr,Tx=Ne("match"),pv=function(e){var t;return _x(e)&&((t=e[Tx])!==void 0?!!t:gx(e)==="RegExp")},Ex=de,fv=se.RegExp,vx=!Ex(function(){var e=!0;try{fv(".","d")}catch{e=!1}var t={},i="",r=e?"dgimsy":"gimsy",n=function(o,l){Object.defineProperty(t,o,{get:function(){return i+=l,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};for(var a in e&&(s.hasIndices="d"),s)n(a,s[a]);return Object.getOwnPropertyDescriptor(fv.prototype,"flags").get.call(t)!==r||i!==r}),yx=lt,_v=function(){var e=yx(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},Sx=De,Ix=Xe,Ax=Qi,gv={correct:vx},Rx=_v,Cx=RegExp.prototype,Ch=gv.correct?function(e){return e.flags}:function(e){return gv.correct||!Ax(Cx,e)||Ix(e,"flags")?e.flags:Sx(Rx,e)},bh=de,kh=se.RegExp,Dh=bh(function(){var e=kh("a","y");return e.lastIndex=2,e.exec("abcd")!==null}),bx=Dh||bh(function(){return!kh("a","y").sticky}),kx=Dh||bh(function(){var e=kh("^r","gy");return e.lastIndex=2,e.exec("str")!==null}),Tv={BROKEN_CARET:kx,MISSED_STICKY:bx,UNSUPPORTED_Y:Dh},Dx=Dt.f,wx=de,Nx=se.RegExp,Ev=wx(function(){var e=Nx(".","s");return!(e.dotAll&&e.test(`
|
||
`)&&e.flags==="s")}),Px=de,Ox=se.RegExp,vv=Px(function(){var e=Ox("(?<a>b)","g");return e.exec("b").groups.a!=="b"||"b".replace(e,"$<a>c")!=="bc"}),Mx=Me,wh=se,$s=pe,Lx=Cd,xx=Gd,Ux=Si,Vx=wn,Fx=Qo.f,yv=Qi,Bx=pv,Sv=St,Hx=Ch,Iv=Tv,Wx=function(e,t,i){i in e||Dx(e,i,{configurable:!0,get:function(){return t[i]},set:function(r){t[i]=r}})},Gx=wt,jx=de,zx=Xe,Jx=gt.enforce,Kx=Tl,Av=Ev,Rv=vv,qx=Ne("match"),ar=wh.RegExp,jn=ar.prototype,Yx=wh.SyntaxError,Xx=$s(jn.exec),Ol=$s("".charAt),Cv=$s("".replace),bv=$s("".indexOf),kv=$s("".slice),Qx=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,Ur=/a/g,Nh=/a/g,Zx=new ar(Ur)!==Ur,Dv=Iv.MISSED_STICKY,$x=Iv.UNSUPPORTED_Y,eU=Mx&&(!Zx||Dv||Av||Rv||jx(function(){return Nh[qx]=!1,ar(Ur)!==Ur||ar(Nh)===Nh||String(ar(Ur,"i"))!=="/a/i"}));if(Lx("RegExp",eU)){for(var Vr=function(e,t){var i,r,n,s,a,o,l=yv(jn,this),c=Bx(e),d=t===void 0,h=[],m=e;if(!l&&c&&d&&e.constructor===Vr)return e;if((c||yv(jn,e))&&(e=e.source,d&&(t=Hx(m))),e=e===void 0?"":Sv(e),t=t===void 0?"":Sv(t),m=e,Av&&"dotAll"in Ur&&(r=!!t&&bv(t,"s")>-1)&&(t=Cv(t,/s/g,"")),i=t,Dv&&"sticky"in Ur&&(n=!!t&&bv(t,"y")>-1)&&$x&&(t=Cv(t,/y/g,"")),Rv&&(s=(function(p){for(var f,T=p.length,E=0,v="",y=[],D=Vx(null),N=!1,S=!1,A=0,L="";E<T;E++){if((f=Ol(p,E))==="\\")f+=Ol(p,++E);else if(f==="]")N=!1;else if(!N)switch(!0){case f==="[":N=!0;break;case f==="(":if(v+=f,kv(p,E+1,E+3)==="?:")continue;Xx(Qx,kv(p,E+1))&&(E+=2,S=!0),A++;continue;case(f===">"&&S):if(L===""||zx(D,L))throw new Yx("Invalid capture group name");D[L]=!0,y[y.length]=[L,A],S=!1,L="";continue}S?L+=f:v+=f}return[v,y]})(e),e=s[0],h=s[1]),a=xx(ar(e,t),l?this:jn,Vr),(r||n||h.length)&&(o=Jx(a),r&&(o.dotAll=!0,o.raw=Vr((function(p){for(var f,T=p.length,E=0,v="",y=!1;E<T;E++)(f=Ol(p,E))!=="\\"?y||f!=="."?(f==="["?y=!0:f==="]"&&(y=!1),v+=f):v+="[\\s\\S]":v+=f+Ol(p,++E);return v})(e),i)),n&&(o.sticky=!0),h.length&&(o.groups=h)),e!==m)try{Ux(a,"source",m===""?"(?:)":m)}catch{}return a},wv=Fx(ar),Nv=0;wv.length>Nv;)Wx(Vr,ar,wv[Nv++]);jn.constructor=Vr,Vr.prototype=jn,Gx(wh,"RegExp",Vr,{constructor:!0})}Kx("RegExp");var zn=De,Ml=pe,tU=St,iU=_v,rU=Tv,nU=wn,sU=gt.get,aU=Ev,oU=vv,lU=rd("native-string-replace",String.prototype.replace),Ll=RegExp.prototype.exec,Ph=Ll,cU=Ml("".charAt),uU=Ml("".indexOf),dU=Ml("".replace),Oh=Ml("".slice),Mh=(function(){var e=/a/,t=/b*/g;return zn(Ll,e,"a"),zn(Ll,t,"a"),e.lastIndex!==0||t.lastIndex!==0})(),Pv=rU.BROKEN_CARET,Lh=/()??/.exec("")[1]!==void 0;(Mh||Lh||Pv||aU||oU)&&(Ph=function(e){var t,i,r,n,s,a,o,l=this,c=sU(l),d=tU(e),h=c.raw;if(h)return h.lastIndex=l.lastIndex,t=zn(Ph,h,d),l.lastIndex=h.lastIndex,t;var m=c.groups,p=Pv&&l.sticky,f=zn(iU,l),T=l.source,E=0,v=d;if(p&&(f=dU(f,"y",""),uU(f,"g")===-1&&(f+="g"),v=Oh(d,l.lastIndex),l.lastIndex>0&&(!l.multiline||l.multiline&&cU(d,l.lastIndex-1)!==`
|
||
`)&&(T="(?: "+T+")",v=" "+v,E++),i=new RegExp("^(?:"+T+")",f)),Lh&&(i=new RegExp("^"+T+"$(?!\\s)",f)),Mh&&(r=l.lastIndex),n=zn(Ll,p?i:l,v),p?n?(n.input=Oh(n.input,E),n[0]=Oh(n[0],E),n.index=l.lastIndex,l.lastIndex+=n[0].length):l.lastIndex=0:Mh&&n&&(l.lastIndex=l.global?n.index+n[0].length:r),Lh&&n&&n.length>1&&zn(lU,n[0],i,function(){for(s=1;s<arguments.length-2;s++)arguments[s]===void 0&&(n[s]=void 0)}),n&&m)for(n.groups=a=nU(null),s=0;s<m.length;s++)a[(o=m[s])[0]]=n[o[1]];return n});var xl=Ph;Ee({target:"RegExp",proto:!0,forced:/./.exec!==xl},{exec:xl});var hU=$i,mU=St,pU=vi,fU=RangeError,Ov=pe,_U=wr,Mv=St,gU=function(e){var t=mU(pU(this)),i="",r=hU(e);if(r<0||r===1/0)throw new fU("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(i+=t);return i},TU=vi,EU=Ov(gU),vU=Ov("".slice),yU=Math.ceil,Lv=function(e){return function(t,i,r){var n,s,a=Mv(TU(t)),o=_U(i),l=a.length,c=r===void 0?" ":Mv(r);return o<=l||c===""?a:((s=EU(c,yU((n=o-l)/c.length))).length>n&&(s=vU(s,0,n)),e?a+s:s+a)}},xv={start:Lv(!1),end:Lv(!0)},Uv=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(oi),SU=xv.end;Ee({target:"String",proto:!0,forced:Uv},{padEnd:function(e){return SU(this,e,arguments.length>1?arguments[1]:void 0)}});var IU=xv.start;Ee({target:"String",proto:!0,forced:Uv},{padStart:function(e){return IU(this,e,arguments.length>1?arguments[1]:void 0)}});var Vv=De,Fv=wt,AU=xl,Bv=de,Hv=Ne,CW=Hv("species"),Wv=RegExp.prototype,xh=pe,RU=$i,CU=St,bU=vi,kU=xh("".charAt),Gv=xh("".charCodeAt),DU=xh("".slice),jv=function(e){return function(t,i){var r,n,s=CU(bU(t)),a=RU(i),o=s.length;return a<0||a>=o?e?"":void 0:(r=Gv(s,a))<55296||r>56319||a+1===o||(n=Gv(s,a+1))<56320||n>57343?e?kU(s,a):r:e?DU(s,a,a+2):n-56320+(r-55296<<10)+65536}},Uh={codeAt:jv(!1),charAt:jv(!0)},wU=Uh.charAt,Vh=pe,NU=Jt,PU=Math.floor,Fh=Vh("".charAt),OU=Vh("".replace),Bh=Vh("".slice),MU=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,LU=/\$([$&'`]|\d{1,2})/g,zv=function(e,t,i,r,n,s){var a=i+e.length,o=r.length,l=LU;return n!==void 0&&(n=NU(n),l=MU),OU(s,l,function(c,d){var h;switch(Fh(d,0)){case"$":return"$";case"&":return e;case"`":return Bh(t,0,i);case"'":return Bh(t,a);case"<":h=n[Bh(d,1,-1)];break;default:var m=+d;if(m===0)return c;if(m>o){var p=PU(m/10);return p===0?c:p<=o?r[p-1]===void 0?Fh(d,1):r[p-1]+Fh(d,1):c}h=r[m-1]}return h===void 0?"":h})},Jv=De,xU=lt,UU=Te,VU=Dr,FU=xl,BU=TypeError,HU=th,Kv=De,Ul=pe,WU=function(e,t,i,r){var n=Hv(e),s=!Bv(function(){var c={};return c[n]=function(){return 7},""[e](c)!==7}),a=s&&!Bv(function(){var c=!1,d=/a/,h;return d.exec=function(){return c=!0,null},d[n](""),!c});if(!s||!a||i){var o=/./[n],l=t(n,""[e],function(c,d,h,m,p){var f=d.exec;return f===AU||f===Wv.exec?s&&!p?{done:!0,value:Vv(o,d,h,m)}:{done:!0,value:Vv(c,h,d,m)}:{done:!1}});Fv(String.prototype,e,l[0]),Fv(Wv,n,l[1])}},GU=de,jU=lt,zU=Te,JU=We,KU=$i,qU=wr,Fr=St,YU=vi,XU=function(e,t,i){return t+(i?wU(e,t).length:1)},QU=xs,ZU=zv,$U=Ch,eV=function(e,t){var i=e.exec;if(UU(i)){var r=Jv(i,e,t);return r!==null&&xU(r),r}if(VU(e)==="RegExp")return Jv(FU,e,t);throw new BU("RegExp#exec called on incompatible receiver")},Hh=Ne("replace"),tV=Math.max,iV=Math.min,rV=Ul([].concat),Wh=Ul([].push),Vl=Ul("".indexOf),qv=Ul("".slice),nV=function(e){return e===void 0?e:String(e)},sV="a".replace(/./,"$0")==="$0",Yv=!!/./[Hh]&&/./[Hh]("a","$0")==="",aV=!GU(function(){var e=/./;return e.exec=function(){var t=[];return t.groups={a:"7"},t},"".replace(e,"$<a>")!=="7"});WU("replace",function(e,t,i){var r=Yv?"$":"$0";return[function(n,s){var a=YU(this),o=JU(n)?QU(n,Hh):void 0;return o?Kv(o,n,a,s):Kv(t,Fr(a),n,s)},function(n,s){var a=jU(this),o=Fr(n);if(typeof s=="string"&&Vl(s,r)===-1&&Vl(s,"$<")===-1){var l=i(t,a,o,s);if(l.done)return l.value}var c=zU(s);c||(s=Fr(s));var d,h=Fr($U(a)),m=Vl(h,"g")!==-1;m&&(d=Vl(h,"u")!==-1,a.lastIndex=0);for(var p,f=[];(p=eV(a,o))!==null&&(Wh(f,p),m);)Fr(p[0])===""&&(a.lastIndex=XU(o,qU(a.lastIndex),d));for(var T="",E=0,v=0;v<f.length;v++){for(var y,D=Fr((p=f[v])[0]),N=tV(iV(KU(p.index),o.length),0),S=[],A=1;A<p.length;A++)Wh(S,nV(p[A]));var L=p.groups;if(c){var U=rV([D],S,N,o);L!==void 0&&Wh(U,L),y=Fr(HU(s,void 0,U))}else y=ZU(D,o,N,S,L,s);N>=E&&(T+=qv(o,E,N)+y,E=N+D.length)}return T+qv(o,E)}]},!aV||!sV||Yv);var Xv=`
|
||
\v\f\r \u2028\u2029\uFEFF`,oV=vi,lV=St,Gh=Xv,Qv=pe("".replace),cV=RegExp("^["+Gh+"]+"),uV=RegExp("(^|[^"+Gh+"])["+Gh+"]+$"),dV=function(e){return function(t){var i=lV(oV(t));return 1&e&&(i=Qv(i,cV,"")),2&e&&(i=Qv(i,uV,"$1")),i}},hV={trim:dV(3)},mV=kn.PROPER,pV=de,Zv=Xv,fV=hV.trim;Ee({target:"String",proto:!0,forced:(function(e){return pV(function(){return!!Zv[e]()||"
"[e]()!=="
"||mV&&Zv[e].name!==e})})("trim")},{trim:function(){return fV(this)}});var Tt,Jn,Fl,jh={exports:{}},_V=AT,zh=Me,ct=se,$v=Te,ey=We,ea=Xe,ty=er,gV=Cn,TV=Si,Jh=wt,EV=Nr,vV=Qi,Kh=sl,Kn=Nn,yV=Ne,SV=nd,iy=gt.enforce,Bl=ct.Int8Array,qh=Bl&&Bl.prototype,ry=ct.Uint8ClampedArray,ny=ry&&ry.prototype,ui=Bl&&Kh(Bl),Yt=qh&&Kh(qh),IV=Object.prototype,Yh=ct.TypeError,sy=yV("toStringTag"),Xh=SV("TYPED_ARRAY_TAG"),ay="TypedArrayConstructor",Ci=_V&&!!Kn&&ty(ct.opera)!=="Opera",oy=!1,or={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},ly={BigInt64Array:8,BigUint64Array:8},cy=function(e){if(!ey(e))return!1;var t=ty(e);return ea(or,t)||ea(ly,t)};for(Tt in or)(Fl=(Jn=ct[Tt])&&Jn.prototype)?iy(Fl)[ay]=Jn:Ci=!1;for(Tt in ly)(Fl=(Jn=ct[Tt])&&Jn.prototype)&&(iy(Fl)[ay]=Jn);if((!Ci||!$v(ui)||ui===Function.prototype)&&(ui=function(){throw new Yh("Incorrect invocation")},Ci))for(Tt in or)ct[Tt]&&Kn(ct[Tt],ui);if((!Ci||!Yt||Yt===IV)&&(Yt=ui.prototype,Ci))for(Tt in or)ct[Tt]&&Kn(ct[Tt].prototype,Yt);if(Ci&&Kh(ny)!==Yt&&Kn(ny,Yt),zh&&!ea(Yt,sy))for(Tt in oy=!0,EV(Yt,sy,{configurable:!0,get:function(){return ey(this)?this[Xh]:void 0}}),or)ct[Tt]&&TV(ct[Tt],Xh,Tt);var bi={NATIVE_ARRAY_BUFFER_VIEWS:Ci,TYPED_ARRAY_TAG:oy&&Xh,aTypedArray:function(e){if(cy(e))return e;throw new Yh("Target is not a typed array")},aTypedArrayConstructor:function(e){if($v(e)&&(!Kn||vV(ui,e)))return e;throw new Yh(gV(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,i,r){if(zh){if(i)for(var n in or){var s=ct[n];if(s&&ea(s.prototype,e))try{delete s.prototype[e]}catch{try{s.prototype[e]=t}catch{}}}Yt[e]&&!i||Jh(Yt,e,i?t:Ci&&qh[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,i){var r,n;if(zh){if(Kn){if(i){for(r in or)if((n=ct[r])&&ea(n,e))try{delete n[e]}catch{}}if(ui[e]&&!i)return;try{return Jh(ui,e,i?t:Ci&&ui[e]||t)}catch{}}for(r in or)!(n=ct[r])||n[e]&&!i||Jh(n,e,t)}},isTypedArray:cy,TypedArray:ui,TypedArrayPrototype:Yt},uy=se,Qh=de,AV=sv,RV=bi.NATIVE_ARRAY_BUFFER_VIEWS,CV=uy.ArrayBuffer,Br=uy.Int8Array,dy=!RV||!Qh(function(){Br(1)})||!Qh(function(){new Br(-1)})||!AV(function(e){new Br,new Br(null),new Br(1.5),new Br(e)},!0)||Qh(function(){return new Br(new CV(2),1,void 0).length!==1}),bV=We,kV=Math.floor,DV=Number.isInteger||function(e){return!bV(e)&&isFinite(e)&&kV(e)===e},wV=$i,NV=RangeError,PV=function(e){var t=wV(e);if(t<0)throw new NV("The argument can't be less than 0");return t},OV=RangeError,hy=function(e,t){var i=PV(e);if(i%t)throw new OV("Wrong offset");return i},MV=Math.round,LV=er,xV=ug,UV=TypeError,my=function(e){var t=xV(e,"number");if(typeof t=="number")throw new UV("Can't convert number to bigint");return BigInt(t)},VV=nr,FV=De,BV=sE,HV=Jt,WV=ci,GV=wl,jV=Zs,zV=Ih,JV=function(e){var t=LV(e);return t==="BigInt64Array"||t==="BigUint64Array"},KV=bi.aTypedArrayConstructor,qV=my,py=function(e){var t,i,r,n,s,a,o,l,c=BV(this),d=HV(e),h=arguments.length,m=h>1?arguments[1]:void 0,p=m!==void 0,f=jV(d);if(f&&!zV(f))for(l=(o=GV(d,f)).next,d=[];!(a=FV(l,o)).done;)d.push(a.value);for(p&&h>2&&(m=VV(m,arguments[2])),i=WV(d),r=new(KV(c))(i),n=JV(r),t=0;i>t;t++)s=p?m(d[t],t):d[t],r[t]=n?qV(s):+s;return r},fy=Fd,YV=eh,XV=We,QV=Ne("species"),_y=Array,ZV=function(e){var t;return fy(e)&&(t=e.constructor,(YV(t)&&(t===_y||fy(t.prototype))||XV(t)&&(t=t[QV])===null)&&(t=void 0)),t===void 0?_y:t},$V=Me,e1=Dt,t1=Rn,gy=function(e,t,i){$V?e1.f(e,t,t1(0,i)):e[t]=i},i1=nr,r1=Go,n1=Jt,s1=ci,Ty=function(e,t){return new(ZV(e))(t===0?0:t)},Zh=gy,a1=function(e){var t=e===1,i=e===2,r=e===3,n=e===4,s=e===6,a=e===7,o=e===5||s;return function(l,c,d){for(var h,m,p=n1(l),f=r1(p),T=s1(f),E=i1(c,d),v=0,y=0,D=t?Ty(l,T):i||a?Ty(l,0):void 0;T>v;v++)if((o||v in f)&&(m=E(h=f[v],v,p),e))if(t)Zh(D,v,m);else if(m)switch(e){case 3:return!0;case 5:return h;case 6:return v;case 2:Zh(D,y++,h)}else switch(e){case 4:return!1;case 7:Zh(D,y++,h)}return s?-1:r||n?n:D}},Ey={forEach:a1(0)},o1=ci,vy=Ee,yy=se,Sy=De,l1=Me,c1=dy,ta=bi,Iy=gl,Ay=zs,u1=Rn,ia=Si,d1=DV,h1=wr,Ry=CT,$h=hy,m1=function(e){var t=MV(e);return t<0?0:t>255?255:255&t},Cy=ad,ra=Xe,p1=er,em=We,f1=Qu,_1=wn,g1=Qi,Hl=Nn,T1=Qo.f,by=py,E1=Ey.forEach,v1=Tl,y1=Nr,ky=Dt,Dy=Fo,wy=function(e,t,i){for(var r=0,n=arguments.length>2?i:o1(t),s=new e(n);n>r;)s[r]=t[r++];return s},S1=Gd,tm=gt.get,I1=gt.set,A1=gt.enforce,Ny=ky.f,R1=Dy.f,im=yy.RangeError,Py=Iy.ArrayBuffer,C1=Py.prototype,b1=Iy.DataView,Wl=ta.NATIVE_ARRAY_BUFFER_VIEWS,Oy=ta.TYPED_ARRAY_TAG,My=ta.TypedArray,na=ta.TypedArrayPrototype,rm=ta.isTypedArray,Gl="BYTES_PER_ELEMENT",nm="Wrong length",jl=function(e,t){y1(e,t,{configurable:!0,get:function(){return tm(this)[t]}})},Ly=function(e){var t;return g1(C1,e)||(t=p1(e))==="ArrayBuffer"||t==="SharedArrayBuffer"},xy=function(e,t){return rm(e)&&!f1(t)&&t in e&&d1(+t)&&t>=0},Uy=function(e,t){return t=Cy(t),xy(e,t)?u1(2,e[t]):R1(e,t)},Vy=function(e,t,i){return t=Cy(t),!(xy(e,t)&&em(i)&&ra(i,"value"))||ra(i,"get")||ra(i,"set")||i.configurable||ra(i,"writable")&&!i.writable||ra(i,"enumerable")&&!i.enumerable?Ny(e,t,i):(e[t]=i.value,e)};l1?(Wl||(Dy.f=Uy,ky.f=Vy,jl(na,"buffer"),jl(na,"byteOffset"),jl(na,"byteLength"),jl(na,"length")),vy({target:"Object",stat:!0,forced:!Wl},{getOwnPropertyDescriptor:Uy,defineProperty:Vy}),jh.exports=function(e,t,i){var r=e.match(/\d+/)[0]/8,n=e+(i?"Clamped":"")+"Array",s="get"+e,a="set"+e,o=yy[n],l=o,c=l&&l.prototype,d={},h=function(p,f){Ny(p,f,{get:function(){return(function(T,E){var v=tm(T);return v.view[s](E*r+v.byteOffset,!0)})(this,f)},set:function(T){return(function(E,v,y){var D=tm(E);D.view[a](v*r+D.byteOffset,i?m1(y):y,!0)})(this,f,T)},enumerable:!0})};Wl?c1&&(l=t(function(p,f,T,E){return Ay(p,c),S1(em(f)?Ly(f)?E!==void 0?new o(f,$h(T,r),E):T!==void 0?new o(f,$h(T,r)):new o(f):rm(f)?wy(l,f):Sy(by,l,f):new o(Ry(f)),p,l)}),Hl&&Hl(l,My),E1(T1(o),function(p){p in l||ia(l,p,o[p])}),l.prototype=c):(l=t(function(p,f,T,E){Ay(p,c);var v,y,D,N=0,S=0;if(em(f)){if(!Ly(f))return rm(f)?wy(l,f):Sy(by,l,f);v=f,S=$h(T,r);var A=f.byteLength;if(E===void 0){if(A%r)throw new im(nm);if((y=A-S)<0)throw new im(nm)}else if((y=h1(E)*r)+S>A)throw new im(nm);D=y/r}else D=Ry(f),v=new Py(y=D*r);for(I1(p,{buffer:v,byteOffset:S,byteLength:y,length:D,view:new b1(v)});N<D;)h(p,N++)}),Hl&&Hl(l,My),c=l.prototype=_1(na)),c.constructor!==l&&ia(c,"constructor",l),A1(c).TypedArrayConstructor=l,Oy&&ia(c,Oy,n);var m=l!==o;d[n]=l,vy({global:!0,constructor:!0,forced:m,sham:!Wl},d),Gl in l||ia(l,Gl,r),Gl in c||ia(c,Gl,r),v1(n)}):jh.exports=function(){};var Fy=jh.exports;Fy("Float32",function(e){return function(t,i,r){return e(this,t,i,r)}}),Fy("Uint8",function(e){return function(t,i,r){return e(this,t,i,r)}});var k1=DT,D1=my,w1=er,N1=De,P1=de,O1=bi.aTypedArray,M1=bi.exportTypedArrayMethod,L1=pe("".slice);M1("fill",function(e){var t=arguments.length;O1(this);var i=L1(w1(this),0,3)==="Big"?D1(e):+e;return N1(k1,this,i,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)},P1(function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),e!==1})),(0,bi.exportTypedArrayStaticMethod)("from",py,dy);var By=se,Hy=De,sm=bi,x1=ci,U1=hy,V1=Jt,Wy=de,F1=By.RangeError,am=By.Int8Array,Gy=am&&am.prototype,jy=Gy&&Gy.set,B1=sm.aTypedArray,H1=sm.exportTypedArrayMethod,om=!Wy(function(){var e=new Uint8ClampedArray(2);return Hy(jy,e,{length:1,0:3},1),e[1]!==3}),W1=om&&sm.NATIVE_ARRAY_BUFFER_VIEWS&&Wy(function(){var e=new am(2);return e.set(1),e.set("2",1),e[0]!==0||e[1]!==2});H1("set",function(e){B1(this);var t=U1(arguments.length>1?arguments[1]:void 0,1),i=V1(e);if(om)return Hy(jy,this,i,t);var r=this.length,n=x1(i),s=0;if(n+t>r)throw new F1("Wrong length");for(;s<n;)this[t+s]=i[s++]},!om||W1);var G1=El,lm=de,j1=zt,z1=Hd,zy=hT,J1=mT,Jy=Zi,Ky=fT,K1=bi.aTypedArray,q1=bi.exportTypedArrayMethod,sa=se.Uint16Array,qn=sa&&G1(sa.prototype.sort),Y1=!(!qn||lm(function(){qn(new sa(2),null)})&&lm(function(){qn(new sa(2),{})})),qy=!!qn&&!lm(function(){if(Jy)return Jy<74;if(zy)return zy<67;if(J1)return!0;if(Ky)return Ky<602;var e,t,i=new sa(516),r=Array(516);for(e=0;e<516;e++)t=e%4,i[e]=515-e,r[e]=e-2*t+3;for(qn(i,function(n,s){return(n/4|0)-(s/4|0)}),e=0;e<516;e++)if(i[e]!==r[e])return!0});q1("sort",function(e){return e!==void 0&&j1(e),qy?qn(this,e):z1(K1(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))},!qy||Y1);var X1=Ee,Q1=De,cm=pe,Yy=vi,Z1=Te,$1=We,e2=pv,aa=St,t2=xs,i2=Ch,r2=zv,n2=Ne("replace"),s2=TypeError,um=cm("".indexOf);cm("".replace);var Xy=cm("".slice),a2=Math.max;X1({target:"String",proto:!0},{replaceAll:function(e,t){var i,r,n,s,a,o,l,c,d,h=Yy(this),m=0,p="";if($1(e)){if(e2(e)&&(i=aa(Yy(i2(e))),!~um(i,"g")))throw new s2("`.replaceAll` does not allow non-global regexes");if(r=t2(e,n2))return Q1(r,e,h,t)}for(n=aa(h),s=aa(e),(a=Z1(t))||(t=aa(t)),o=s.length,l=a2(1,o),c=um(n,s);c!==-1;)d=a?aa(t(s,c,n)):r2(s,n,c,[],void 0,t),p+=Xy(n,m,c)+d,m=c+o,c=c+l>n.length?-1:um(n,s,c+l);return m<n.length&&(p+=Xy(n,m)),p}});var Qy={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},dm=zo("span").classList,Zy=dm&&dm.constructor&&dm.constructor.prototype,$y=Zy===Object.prototype?void 0:Zy,o2=Ey.forEach,l2=ll("forEach")?[].forEach:function(e){return o2(this,e,arguments.length>1?arguments[1]:void 0)},eS=se,tS=Qy,c2=$y,hm=l2,u2=Si,iS=function(e){if(e&&e.forEach!==hm)try{u2(e,"forEach",hm)}catch{e.forEach=hm}};for(var mm in tS)tS[mm]&&iS(eS[mm]&&eS[mm].prototype);iS(c2);var rS=se,nS=Qy,d2=$y,oa=VP,sS=Si,h2=Mr,pm=Ne("iterator"),fm=oa.values,aS=function(e,t){if(e){if(e[pm]!==fm)try{sS(e,pm,fm)}catch{e[pm]=fm}if(h2(e,t,!0),nS[t]){for(var i in oa)if(e[i]!==oa[i])try{sS(e,i,oa[i])}catch{e[i]=oa[i]}}}};for(var _m in nS)aS(rS[_m]&&rS[_m].prototype,_m);aS(d2,"DOMTokenList");var oS=yl.clear;Ee({global:!0,bind:!0,enumerable:!0,forced:se.clearImmediate!==oS},{clearImmediate:oS});var lS=se,m2=th,p2=Te,f2=Vd,_2=oi,g2=js,T2=vl,E2=lS.Function,v2=/MSIE .\./.test(_2)||f2==="BUN"&&(function(){var e=lS.Bun.version.split(".");return e.length<3||e[0]==="0"&&(e[1]<3||e[1]==="3"&&e[2]==="0")})(),y2=Ee,cS=se,uS=yl.set,S2=function(e,t){var i=1;return v2?function(r,n){var s=T2(arguments.length,1)>i,a=p2(r)?r:E2(r),o=s?g2(arguments,i):[],l=s?function(){m2(a,this,o)}:a;return e(l)}:e},dS=cS.setImmediate?S2(uS):uS;y2({global:!0,bind:!0,enumerable:!0,forced:cS.setImmediate!==dS},{setImmediate:dS});var I2=Uh.charAt,A2=St,hS=gt,R2=$g,mS=xd,pS="String Iterator",C2=hS.set,b2=hS.getterFor(pS);R2(String,"String",function(e){C2(this,{type:pS,string:A2(e),index:0})},function(){var e,t=b2(this),i=t.string,r=t.index;return r>=i.length?mS(void 0,!0):(e=I2(i,r),t.index+=e.length,mS(e,!1))});var k2=de,D2=Me,w2=Ne("iterator"),fS=!k2(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&&!D2||!t.sort||e.href!=="https://a/c%20d?a=1&c=3"||t.get("c")!=="3"||String(new URLSearchParams("?a=1"))!=="a=1"||!t[w2]||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"}),_S=Me,N2=pe,P2=De,O2=de,gm=Mg,M2=Ad,L2=zu,x2=Jt,U2=Go,Yn=Object.assign,gS=Object.defineProperty,V2=N2([].concat),F2=!Yn||O2(function(){if(_S&&Yn({b:1},Yn(gS({},"a",{enumerable:!0,get:function(){gS(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}),Yn({},e)[i]!==7||gm(Yn({},t)).join("")!==r})?function(e,t){for(var i=x2(e),r=arguments.length,n=1,s=M2.f,a=L2.f;r>n;)for(var o,l=U2(arguments[n++]),c=s?V2(gm(l),s(l)):gm(l),d=c.length,h=0;d>h;)o=c[h++],_S&&!P2(a,l,o)||(i[o]=l[o]);return i}:Yn,B2=lt,H2=QE,W2=Me,G2=Fd,j2=TypeError,z2=Object.getOwnPropertyDescriptor,J2=W2&&!(function(){if(this!==void 0)return!0;try{Object.defineProperty([],"length",{writable:!1}).length=1}catch(e){return e instanceof TypeError}})()?function(e,t){if(G2(e)&&!z2(e,"length").writable)throw new j2("Cannot set read only .length");return e.length=t}:function(e,t){return e.length=t},K2=nr,q2=De,Y2=Jt,X2=function(e,t,i,r){try{return r?t(B2(i)[0],i[1]):t(i)}catch(n){H2(e,"throw",n)}},Q2=Ih,Z2=eh,$2=ci,TS=gy,eF=J2,tF=wl,iF=Zs,ES=Array,Hr=pe,Tm=2147483647,rF=/[^\0-\u007E]/,vS=/[.\u3002\uFF0E\uFF61]/g,yS="Overflow: input needs wider integers to process",SS=RangeError,nF=Hr(vS.exec),Xn=Math.floor,Em=String.fromCharCode,IS=Hr("".charCodeAt),AS=Hr([].join),lr=Hr([].push),sF=Hr("".replace),aF=Hr("".split),oF=Hr("".toLowerCase),RS=function(e){return e+22+75*(e<26)},lF=function(e,t,i){var r=0;for(e=i?Xn(e/700):e>>1,e+=Xn(e/t);e>455;)e=Xn(e/35),r+=36;return Xn(r+36*e/(e+38))},cF=function(e){var t=[];e=(function(v){for(var y=[],D=0,N=v.length;D<N;){var S=IS(v,D++);if(S>=55296&&S<=56319&&D<N){var A=IS(v,D++);(64512&A)==56320?lr(y,((1023&S)<<10)+(1023&A)+65536):(lr(y,S),D--)}else lr(y,S)}return y})(e);var i,r,n=e.length,s=128,a=0,o=72;for(i=0;i<e.length;i++)(r=e[i])<128&&lr(t,Em(r));var l=t.length,c=l;for(l&&lr(t,"-");c<n;){var d=Tm;for(i=0;i<e.length;i++)(r=e[i])>=s&&r<d&&(d=r);var h=c+1;if(d-s>Xn((Tm-a)/h))throw new SS(yS);for(a+=(d-s)*h,s=d,i=0;i<e.length;i++){if((r=e[i])<s&&++a>Tm)throw new SS(yS);if(r===s){for(var m=a,p=36;;){var f=p<=o?1:p>=o+26?26:p-o;if(m<f)break;var T=m-f,E=36-f;lr(t,Em(RS(f+T%E))),m=Xn(T/E),p+=36}lr(t,Em(RS(m))),o=lF(a,h,c===l),a=0,c++}}a++,s++}return AS(t,"")},uF=Ee,dF=pe,hF=Zo,mF=RangeError,CS=String.fromCharCode,bS=String.fromCodePoint,pF=dF([].join);uF({target:"String",stat:!0,arity:1,forced:!!bS&&bS.length!==1},{fromCodePoint:function(e){for(var t,i=[],r=arguments.length,n=0;r>n;){if(t=+arguments[n++],hF(t,1114111)!==t)throw new mF(t+" is not a valid code point");i[n]=t<65536?CS(t):CS(55296+((t-=65536)>>10),t%1024+56320)}return pF(i,"")}});var vm=Ee,kS=se,ym=yE,fF=yi,zl=De,Xt=pe,la=Me,DS=fS,wS=wt,_F=Nr,gF=RT,TF=Mr,EF=Kg,Sm=gt,NS=zs,Im=Te,vF=Xe,yF=nr,SF=er,IF=lt,PS=We,ut=St,AF=wn,OS=Rn,MS=wl,RF=Zs,Jl=xd,Qn=vl,CF=Hd,bF=Ne("iterator"),Zn="URLSearchParams",LS=Zn+"Iterator",xS=Sm.set,Nt=Sm.getterFor(Zn),kF=Sm.getterFor(LS),US=ym("fetch"),Kl=ym("Request"),ca=ym("Headers"),Am=Kl&&Kl.prototype,VS=ca&&ca.prototype,DF=kS.TypeError,wF=kS.encodeURIComponent,NF=String.fromCharCode,PF=fF("String","fromCodePoint"),OF=parseInt,ql=Xt("".charAt),FS=Xt([].join),cr=Xt([].push),BS=Xt("".replace),MF=Xt([].shift),HS=Xt([].splice),WS=Xt("".split),GS=Xt("".slice),LF=Xt(/./.exec),xF=/\+/g,UF=/^[0-9a-f]+$/i,jS=function(e,t){var i=GS(e,t,t+2);return LF(UF,i)?OF(i,16):NaN},VF=function(e){for(var t=0,i=128;i>0&&(e&i)!==0;i>>=1)t++;return t},FF=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},zS=function(e){for(var t=(e=BS(e,xF," ")).length,i="",r=0;r<t;){var n=ql(e,r);if(n==="%"){if(ql(e,r+1)==="%"||r+3>t){i+="%",r++;continue}var s=jS(e,r+1);if(s!=s){i+=n,r++;continue}r+=2;var a=VF(s);if(a===0)n=NF(s);else{if(a===1||a>4){i+="�",r++;continue}for(var o=[s],l=1;l<a&&!(++r+3>t||ql(e,r)!=="%");){var c=jS(e,r+1);if(c!=c){r+=3;break}if(c>191||c<128)break;cr(o,c),r+=2,l++}if(o.length!==a){i+="�";continue}var d=FF(o);d===null?i+="�":n=PF(d)}}i+=n,r++}return i},BF=/[!'()~]|%20/g,HF={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},WF=function(e){return HF[e]},JS=function(e){return BS(wF(e),BF,WF)},Rm=EF(function(e,t){xS(this,{type:LS,target:Nt(e).entries,index:0,kind:t})},Zn,function(){var e=kF(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,Jl(void 0,!0);var r=t[i];switch(e.kind){case"keys":return Jl(r.key,!1);case"values":return Jl(r.value,!1)}return Jl([r.key,r.value],!1)},!0),KS=function(e){this.entries=[],this.url=null,e!==void 0&&(PS(e)?this.parseObject(e):this.parseQuery(typeof e=="string"?ql(e,0)==="?"?GS(e,1):e:ut(e)))};KS.prototype={type:Zn,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,n,s,a,o,l=this.entries,c=RF(e);if(c)for(i=(t=MS(e,c)).next;!(r=zl(i,t)).done;){if(s=(n=MS(IF(r.value))).next,(a=zl(s,n)).done||(o=zl(s,n)).done||!zl(s,n).done)throw new DF("Expected sequence with length 2");cr(l,{key:ut(a.value),value:ut(o.value)})}else for(var d in e)vF(e,d)&&cr(l,{key:d,value:ut(e[d])})},parseQuery:function(e){if(e)for(var t,i,r=this.entries,n=WS(e,"&"),s=0;s<n.length;)(t=n[s++]).length&&(i=WS(t,"="),cr(r,{key:zS(MF(i)),value:zS(FS(i,"="))}))},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)e=t[r++],cr(i,JS(e.key)+"="+JS(e.value));return FS(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var Yl=function(){NS(this,$n);var e=xS(this,new KS(arguments.length>0?arguments[0]:void 0));la||(this.size=e.entries.length)},$n=Yl.prototype;if(gF($n,{append:function(e,t){var i=Nt(this);Qn(arguments.length,2),cr(i.entries,{key:ut(e),value:ut(t)}),la||this.size++,i.updateURL()},delete:function(e){for(var t=Nt(this),i=Qn(arguments.length,1),r=t.entries,n=ut(e),s=i<2?void 0:arguments[1],a=s===void 0?s:ut(s),o=0;o<r.length;){var l=r[o];if(l.key!==n||a!==void 0&&l.value!==a)o++;else if(HS(r,o,1),a!==void 0)break}la||(this.size=r.length),t.updateURL()},get:function(e){var t=Nt(this).entries;Qn(arguments.length,1);for(var i=ut(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){var t=Nt(this).entries;Qn(arguments.length,1);for(var i=ut(e),r=[],n=0;n<t.length;n++)t[n].key===i&&cr(r,t[n].value);return r},has:function(e){for(var t=Nt(this).entries,i=Qn(arguments.length,1),r=ut(e),n=i<2?void 0:arguments[1],s=n===void 0?n:ut(n),a=0;a<t.length;){var o=t[a++];if(o.key===r&&(s===void 0||o.value===s))return!0}return!1},set:function(e,t){var i=Nt(this);Qn(arguments.length,1);for(var r,n=i.entries,s=!1,a=ut(e),o=ut(t),l=0;l<n.length;l++)(r=n[l]).key===a&&(s?HS(n,l--,1):(s=!0,r.value=o));s||cr(n,{key:a,value:o}),la||(this.size=n.length),i.updateURL()},sort:function(){var e=Nt(this);CF(e.entries,function(t,i){return t.key>i.key?1:-1}),e.updateURL()},forEach:function(e){for(var t,i=Nt(this).entries,r=yF(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 Rm(this,"keys")},values:function(){return new Rm(this,"values")},entries:function(){return new Rm(this,"entries")}},{enumerable:!0}),wS($n,bF,$n.entries,{name:"entries"}),wS($n,"toString",function(){return Nt(this).serialize()},{enumerable:!0}),la&&_F($n,"size",{get:function(){return Nt(this).entries.length},configurable:!0,enumerable:!0}),TF(Yl,Zn),vm({global:!0,constructor:!0,forced:!DS},{URLSearchParams:Yl}),!DS&&Im(ca)){var GF=Xt(VS.has),jF=Xt(VS.set),qS=function(e){if(PS(e)){var t,i=e.body;if(SF(i)===Zn)return t=e.headers?new ca(e.headers):new ca,GF(t,"content-type")||jF(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),AF(e,{body:OS(0,ut(i)),headers:OS(0,t)})}return e};if(Im(US)&&vm({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return US(e,arguments.length>1?qS(arguments[1]):{})}}),Im(Kl)){var Cm=function(e){return NS(this,Am),new Kl(e,arguments.length>1?qS(arguments[1]):{})};Am.constructor=Cm,Cm.prototype=Am,vm({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:Cm})}}var Pt,zF=Ee,bm=Me,JF=fS,km=se,YS=nr,Ot=pe,Xl=wt,Mt=Nr,KF=zs,Dm=Xe,wm=F2,es=function(e){var t=Y2(e),i=Z2(this),r=arguments.length,n=r>1?arguments[1]:void 0,s=n!==void 0;s&&(n=K2(n,r>2?arguments[2]:void 0));var a,o,l,c,d,h,m=iF(t),p=0;if(!m||this===ES&&Q2(m))for(a=$2(t),o=i?new this(a):ES(a);a>p;p++)h=s?n(t[p],p):t[p],TS(o,p,h);else for(o=i?new this:[],d=(c=tF(t,m)).next;!(l=q2(d,c)).done;p++)h=s?X2(c,n,[l.value,p],!0):l.value,TS(o,p,h);return eF(o,p),o},Qt=js,qF=Uh.codeAt,YF=function(e){var t,i,r=[],n=aF(sF(oF(e),vS,"."),".");for(t=0;t<n.length;t++)i=n[t],lr(r,nF(rF,i)?"xn--"+cF(i):i);return AS(r,".")},ki=St,XF=Mr,QF=vl,XS={URLSearchParams:Yl,getState:Nt},QS=gt,ZF=QS.set,Ql=QS.getterFor("URL"),$F=XS.URLSearchParams,e3=XS.getState,ua=km.URL,Nm=km.TypeError,Zl=km.parseInt,t3=Math.floor,ZS=Math.pow,Lt=Ot("".charAt),Zt=Ot(/./.exec),da=Ot([].join),i3=Ot(1.1.toString),r3=Ot([].pop),ts=Ot([].push),Pm=Ot("".replace),n3=Ot([].shift),s3=Ot("".split),ha=Ot("".slice),$l=Ot("".toLowerCase),a3=Ot([].unshift),Om="Invalid scheme",Wr="Invalid host",$S="Invalid port",eI=/[a-z]/i,o3=/[\d+-.a-z]/i,Mm=/\d/,l3=/^0x/i,c3=/^[0-7]+$/,u3=/^\d+$/,tI=/^[\da-f]+$/i,d3=/[\0\t\n\r #%/:<>?@[\\\]^|]/,h3=/[\0\t\n\r #/:<>?@[\\\]^|]/,m3=/^[\u0000-\u0020]+/,p3=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,f3=/[\t\n\r]/g,ma=function(e){var t,i,r,n;if(typeof e=="number"){for(t=[],i=0;i<4;i++)a3(t,e%256),e=t3(e/256);return da(t,".")}if(typeof e=="object"){for(t="",r=(function(s){for(var a=null,o=1,l=null,c=0,d=0;d<8;d++)s[d]!==0?(c>o&&(a=l,o=c),l=null,c=0):(l===null&&(l=d),++c);return c>o?l:a})(e),i=0;i<8;i++)n&&e[i]===0||(n&&(n=!1),r===i?(t+=i?":":"::",n=!0):(t+=i3(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},ec={},iI=wm({},ec,{" ":1,'"':1,"<":1,">":1,"`":1}),rI=wm({},iI,{"#":1,"?":1,"{":1,"}":1}),Lm=wm({},rI,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),ur=function(e,t){var i=qF(e,0);return i>32&&i<127&&!Dm(t,e)?e:encodeURIComponent(e)},tc={ftp:21,file:null,http:80,https:443,ws:80,wss:443},pa=function(e,t){var i;return e.length===2&&Zt(eI,Lt(e,0))&&((i=Lt(e,1))===":"||!t&&i==="|")},nI=function(e){var t;return e.length>1&&pa(ha(e,0,2))&&(e.length===2||(t=Lt(e,2))==="/"||t==="\\"||t==="?"||t==="#")},_3=function(e){return e==="."||$l(e)==="%2e"},g3=function(e){return(e=$l(e))===".."||e==="%2e."||e===".%2e"||e==="%2e%2e"},xm={},sI={},Um={},aI={},oI={},Vm={},lI={},cI={},ic={},rc={},Fm={},Bm={},Hm={},Wm={},uI={},Gm={},is={},di={},dI={},Gr={},Di={},jm=function(e,t,i){var r,n,s,a=ki(e);if(t){if(n=this.parse(a))throw new Nm(n);this.searchParams=null}else{if(i!==void 0&&(r=new jm(i,!0)),n=this.parse(a,null,r))throw new Nm(n);(s=e3(new $F)).bindURL(this),this.searchParams=s}};jm.prototype={type:"URL",parse:function(e,t,i){var r,n,s,a,o=this,l=t||xm,c=0,d="",h=!1,m=!1,p=!1;for(e=ki(e),t||(o.scheme="",o.username="",o.password="",o.host=null,o.port=null,o.path=[],o.query=null,o.fragment=null,o.cannotBeABaseURL=!1,e=Pm(e,m3,""),e=Pm(e,p3,"$1")),e=Pm(e,f3,""),r=es(e);c<=r.length;){switch(n=r[c],l){case xm:if(!n||!Zt(eI,n)){if(t)return Om;l=Um;continue}d+=$l(n),l=sI;break;case sI:if(n&&(Zt(o3,n)||n==="+"||n==="-"||n==="."))d+=$l(n);else{if(n!==":"){if(t)return Om;d="",l=Um,c=0;continue}if(t&&(o.isSpecial()!==Dm(tc,d)||d==="file"&&(o.includesCredentials()||o.port!==null)||o.scheme==="file"&&!o.host))return;if(o.scheme=d,t)return void(o.isSpecial()&&tc[o.scheme]===o.port&&(o.port=null));d="",o.scheme==="file"?l=Wm:o.isSpecial()&&i&&i.scheme===o.scheme?l=aI:o.isSpecial()?l=cI:r[c+1]==="/"?(l=oI,c++):(o.cannotBeABaseURL=!0,ts(o.path,""),l=dI)}break;case Um:if(!i||i.cannotBeABaseURL&&n!=="#")return Om;if(i.cannotBeABaseURL&&n==="#"){o.scheme=i.scheme,o.path=Qt(i.path),o.query=i.query,o.fragment="",o.cannotBeABaseURL=!0,l=Di;break}l=i.scheme==="file"?Wm:Vm;continue;case aI:if(n!=="/"||r[c+1]!=="/"){l=Vm;continue}l=ic,c++;break;case oI:if(n==="/"){l=rc;break}l=di;continue;case Vm:if(o.scheme=i.scheme,n===Pt)o.username=i.username,o.password=i.password,o.host=i.host,o.port=i.port,o.path=Qt(i.path),o.query=i.query;else if(n==="/"||n==="\\"&&o.isSpecial())l=lI;else if(n==="?")o.username=i.username,o.password=i.password,o.host=i.host,o.port=i.port,o.path=Qt(i.path),o.query="",l=Gr;else{if(n!=="#"){o.username=i.username,o.password=i.password,o.host=i.host,o.port=i.port,o.path=Qt(i.path),o.path.length--,l=di;continue}o.username=i.username,o.password=i.password,o.host=i.host,o.port=i.port,o.path=Qt(i.path),o.query=i.query,o.fragment="",l=Di}break;case lI:if(!o.isSpecial()||n!=="/"&&n!=="\\"){if(n!=="/"){o.username=i.username,o.password=i.password,o.host=i.host,o.port=i.port,l=di;continue}l=rc}else l=ic;break;case cI:if(l=ic,n!=="/"||Lt(d,c+1)!=="/")continue;c++;break;case ic:if(n!=="/"&&n!=="\\"){l=rc;continue}break;case rc:if(n==="@"){h&&(d="%40"+d),h=!0,s=es(d);for(var f=0;f<s.length;f++){var T=s[f];if(T!==":"||p){var E=ur(T,Lm);p?o.password+=E:o.username+=E}else p=!0}d=""}else if(n===Pt||n==="/"||n==="?"||n==="#"||n==="\\"&&o.isSpecial()){if(h&&d==="")return"Invalid authority";c-=es(d).length+1,d="",l=Fm}else d+=n;break;case Fm:case Bm:if(t&&o.scheme==="file"){l=Gm;continue}if(n!==":"||m){if(n===Pt||n==="/"||n==="?"||n==="#"||n==="\\"&&o.isSpecial()){if(o.isSpecial()&&d==="")return Wr;if(t&&d===""&&(o.includesCredentials()||o.port!==null))return;if(a=o.parseHost(d))return a;if(d="",l=is,t)return;continue}n==="["?m=!0:n==="]"&&(m=!1),d+=n}else{if(d==="")return Wr;if(a=o.parseHost(d))return a;if(d="",l=Hm,t===Bm)return}break;case Hm:if(!Zt(Mm,n)){if(n===Pt||n==="/"||n==="?"||n==="#"||n==="\\"&&o.isSpecial()||t){if(d!==""){var v=Zl(d,10);if(v>65535)return $S;o.port=o.isSpecial()&&v===tc[o.scheme]?null:v,d=""}if(t)return;l=is;continue}return $S}d+=n;break;case Wm:if(o.scheme="file",n==="/"||n==="\\")l=uI;else{if(!i||i.scheme!=="file"){l=di;continue}switch(n){case Pt:o.host=i.host,o.path=Qt(i.path),o.query=i.query;break;case"?":o.host=i.host,o.path=Qt(i.path),o.query="",l=Gr;break;case"#":o.host=i.host,o.path=Qt(i.path),o.query=i.query,o.fragment="",l=Di;break;default:nI(da(Qt(r,c),""))||(o.host=i.host,o.path=Qt(i.path),o.shortenPath()),l=di;continue}}break;case uI:if(n==="/"||n==="\\"){l=Gm;break}i&&i.scheme==="file"&&!nI(da(Qt(r,c),""))&&(pa(i.path[0],!0)?ts(o.path,i.path[0]):o.host=i.host),l=di;continue;case Gm:if(n===Pt||n==="/"||n==="\\"||n==="?"||n==="#"){if(!t&&pa(d))l=di;else if(d===""){if(o.host="",t)return;l=is}else{if(a=o.parseHost(d))return a;if(o.host==="localhost"&&(o.host=""),t)return;d="",l=is}continue}d+=n;break;case is:if(o.isSpecial()){if(l=di,n!=="/"&&n!=="\\")continue}else if(t||n!=="?")if(t||n!=="#"){if(n!==Pt&&(l=di,n!=="/"))continue}else o.fragment="",l=Di;else o.query="",l=Gr;break;case di:if(n===Pt||n==="/"||n==="\\"&&o.isSpecial()||!t&&(n==="?"||n==="#")){if(g3(d)?(o.shortenPath(),n==="/"||n==="\\"&&o.isSpecial()||ts(o.path,"")):_3(d)?n==="/"||n==="\\"&&o.isSpecial()||ts(o.path,""):(o.scheme==="file"&&!o.path.length&&pa(d)&&(o.host&&(o.host=""),d=Lt(d,0)+":"),ts(o.path,d)),d="",o.scheme==="file"&&(n===Pt||n==="?"||n==="#"))for(;o.path.length>1&&o.path[0]==="";)n3(o.path);n==="?"?(o.query="",l=Gr):n==="#"&&(o.fragment="",l=Di)}else d+=ur(n,rI);break;case dI:n==="?"?(o.query="",l=Gr):n==="#"?(o.fragment="",l=Di):n!==Pt&&(o.path[0]+=ur(n,ec));break;case Gr:t||n!=="#"?n!==Pt&&(n==="'"&&o.isSpecial()?o.query+="%27":o.query+=n==="#"?"%23":ur(n,ec)):(o.fragment="",l=Di);break;case Di:n!==Pt&&(o.fragment+=ur(n,iI))}c++}},parseHost:function(e){var t,i,r;if(Lt(e,0)==="["){if(Lt(e,e.length-1)!=="]"||(t=(function(n){var s,a,o,l,c,d,h,m=[0,0,0,0,0,0,0,0],p=0,f=null,T=0,E=function(){return Lt(n,T)};if(E()===":"){if(Lt(n,1)!==":")return;T+=2,f=++p}for(;E();){if(p===8)return;if(E()!==":"){for(s=a=0;a<4&&Zt(tI,E());)s=16*s+Zl(E(),16),T++,a++;if(E()==="."){if(a===0||(T-=a,p>6))return;for(o=0;E();){if(l=null,o>0){if(!(E()==="."&&o<4))return;T++}if(!Zt(Mm,E()))return;for(;Zt(Mm,E());){if(c=Zl(E(),10),l===null)l=c;else{if(l===0)return;l=10*l+c}if(l>255)return;T++}m[p]=256*m[p]+l,++o!==2&&o!==4||p++}if(o!==4)return;break}if(E()===":"){if(T++,!E())return}else if(E())return;m[p++]=s}else{if(f!==null)return;T++,f=++p}}if(f!==null)for(d=p-f,p=7;p!==0&&d>0;)h=m[p],m[p--]=m[f+d-1],m[f+--d]=h;else if(p!==8)return;return m})(ha(e,1,-1)),!t))return Wr;this.host=t}else if(this.isSpecial()){if(e=YF(e),Zt(d3,e)||(t=(function(n){var s,a,o,l,c,d,h,m=s3(n,".");if(m.length&&m[m.length-1]===""&&m.length--,(s=m.length)>4)return n;for(a=[],o=0;o<s;o++){if((l=m[o])==="")return n;if(c=10,l.length>1&&Lt(l,0)==="0"&&(c=Zt(l3,l)?16:8,l=ha(l,c===8?1:2)),l==="")d=0;else{if(!Zt(c===10?u3:c===8?c3:tI,l))return n;d=Zl(l,c)}ts(a,d)}for(o=0;o<s;o++)if(d=a[o],o===s-1){if(d>=ZS(256,5-s))return null}else if(d>255)return null;for(h=r3(a),o=0;o<a.length;o++)h+=a[o]*ZS(256,3-o);return h})(e),t===null))return Wr;this.host=t}else{if(Zt(h3,e))return Wr;for(t="",i=es(e),r=0;r<i.length;r++)t+=ur(i[r],ec);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||this.scheme==="file"},includesCredentials:function(){return this.username!==""||this.password!==""},isSpecial:function(){return Dm(tc,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||this.scheme==="file"&&t===1&&pa(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,a=e.path,o=e.query,l=e.fragment,c=t+":";return n!==null?(c+="//",e.includesCredentials()&&(c+=i+(r?":"+r:"")+"@"),c+=ma(n),s!==null&&(c+=":"+s)):t==="file"&&(c+="//"),c+=e.cannotBeABaseURL?a[0]:a.length?"/"+da(a,"/"):"",o!==null&&(c+="?"+o),l!==null&&(c+="#"+l),c},setHref:function(e){var t=this.parse(e);if(t)throw new Nm(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if(e==="blob")try{return new rs(e.path[0]).origin}catch{return"null"}return e!=="file"&&this.isSpecial()?e+"://"+ma(this.host)+(t!==null?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(ki(e)+":",xm)},getUsername:function(){return this.username},setUsername:function(e){var t=es(ki(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=ur(t[i],Lm)}},getPassword:function(){return this.password},setPassword:function(e){var t=es(ki(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=ur(t[i],Lm)}},getHost:function(){var e=this.host,t=this.port;return e===null?"":t===null?ma(e):ma(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,Fm)},getHostname:function(){var e=this.host;return e===null?"":ma(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,Bm)},getPort:function(){var e=this.port;return e===null?"":ki(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||((e=ki(e))===""?this.port=null:this.parse(e,Hm))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+da(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,is))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){(e=ki(e))===""?this.query=null:(Lt(e,0)==="?"&&(e=ha(e,1)),this.query="",this.parse(e,Gr)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){(e=ki(e))!==""?(Lt(e,0)==="#"&&(e=ha(e,1)),this.fragment="",this.parse(e,Di)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var rs=function(e){var t=KF(this,dt),i=QF(arguments.length,1)>1?arguments[1]:void 0,r=ZF(t,new jm(e,!1,i));bm||(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())},dt=rs.prototype,xt=function(e,t){return{get:function(){return Ql(this)[e]()},set:t&&function(i){return Ql(this)[t](i)},configurable:!0,enumerable:!0}};if(bm&&(Mt(dt,"href",xt("serialize","setHref")),Mt(dt,"origin",xt("getOrigin")),Mt(dt,"protocol",xt("getProtocol","setProtocol")),Mt(dt,"username",xt("getUsername","setUsername")),Mt(dt,"password",xt("getPassword","setPassword")),Mt(dt,"host",xt("getHost","setHost")),Mt(dt,"hostname",xt("getHostname","setHostname")),Mt(dt,"port",xt("getPort","setPort")),Mt(dt,"pathname",xt("getPathname","setPathname")),Mt(dt,"search",xt("getSearch","setSearch")),Mt(dt,"searchParams",xt("getSearchParams")),Mt(dt,"hash",xt("getHash","setHash"))),Xl(dt,"toJSON",function(){return Ql(this).serialize()},{enumerable:!0}),Xl(dt,"toString",function(){return Ql(this).serialize()},{enumerable:!0}),ua){var hI=ua.createObjectURL,mI=ua.revokeObjectURL;hI&&Xl(rs,"createObjectURL",YS(hI,ua)),mI&&Xl(rs,"revokeObjectURL",YS(mI,ua))}XF(rs,"URL"),zF({global:!0,constructor:!0,forced:!JF,sham:!bm},{URL:rs});var T3=De;Ee({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return T3(URL.prototype.toString,this)}});let pI=!0,fI=!0;function fa(e,t,i){const r=e.match(t);return r&&r.length>=i&&parseFloat(r[i],10)}function jr(e,t,i){if(!e.RTCPeerConnection)return;const r=e.RTCPeerConnection.prototype,n=r.addEventListener;r.addEventListener=function(a,o){if(a!==t)return n.apply(this,arguments);const l=c=>{const d=i(c);d&&(o.handleEvent?o.handleEvent(d):o(d))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(o,l),n.apply(this,[a,l])};const s=r.removeEventListener;r.removeEventListener=function(a,o){if(a!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(o))return s.apply(this,arguments);const l=this._eventMap[t].get(o);return this._eventMap[t].delete(o),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[a,l])},Object.defineProperty(r,"on"+t,{get(){return this["_on"+t]},set(a){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),a&&this.addEventListener(t,this["_on"+t]=a)},enumerable:!0,configurable:!0})}function E3(e){return typeof e!="boolean"?new Error("Argument type: "+typeof e+". Please use a boolean."):(pI=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function v3(e){return typeof e!="boolean"?new Error("Argument type: "+typeof e+". Please use a boolean."):(fI=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function _I(){if(typeof window=="object"){if(pI)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function zm(e,t){fI&&console.warn(e+" is deprecated, please use "+t+" instead.")}function gI(e){return Object.prototype.toString.call(e)==="[object Object]"}function TI(e){return gI(e)?Object.keys(e).reduce(function(t,i){const r=gI(e[i]),n=r?TI(e[i]):e[i],s=r&&!Object.keys(n).length;return n===void 0||s?t:Object.assign(t,{[i]:n})},{}):e}function Jm(e,t,i){t&&!i.has(t.id)&&(i.set(t.id,t),Object.keys(t).forEach(r=>{r.endsWith("Id")?Jm(e,e.get(t[r]),i):r.endsWith("Ids")&&t[r].forEach(n=>{Jm(e,e.get(n),i)})}))}function EI(e,t,i){const r=i?"outbound-rtp":"inbound-rtp",n=new Map;if(t===null)return n;const s=[];return e.forEach(a=>{a.type==="track"&&a.trackIdentifier===t.id&&s.push(a)}),s.forEach(a=>{e.forEach(o=>{o.type===r&&o.trackId===a.id&&Jm(e,o,n)})}),n}const vI=_I;function yI(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const r=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const o={};return Object.keys(a).forEach(l=>{if(l==="require"||l==="advanced"||l==="mediaSource")return;const c=typeof a[l]=="object"?a[l]:{ideal:a[l]};c.exact!==void 0&&typeof c.exact=="number"&&(c.min=c.max=c.exact);const d=function(h,m){return h?h+m.charAt(0).toUpperCase()+m.slice(1):m==="deviceId"?"sourceId":m};if(c.ideal!==void 0){o.optional=o.optional||[];let h={};typeof c.ideal=="number"?(h[d("min",l)]=c.ideal,o.optional.push(h),h={},h[d("max",l)]=c.ideal,o.optional.push(h)):(h[d("",l)]=c.ideal,o.optional.push(h))}c.exact!==void 0&&typeof c.exact!="number"?(o.mandatory=o.mandatory||{},o.mandatory[d("",l)]=c.exact):["min","max"].forEach(h=>{c[h]!==void 0&&(o.mandatory=o.mandatory||{},o.mandatory[d(h,l)]=c[h])})}),a.advanced&&(o.optional=(o.optional||[]).concat(a.advanced)),o},n=function(a,o){if(t.version>=61)return o(a);if((a=JSON.parse(JSON.stringify(a)))&&typeof a.audio=="object"){const l=function(c,d,h){d in c&&!(h in c)&&(c[h]=c[d],delete c[d])};l((a=JSON.parse(JSON.stringify(a))).audio,"autoGainControl","googAutoGainControl"),l(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=r(a.audio)}if(a&&typeof a.video=="object"){let l=a.video.facingMode;l=l&&(typeof l=="object"?l:{ideal:l});const c=t.version<66;if(l&&(l.exact==="user"||l.exact==="environment"||l.ideal==="user"||l.ideal==="environment")&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||c)){let d;if(delete a.video.facingMode,l.exact==="environment"||l.ideal==="environment"?d=["back","rear"]:l.exact!=="user"&&l.ideal!=="user"||(d=["front"]),d)return i.mediaDevices.enumerateDevices().then(h=>{h=h.filter(p=>p.kind==="videoinput");let m=h.find(p=>d.some(f=>p.label.toLowerCase().includes(f)));return!m&&h.length&&d.includes("back")&&(m=h[h.length-1]),m&&(a.video.deviceId=l.exact?{exact:m.deviceId}:{ideal:m.deviceId}),a.video=r(a.video),vI("chrome: "+JSON.stringify(a)),o(a)})}a.video=r(a.video)}return vI("chrome: "+JSON.stringify(a)),o(a)},s=function(a){return t.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=(function(a,o,l){n(a,c=>{i.webkitGetUserMedia(c,o,d=>{l&&l(s(d))})})}).bind(i),i.mediaDevices.getUserMedia){const a=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(o){return n(o,l=>a(l).then(c=>{if(l.audio&&!c.getAudioTracks().length||l.video&&!c.getVideoTracks().length)throw c.getTracks().forEach(d=>{d.stop()}),new DOMException("","NotFoundError");return c},c=>Promise.reject(s(c))))}}}function SI(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function II(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(a=>a.track&&a.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(a=>a.track&&a.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 jr(e,"track",t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t))}function AI(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(a,o){let l=n.apply(this,arguments);return l||(l=t(this,a),this._senders.push(l)),l};const s=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(a){s.apply(this,arguments);const o=this._senders.indexOf(a);o!==-1&&this._senders.splice(o,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 a=this._senders.find(o=>o.track===s);a&&this._senders.splice(this._senders.indexOf(a),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 RI(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=>EI(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}),jr(e,"track",r=>(r.receiver._pc=r.srcElement,r)),e.RTCRtpReceiver.prototype.getStats=function(){const r=this;return this._pc.getStats().then(n=>EI(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(a=>{a.track===i&&(r?s=!0:r=a)}),this.getReceivers().forEach(a=>(a.track===i&&(n?s=!0:n=a),a.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 CI(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,a){if(!a)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const o=t.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(o)===-1&&this._shimmedLocalStreams[a.id].push(o):this._shimmedLocalStreams[a.id]=[a,o],o};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(s){this._shimmedLocalStreams=this._shimmedLocalStreams||{},s.getTracks().forEach(l=>{if(this.getSenders().find(c=>c.track===l))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();i.apply(this,arguments);const o=this.getSenders().filter(l=>a.indexOf(l)===-1);this._shimmedLocalStreams[s.id]=[s].concat(o)};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(a=>{const o=this._shimmedLocalStreams[a].indexOf(s);o!==-1&&this._shimmedLocalStreams[a].splice(o,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),n.apply(this,arguments)}}function bI(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return CI(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const l=i.apply(this);return this._reverseStreams=this._reverseStreams||{},l.map(c=>this._reverseStreams[c.id])};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(l){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},l.getTracks().forEach(c=>{if(this.getSenders().find(d=>d.track===c))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[l.id]){const c=new e.MediaStream(l.getTracks());this._streams[l.id]=c,this._reverseStreams[c.id]=l,l=c}r.apply(this,[l])};const n=e.RTCPeerConnection.prototype.removeStream;function s(l,c){let d=c.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const m=l._reverseStreams[h],p=l._streams[m.id];d=d.replace(new RegExp(p.id,"g"),m.id)}),new RTCSessionDescription({type:c.type,sdp:d})}e.RTCPeerConnection.prototype.removeStream=function(l){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[l.id]||l]),delete this._reverseStreams[this._streams[l.id]?this._streams[l.id].id:l.id],delete this._streams[l.id]},e.RTCPeerConnection.prototype.addTrack=function(l,c){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const d=[].slice.call(arguments,1);if(d.length!==1||!d[0].getTracks().find(m=>m===l))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(m=>m.track===l))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const h=this._streams[c.id];if(h)h.addTrack(l),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const m=new e.MediaStream([l]);this._streams[c.id]=m,this._reverseStreams[m.id]=c,this.addStream(m)}return this.getSenders().find(m=>m.track===l)},["createOffer","createAnswer"].forEach(function(l){const c=e.RTCPeerConnection.prototype[l],d={[l](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?c.apply(this,[m=>{const p=s(this,m);h[0].apply(null,[p])},m=>{h[1]&&h[1].apply(null,m)},arguments[2]]):c.apply(this,arguments).then(m=>s(this,m))}};e.RTCPeerConnection.prototype[l]=d[l]});const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=(function(l,c){let d=c.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const m=l._reverseStreams[h],p=l._streams[m.id];d=d.replace(new RegExp(m.id,"g"),p.id)}),new RTCSessionDescription({type:c.type,sdp:d})})(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const o=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const l=o.get.apply(this);return l.type===""?l:s(this,l)}}),e.RTCPeerConnection.prototype.removeTrack=function(l){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!l._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(l._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let c;this._streams=this._streams||{},Object.keys(this._streams).forEach(d=>{this._streams[d].getTracks().find(h=>l.track===h)&&(c=this._streams[d])}),c&&(c.getTracks().length===1?this.removeStream(this._reverseStreams[c.id]):c.removeTrack(l.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Km(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 kI(e,t){jr(e,"negotiationneeded",i=>{const r=i.target;if(!(t.version<72||r.getConfiguration&&r.getConfiguration().sdpSemantics==="plan-b")||r.signalingState==="stable")return i})}var DI=Object.freeze({__proto__:null,shimMediaStream:SI,shimOnTrack:II,shimGetSendersWithDtmf:AI,shimSenderReceiverGetStats:RI,shimAddTrackRemoveTrackWithNative:CI,shimAddTrackRemoveTrack:bI,shimPeerConnection:Km,fixNegotiationNeeded:kI,shimGetUserMedia:yI});function wI(e,t){const i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(n,s,a){zm("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(n).then(s,a)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const n=function(a,o,l){o in a&&!(l in a)&&(a[l]=a[o],delete a[o])},s=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),n(a.audio,"autoGainControl","mozAutoGainControl"),n(a.audio,"noiseSuppression","mozNoiseSuppression")),s(a)},r&&r.prototype.getSettings){const a=r.prototype.getSettings;r.prototype.getSettings=function(){const o=a.apply(this,arguments);return n(o,"mozAutoGainControl","autoGainControl"),n(o,"mozNoiseSuppression","noiseSuppression"),o}}if(r&&r.prototype.applyConstraints){const a=r.prototype.applyConstraints;r.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),n(o,"autoGainControl","mozAutoGainControl"),n(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function NI(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 qm(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],a={[n](){return arguments[0]=new(n==="addIceCandidate"?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};e.RTCPeerConnection.prototype[n]=a[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,a]=arguments;return r.apply(this,[n||null]).then(o=>{if(t.version<53&&!s)try{o.forEach(l=>{l.type=i[l.type]||l.type})}catch(l){if(l.name!=="TypeError")throw l;o.forEach((c,d)=>{o.set(d,Object.assign({},c,{type:i[c.type]||c.type}))})}return o}).then(s,a)}}function PI(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 OI(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}),jr(e,"track",i=>(i.receiver._pc=i.srcElement,i)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function MI(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(t){zm("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function LI(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function xI(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,a=s.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=i,s.sendEncodings=i,this.setParametersPromises.push(s.setParameters(a).then(()=>{delete s.sendEncodings}).catch(()=>{delete s.sendEncodings})))}return n})}function UI(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 VI(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 FI(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 BI=Object.freeze({__proto__:null,shimOnTrack:NI,shimPeerConnection:qm,shimSenderGetStats:PI,shimReceiverGetStats:OI,shimRemoveStream:MI,shimRTCDataChannel:LI,shimAddTransceiver:xI,shimGetParameters:UI,shimCreateOffer:VI,shimCreateAnswer:FI,shimGetUserMedia:wI,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 HI(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 WI(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 GI(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,a=t.addIceCandidate;t.createOffer=function(l,c){const d=arguments.length>=2?arguments[2]:arguments[0],h=i.apply(this,[d]);return c?(h.then(l,c),Promise.resolve()):h},t.createAnswer=function(l,c){const d=arguments.length>=2?arguments[2]:arguments[0],h=r.apply(this,[d]);return c?(h.then(l,c),Promise.resolve()):h};let o=function(l,c,d){const h=n.apply(this,[l]);return d?(h.then(c,d),Promise.resolve()):h};t.setLocalDescription=o,o=function(l,c,d){const h=s.apply(this,[l]);return d?(h.then(c,d),Promise.resolve()):h},t.setRemoteDescription=o,o=function(l,c,d){const h=a.apply(this,[l]);return d?(h.then(c,d),Promise.resolve()):h},t.addIceCandidate=o}function jI(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(zI(n))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=(function(i,r,n){t.mediaDevices.getUserMedia(i).then(r,n)}).bind(t))}function zI(e){return e&&e.video!==void 0?Object.assign({},e,{video:TI(e.video)}):e}function JI(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 a=i.iceServers[s];a.urls===void 0&&a.url?(zm("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,n.push(a)):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 KI(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 qI(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 YI(e){typeof e!="object"||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var XI=Object.freeze({__proto__:null,shimLocalStreamsAPI:HI,shimRemoteStreamsAPI:WI,shimCallbacksAPI:GI,shimGetUserMedia:jI,shimConstraints:zI,shimRTCIceServerUrls:JI,shimTrackEventTransceiver:KI,shimCreateOfferLegacy:qI,shimAudioContext:YI}),QI={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(`
|
||
`).map(r=>r.trim())},t.splitSections=function(i){return i.split(`
|
||
m=`).map((r,n)=>(n>0?"m="+r:r).trim()+`\r
|
||
`)},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
|
||
`},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
|
||
`},t.parseFmtp=function(i){const r={};let n;const s=i.substring(i.indexOf(" ")+1).split(";");for(let a=0;a<s.length;a++)n=s[a].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(a=>{i.parameters[a]!==void 0?s.push(a+"="+i.parameters[a]):s.push(a)}),r+="a=fmtp:"+n+" "+s.join(";")+`\r
|
||
`}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
|
||
`}),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
|
||
`;return i.fingerprints.forEach(s=>{n+="a=fingerprint:"+s.algorithm+" "+s.value+`\r
|
||
`}),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
|
||
`},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
|
||
a=ice-pwd:`+i.password+`\r
|
||
`;return i.iceLite&&(r+=`a=ice-lite\r
|
||
`),r},t.parseRtpParameters=function(i){const r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(i)[0].split(" ");r.profile=n[2];for(let a=3;a<n.length;a++){const o=n[a],l=t.matchPrefix(i,"a=rtpmap:"+o+" ")[0];if(l){const c=t.parseRtpMap(l),d=t.matchPrefix(i,"a=fmtp:"+o+" ");switch(c.parameters=d.length?t.parseFmtp(d[0]):{},c.rtcpFeedback=t.matchPrefix(i,"a=rtcp-fb:"+o+" ").map(t.parseRtcpFb),r.codecs.push(c),c.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(c.name.toUpperCase())}}}t.matchPrefix(i,"a=extmap:").forEach(a=>{r.headerExtensions.push(t.parseExtmap(a))});const s=t.matchPrefix(i,"a=rtcp-fb:* ").map(t.parseRtcpFb);return r.codecs.forEach(a=>{s.forEach(o=>{a.rtcpFeedback.find(l=>l.type===o.type&&l.parameter===o.parameter)||a.rtcpFeedback.push(o)})}),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(a=>a.preferredPayloadType!==void 0?a.preferredPayloadType:a.payloadType).join(" ")+`\r
|
||
`,n+=`c=IN IP4 0.0.0.0\r
|
||
`,n+=`a=rtcp:9 IN IP4 0.0.0.0\r
|
||
`,r.codecs.forEach(a=>{n+=t.writeRtpMap(a),n+=t.writeFmtp(a),n+=t.writeRtcpFb(a)});let s=0;return r.codecs.forEach(a=>{a.maxptime>s&&(s=a.maxptime)}),s>0&&(n+="a=maxptime:"+s+`\r
|
||
`),r.headerExtensions&&r.headerExtensions.forEach(a=>{n+=t.writeExtmap(a)}),n},t.parseRtpEncodingParameters=function(i){const r=[],n=t.parseRtpParameters(i),s=n.fecMechanisms.indexOf("RED")!==-1,a=n.fecMechanisms.indexOf("ULPFEC")!==-1,o=t.matchPrefix(i,"a=ssrc:").map(m=>t.parseSsrcMedia(m)).filter(m=>m.attribute==="cname"),l=o.length>0&&o[0].ssrc;let c;const d=t.matchPrefix(i,"a=ssrc-group:FID").map(m=>m.substring(17).split(" ").map(p=>parseInt(p,10)));d.length>0&&d[0].length>1&&d[0][0]===l&&(c=d[0][1]),n.codecs.forEach(m=>{if(m.name.toUpperCase()==="RTX"&&m.parameters.apt){let p={ssrc:l,codecPayloadType:parseInt(m.parameters.apt,10)};l&&c&&(p.rtx={ssrc:c}),r.push(p),s&&(p=JSON.parse(JSON.stringify(p)),p.fec={ssrc:l,mechanism:a?"red+ulpfec":"red"},r.push(p))}}),r.length===0&&l&&r.push({ssrc:l});let h=t.matchPrefix(i,"b=");return h.length&&(h=h[0].indexOf("b=TIAS:")===0?parseInt(h[0].substring(7),10):h[0].indexOf("b=AS:")===0?1e3*parseInt(h[0].substring(5),10)*.95-16e3:void 0,r.forEach(m=>{m.maxBitrate=h})),r},t.parseRtcpParameters=function(i){const r={},n=t.matchPrefix(i,"a=ssrc:").map(o=>t.parseSsrcMedia(o)).filter(o=>o.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 a=t.matchPrefix(i,"a=rtcp-mux");return r.mux=a.length>0,r},t.writeRtcpParameters=function(i){let r="";return i.reducedSize&&(r+=`a=rtcp-rsize\r
|
||
`),i.mux&&(r+=`a=rtcp-mux\r
|
||
`),i.ssrc!==void 0&&i.cname&&(r+="a=ssrc:"+i.ssrc+" cname:"+i.cname+`\r
|
||
`),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(a=>t.parseSsrcMedia(a)).filter(a=>a.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 a=t.matchPrefix(i,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:r.fmt,maxMessageSize:s};const o=t.matchPrefix(i,"a=sctpmap:");if(o.length>0){const l=o[0].substring(10).split(" ");return{port:parseInt(l[0],10),protocol:l[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
|
||
`,`c=IN IP4 0.0.0.0\r
|
||
`,"a=sctp-port:"+r.port+`\r
|
||
`]:["m="+i.kind+" 9 "+i.protocol+" "+r.port+`\r
|
||
`,`c=IN IP4 0.0.0.0\r
|
||
`,"a=sctpmap:"+r.port+" "+r.protocol+` 65535\r
|
||
`],r.maxMessageSize!==void 0&&n.push("a=max-message-size:"+r.maxMessageSize+`\r
|
||
`),n.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(i,r,n){let s;const a=r!==void 0?r:2;return s=i||t.generateSessionId(),`v=0\r
|
||
o=`+(n||"thisisadapterortc")+" "+s+" "+a+` IN IP4 127.0.0.1\r
|
||
s=-\r
|
||
t=0 0\r
|
||
`},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})(QI);var ZI=QI.exports,ns=Dk(ZI),y3=B_({__proto__:null,default:ns},[ZI]);function nc(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=ns.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,jr(e,"icecandidate",i=>(i.candidate&&Object.defineProperty(i,"candidate",{value:new e.RTCIceCandidate(i.candidate),writable:"false"}),i))}function Ym(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||jr(e,"icecandidate",t=>{if(t.candidate){const i=ns.parseCandidate(t.candidate.candidate);i.type==="relay"&&(t.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[i.priority>>24])}return t})}function sc(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=ns.splitSections(r.sdp);return n.shift(),n.some(s=>{const a=ns.parseMLine(s);return a&&a.kind==="application"&&a.protocol.indexOf("SCTP")!==-1})})(arguments[0])){const r=(function(l){const c=l.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const d=parseInt(c[1],10);return d!=d?-1:d})(arguments[0]),n=(function(l){let c=65536;return t.browser==="firefox"&&(c=t.version<57?l===-1?16384:2147483637:t.version<60?t.version===57?65535:65536:2147483637),c})(r),s=(function(l,c){let d=65536;t.browser==="firefox"&&t.version===57&&(d=65535);const h=ns.matchPrefix(l.sdp,"a=max-message-size:");return h.length>0?d=parseInt(h[0].substring(19),10):t.browser==="firefox"&&c!==-1&&(d=2147483637),d})(arguments[0],r);let a;a=n===0&&s===0?Number.POSITIVE_INFINITY:n===0||s===0?Math.max(n,s):Math.min(n,s);const o={};Object.defineProperty(o,"maxMessageSize",{get:()=>a}),this._sctp=o}return i.apply(this,arguments)}}function ac(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(r,n){const s=r.send;r.send=function(){const a=arguments[0],o=a.length||a.size||a.byteLength;if(r.readyState==="open"&&n.sctp&&o>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},jr(e,"datachannel",r=>(t(r.channel,r.target),r))}function Xm(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 a=new Event("connectionstatechange",n);s.dispatchEvent(a)}return n},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}})}function Qm(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(`
|
||
a=extmap-allow-mixed`)!==-1){const n=r.sdp.split(`
|
||
`).filter(s=>s.trim()!=="a=extmap-allow-mixed").join(`
|
||
`);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 oc(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 lc(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 S3=Object.freeze({__proto__:null,shimRTCIceCandidate:nc,shimRTCIceCandidateRelayProtocol:Ym,shimMaxMessageSize:sc,shimSendThrowTypeError:ac,shimConnectionState:Xm,removeExtmapAllowMixed:Qm,shimAddIceCandidateNullOrEmpty:oc,shimParameterlessSetLocalDescription:lc});(function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const i=_I,r=(function(s){const a={browser:null,version:null};if(s===void 0||!s.navigator||!s.navigator.userAgent)return a.browser="Not a browser.",a;const{navigator:o}=s;if(o.userAgentData&&o.userAgentData.brands){const l=o.userAgentData.brands.find(c=>c.brand==="Chromium");if(l)return{browser:"chrome",version:parseInt(l.version,10)}}if(o.mozGetUserMedia)a.browser="firefox",a.version=parseInt(fa(o.userAgent,/Firefox\/(\d+)\./,1));else if(o.webkitGetUserMedia||s.isSecureContext===!1&&s.webkitRTCPeerConnection)a.browser="chrome",a.version=parseInt(fa(o.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else{if(!s.RTCPeerConnection||!o.userAgent.match(/AppleWebKit\/(\d+)\./))return a.browser="Not a supported browser.",a;a.browser="safari",a.version=parseInt(fa(o.userAgent,/AppleWebKit\/(\d+)\./,1)),a.supportsUnifiedPlan=s.RTCRtpTransceiver&&"currentDirection"in s.RTCRtpTransceiver.prototype,a._safariVersion=fa(o.userAgent,/Version\/(\d+(\.?\d+))/,1)}return a})(e),n={browserDetails:r,commonShim:S3,extractVersion:fa,disableLog:E3,disableWarnings:v3,sdp:y3};switch(r.browser){case"chrome":if(!DI||!Km||!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=DI,oc(e,r),lc(e),yI(e,r),SI(e),Km(e,r),II(e),bI(e,r),AI(e),RI(e),kI(e,r),nc(e),Ym(e),Xm(e),sc(e,r),ac(e),Qm(e,r);break;case"firefox":if(!BI||!qm||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),n;i("adapter.js shimming firefox."),n.browserShim=BI,oc(e,r),lc(e),wI(e,r),qm(e,r),NI(e),MI(e),PI(e),OI(e),LI(e),xI(e),UI(e),VI(e),FI(e),nc(e),Xm(e),sc(e,r),ac(e);break;case"safari":if(!XI||!t.shimSafari)return i("Safari shim is not included in this adapter release."),n;i("adapter.js shimming safari."),n.browserShim=XI,oc(e,r),lc(e),JI(e),qI(e),GI(e),HI(e),WI(e),KI(e),jI(e),YI(e),nc(e),Ym(e),sc(e,r),ac(e),Qm(e,r);break;default:i("Unsupported browser!")}})({window:typeof window>"u"?void 0:window});var B,I3=Object.create,_a=Object.defineProperty,A3=Object.defineProperties,$I=Object.getOwnPropertyDescriptor,R3=Object.getOwnPropertyDescriptors,C3=Object.getOwnPropertyNames,cc=Object.getOwnPropertySymbols,eA=Object.getPrototypeOf,Zm=Object.prototype.hasOwnProperty,tA=Object.prototype.propertyIsEnumerable,b3=Reflect.get,ga=Math.pow,$m=(e,t,i)=>t in e?_a(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,x=(e,t)=>{for(var i in t||(t={}))Zm.call(t,i)&&$m(e,i,t[i]);if(cc)for(var i of cc(t))tA.call(t,i)&&$m(e,i,t[i]);return e},W=(e,t)=>A3(e,R3(t)),iA=(e,t)=>{var i={};for(var r in e)Zm.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(e!=null&&cc)for(var r of cc(e))t.indexOf(r)<0&&tA.call(e,r)&&(i[r]=e[r]);return i},wi=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ni=(e,t)=>{for(var i in t)_a(e,i,{get:t[i],enumerable:!0})},Ge=(e,t,i)=>(i=e!=null?I3(eA(e)):{},((r,n,s,a)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of C3(n))!Zm.call(r,o)&&o!==s&&_a(r,o,{get:()=>n[o],enumerable:!(a=$I(n,o))||a.enumerable});return r})(!t&&e&&e.__esModule?i:_a(i,"default",{value:e,enumerable:!0}),e)),M=(e,t,i,r)=>{for(var n,s=$I(t,i),a=e.length-1;a>=0;a--)(n=e[a])&&(s=n(t,i,s)||s);return s&&_a(t,i,s),s},u=(e,t,i)=>$m(e,typeof t!="symbol"?t+"":t,i),Et=(e,t,i)=>b3(eA(e),i,t),g=(e,t,i)=>new Promise((r,n)=>{var s=l=>{try{o(i.next(l))}catch(c){n(c)}},a=l=>{try{o(i.throw(l))}catch(c){n(c)}},o=l=>l.done?r(l.value):Promise.resolve(l.value).then(s,a);o((i=i.apply(e,t)).next())}),it=wi((e,t)=>{var i=Object.prototype.hasOwnProperty,r="~";function n(){}function s(c,d,h){this.fn=c,this.context=d,this.once=h||!1}function a(c,d,h,m,p){if(typeof h!="function")throw new TypeError("The listener must be a function");var f=new s(h,m||c,p),T=r?r+d:d;return c._events[T]?c._events[T].fn?c._events[T]=[c._events[T],f]:c._events[T].push(f):(c._events[T]=f,c._eventsCount++),c}function o(c,d){--c._eventsCount===0?c._events=new n:delete c._events[d]}function l(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(r=!1)),l.prototype.eventNames=function(){var c,d,h=[];if(this._eventsCount===0)return h;for(d in c=this._events)i.call(c,d)&&h.push(r?d.slice(1):d);return Object.getOwnPropertySymbols?h.concat(Object.getOwnPropertySymbols(c)):h},l.prototype.listeners=function(c){var d=r?r+c:c,h=this._events[d];if(!h)return[];if(h.fn)return[h.fn];for(var m=0,p=h.length,f=new Array(p);m<p;m++)f[m]=h[m].fn;return f},l.prototype.listenerCount=function(c){var d=r?r+c:c,h=this._events[d];return h?h.fn?1:h.length:0},l.prototype.emit=function(c,d,h,m,p,f){var T=r?r+c:c;if(!this._events[T])return!1;var E,v,y=this._events[T],D=arguments.length;if(y.fn){switch(y.once&&this.removeListener(c,y.fn,void 0,!0),D){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,d),!0;case 3:return y.fn.call(y.context,d,h),!0;case 4:return y.fn.call(y.context,d,h,m),!0;case 5:return y.fn.call(y.context,d,h,m,p),!0;case 6:return y.fn.call(y.context,d,h,m,p,f),!0}for(v=1,E=new Array(D-1);v<D;v++)E[v-1]=arguments[v];y.fn.apply(y.context,E)}else{var N,S=y.length;for(v=0;v<S;v++)switch(y[v].once&&this.removeListener(c,y[v].fn,void 0,!0),D){case 1:y[v].fn.call(y[v].context);break;case 2:y[v].fn.call(y[v].context,d);break;case 3:y[v].fn.call(y[v].context,d,h);break;case 4:y[v].fn.call(y[v].context,d,h,m);break;default:if(!E)for(N=1,E=new Array(D-1);N<D;N++)E[N-1]=arguments[N];y[v].fn.apply(y[v].context,E)}}return!0},l.prototype.on=function(c,d,h){return a(this,c,d,h,!1)},l.prototype.once=function(c,d,h){return a(this,c,d,h,!0)},l.prototype.removeListener=function(c,d,h,m){var p=r?r+c:c;if(!this._events[p])return this;if(!d)return o(this,p),this;var f=this._events[p];if(f.fn)f.fn===d&&(!m||f.once)&&(!h||f.context===h)&&o(this,p);else{for(var T=0,E=[],v=f.length;T<v;T++)(f[T].fn!==d||m&&!f[T].once||h&&f[T].context!==h)&&E.push(f[T]);E.length?this._events[p]=E.length===1?E[0]:E:o(this,p)}return this},l.prototype.removeAllListeners=function(c){var d;return c?(d=r?r+c:c,this._events[d]&&o(this,d)):(this._events=new n,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=r,l.EventEmitter=l,t!==void 0&&(t.exports=l)}),ep=wi((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")})})}),k3=wi(e=>{var t=function(a){return String(Number(a))===a?Number(a):a},i=function(a,o,l){var c=a.name&&a.names;a.push&&!o[a.push]?o[a.push]=[]:c&&!o[a.name]&&(o[a.name]={});var d=a.push?{}:c?o[a.name]:o;(function(h,m,p,f){if(f&&!p)m[f]=t(h[1]);else for(var T=0;T<p.length;T+=1)h[T+1]!=null&&(m[p[T]]=t(h[T+1]))})(l.match(a.reg),d,a.names,a.name),a.push&&o[a.push].push(d)},r=ep(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(a){var o={},l=[],c=o;return a.split(/(\r\n|\r|\n)/).filter(n).forEach(function(d){var h=d[0],m=d.slice(2);h==="m"&&(l.push({rtp:[],fmtp:[]}),c=l[l.length-1]);for(var p=0;p<(r[h]||[]).length;p+=1){var f=r[h][p];if(f.reg.test(m))return i(f,c,m)}}),o.media=l,o};var s=function(a,o){var l=o.split(/=(.+)/,2);return l.length===2?a[l[0]]=t(l[1]):l.length===1&&o.length>1&&(a[l[0]]=void 0),a};e.parseParams=function(a){return a.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(a){return a.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(a){for(var o=[],l=a.split(" ").map(t),c=0;c<l.length;c+=3)o.push({component:l[c],ip:l[c+1],port:l[c+2]});return o},e.parseImageAttributes=function(a){return a.split(" ").map(function(o){return o.substring(1,o.length-1).split(",").reduce(s,{})})},e.parseSimulcastStreamList=function(a){return a.split(";").map(function(o){return o.split(",").map(function(l){var c,d=!1;return l[0]!=="~"?c=t(l):(c=t(l.substring(1,l.length)),d=!0),{scid:c,paused:d}})})}}),D3=wi((e,t)=>{var i=ep(),r=/%[sdv%]/g,n=function(l){var c=1,d=arguments,h=d.length;return l.replace(r,function(m){if(c>=h)return m;var p=d[c];switch(c+=1,m){case"%%":return"%";case"%s":return String(p);case"%d":return Number(p);case"%v":return""}})},s=function(l,c,d){var h=[l+"="+(c.format instanceof Function?c.format(c.push?d:d[c.name]):c.format)];if(c.names)for(var m=0;m<c.names.length;m+=1){var p=c.names[m];c.name?h.push(d[c.name][p]):h.push(d[c.names[m]])}else h.push(d[c.name]);return n.apply(null,h)},a=["v","o","s","i","u","e","p","c","b","t","r","z","a"],o=["i","c","b","a"];t.exports=function(l,c){c=c||{},l.version==null&&(l.version=0),l.name==null&&(l.name=" "),l.media.forEach(function(p){p.payloads==null&&(p.payloads="")});var d=c.outerOrder||a,h=c.innerOrder||o,m=[];return d.forEach(function(p){i[p].forEach(function(f){f.name in l&&l[f.name]!=null?m.push(s(p,f,l)):f.push in l&&l[f.push]!=null&&l[f.push].forEach(function(T){m.push(s(p,f,T))})})}),l.media.forEach(function(p){m.push(s("m",i.m[0],p)),h.forEach(function(f){i[f].forEach(function(T){T.name in p&&p[T.name]!=null?m.push(s(f,T,p)):T.push in p&&p[T.push]!=null&&p[T.push].forEach(function(E){m.push(s(f,T,E))})})})}),m.join(`\r
|
||
`)+`\r
|
||
`}}),w3=wi(e=>{var t=k3(),i=D3(),r=ep();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}),rA=wi((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")})})}),N3=wi(e=>{var t=function(a){return String(Number(a))===a?Number(a):a},i=function(a,o,l){var c=a.name&&a.names;a.push&&!o[a.push]?o[a.push]=[]:c&&!o[a.name]&&(o[a.name]={});var d=a.push?{}:c?o[a.name]:o;(function(h,m,p,f){if(f&&!p)m[f]=t(h[1]);else for(var T=0;T<p.length;T+=1)h[T+1]!=null&&(m[p[T]]=t(h[T+1]))})(l.match(a.reg),d,a.names,a.name),a.push&&o[a.push].push(d)},r=rA(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(a){var o={},l=[],c=o;return a.split(/(\r\n|\r|\n)/).filter(n).forEach(function(d){var h=d[0],m=d.slice(2);h==="m"&&(l.push({rtp:[],fmtp:[]}),c=l[l.length-1]);for(var p=0;p<(r[h]||[]).length;p+=1){var f=r[h][p];if(f.reg.test(m))return i(f,c,m)}}),o.media=l,o};var s=function(a,o){var l=o.split(/=(.+)/,2);return l.length===2?a[l[0]]=t(l[1]):l.length===1&&o.length>1&&(a[l[0]]=void 0),a};e.parseParams=function(a){return a.split(/;\s?/).reduce(s,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(a){return a.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(a){for(var o=[],l=a.split(" ").map(t),c=0;c<l.length;c+=3)o.push({component:l[c],ip:l[c+1],port:l[c+2]});return o},e.parseImageAttributes=function(a){return a.split(" ").map(function(o){return o.substring(1,o.length-1).split(",").reduce(s,{})})},e.parseSimulcastStreamList=function(a){return a.split(";").map(function(o){return o.split(",").map(function(l){var c,d=!1;return l[0]!=="~"?c=t(l):(c=t(l.substring(1,l.length)),d=!0),{scid:c,paused:d}})})}}),P3=wi((e,t)=>{var i=rA(),r=/%[sdv%]/g,n=function(l){var c=1,d=arguments,h=d.length;return l.replace(r,function(m){if(c>=h)return m;var p=d[c];switch(c+=1,m){case"%%":return"%";case"%s":return String(p);case"%d":return Number(p);case"%v":return""}})},s=function(l,c,d){var h=[l+"="+(c.format instanceof Function?c.format(c.push?d:d[c.name]):c.format)];if(c.names)for(var m=0;m<c.names.length;m+=1){var p=c.names[m];c.name?h.push(d[c.name][p]):h.push(d[c.names[m]])}else h.push(d[c.name]);return n.apply(null,h)},a=["v","o","s","i","u","e","p","c","b","t","r","z","a"],o=["i","c","b","a"];t.exports=function(l,c){c=c||{},l.version==null&&(l.version=0),l.name==null&&(l.name=" "),l.media.forEach(function(p){p.payloads==null&&(p.payloads="")});var d=c.outerOrder||a,h=c.innerOrder||o,m=[];return d.forEach(function(p){i[p].forEach(function(f){f.name in l&&l[f.name]!=null?m.push(s(p,f,l)):f.push in l&&l[f.push]!=null&&l[f.push].forEach(function(T){m.push(s(p,f,T))})})}),l.media.forEach(function(p){m.push(s("m",i.m[0],p)),h.forEach(function(f){i[f].forEach(function(T){T.name in p&&p[T.name]!=null?m.push(s(f,T,p)):T.push in p&&p[T.push]!=null&&p[T.push].forEach(function(E){m.push(s(f,T,E))})})})}),m.join(`\r
|
||
`)+`\r
|
||
`}}),nA=wi(e=>{var t=N3(),i=P3();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}),O3=Ge(it()),sA=((B=sA||{})[B.INVALID_PARAMETER=4096]="INVALID_PARAMETER",B[B.INVALID_OPERATION=4097]="INVALID_OPERATION",B[B.NOT_SUPPORTED=4098]="NOT_SUPPORTED",B[B.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",B[B.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",B[B.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",B[B.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",B[B.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",B[B.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",B[B.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",B[B.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",B[B.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",B[B.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",B[B.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",B[B.CLIENT_BANNED=16448]="CLIENT_BANNED",B[B.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",B[B.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",B[B.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",B[B.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",B[B.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",B[B.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",B[B.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",B[B.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",B[B.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",B[B.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",B[B.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",B[B.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",B[B.API_CALL_ABORTED=16461]="API_CALL_ABORTED",B[B.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",B[B.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",B[B.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",B[B.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",B[B.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",B[B.UNKNOWN=65535]="UNKNOWN",B),C=sA,aA=class extends Error{constructor(e){let{name:t="RtcError",message:i,code:r=C.UNKNOWN,extraCode:n=0,constraint:s}=e,a="<".concat((function(l){for(let c in C)if(C[c]===l)return c;return"UNKNOWN"})(r)," 0x").concat(r.toString(16),">"),o="".concat(i).concat(s?" constraint: ".concat(s):"").concat(i!=null&&i.includes(a)?"":" ".concat(a));super(o),u(this,"code"),u(this,"extraCode"),u(this,"message"),u(this,"originMessage"),u(this,"name"),u(this,"constraint"),this.code=r,this.extraCode=n,this.name=t,this.message=o,this.constraint=s,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},O=aA,tp=0,oA=!0,lA=function(e){tp=e;let t=new Date;t.setTime(t.getTime()+e),P[oA?"info":"debug"]("baseTime from server: ".concat(t," offset: ").concat(e)),oA=!1},M3=function(){return tp},Ta=function(){return Date.now()+tp},cA=function(){let e=new Date;return e.setTime(Ta()),e.toLocaleString()},ip=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)},$t={};Ni($t,{REPORT_TYPE:()=>Lp,buildSSOPackage:()=>us,bytes2ms:()=>BA,calculateScaleResolutionDownNumber:()=>Rc,concatArrayBuffers:()=>xp,convertObjectNumberToInt:()=>Ac,copyProperties:()=>FA,deepClone:()=>cs,deepCloneBasic:()=>Cc,deepMerge:()=>Li,delay:()=>mi,fibonacci:()=>ls,formatedTime:()=>ZA,getConstructorName:()=>vc,getContainerFromElement:()=>QA,getEnv:()=>MA,getFirst16Bits:()=>eR,getInternalVersion:()=>qA,getLast16Bits:()=>Up,getLoggerUrl:()=>os,getMediaStreamTrackInfo:()=>Mp,getMuteStateFromFlag:()=>Yr,getNetworkType:()=>Ec,getNumNetworkType:()=>Na,getReconnectionTimeout:()=>qr,getStringByteLength:()=>Ic,getTestSignalDomain:()=>LA,getTurnServer:()=>XA,getUint32Version:()=>Np,getValueType:()=>Je,getVersionFromInternalVersion:()=>YA,getViewListFromView:()=>xa,glog:()=>WA,ipv4ToUint32:()=>La,isArray:()=>Ue,isAudioWorkletSupported:()=>zA,isBoolean:()=>Se,isConstructor:()=>Oa,isEmpty:()=>yc,isFunction:()=>Pe,isLangChinese:()=>Mi,isMediaStreamTrack:()=>GA,isNumber:()=>le,isObject:()=>hi,isOverseaSdkAppId:()=>pr,isPlainObject:()=>Ut,isPortrait:()=>wp,isPromise:()=>Pa,isRemoteTrack:()=>jA,isRotate90Or270:()=>fr,isSetSinkIdSupported:()=>JA,isString:()=>he,isUndefined:()=>I,isVideoMixerOutputTrack:()=>Xr,loadImage:()=>Ua,loadVideo:()=>$A,ms2bytes:()=>HA,ms2samples:()=>Dp,normalizeUrl:()=>Op,performanceNow:()=>J,promiseAny:()=>Ma,samples2ms:()=>kp,setNetworkTypeFromWebRTC:()=>bp,stringify:()=>ti,stringifyIncludeValue:()=>Sc,throttlePromise:()=>Pp});var uA={};Ni(uA,{ASR_ROBOT_FROM_TYPE:()=>Tc,AUDIO_MUTE_BIT:()=>mp,AUDIO_STAT_BIT:()=>Ia,AUX_STAT_BIT:()=>hc,AUX_STREAM_MSID:()=>yA,BACKEND_ENV:()=>dp,BASE_DOC_URL:()=>Pi,BASE_HOST:()=>hA,CAPABILITIES_KEYS:()=>gp,CLASS_NAME:()=>iB,CLOUD_CONSOLE_URL:()=>V3,CROSS_ROOM_BIT:()=>EA,DATA_CHANNEL_FROM_TYPE_BIT:()=>vA,DATA_FREEZE_TIMING:()=>fp,DOC_BILLING_CN:()=>ap,DOC_BILLING_OVERSEA:()=>op,DOC_URL:()=>F3,DTLS_STATE_UNKNOWN:()=>hr,ENV_NAME:()=>zr,EXCHANGE_SDP_TIMEOUT:()=>bA,IS_WORKER:()=>dc,IS_WORKLET:()=>np,KIBANA_EVENT:()=>Qe,LOCAL_STREAM_PUBLISH_STATE:()=>kA,LOGGER_CMD_TYPE:()=>va,LOGGER_DOMAIN:()=>mA,LOGGER_DOMAIN_OVERSEA:()=>pA,LOG_LEVEL:()=>dr,LOG_LEVEL_NAME:()=>nB,MAIN_STREAM_MSID:()=>mc,MAX_RTT:()=>gc,MICROPHONE_COMMUNICATIONS:()=>rB,MICROPHONE_DEFAULT:()=>Ra,MUTE_ALL_BIT:()=>W3,NAME:()=>_,NETWORK_TYPE:()=>lp,NOT_SUPPORTED_H264:()=>fc,PAUSED_RETRY_COUNT:()=>Kr,PEERCONNECTION_CONNECTING_TIMEOUT:()=>_p,PEER_CONNECTION_STATE:()=>Be,PEER_LEAVE_REASON:()=>DA,RECOVER_CAPTURE_INTERVAL:()=>ba,REMOTE_STREAM_TYPE_AUX:()=>IA,REMOTE_STREAM_TYPE_MAIN:()=>SA,RENDER_FREEZE_TIMING:()=>Z3,SCHEDULE_DOMAIN:()=>mr,SCHEDULE_TIMEOUT:()=>tB,SDP_SEMANTICS_PLAN_B:()=>pc,SDP_SEMANTICS_UNIFIED_PLAN:()=>Aa,SECOND_HOST:()=>x3,SIGNAL_PING_PONG_INTERVAL:()=>H3,SIGNAL_PING_TIMEOUT:()=>B3,SIGNAL_RECONNECTION_COUNT:()=>X3,SMALL_STAT_BIT:()=>hp,SPEAKER_DEFAULT:()=>_c,STORAGE_EXPIRES_TIME:()=>_A,STREAM_TYPE_BIG:()=>$3,STREAM_TYPE_SMALL:()=>eB,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Ca,SYNC_USER_LIST_INTERVAL:()=>Q3,Scene:()=>TA,THIRD_HOST:()=>U3,TRANSPORT_DIRECTION:()=>oe,TRTC_ERROR_ASSISTANCE:()=>fA,TRTC_QUALITY_BAD:()=>K3,TRTC_QUALITY_DISCONNECTED:()=>Y3,TRTC_QUALITY_EXCELLENT:()=>j3,TRTC_QUALITY_GOOD:()=>z3,TRTC_QUALITY_POOR:()=>J3,TRTC_QUALITY_UNKNOWN:()=>G3,TRTC_QUALITY_VERY_BAD:()=>q3,UPDATE_OFFER_TIMEOUT:()=>CA,VIDEO_MUTE_BIT:()=>pp,VIDEO_STAT_BIT:()=>Sa,WEBGL_ATTRIBUTES:()=>wA,audioProfileMap:()=>cp,defaultBigVideoProfile:()=>ya,defaultSmallVideoProfile:()=>gA,getRetryCount:()=>ss,getScriptDir:()=>L3,innerVersion:()=>uc,loggerProxy:()=>sp,screenProfileMap:()=>up,setLoggerProxy:()=>Ea,setRetryCount:()=>RA,setVersion:()=>dA,version:()=>ei,videoProfileMap:()=>Oi});var uc="4.15.00.1600",ei="5.0.0";function dA(e){ei=e;let[t,i,r]=e.split(".").map(n=>parseInt(n,10));uc="".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 rp,At,dc=typeof importScripts<"u",np=typeof registerProcessor<"u",L3=()=>{let e=dc?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},sp="",Ea=e=>sp=e,hA="web.sdk.qcloud.com",x3="web.sdk.tencent.cn",U3="web.sdk.cloud.tencent.cn",V3="https://console.cloud.tencent.com/trtc",Pi="https://".concat(hA,"/trtc/webrtc/doc"),F3="".concat(Pi,"/zh-cn/"),ap="https://cloud.tencent.com/document/product/647/85386",op="https://trtc.io/document/56025",mA="https://yun.tim.qq.com",pA="https://apisgp.my-imcloud.com",fA="trtc_error_assistance",va={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},zr={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},dr=((At=dr||{})[At.TRACE=0]="TRACE",At[At.DEBUG=1]="DEBUG",At[At.INFO=2]="INFO",At[At.WARN=3]="WARN",At[At.ERROR=4]="ERROR",At[At.NONE=5]="NONE",At),B3=18e3,H3=2e3,lp={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},_A=6048e5,cp={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}},Oi={"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}},ya=Oi["480p_2"],gA=Oi["120p_2"],up={"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}},_={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"},oe={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},dp={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},TA=((rp=TA||{}).LIVE="live",rp.RTC="rtc",rp),Sa=1,hp=2,hc=4,Ia=8,mp=64,pp=16,W3=112,EA=128,vA=256,mc="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",yA="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",SA=_.MAIN,IA=_.AUXILIARY,G3=0,j3=1,z3=2,J3=3,K3=4,q3=5,Y3=6,hr="unknown",Be={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},AA=1/0;function RA(e){AA=e}function ss(){return AA}var Jr,X3=30,Qe={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"},Q3=1e4,CA=1e4,bA=1e4,Aa="unified-plan",pc="plan-b",fc=1028,kA=((Jr=kA||{})[Jr.UNPUBLISH=-1]="UNPUBLISH",Jr[Jr.PUBLISHING=0]="PUBLISHING",Jr[Jr.PUBLISHED=1]="PUBLISHED",Jr),fp=500,Z3=1e3,$3=_.BIG,eB=_.SMALL,_p=1e4,mr={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"},tB=2e3,iB={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Kr=5,Ra="default",_c=Ra,rB="communications",nB=Object.keys(dr),DA=["normal leave","timeout leave","kick","role change"],Ca=10,ba=2e3,gp=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],gc=1e4,Tc=14,wA={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},sB=function(e,t,i,r){return new(i||(i=Promise))(function(n,s){function a(c){try{l(r.next(c))}catch(d){s(d)}}function o(c){try{l(r.throw(c))}catch(d){s(d)}}function l(c){c.done?n(c.value):(function(d){return d instanceof i?d:new i(function(h){h(d)})})(c.value).then(a,o)}l((r=r.apply(e,[])).next())})},Tp=Symbol(32),Ep=Symbol(16),vp=Symbol(8),as=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 sB(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(Tp)}readU16(){return this.read(Ep)}readU8(){return this.read(vp)}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===Tp){if(r(4))return;e=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===Ep){if(r(2))return;e=t[0]<<8|t[1]}else if(this.need===vp){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}};as.U32=Tp,as.U16=Ep,as.U8=vp;var aB=128;function yp(e){let t=new as;for(;e>=128;)t.malloc(1)[0]=255&e|aB,e>>>=7;return t.malloc(1)[0]=255&e,t.buffer||new Uint8Array(0)}function Sp(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=new as,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(yp(e));break;case"string":i.malloc(1)[0]=2|r;let s=new TextEncoder().encode(e);i.write(yp(s.length));let a=i.malloc(s.length);for(let l=0;l<s.length;l++)a[l]=s[l];break;case"object":let o=new as;if(Array.isArray(e))for(let l=0;l<e.length;l++){let c=Sp(e[l],l+1);c&&o.write(c)}else{let l=1;for(let c in e){let d=Sp(e[c],l++);d&&o.write(d)}}t===0?o.buffer&&i.write(o.buffer):(i.malloc(1)[0]=2|r,o.buffer&&(i.write(yp(o.buffer.length)),i.write(o.buffer)))}return i.buffer||new Uint8Array(0)}var NA=class{constructor(){u(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 PA(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 vt(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function OA(e,t){return e[t]}function ka(e,t,i){return new TextDecoder().decode((function(r,n,s){return r.slice(n,n+s)})(e,t,i))}var Ip=0,Ap=2654435769,Rp=16,Da=2,wa=7;function oB(e,t){let i=new NA,r=(function(y,D,N){let S=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:N,appId:y,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:S,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:D}})(t,e,Ip);Ip=Ip+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 a=new NA;a.writeInt32(0),a.writeInt32(r.reqHead.seqNumber),a.writeInt32(r.reqHead.appId),a.writeByte(r.reqHead.appId>>>24&255),a.writeByte(r.reqHead.appId>>>16&255),a.writeByte(r.reqHead.appId>>>8&255),a.writeByte(255&r.reqHead.appId);for(let y=4;y<16;y++)a.writeByte(0);let o=new TextEncoder().encode(r.reqHead.a2);a.writeInt32(o.length+4),o.length&&a.writeBytes(o);let l=new TextEncoder().encode(r.reqHead.serviceCmd);a.writeInt32(l.length+4),l.length&&a.writeBytes(l);let c=new TextEncoder().encode(r.reqHead.cookie);a.writeInt32(c.length+4),c.length&&a.writeBytes(c);let d=new TextEncoder().encode(r.reqHead.imei);a.writeInt32(d.length+4),d.length&&a.writeBytes(d);let h=new TextEncoder().encode(r.reqHead.ksid);a.writeInt32(h.length+4),h.length&&a.writeBytes(h);let m=new TextEncoder().encode(r.reqHead.clientVersionInfo);a.writeInt16(m.length+2),m.length&&a.writeBytes(m);let p=a.length;a.data[0]=p>>>24&255,a.data[1]=p>>>16&255,a.data[2]=p>>>8&255,a.data[3]=255&p,he(e)&&(e=new TextEncoder().encode(e)),a.writeInt32(e.length+4),e.length&&a.writeBytes(e);let f=new Uint8Array(a.data),T=null;r.encryption===1?T=new TextEncoder().encode(r.uin):r.encryption===2&&(T=new Uint8Array(16)),T&&(f=(function(y,D){let N=y.length,S=(N+1+Da+wa)%8;S&&(S=8-S);let A=N+1+Da+wa+S,L=new Uint8Array(A),U=0,q=new Uint8Array(8),fe=new Uint8Array(8),Re=new Uint8Array(8),ne=0;q[0]=248&Math.floor(256*Math.random())|S,ne=1;for(let xe=0;xe<S;xe++)q[ne]=255&Math.floor(256*Math.random()),ne+=1;for(let xe=0;xe<Da;)if(ne<8&&(q[ne]=255&Math.floor(256*Math.random()),ne+=1,xe+=1),ne===8){Cp(q,D,fe,Re,L,U),U+=8,ne=0;for(let yt=0;yt<8;yt++)Re[yt]=L[U-8+yt]}let ft=0;for(;ft<N;)if(ne<8&&(q[ne]=y[ft],ne+=1,ft+=1),ne===8){Cp(q,D,fe,Re,L,U),U+=8,ne=0;for(let xe=0;xe<8;xe++)Re[xe]=L[U-8+xe]}for(let xe=0;xe<wa;)if(ne<8&&(q[ne]=0,ne+=1,xe+=1),ne===8){Cp(q,D,fe,Re,L,U),U+=8,ne=0;for(let yt=0;yt<8;yt++)Re[yt]=L[U-8+yt]}return L})(f,T)),i.writeBytes(f);let E=new Uint8Array(i.data),v=E.length;return E[0]=v>>>24&255,E[1]=v>>>16&255,E[2]=v>>>8&255,E[3]=255&v,E}function Cp(e,t,i,r,n,s){for(let a=0;a<8;a++)e[a]^=r[a];(function(a,o,l,c){let d=vt(a,0),h=vt(a,4),m=[];for(let f=0;f<4;f++)m[f]=vt(o,4*f);let p=0;for(let f=0;f<Rp;f++)p+=Ap,p>>>=0,d+=(h<<4)+m[0]^h+p^(h>>>5)+m[1],d>>>=0,h+=(d<<4)+m[2]^d+p^(d>>>5)+m[3],h>>>=0;PA(l,d,c),PA(l,h,c+4)})(e,t,n,s);for(let a=0;a<8;a++)n[s+a]^=i[a];for(let a=0;a<8;a++)i[a]=e[a]}var MA=function(){return new URLSearchParams(location.search).get("trtc_env")||""},LA=function(e){return e.includes(".")?e:"".concat(e).concat(".rtc.qq.com")},pr=e=>Number(e)<14e8,os=function(e,t){let i;i=sp||(pr(e)?pA:mA);let r=Math.floor(Math.random()*ga(2,31));return"".concat(i,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},xA="unknown";function Ec(){(function(){var s;UA||(UA=!0,(s=navigator.connection)==null||s.addEventListener("typechange",lB))})();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?VA(r,n):xA}function lB(){P.warn("netType changed",Ec())}var UA=!1;function VA(e,t){if(lp[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function bp(e){xA=VA(e)}function Na(){return lp[Ec()]}function FA(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 BA(e){return kp(e/4,arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function kp(e){return 1e3*e/(arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function HA(e){return 4*Dp(e,arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function Dp(e){return e*(arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)/1e3}var WA=typeof window<"u"&&typeof window.glog=="function"?window.glog:()=>{},Mi=()=>{let e=navigator.language;return e=e.substring(0,2),e==="zh"},Ut=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 ls(e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;return e<=1?t:ls(e-1,t,(arguments.length>1&&arguments[1]!==void 0?arguments[1]:1)+t)}function qr(e){return e>8?3e4:1e3*ls(e)}function Je(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var Pe=e=>typeof e=="function",I=e=>e===void 0,he=e=>typeof e=="string",le=e=>typeof e=="number",Se=e=>typeof e=="boolean",hi=e=>Je(e)==="object",Ue=e=>Je(e)==="array",GA=e=>Je(e)==="MediaStreamTrack".toLowerCase(),jA=e=>e.isRemote,Pa=e=>Je(e)==="promise",Oa=e=>Pe(e)&&e.prototype.constructor===e,vc=e=>Oa(e)?e.prototype.constructor.name:"",zA=typeof AudioWorkletNode<"u",JA=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype;function Ma(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 J(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var KA=e=>+e<10?"0".concat(e):e,qA=e=>{let t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;let i=t.split("."),r=KA(i[1])+KA(i[2]);return i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15"),"".concat(i.join("."),".").concat(r)},YA=e=>{let t=e.split(".");if(t.length!==4)return e;let i=t[0],r=t[3];if(r.length<4)return e;let n=parseInt(r.substring(0,r.length-2),10),s=parseInt(r.substring(r.length-2),10);return"".concat(i,".").concat(n,".").concat(s)},cB=Object.prototype.hasOwnProperty;function yc(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(Ut(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(cB.call(e,t))return!1;return!0}return!1}function Yr(e,t){return{userId:t,hasAudio:!!(e&Ia),hasVideo:!!(e&Sa),hasAuxiliary:!!(e&hc),hasSmall:!!(e&hp),audioMuted:!!(e&mp),videoMuted:!!(e&pp),audioAvailable:!(!(e&Ia)||e&mp),videoAvailable:!(!(e&Sa)||e&pp),hasDatachannel:!!(e&vA)}}function XA(e){let t={urls:e.url.startsWith("turn:")||e.url.startsWith("turns:")?e.url:"turn:".concat(e.url)};return!I(e.username)&&!I(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",I(e.credentialType)||(t.credentialType=e.credentialType)),t}function La(e){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];if(!he(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 Li=function(e,t,i,r){if(!hi(e)||!hi(t))return 0;let n,s=0,a=Object.keys(t);for(let o=0,l=a.length;o<l;o++)if(n=a[o],!(I(t[n])||i&&i.includes(n)))if(hi(e[n])&&hi(t[n]))s+=Li(e[n],t[n],i,r);else{if(r&&r.includes(t[n]))continue;e[n]!==t[n]&&(e[n]=cs(t[n]),s+=1)}return s};function cs(e){if(Ue(e)){let t=[];return e.forEach((i,r)=>{t[r]=cs(i)}),t}if(hi(e)){let t={};return Object.keys(e).forEach(i=>{t[i]=cs(e[i])}),t}return e}var xa=e=>{let t=[];if(Ue(e))t=[...e];else if(he(e)){let i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},QA=e=>he(e)?document.getElementById(e):e,ZA=()=>(e=>{let t=l=>l<10?"0".concat(l):"".concat(l),i=e.getFullYear(),r=e.getMonth()+1,n=e.getDate(),s=t(e.getHours()),a=t(e.getMinutes()),o=t(e.getSeconds());return"".concat(i,"/").concat(r,"/").concat(n," ").concat(s,":").concat(a,":").concat(o)})(new Date);function ti(e,t){let{keysToInclude:i,keysToExclude:r}=t;try{if(Ue(e))return"[".concat(e.map(o=>ti(o,{keysToInclude:i,keysToExclude:r})).join(","),"]");if(!Ut(e)||!Ue(i)&&!Ue(r))return JSON.stringify(e);let n={},s=new Set(i),a=new Set(r);return Object.keys(e).forEach(o=>{(a.size===0&&s.has(o)||s.size===0&&!a.has(o))&&(n[o]=Ut(e[o])||Ue(e[o])?JSON.parse(ti(e[o],{keysToExclude:r,keysToInclude:i})):e[o])}),JSON.stringify(n)}catch{return"{}"}}function Sc(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)}),ti(e,{keysToInclude:i})}function Ic(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var wp=()=>{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},Ua=e=>g(null,null,function*(){return new Promise((t,i)=>{let r;if(he(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 O({code:C.INVALID_PARAMETER,message:"load image failed, url: ".concat(e)}))}})}),Np=e=>{let t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},Ac=e=>(Object.keys(e).forEach(t=>{le(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(Ut(e[t])||Ue(e[t]))&&Ac(e[t])}),e);function mi(e,t){return new Promise(i=>{let r=setTimeout(i,e);t&&t(r)})}function Pp(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 Op(e){return e.replace(/(^|[^:])\/{2,}/g,"$1/")}function Mp(e){var t;try{let{width:i,height:r,frameRate:n,sampleRate:s,sampleSize:a,channelCount:o}=(t=e.getSettings)==null?void 0:t.call(e),l=e.kind===_.AUDIO?"".concat(s,"x").concat(a,"@").concat(o):"".concat(i,"x").concat(r,"@").concat(n),c=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(l).concat(c)}catch{return""}}function Rc(e,t){return e.width*e.height===t.width*t.height?1:wp()&&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 fr(e){return e===90||e===270}function $A(e){return g(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 Cc(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]=Cc(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]=Cc(e[r],t)}),i}return e}var Lp=(e=>(e[e.END_REPORT=2001]="END_REPORT",e[e.LOG=2002]="LOG",e[e.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",e))(Lp||{});function us(e,t,i,r){try{let n=(function(s,a,o,l){let c={data:s,random:Math.floor(2147483648*Math.random()),sdkAppId:o};return I(l)||(c=W(x({},c),{gzip:+l})),{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:a,bytes_report_data:JSON.stringify(c)}}})(e,t,i,r);return oB(Sp(n),i)}catch{return JSON.stringify(e)}}function xp(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 Up(e){return(65535&e)>>>0}function eR(e){return(4294901760&e)>>>0}function Xr(e,t){return!!(e&&e instanceof CanvasCaptureMediaStreamTrack&&e.canvas.id.includes("trtc_mix")&&t!=null&&t.isUsingVideoMixerInternalTrack)}function uB(e){let t=(function(i){try{let r={},n=0;r.totalLength=vt(i,n),n+=4,r.version=vt(i,n),n+=4,r.encryption=OA(i,n),n+=1,r.uinType=OA(i,n),n+=1,r.uinLength=vt(i,n),n+=4,r.uin=r.uinLength>4?ka(i,n,r.uinLength-4):"",n+=r.uinLength-4;let s=i.slice(n);return r.encryption===2?(i=(function(a,o){let l=0,c=new Uint8Array(8).fill(0),d=new Uint8Array(a.slice(0,8)),h=tR(d,o),m=7&h[0],p=a.length-1-m-Da-wa,f=new Uint8Array(p),T=0,E=c,v=a.slice(0,8);l=8;let y=1;y+=m;for(let N=1;N<=Da;)if(y<8)y++,N++;else if(y===8){let S=Vp(a,l,E,v,h,o);E=S.ivPreCrypt,v=S.ivCurCrypt,h=S.debiBuf,l=S.bufPos,y=0}let D=p;for(;D>0;)if(y<8)f[T++]=h[y]^E[y],y++,D--;else if(y===8){let N=Vp(a,l,E,v,h,o);E=N.ivPreCrypt,v=N.ivCurCrypt,h=N.debiBuf,l=N.bufPos,y=0}for(let N=1;N<=wa;)if(y<8)h[y],E[y],y++,N++;else if(y===8){if(l>=a.length)break;let S=Vp(a,l,E,v,h,o);if(!S.success)break;E=S.ivPreCrypt,v=S.ivCurCrypt,h=S.debiBuf,l=S.bufPos,y=0}return f})(s,new Uint8Array(16).fill(0)),r.decrypted=!0,n=0):(i=s,n=0),r.rspHeadLength=vt(i,n),n+=4,r.seqNo=vt(i,n),n+=4,r.retCode=vt(i,n),n+=4,r.retStrLength=vt(i,n),n+=4,r.retStr=r.retStrLength?ka(i,n,r.retStrLength-4):"",n+=r.retStrLength-4,r.serviceCmdLength=vt(i,n),n+=4,r.serviceCmd=r.serviceCmdLength?ka(i,n,r.serviceCmdLength-4):"",n+=r.serviceCmdLength-4,r.cookieLength=vt(i,n),n+=4,r.cookie=r.cookieLength?ka(i,n,r.cookieLength-4):"",n+=r.cookieLength-4,r.flag=vt(i,n),n+=4,r.busiBuffLength=vt(i,n),n+=4,r.busiBuff=r.busiBuffLength?ka(i,n,r.busiBuffLength-4):"",n+=r.busiBuffLength-4,r}catch{}})(e);return t==null?void 0:t.busiBuff}function tR(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=Ap*Rp>>>0;for(let s=0;s<Rp;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-=Ap,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 Vp(e,t,i,r,n,s){if(t+8>e.length)return{success:!1};let a=new Uint8Array(r),o=e.slice(t,t+8),l=new Uint8Array(8);for(let c=0;c<8;c++)l[c]=n[c]^o[c];return{success:!0,ivPreCrypt:a,ivCurCrypt:o,debiBuf:tR(l,s),bufPos:t+8}}var iR=typeof TextDecoder<"u"?new TextDecoder:void 0;function Va(e){let{url:t,body:i,method:r="POST",timeout:n,priority:s}=e;return new Promise((a,o)=>{if("fetch"in window)return fetch(t,{method:r,body:i,priority:s}).then(c=>c.clone().json().then(d=>({data:d}),()=>c.arrayBuffer().then(d=>({data:uB(new Uint8Array(d))||(iR?iR.decode(d):d)})))).then(a,o);let l=new XMLHttpRequest;l.onreadystatechange=()=>{if(l.readyState===4)if(l.status>=200&&l.status<300)try{let c=JSON.parse(l.response);a({data:c})}catch{a({data:l.response})}else o({status:l.status,statusText:l.statusText||"request failed!"})},l.timeout=n||5e3,l.open(r,t,!0),l.send(i)})}function rR(e){return g(this,null,function*(){let t=J(),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 P.debug("compressJSON ".concat(i.length," -> ").concat(n.byteLength," ").concat(J()-t,"ms")),n}catch{return i}})}var dB=Object.prototype.hasOwnProperty,Qr=e=>typeof e=="function",Vt=e=>e===void 0,Fp=e=>typeof e=="string",nR=e=>typeof e=="boolean",Bp=e=>e.isRemote,sR=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)},Fa=function(e){let{retryFunction:t,settings:i,onError:r,onRetrying:n,onRetryFailed:s,onRetrySuccess:a,context:o}=e;return function(){for(var l=arguments.length,c=new Array(l),d=0;d<l;d++)c[d]=arguments[d];let{retries:h=5,timeout:m=1e3}=i,p=0,f=-1,T=0,E=(v,y)=>g(this,null,function*(){let D=o||this;try{let N=yield t.apply(D,c);p>0&&a&&a.call(this,p),p=0,v(N)}catch(N){let S=()=>{clearTimeout(f),p=0,T=2,y(N)},A=()=>{T!==2&&p<(Qr(h)?h():h)?(p++,T=1,Qr(n)&&n.call(this,p,S),f=window.setTimeout(()=>{f=-1,E(v,y)},Qr(m)?m(p):m)):(S(),Qr(s)&&s.call(this,N))};Qr(r)?r.call(this,{error:N,retry:A,reject:y,retryFuncArgs:c,retriedCount:p}):A()}});return new Promise(E)}},Hp=class gk{constructor(t){u(this,"_parentPath"),u(this,"userId"),u(this,"remoteUserId"),u(this,"id"),u(this,"sdkAppId"),u(this,"type"),u(this,"isLocal"),this.id=t.id,this.userId=t.userId,this.sdkAppId=t.sdkAppId,this.remoteUserId=t.remoteUserId,this.isLocal=!nR(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 gk({id:t.id,userId:Vt(t.userId)?this.userId:t.userId,sdkAppId:Vt(t.sdkAppId)?this.sdkAppId:t.sdkAppId,type:Vt(t.type)?this.type:t.type,isLocal:Vt(t.isLocal)?this.isLocal:t.isLocal,remoteUserId:Vt(t.remoteUserId)?this.remoteUserId:t.remoteUserId});return i.bindParent(this),i}bindParent(t){let i=t.getFullId();this._parentPath!==i&&(this._parentPath=i,this.userId=t.userId||this.userId,this.sdkAppId=t.sdkAppId||this.sdkAppId,this.debug("bindParent: ".concat(t.id)))}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):"","]")),P.log(t,i,Vt(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(sR(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 a in s)if(dB.call(s,a))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)}},aR={};Ni(aR,{ANDROID_VERSION:()=>kc,CHROME_MAJOR_VERSION:()=>Ht,CHROME_VERSION:()=>lf,EDGE_VERSION:()=>jp,EDG_MAJOR_VERSION:()=>cR,EDG_VERSION:()=>zp,ELECTRON_MAJOR_VERSION:()=>pR,FIREFOX_MAJOR_VERSION:()=>Dc,FIREFOX_VERSION:()=>Gp,HUAWEI_VERSION:()=>nf,IE_VERSION:()=>_B,IOS_MAIN_VERSION:()=>Rt,IOS_VERSION:()=>rt,IPADQQB_VERSION:()=>$p,IS_ANDROID:()=>Oe,IS_ANDROID_WEBVIEW:()=>vB,IS_ANY_SAFARI:()=>en,IS_CHROME:()=>Bc,IS_CHROME_OS:()=>ef,IS_CHROMIUM_128_TO_143:()=>ps,IS_CHROMIUM_BASE:()=>Bt,IS_DESKTOP_IOS_CHROME:()=>gR,IS_EDG:()=>Ha,IS_EDGE:()=>hs,IS_ELECTRON:()=>TB,IS_FIREFOX:()=>me,IS_HEADLESS_CHROME:()=>mR,IS_HONOR:()=>hR,IS_HUAWEI:()=>rf,IS_HUAWEIBROWSER:()=>xc,IS_IE:()=>uR,IS_IE8:()=>fB,IS_IOS:()=>be,IS_IOS_13_OR_14:()=>_R,IS_IOS_15_1:()=>fR,IS_IOS_CHROME:()=>qa,IS_IPAD:()=>ds,IS_IPADQQB:()=>Mc,IS_IPAD_PRO:()=>Wp,IS_IPHONE:()=>Zr,IS_IPOD:()=>lR,IS_LINUX:()=>za,IS_LOCAL:()=>tn,IS_MAC:()=>gr,IS_MACQQB:()=>Oc,IS_MIBROWSER:()=>Lc,IS_MQQB:()=>Ga,IS_NATIVE_ANDROID:()=>pB,IS_OLD_ANDROID:()=>mB,IS_OPENHARMONY:()=>Ka,IS_OPPOBROWSER:()=>Ja,IS_SAFARI:()=>Ze,IS_SAFARI_15_1:()=>yB,IS_SAMSUNGBROWSER:()=>Uc,IS_SOGOU:()=>Nc,IS_SOGOUM:()=>wc,IS_TBS:()=>pi,IS_UCBROWSER:()=>dR,IS_VIVOBROWSER:()=>Vc,IS_WECHAT:()=>_r,IS_WIN:()=>ms,IS_WQQB:()=>Pc,IS_WX:()=>gB,IS_X5MQQB:()=>Wa,IS_XWEB:()=>$r,MACQQB_VERSION:()=>Zp,MI_VERSION:()=>tf,MQQB_VERSION:()=>ja,OPENHARMONY_VERSION:()=>EB,OPPO_VERSION:()=>af,SAFARI_VERSION:()=>xi,SAMSUNG_VERSION:()=>sf,SOGOUM_VERSION:()=>Jp,SOGOU_VERSION:()=>Kp,TBS_VERSION:()=>qp,UA_DATA_STRING:()=>Vi,USER_AGENT:()=>Ft,VIVO_VERSION:()=>of,WECHAT_VERSION:()=>Xp,WQQB_VERSION:()=>Qp,XWEB_VERSION:()=>Yp,browserInfo:()=>Tr,getBrowserCoreNumber:()=>yR,getBrowserInfo:()=>TR,getChromeMajorVersion:()=>Fc,getDeviceModel:()=>nn,getDeviceModelFromUA:()=>df,getGPUInfo:()=>fs,getOSName:()=>hf,getOSNumber:()=>Gc,getOSString:()=>Er,getOSType:()=>AB,getTerminalType:()=>SR,getUserAgentData:()=>Wc,isAMDGPU:()=>ER,isAppleSiliconGPU:()=>IB,isLocalStorageEnabled:()=>rn,isMobile:()=>Hc,isNvidiaGPU:()=>SB,isRealIOS:()=>Ba,isVersionLargerThan:()=>Ui,isVersionSmallerThan:()=>cf});var Ft=typeof navigator>"u"?"":navigator.userAgent,$=e=>new RegExp(e,"i").test(Ft),Ve=e=>{if($(e)){let t=new RegExp("".concat(e,"\\/([\\d.]+)")),i=Ft.match(t);if(i&&i[1])return i[1]}return""},bc=e=>{if($(e)){let t=new RegExp("".concat(e,"\\/(\\d+)")),i=Ft.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},oR=/AppleWebKit\/([\d.]+)/i.exec(Ft),hB=oR?parseFloat(oR[1]):NaN,ds=$("iPad"),Wp=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&$("Macintosh"),Zr=$("iPhone")&&!ds,lR=$("iPod"),be=Zr||ds||lR||Wp,Ba=()=>{try{return be&&navigator.maxTouchPoints>1&&navigator.vendor.includes("Apple")}catch{return be}},Oe=$("Android"),kc=(function(){if(Oe){let e=Ft.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})(),mB=Oe&&$("webkit")&&kc<2.3,pB=Oe&&kc<5&&hB<537,me=$("Firefox"),Gp=Ve("Firefox"),Dc=bc("Firefox"),hs=$("Edge"),jp=Ve("Edge"),Ha=$("Edg"),zp=Ve("Edg"),cR=bc("Edg"),wc=$("SogouMobileBrowser"),Jp=Ve("SogouMobileBrowser"),Nc=$("MetaSr\\s"),Kp=Ve("MetaSr\\s"),pi=$("TBS"),qp=Ve("TBS"),$r=$("XWEB"),Yp=Ve("XWEB"),fB=$("MSIE\\s8\\.0"),uR=$("MSIE\\/\\d+"),_B=(function(){if(uR){let e=/MSIE\s(\d+)\.\d/.exec(Ft),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(Ft)&&/rv:11.0/.test(Ft)&&(t=11),t}return NaN})(),_r=$("(micromessenger|webbrowser)"),Xp=Ve("MicroMessenger"),Wa=!pi&&$("MQQBrowser")&&$("COVC"),Ga=!pi&&$("MQQBrowser")&&!$("COVC"),ja=Ga||Wa?Ve("MQQBrowser"):"",Pc=!pi&&$(" QQBrowser"),Qp=Ve(" QQBrowser"),Oc=!pi&&$("QQBrowserLite"),Zp=Ve("QQBrowserLite"),Mc=!pi&&$("MQBHD"),$p=Ve("MQBHD"),ms=$("Windows"),gr=!be&&$("MAC OS X"),za=!Oe&&$("Linux"),ef=$("CrOS"),gB=$("MicroMessenger"),dR=$("UCBrowser"),TB=$("Electron"),Lc=$("MiuiBrowser"),tf=Ve("MiuiBrowser"),xc=$("HuaweiBrowser"),rf=$("Huawei")||$("HUAWEI"),hR=$("Honor")||$("HONOR"),nf=Ve("HuaweiBrowser"),Uc=$("SamsungBrowser"),sf=Ve("SamsungBrowser"),Ja=$("HeyTapBrowser"),af=Ve("HeyTapBrowser"),Vc=$("VivoBrowser"),of=Ve("VivoBrowser"),Ka=$("OpenHarmony"),EB=Ve("OpenHarmony"),Fc=()=>bc("Chrome"),qa=$("CriOS"),Bt=$("Chrome"),Bc=!hs&&!Nc&&!wc&&!pi&&!$r&&!Ha&&!Pc&&!Lc&&!xc&&!Uc&&!Ja&&!Vc&&Bt,mR=$("HeadlessChrome"),Ht=Fc(),ps=Bt&&Ht>=128&&Ht<=143,lf=Ve("Chrome"),pR=bc("Electron"),Ze=!Bt&&!Ga&&!Wa&&!Oc&&!Mc&&$("Safari"),en=Ze||be,xi=Ve("Version"),vB=/Android.*(wv|.0.0.0)/.test(Ft),rt=(()=>{if(Wp)return xi;if(be){let e=Ft.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""})();function cf(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,a=r[n]||0;if(s<a)return!0;if(s>a)return!1}return!1}function Ui(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 a=r[s]||0,o=n[s]||0;if(a>o)return!0;if(a<o)return!1}return i}var Rt=Number(rt.split(".")[0]),yB=xi==="15.1",fR=rt==="15.1",_R=(()=>{let e=Number(rt.split(".")[0]);return e===14||e===13})(),gR=qa&&xi==="11.1.1",tn=typeof location<"u"&&(location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"),rn=(()=>{let e;return()=>{if(e===void 0)try{e=!!window.localStorage}catch{e=!1}return e}})(),Tr=TR();function TR(){let e=new Map([[me,["Firefox",Gp]],[Ha,["Edg",zp]],[Bc,["Chrome",lf]],[qa,["ChiOS",Ve("CriOS")]],[Ze&&!qa,["Safari",xi]],[pi,["TBS",qp]],[$r,["XWEB",Yp]],[_r&&Zr,["WeChat",Xp]],[Pc,["QQ(Win)",Qp]],[Ga,["QQ(Mobile)",ja]],[Wa,["QQ(Mobile X5)",ja]],[Oc,["QQ(Mac)",Zp]],[Mc,["QQ(iPad)",$p]],[Lc,["MI",tf]],[xc,["HW",nf]],[Uc,["Samsung",sf]],[Ja,["OPPO",af]],[Vc,["VIVO",of]],[hs,["EDGE",jp]],[wc,["SogouMobile",Jp]],[Nc,["Sogou",Kp]]]),t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var ve=null;function Hc(){return ve&&typeof ve.mobile=="boolean"?ve.mobile:Oe||be||Zr||ds||Ka}var Vi="";function Wc(){return g(this,null,function*(){if(ve)return ve;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return(ve=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!Vi&&(Vi="UAData: ".concat(ve.platform,"/").concat(ve.platformVersion),ve.architecture&&ve.bitness&&(Vi+=" ".concat(ve.architecture,"/").concat(ve.bitness)),ve.mobile&&(Vi+=" mobile"),ve.model&&(Vi+=" model: ".concat(ve.model.replace(/\s+/g,"/"))),ve.fullVersionList&&(Vi+=" ".concat(ve.fullVersionList.filter(e=>e.brand!=="Not/A)Brand").map(e=>"".concat(e.brand,"/").concat(e.version)).join(",")))),ve}catch{return null}})}var uf="";function fs(){try{if(uf)return uf;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 uf="".concat(r," ").concat(n)}return""}catch{return""}}function ER(){try{let e=fs();return e.includes("AMD")||e.includes("ATI")}catch{return!1}}function SB(){try{let e=fs();return e.includes("NVIDIA")||e.includes("GeForce")}catch{return!1}}function IB(){try{return fs().includes("Apple M")}catch{return!1}}function nn(){return(ve==null?void 0:ve.model)||df()||""}function df(){let e=Ft.match(/;\s*([^;)]+)\s+Build\//);return e!=null&&e[1]?e[1].trim():null}var vR=new Map([[Oe,"Android"],[be,"iOS"],[ms,"Windows"],[gr,"MacOS"],[za,"Linux"],[ef,"ChromeOS"]]),hf=function(){return vR.get(!0)?vR.get(!0):ve?ve.platform:"unknown"};function Gc(){return ms?1:Oe?2:gr?3:be?4:za?5:ef?6:Ka?7:0}function yR(){return _r||$r?4:Bt?1:Ze?2:me?3:0}var Er=()=>{let e=hf();return ve!=null&&ve.platformVersion?e+="/".concat(ve.platformVersion):be?e+="/".concat(rt):Oe&&(e+="/".concat(kc)),e+="/".concat(Tr.name,"/").concat(Ze&&!qa?Tr.version:Tr.version.split(".")[0]),ve!=null&&ve.architecture&&(e+="/".concat(ve.architecture)),e};function SR(){return Oe?4:Zr?2:ds?3:gr?12:ms?5:za?13:Ka?22:1}function AB(){return Oe?"Android":Zr?"iPhone":ds?"iPad":gr?"Mac":ms?"Windows":za?"Linux":"unknown"}var H,R=new(Ge(it(),1)).default,IR=((H=IR||{}).ROOM_DESTROY="1",H.JOIN_START="21",H.JOIN_SCHEDULE_SUCCESS="22",H.JOIN_SIGNAL_CONNECTION_START="23",H.JOIN_SIGNAL_CONNECTION_END="24",H.JOIN_SEND_CMD="25",H.JOIN_RECEIVED_CMD_RES="26",H.JOIN_SUCCESS="27",H.JOIN_FAILED="28",H.LEAVE_START="51",H.LEAVE_SEND_CMD="52",H.LEAVE_SUCCESS="53",H.PUBLISH_START="61",H.SEND_FIRST_VIDEO_FRAME="62",H.PUBLISH_FAILED="63",H.SUBSCRIBE_START="81",H.SUBSCRIBE_SUCCESS="82",H.SUBSCRIBE_FAILED="84",H.UNSUBSCRIBE_SUCCESS="83",H.LOCAL_TRACK_CAPTURE_START="101",H.LOCAL_TRACK_CAPTURE_SUCCESS="102",H.LOCAL_TRACK_CAPTURE_FAILED="103",H.LOCAL_TRACK_PUBLISHED="104",H.LOCAL_TRACK_UNPUBLISHED="105",H.LOCAL_TRACK_REPLACED="106",H.SWITCH_DEVICE_SUCCESS="107",H.TRACK_MUTED="108",H.TRACK_UNMUTED="109",H.REMOTE_TRACK_SUBSCRIBED="110",H.REMOTE_TRACK_UNSUBSCRIBED="111",H.LOCAL_TRACK_RECAPTURE="112",H.LOCAL_AUDIO_STARTED="113",H.LOCAL_AUDIO_STOPPED="114",H.REMOTE_AUDIO_STARTED="115",H.REMOTE_AUDIO_STOPPED="116",H.LOCAL_TRACK_STOPPED="117",H.LOCAL_VIDEO_TRACK_PREPROCESSED="118",H.PLAY_TRACK_START="151",H.PLAYER_STATE_CHANGED="152",H.VIDEO_LOADED_DATA="153",H.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",H.AUDIO_CONTEXT_LONG_SUSPENDED="155",H.REMOTE_VIDEO_PLAY_START="156",H.REMOTE_VIDEO_PLAY_FINISH="157",H.SIGNAL_CONNECTION_STATE_CHANGED="201",H.PEER_CONNECTION_STATE_CHANGED="202",H.SINGLE_CONNECTION_STAT="203",H.SPC_RECONNECTED="204",H.HEARTBEAT_REPORT="251",H.RECEIVED_PUBLISHED_USER_LIST="252",H.REMOTE_PUBLISH_STATE_CHANGED="253",H.AUDIO_LEVEL_INTERVAL="260",H.NETWORK_QUALITY="261",H.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",H.QUALITY_LIMITATION_CHANGED="263",H.LOG="264",H.AUDIO_PROCESSOR_DEBUG="265",H.SSO_SWITCH="266",H.SEI_MESSAGE="267",H.USER_PAUSE_IN_PIP="268",H.USER_RESUME_IN_PIP="269",H.ENTER_PICTURE_IN_PICTURE="270",H.LEAVE_PICTURE_IN_PICTURE="271",H.SWITCH_ROOM_START="401",H.SWITCH_ROOM_SUCCESS="407",H.SWITCH_ROOM_FAILED="408",H),b=IR,Ya=new class{constructor(){u(this,"enable",!1),u(this,"ssoFailCount",0),R.on("22",e=>{let{schedule:t}=e;var i;(i=t==null?void 0:t.config)!=null&&i.sso&&R.emit("266",{enable:!0})}),R.on("266",e=>{let{enable:t}=e;this.enable=t})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&R.emit("266",{enable:!1})}},AR=class Tk{constructor(){u(this,"_isEnableUploadLog",!0),u(this,"_localJoinedUser",new Map),u(this,"_queue",[]),u(this,"_timeoutId",-1),u(this,"_logLevel",1),u(this,"_logLevelToUpload",2),!dc&&!np&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){R.on(b.JOIN_SCHEDULE_SUCCESS,t=>{let{schedule:i}=t;var r;(r=i==null?void 0:i.config)!=null&&r.logLevelToUpload&&dr[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),R.on(b.JOIN_START,t=>{let{params:i}=t;this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),R.on(b.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:a}=n;t.map.has(s)?t.map.get(s).logs.push(r):t.map.set(s,{userId:s,sdkAppId:a,logs:[r]})});else if(he(r.userId)&&le(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 g(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:a,sdkAppId:o,logs:l}=n[s],c={timestamp:cA(),sdkAppId:String(o),userId:a,version:ei,log:l.map(m=>m.log).join(`
|
||
`)},d=JSON.stringify(c),h=Ya.enable?us(c,2002,o):d;yield this.uploadLogWithRetry(h,o,h instanceof Uint8Array,d),l.forEach(m=>m.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 Fa({retryFunction:()=>Va({url:os(i,va.LOG),body:t,timeout:5e3,priority:"low"}).then(s=>{r&&s.data!=="ok"&&(Ya.handleUploadFailed(),this.uploadLogWithRetry(n,i,!1,n))}),settings:{retries:3,timeout:2e3},onError:s=>{let{retry:a}=s;a()}})()}getPrefix(t){let i=new Date;return i.setTime(Ta()),"[".concat(ip(i),"] <").concat(dr[t],">")}getLogLevel(){return this._logLevel}setLogLevel(t){I(dr[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(he(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,a={log:i.reduce((o,l)=>"".concat(o," ").concat(this.logChunkToString(l)).trim(),""),level:t,userId:n,sdkAppId:s,forAllJoinedClients:r};R.emit(b.LOG,{log:a}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(a)}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 a;if(i.unshift(this.getPrefix(t)),this.addLogToQueue(t,i,r,n,s),t<this._logLevel)return;let o=((a=dr[t])==null?void 0:a.toLowerCase())||"info";Tk.PRINT_LOG_TAG?console[o]("%cTRTC%c%s","padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;","display: inline",...i):console[o](...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 Hp){let i=t,{parent:r}=i,n=iA(i,["parent"]),s=new Hp(n);return s.bindParent(r),s}return new Hp(t)}checkURLParam(){let t=new URLSearchParams(location.search).get("logLevelToUpload"),i=t?Number(t):-1;dr[i]&&(this._logLevelToUpload=i)}getQueue(){return this._queue}};u(AR,"PRINT_LOG_TAG",!(be||Oe||mR));var P=new AR,RR=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)})},mf=new class{constructor(){u(this,"_prefix","TRTC"),u(this,"_queue",new Map)}getRealKey(e){return"".concat(this._prefix,"_").concat(e)}checkStorage(){rn()&&(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(rn())try{for(let[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(e){P.warn(e)}}getItem(e){if(!rn())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){P.warn(t)}}setItem(e,t){if(rn())try{let i={expiresIn:Date.now()+_A,value:t};this._queue.set(this.getRealKey(e),i)}catch(i){P.warn(i)}}deleteItem(e){if(!rn())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(t){return P.warn(t),!1}}clear(){if(rn())try{localStorage.clear()}catch(e){P.warn(e)}}},_s={};Ni(_s,{HTTPS_API:()=>MB,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>xC,IS_GET_CAPABILITIES_SUPPORTED:()=>LC,IS_GET_SETTINGS_SUPPORTED:()=>Es,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>MC,IS_INSERTABLE_STREAM_SUPPORTED:()=>an,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>qc,IS_RTC_RTP_SENDER_SUPPORTED:()=>to,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>Kc,IS_SEI_SUPPORTED:()=>kf,IS_SPC_SUPPORTED:()=>eo,basis:()=>UB,capabilityCheck:()=>WC,checkSystemRequirementsInternal:()=>Sf,decodeSupportStatus:()=>yf,detectH264SupportedByFakeStreaming:()=>bC,detectVideoCodecCapabilities:()=>zC,detectVideoDecoderCapabilities:()=>KC,detectVideoEncoderCapabilities:()=>JC,encodeSupportStatus:()=>vf,getBrowserInfo:()=>wB,getDisplayResolution:()=>kC,getH264ProfileLevelIds:()=>qC,isAddTransceiverSupported:()=>ri,isBrowserSupported:()=>gf,isCanvasCaptureStreamAPISupported:()=>NC,isCanvasSmallStreamSupported:()=>Rf,isGetReceiversSupported:()=>Jc,isGetSendersSupported:()=>$a,isGetTransceiversSupported:()=>Ts,isGetUserMediaSupported:()=>DC,isMediaDevicesSupported:()=>Tf,isMediaSessionSupported:()=>UC,isMediaStreamTrackGeneratorSupported:()=>NB,isMediaStreamTrackProcessorSupported:()=>Ef,isReplaceTrackSupported:()=>OC,isRequestVideoFrameCallbackSupported:()=>io,isSIMDSupported:()=>FC,isScaleResolutionDownBySupported:()=>PC,isScreenCaptureApiAvailable:()=>zc,isSelectedCandidatePair:()=>Za,isSetParametersSupported:()=>bf,isSetSinkIdSupported:()=>OB,isSmallStreamSupported:()=>Cf,isStopTransceiverSupported:()=>xB,isTRTCSupported:()=>PB,isUnifiedPlanDefault:()=>LB,isUsedInHttpProtocol:()=>sn,isWebAudioSupported:()=>wC,isWebCodecSupported:()=>wf,isWebCodecsSupported:()=>jc,isWebRTCSupported:()=>Df,isWebTransportSupported:()=>VC});var CR={};Ni(CR,{AUDIO_LEVEL_SCALE:()=>fi,AlphaStitchingType:()=>_f,AudioCodecPipelineType:()=>cC,AudioDecoderDowngradeState:()=>WR,AudioPlayerMode:()=>rC,AudioType:()=>KR,BASIC_TYPE:()=>oC,BannedReason:()=>nC,CONNECTION_CLOSED_REASON:()=>DR,CheckPermissionType:()=>fC,ClientEvent:()=>wR,CodecType:()=>uC,ConnectionEvent:()=>kR,ConnectionState:()=>HR,DECODE_FAILED_ERROR_CODE:()=>dC,DenoiserMode:()=>aC,DeviceType:()=>_C,FacingMode:()=>tC,FrameWorkType:()=>bR,LatencyLevel:()=>gC,LeaveReason:()=>sC,LocalTrackEvent:()=>PR,MULTI_VIDEO_DATA_TYPE:()=>QR,MediaType:()=>JR,MediaTypeLabel:()=>RB,MonitorEventId:()=>ZR,MutedFlag:()=>UR,NetworkQualityValue:()=>$R,PlayerState:()=>OR,ReceiveMode:()=>eC,RemoteStreamType:()=>XR,RemoteTrackEvent:()=>xR,RoomEvent:()=>MR,SMALL_MODE:()=>pC,SceneNumber:()=>VR,StreamEvent:()=>NR,StreamType:()=>YR,SubscribeMediaType:()=>CB,TIMER_TYPE:()=>mC,TRACK_ACTION:()=>zR,TRACK_KIND:()=>jR,TrackEvent:()=>LR,UserRole:()=>BR,UserRoleNumber:()=>FR,VideoCodec:()=>ff,VideoCodecPipelineType:()=>lC,VideoContentHint:()=>hC,VideoDecoderDowngradeState:()=>GR,VideoPlayerMode:()=>iC,VideoType:()=>qR});var ke,je,V,pf,Xa,ht,Ce,Fi,gs,$e,nt,bR=(e=>(e[e.WEBRTC=30]="WEBRTC",e[e.WASM=37]="WASM",e))(bR||{}),kR=((nt=kR||{}).TRACK_ADDED="track-added",nt.TRACK_UPDATED="track-updated",nt.TRACK_SUBSCRIBED="track-subscribed",nt.STREAM_ADDED="stream-added",nt.STREAM_REMOVED="stream-removed",nt.STREAM_UPDATED="stream-updated",nt.STREAM_PUBLISHED="stream-published",nt.STREAM_SUBSCRIBED="stream-subscribed",nt.STREAM_UNSUBSCRIBED="stream-unsubscribed",nt.STATE_CHANGED="state-changed",nt.ERROR="error",nt.CONNECTION_STATE_CHANGED="connection-state-changed",nt.FIREWALL_RESTRICTION="firewall-restriction",nt.SEI_MESSAGE="sei-message",nt.CLOSED="closed",nt),DR=(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))(DR||{}),wR=(($e=wR||{}).STREAM_ADDED="stream-added",$e.STREAM_REMOVED="stream-removed",$e.STREAM_UPDATED="stream-updated",$e.STREAM_SUBSCRIBED="stream-subscribed",$e.CONNECTION_STATE_CHANGED="connection-state-changed",$e.PEER_JOIN="peer-join",$e.PEER_LEAVE="peer-leave",$e.MUTE_AUDIO="mute-audio",$e.MUTE_VIDEO="mute-video",$e.UNMUTE_AUDIO="unmute-audio",$e.UNMUTE_VIDEO="unmute-video",$e.CLIENT_BANNED="client-banned",$e.NETWORK_QUALITY="network-quality",$e.AUDIO_VOLUME="audio-volume",$e.SEI_MESSAGE="sei-message",$e.ERROR="error",$e),NR=((gs=NR||{}).PLAYER_STATE_CHANGED="player-state-changed",gs.SCREEN_SHARING_STOPPED="screen-sharing-stopped",gs.CONNECTION_STATE_CHANGED="connection-state-changed",gs.DEVICE_AUTO_RECOVERED="device-auto-recovered",gs.ERROR="error",gs),PR=((Fi=PR||{}).DEVICE_AUTO_RECOVERED="1",Fi.DEVICE_RECOVER_FAILED="5",Fi.DEVICE_CHANGED="2",Fi.ERROR="3",Fi.PUBLISH_STATE_CHANGED="4",Fi.ENCODE_FAILED="6",Fi.TRACK_ENDED="7",Fi.RENDER="render",Fi),OR=(e=>(e.PAUSED="PAUSED",e.PLAYING="PLAYING",e.STOPPED="STOPPED",e))(OR||{}),MR=((Ce=MR||{}).PEER_JOIN="peer-join",Ce.PEER_LEAVE="peer-leave",Ce.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",Ce.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",Ce.BANNED="banned",Ce.NETWORK_QUALITY="network-quality",Ce.AUDIO_VOLUME="audio-volume",Ce.SEI_MESSAGE="sei-message",Ce.ERROR="error",Ce.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",Ce.REMOTE_PUBLISHED="remote-published",Ce.REMOTE_UNPUBLISHED="remote-unpublished",Ce.FIREWALL_RESTRICTION="firewall-restriction",Ce.HEARTBEAT_REPORT="heartbeat-report",Ce.CUSTOM_MESSAGE="custom-message",Ce.LAYER_DATA="layerData",Ce.FIRST_VIDEO_FRAME="first-video-frame",Ce.DUMP="dump",Ce.AUDIO_FRAME="audio-frame",Ce.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",Ce.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",Ce.NTP_TIME_UPDATED="ntp-time-updated",Ce.DATA_CHANNEL_MESSAGE="data-channel-message",Ce.ASR_ROBOT_PEER_JOIN="asr-robot-peer-join",Ce.ASR_ROBOT_PEER_LEAVE="asr-robot-peer-leave",Ce),LR=(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))(LR||{}),xR=(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))(xR||{}),UR=((ht=UR||{})[ht.VIDEO=1]="VIDEO",ht[ht.SMALL=2]="SMALL",ht[ht.AUX=4]="AUX",ht[ht.AUDIO=8]="AUDIO",ht[ht.VIDEO_MUTE=16]="VIDEO_MUTE",ht[ht.AUX_MUTE=32]="AUX_MUTE",ht[ht.AUDIO_MUTE=64]="AUDIO_MUTE",ht),VR=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(VR||{}),FR=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(FR||{}),BR=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(BR||{}),HR=(e=>(e.CONNECTED="CONNECTED",e.DISCONNECTED="DISCONNECTED",e.CONNECTING="CONNECTING",e.RECONNECTED="RECONNECTED",e.RECONNECTING="RECONNECTING",e))(HR||{}),WR=((Xa=WR||{}).INITIALIZED="INITIALIZED",Xa.STARTING="STARTING",Xa.STARTED="STARTED",Xa.FAILED="FAILED",Xa),GR=(e=>(e.INITIALIZED="INITIALIZED",e.STARTING="STARTING",e.STARTED="STARTED",e.FAILED="FAILED",e))(GR||{}),jR=(e=>(e.AUDIO="audio",e.VIDEO="video",e.AUXILIARY="auxVideo",e))(jR||{}),zR=(e=>(e.ADD="add",e.REMOVE="remove",e))(zR||{}),JR=(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))(JR||{}),RB={1:"audio",2:"auxVideo",4:"video"},KR=((pf=KR||{})[pf.opus=111]="opus",pf),qR=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(qR||{}),YR=(e=>(e.Big="big",e.Small="small",e))(YR||{}),XR=(e=>(e.Main="main",e.Aux="auxiliary",e))(XR||{}),QR=(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))(QR||{}),ZR=((V=ZR||{})[V.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",V[V.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",V[V.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",V[V.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",V[V.MUTE_AUDIO=32772]="MUTE_AUDIO",V[V.MUTE_VIDEO=32773]="MUTE_VIDEO",V[V.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",V[V.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",V[V.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",V[V.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",V[V.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",V[V.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",V[V.SWITCH_CAMERA=32780]="SWITCH_CAMERA",V[V.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",V[V.REPLACE_VIDEO=32782]="REPLACE_VIDEO",V[V.REPLACE_AUDIO=32783]="REPLACE_AUDIO",V[V.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",V[V.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",V[V.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",V[V.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",V[V.JOIN=32788]="JOIN",V[V.LEAVE=32789]="LEAVE",V[V.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",V[V.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",V[V.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",V[V.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",V[V.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",V[V.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",V[V.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",V[V.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",V[V.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",V[V.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",V[V.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",V[V.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",V[V.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",V[V.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",V[V.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",V[V.PUBLISH_AUX=32805]="PUBLISH_AUX",V[V.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",V[V.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",V[V.VIDEO_ENCODER=4004]="VIDEO_ENCODER",V[V.VIDEO_DECODER=4005]="VIDEO_DECODER",V),$R=(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))($R||{}),eC=(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))(eC||{}),tC=(e=>(e.user="user",e.environment="environment",e))(tC||{}),iC=(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))(iC||{}),rC=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(rC||{}),nC=(e=>(e.BANNED="banned",e.KICK="kick",e.USER_TIME_OUT="user_time_out",e.ROOM_DISBAND="room_disband",e))(nC||{}),sC=((je=sC||{})[je.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",je[je.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",je[je.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",je[je.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",je[je.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",je[je.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",je[je.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",je[je.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",je[je.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",je),fi=1e8,aC=(e=>(e[e.NORMAL=0]="NORMAL",e[e.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",e))(aC||{}),CB=class{constructor(){u(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)}},oC=(e=>(e.String="string",e.Number="number",e.Boolean="boolean",e.Array="array",e.Object="object",e))(oC||{}),ff=(e=>(e.H264="h264",e.H265="h265",e.VP8="vp8",e.VP9="vp9",e.AV1="av1",e))(ff||{}),lC=(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))(lC||{}),cC=(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))(cC||{}),uC=(e=>(e.WebRTC="webrtc",e.WebCodecs="webcodecs",e.WebAssembly="webassembly",e))(uC||{}),dC=((ke=dC||{})[ke.SUCCESS=0]="SUCCESS",ke[ke.FAILED=1]="FAILED",ke[ke.WEBCODEC_INIT=2]="WEBCODEC_INIT",ke[ke.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",ke[ke.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",ke[ke.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",ke[ke.WASM_INIT=6]="WASM_INIT",ke[ke.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",ke[ke.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",ke[ke.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",ke[ke.TEST=10]="TEST",ke[ke.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",ke),hC=(e=>(e.NONE="",e.DETAIL="detail",e.MOTION="motion",e.TEXT="text",e))(hC||{}),mC=(e=>(e.INTERVAL="interval",e.TIMEOUT="timeout",e.RAF="raf",e.RIC="ric",e.INTERVAL_IN_WORKER="intervalInWorker",e))(mC||{}),pC=(e=>(e.CANVAS="canvas",e.API="api",e))(pC||{}),fC=(e=>(e[e.NONE=0]="NONE",e[e.MICROPHONE=1]="MICROPHONE",e[e.CAMERA=2]="CAMERA",e[e.BOTH=3]="BOTH",e))(fC||{}),_C=(e=>(e.CAMERA="camera",e.MICROPHONE="microphone",e))(_C||{}),_f=(e=>(e[e.none=0]="none",e[e.horizontal=1]="horizontal",e[e.vertical=2]="vertical",e))(_f||{}),gC=(e=>(e[e.LOW=1]="LOW",e[e.NORMAL=2]="NORMAL",e))(gC||{}),K={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",SWITCH_PLAYBACK_QUALITY_TIMEOUT:"SWITCH_PLAYBACK_QUALITY_TIMEOUT"},ii={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),a="";return a=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(s,"' must be type of ").concat(a," when calling ").concat(r,"(), received type: ").concat(Je(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),a="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(s,"' must be instanceof ").concat(a," when calling ").concat(r,"(), received type: ").concat(Je(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,"()"),SWITCH_PLAYBACK_QUALITY_TIMEOUT:e=>"switchPlaybackQuality timeout: waiting for first frame of user ".concat(e.userId,".")},TC=(e,t)=>t?"".concat(Pi,"/").concat(e,"/").concat(t):"".concat(Pi,"/").concat(e,"/index.html"),bB=()=>{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(fA);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 Y(e){let{key:t,data:i,link:r,addDocLink:n=!0}=e,s="",a="",o="";Pe(ii[t])?s=ii[t](i):he(ii[t])&&(s=ii[t]);let{TRTC_ERROR_INFO:l,TRTC_ERROR_LINK:c}=bB();r?o="".concat(r.className,".html#").concat(r.fnName):c&&c[t]&&(Pe(c[t])?o=c[t](i):he(c[t])&&(o=c[t]));let d=s;return Mi()&&(l&&l[t]&&(Pe(l[t])?a=l[t](i):he(l[t])&&(a=l[t])),a&&(d=n?"".concat(a,`
|
||
请查看文档: `).concat(TC("zh-cn",o),`
|
||
|
||
`):"".concat(a,`
|
||
|
||
`),d+=s)),n&&(d+=`
|
||
Refer to: `.concat(TC("en",o),`
|
||
`)),d}var Z,ae,EC=Ge(w3(),1),vC=class{constructor(){let e=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];u(this,"countMap",new Map),u(this,"distributionMap",new Map),u(this,"version"),u(this,"log",P.createLogger({id:"kv"})),e&&(R.on("102",t=>{let{track:i,cost:r}=t;this.addSuccessEvent({key:i.kind===_.AUDIO?501700:511700,cost:r})}),R.on("103",t=>{let{track:i,error:r}=t;this.addFailedEvent({key:i.kind===_.AUDIO?501700:511700,error:r})}),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:Np(this.version||ei),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(a=>{let[o,l]=a;return{uint32_item_key:o,uint32_item_value:l}})}}),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 a;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 o=((a=this.distributionMap)==null?void 0:a.get(t))||new Map,l=0;if(le(r))l=Math.floor(i/r);else for(let c=r.length-1;c>0;c--)if(i>r[c]){l=c;break}o.set(l,(o.get(l)||0)+1),this.distributionMap.set(t,o)}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=C.UNKNOWN;i&&(le(i)?r=i:(!I(i.extraCode)||!I(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})}},yC=((Z=yC||{})[Z.enterRoom=500700]="enterRoom",Z[Z.exitRoom=500701]="exitRoom",Z[Z.switchRole=500702]="switchRole",Z[Z.destroy=500703]="destroy",Z[Z.startLocalAudio=500704]="startLocalAudio",Z[Z.updateLocalAudio=500705]="updateLocalAudio",Z[Z.stopLocalAudio=500706]="stopLocalAudio",Z[Z.startLocalVideo=500707]="startLocalVideo",Z[Z.updateLocalVideo=500708]="updateLocalVideo",Z[Z.stopLocalVideo=500709]="stopLocalVideo",Z[Z.startScreenShare=500710]="startScreenShare",Z[Z.updateScreenShare=500711]="updateScreenShare",Z[Z.stopScreenShare=500712]="stopScreenShare",Z[Z.startRemoteVideo=500713]="startRemoteVideo",Z[Z.updateRemoteVideo=500714]="updateRemoteVideo",Z[Z.stopRemoteVideo=500715]="stopRemoteVideo",Z[Z.muteRemoteAudio=500716]="muteRemoteAudio",Z[Z.setRemoteAudioVolume=500717]="setRemoteAudioVolume",Z[Z.use=500718]="use",Z[Z.switchRoom=500719]="switchRoom",Z[Z.getPermissions=500720]="getPermissions",Z[Z.sendSEIMessage=5e5]="sendSEIMessage",Z[Z.sendCustomMessage=500001]="sendCustomMessage",Z),SC=(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))(SC||{}),IC=(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))(IC||{}),AC=(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))(AC||{}),RC=((ae=RC||{})[ae.DECODER_TYPE=514700]="DECODER_TYPE",ae[ae.DECODER_HW_SW=514701]="DECODER_HW_SW",ae[ae.DECODE_RESULT=514702]="DECODE_RESULT",ae[ae.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",ae[ae.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",ae[ae.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",ae[ae.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",ae[ae.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",ae[ae.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",ae[ae.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",ae[ae.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",ae[ae.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",ae[ae.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",ae[ae.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",ae[ae.H264_PROFILE_LEVEL_ID_HIGH=514714]="H264_PROFILE_LEVEL_ID_HIGH",ae[ae.H264_PROFILE_LEVEL_ID_MAIN=514715]="H264_PROFILE_LEVEL_ID_MAIN",ae[ae.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",ae[ae.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",ae[ae.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",ae),kB=new vC(!0),Qa=new vC(!1),w=kB,ie={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}},DB=new Map([[me,["Firefox",Gp]],[Ha,["Edg",zp]],[Bc,["Chrome",lf]],[Ze,["Safari",xi]],[pi,["TBS",qp]],[$r,["XWEB",Yp]],[_r&&Zr,["WeChat",Xp]],[Pc,["QQ(Win)",Qp]],[Ga,["QQ(Mobile)",ja]],[Wa,["QQ(Mobile X5)",ja]],[Oc,["QQ(Mac)",Zp]],[Mc,["QQ(iPad)",$p]],[Lc,["MI",tf]],[xc,["HW",nf]],[Uc,["Samsung",sf]],[Ja,["OPPO",af]],[Vc,["VIVO",of]],[hs,["EDGE",jp]],[wc,["SogouMobile",Jp]],[Nc,["Sogou",Kp]]]);function wB(){let e=DB.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var gf=function(){return!(dR||hs||Ha&&cR<80||me&&Dc<56)},jc=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(e=>e in window)},Tf=function(){if(!navigator.mediaDevices)return sn()||P.error(ii.NOT_SUPPORTED_MEDIA),!1;let e=["getUserMedia","enumerateDevices"];return e.filter(t=>t in navigator.mediaDevices).length===e.length},CC=!1;function sn(){return location.protocol==="http:"&&!tn&&(CC||P.error(Y({key:K.NOT_SUPPORTED_HTTP})),CC=!0,!0)}var Ef=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},NB=function(){return!(window==null||!window.MediaStreamTrackGenerator)},vf=function(){return g(this,null,function*(){var e,t,i;if(ie.detail.isH264EncodeSupported&&ie.detail.isVp8EncodeSupported)return{isH264EncodeSupported:ie.detail.isH264EncodeSupported,isVp8EncodeSupported:ie.detail.isVp8EncodeSupported,isH265EncodeSupported:ie.detail.isH265EncodeSupported};let r,n=!1,s=!1,a=!1;try{let o=new RTCPeerConnection,l=document.createElement(_.CANVAS);l.getContext("2d");let c=l.captureStream(0);return o.addTrack(c.getVideoTracks()[0],c),r=yield o.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,a=((i=r.sdp)==null?void 0:i.toLowerCase().indexOf("h265"))!==-1,o.close(),{isH264EncodeSupported:n,isVp8EncodeSupported:s,isH265EncodeSupported:a}}catch{return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}})},yf=function(){return g(this,null,function*(){var e;if(ie.detail.isH264DecodeSupported&&ie.detail.isVp8DecodeSupported)return{isH264DecodeSupported:ie.detail.isH264DecodeSupported,isVp8DecodeSupported:ie.detail.isVp8DecodeSupported,isH265DecodeSupported:ie.detail.isH265DecodeSupported};let t,i=!1,r=!1;try{let n=new RTCPeerConnection;ri()?(n.addTransceiver(_.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}}})},Sf=Pp(e=>g(null,null,function*(){let t=Date.now(),i=Df(),r=Tf(),n=jc();if(ie.detail.isWebRTCSupported=i,ie.detail.isMediaDevicesSupported=r,ie.detail.isWebCodecsSupported=n,ie.detail.isScreenShareSupported=zc(),ie.detail.isSmallStreamSupported=Cf(),e===37)return Object.assign(ie.detail,yield(function(){return g(this,null,function*(){return Af||(Af=new Promise(f=>g(null,null,function*(){let T={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!jc())return void f(T);let E=null,v=null,y=null,D=()=>{y&&clearTimeout(y),E=null,v=null};try{E=document.createElement("canvas"),v=E.getContext("2d"),E.width=320,E.height=240;let N=0,S=()=>{!v||!E||(v.fillStyle="hsl(".concat(N%360,", 50%, 50%)"),v.fillRect(0,0,E.width,E.height),v.fillStyle="white",v.font="20px Arial",v.fillText("Frame ".concat(N),10,30),N++)};y=setTimeout(()=>{D(),f(T)},5e3);let A=[{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(A.map(L=>g(null,null,function*(){let U,q={type:L.type,encodeSupported:!1,decodeSupported:!1};try{U=yield new Promise((fe,Re)=>g(null,null,function*(){try{let ne=new VideoEncoder({output:xe=>{fe(xe),q.encodeSupported=!0},error:Re});ne.configure(L.encodeConfig),S();let ft=new VideoFrame(E,{timestamp:0});ne.encode(ft,{keyFrame:!0}),ft.close(),yield ne.flush(),ne.close()}catch(ne){Re(ne)}}))}catch(fe){return P.warn("".concat(L.type," encoder error:"),fe),q}try{yield new Promise((fe,Re)=>g(null,null,function*(){try{let ne=new VideoDecoder({output:ft=>{q.decodeSupported=!0,fe(0),ft.close()},error:Re});ne.configure(L.decodeConfig),ne.decode(U),yield ne.flush(),ne.close()}catch(ne){Re(ne)}}))}catch(fe){P.warn("".concat(L.type," decoder error:"),fe)}return q})))).forEach(L=>{L.type==="h264"?(T.isH264EncodeSupported=L.encodeSupported,T.isH264DecodeSupported=L.decodeSupported):L.type==="vp8"&&(T.isVp8EncodeSupported=L.encodeSupported,T.isVp8DecodeSupported=L.decodeSupported)}),D(),f(T)}catch(N){D(),P.warn("detectWebCodecsSupported failed:",N),f(T)}})),Af)})})()),ie.detail.isBrowserSupported=n,ie.result=r&&n,ie.result||P.error("".concat(navigator.userAgent," ").concat(Sc(ie.detail,!1))),HC(e),w.addNumber({key:523800,value:Date.now()-t}),ie;if(ie.result&&ie.detail.isH264EncodeSupported&&ie.detail.isVp8EncodeSupported&&ie.detail.isH265EncodeSupported&&ie.detail.isH264DecodeSupported&&ie.detail.isVp8DecodeSupported&&ie.detail.isH265DecodeSupported)return ie;let s=gf(),{encode:a,decode:o}=yield(function(){return g(this,null,function*(){let[f,T]=yield Promise.all([vf(),yf()]);return{encode:{h264:f.isH264EncodeSupported,vp8:f.isVp8EncodeSupported,h265:f.isH265EncodeSupported},decode:{h264:T.isH264DecodeSupported,vp8:T.isVp8DecodeSupported,h265:T.isH265DecodeSupported}}})})(),{h264:l,vp8:c}=a,{h264:d}=o,{h265:h}=a,{vp8:m,h265:p}=o;if(!l||!c){let f=yield vf();P.warn("detect encode again h264:".concat(l," vp8:").concat(c," result: ").concat(JSON.stringify(f))),l=f.isH264EncodeSupported,c=f.isVp8EncodeSupported}if(l&&d&&Oe&&Bt&&!$r&&!pi&&(!Ja||Ht!==115)){let{encode:f,decode:T}=yield bC();l=f,d=T}return ie.result=s&&i&&r&&(l||c)&&(d||m),ie.detail.isBrowserSupported=s,ie.detail.isWebRTCSupported=i,ie.detail.isH264EncodeSupported=l,ie.detail.isVp8EncodeSupported=c,ie.detail.isH265EncodeSupported=h,ie.detail.isH264DecodeSupported=d,ie.detail.isVp8DecodeSupported=m,ie.detail.isH265DecodeSupported=p,ie.result||P.error("".concat(navigator.userAgent," ").concat(Sc(ie.detail,!1))),HC(),w.addNumber({key:523800,value:Date.now()-t}),ie})),PB=function(){return ie.result},zc=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},OB=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype,If=null;function bC(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3;return g(this,null,function*(){return If||(If=new Promise(t=>g(null,null,function*(){let i={encode:!1,decode:!1},r=()=>{};try{let n=document.createElement("canvas"),s=n.getContext("2d");n.width=640,n.height=480;let a=setInterval(()=>{s.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))},66),o=-1,l=-1;r=()=>{clearInterval(o),clearInterval(a),clearTimeout(l),d.close(),h.close(),c.getTracks().forEach(E=>E.stop())},l=setTimeout(()=>{r(),t(i)},e);let c=n.captureStream(),d=new RTCPeerConnection({}),h=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});d.addEventListener("icecandidate",E=>h.addIceCandidate(E.candidate)),h.addEventListener("icecandidate",E=>d.addIceCandidate(E.candidate)),d.addTrack(c.getVideoTracks()[0],c);let m=yield d.createOffer();yield d.setLocalDescription(m),yield h.setRemoteDescription(m);let p=yield h.createAnswer(),f=EC.default.parse(p.sdp),T=f.media[0].rtp.findIndex(E=>E.codec==="H264");f.media[0].rtp=[f.media[0].rtp[T]],f.media[0].fmtp=f.media[0].fmtp.filter(E=>E.payload===f.media[0].rtp[0].payload),f.media[0].rtcpFb&&(f.media[0].rtcpFb=f.media[0].rtcpFb.filter(E=>E.payload===f.media[0].rtp[0].payload)),p.sdp=EC.default.write(f),yield h.setLocalDescription(p),yield d.setRemoteDescription(p),o=setInterval(()=>g(null,null,function*(){i.encode&&i.decode&&(r(),t(i));let E=d.getSenders()[0],v=h.getReceivers()[0];if(!E||!v)return;let[y,D]=yield Promise.all([E.getStats(),v.getStats()]);i.encode||y.forEach(N=>{N.type==="outbound-rtp"&&(N.mediaType===_.VIDEO||N.kind===_.VIDEO)&&N.bytesSent>0&&(i.encode=!0)}),i.decode||D.forEach(N=>{N.type==="inbound-rtp"&&(N.mediaType===_.VIDEO||N.kind===_.VIDEO)&&N.bytesReceived>0&&(i.decode=!0)})}),100)}catch(n){r(),P.warn("detectH264Supported failed",n),t({encode:!0,decode:!0})}})).then(t=>(t.encode||(t.decode=!0),(!t.encode||!t.decode)&&P.warn("detectH264Supported encode: ".concat(t.encode," decode: ").concat(t.decode," ").concat(Vi)),t)),If)})}var Af=null,MB=(e,t,i)=>{location.protocol==="http:"&&!tn&&(e[t]=()=>{throw new O({code:C.INVALID_OPERATION,message:ii.NOT_SUPPORTED_HTTP})})},Za=function(e){return!(e.type!=="candidate-pair"||!e.nominated||e.state!=="in-progress"&&e.state!=="succeeded")&&!(Se(e.selected)&&!e.selected)};function kC(){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 DC(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function wC(){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 NC(){return"captureStream"in HTMLCanvasElement.prototype}function Rf(){return!(_r||be||Ht&&Ht<63)&&!(!gf()||!NC())}function PC(){return!(Ht<74||hs||Rt<11||Dc<46)}function Cf(){return Rf()||PC()}var LB=function(){if(I(window.RTCRtpTransceiver)||!ri()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:Aa}),e.addTransceiver(_.AUDIO),t=!0}catch{}return e==null||e.close(),t};function Jc(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function $a(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function Ts(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function ri(){return!(Rt===11&&!gR)&&"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var eo=!(!ri()||Bt&&Ht<86);function xB(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var to="RTCRtpSender"in window;function OC(){return to&&"replaceTrack"in window.RTCRtpSender.prototype}function bf(){return to&&"setParameters"in window.RTCRtpSender.prototype&&$a()}var MC="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,Es=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,LC=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,xC=typeof InputDeviceInfo<"u"&&"getCapabilities"in InputDeviceInfo.prototype,an=to&&"createEncodedStreams"in window.RTCRtpSender.prototype&&Fc()>=86,Kc="RTCRtpScriptTransform"in window,kf=to&&(an||Kc),Df=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(e=>e in window).length>0};function wf(){let e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return I(window.AudioDecoder)||(e.AudioDecoder=!0),I(window.AudioEncoder)||(e.AudioEncoder=!0),I(window.VideoDecoder)||(e.VideoDecoder=!0),I(window.VideoEncoder)||(e.VideoEncoder=!0),I(window.ImageDecoder)||(e.ImageDecoder=!0),e}function UC(){return"mediaSession"in navigator&&!I(navigator.mediaSession.setActionHandler)}function VC(){return!I(window.WebTransport)}function FC(){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 UB(){let e={browser:"".concat(Tr.name,"/").concat(Tr.version),os:hf(),displayResolution:kC(),isScreenShareSupported:zc(),isWebRTCSupported:Df(),isGetUserMediaSupported:DC(),isWebAudioSupported:wC(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:wf(),isMediaSessionSupported:UC(),isWebTransportSupported:VC()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var BC="checkResult";function HC(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:30;mf.setItem(BC+e,{ua:navigator.userAgent,checkResult:ie})}function WC(e){sn();let t=mf.getItem(BC+e);t&&t.ua===navigator.userAgent&&t.checkResult&&(function(i,r){return!!hi(i)&&Object.keys(r).every(n=>n in i)})(t.checkResult.detail,ie.detail)&&(ie=t.checkResult),Sf(e)}function io(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var qc="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function GC(e){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[e]}var jC=!1;function zC(){return g(this,null,function*(){var e;try{if(jC||(e=navigator==null?void 0:navigator.mediaCapabilities)==null||!e.encodingInfo)return;let t=Gc(),i=yR();if(t===0||i===0)return;jC=!0;let r=["H264","VP8","VP9","AV1","H265"],[n,s]=yield Promise.all([JC(r),KC(r)]);n&&Object.keys(n).forEach(l=>{let c=GC(l.toLowerCase());w.addEnum({key:513707,value:+"".concat(c).concat(+n[l].supported).concat(+n[l].powerEfficient).concat(t).concat(i),useUV:!1})}),s&&Object.keys(s).forEach(l=>{let c=GC(l.toLowerCase());w.addEnum({key:514713,value:+"".concat(c).concat(+s[l].supported).concat(+s[l].powerEfficient).concat(t).concat(i),useUV:!1})});let{sender:a,receiver:o}=qC();w.addEnum({key:513708,value:+"".concat(t).concat(i).concat(+a.high),useUV:!1}),w.addEnum({key:513709,value:+"".concat(t).concat(i).concat(+a.main),useUV:!1}),w.addEnum({key:514714,value:+"".concat(t).concat(i).concat(+o.high),useUV:!1}),w.addEnum({key:514715,value:+"".concat(t).concat(i).concat(+o.main),useUV:!1})}catch(t){P.info("detectVideoCodecCapabilities failed",t)}})}function JC(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 g(this,null,function*(){let s={};try{for(let a of e){let o=yield navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:"video/".concat(a),width:t,height:i,bitrate:n,framerate:r}});s[a]=o}}catch{}return s})}function KC(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 g(this,null,function*(){let s={};try{for(let a of e){let o=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:"video/".concat(a),width:t,height:i,bitrate:n,framerate:r}});s[a]=o}}catch{}return s})}function qC(){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){P.warn("get H264 profile levelId failed",t)}return e}var VB=Ge(it(),1),YC=Symbol("instance"),Yc=Symbol("cacheResult"),Nf=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,no.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},Pf=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}},ro=new Map;function Ke(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(r,n,s)=>{let a=i.action||n;if(!i.context){let l=ro.get(r)||[];ro.has(r)||ro.set(r,l),l.push({from:e,to:t,action:a})}let o=s.value;s.value=function(){let l=this;for(var c=arguments.length,d=new Array(c),h=0;h<c;h++)d[h]=arguments[h];if(i.context&&(l=re.get(typeof i.context=="function"?i.context.call(this,...d):i.context)),l.state===t)return i.sync?l[Yc]:Promise.resolve(l[Yc]);l.state instanceof Nf&&l.state.action==i.abortAction&&l.state.abort(l);let m=null;Array.isArray(e)?e.length==0?l.state instanceof Nf&&l.state.abort(l):(typeof l.state!="string"||!e.includes(l.state))&&(m=new Pf(l._state,"".concat(l.name," ").concat(a," to ").concat(t," failed: current state ").concat(l._state," not from ").concat(e.join("|")))):e!==l.state&&(m=new Pf(l._state,"".concat(l.name," ").concat(a," to ").concat(t," failed: current state ").concat(l._state," not from ").concat(e)));let p=y=>{if(i.fail&&i.fail.call(this,y),i.sync){if(i.ignoreError)return y;throw y}return i.ignoreError?Promise.resolve(y):Promise.reject(y)};if(m)return p(m);let f=l.state,T=new Nf(f,t,a);no.call(l,T);let E=y=>{var D;return l[Yc]=y,T.aborted||(no.call(l,t),(D=i.success)===null||D===void 0||D.call(this,l[Yc])),y},v=y=>(no.call(l,f,y),p(y));try{let y=o.apply(this,d);return(function(D){return typeof D=="object"&&D&&"then"in D})(y)?y.then(E).catch(v):i.sync?E(y):Promise.resolve(E(y))}catch(y){return v(new Pf(l._state,"".concat(l.name," ").concat(a," from ").concat(e," to ").concat(t," failed: ").concat(y),y instanceof Error?y:new Error(String(y))))}}}}var FB=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 no(e,t){let i=this._state;this._state=e;let r=e.toString();e&&this.emit(r,i),this.emit(re.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var re=class jt extends VB.default{constructor(t,i,r){super(),this.name=t,this.groupName=i,this._state=jt.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[YC];n?this.name=n.name+"-"+n.count++:r[YC]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let t=Object.getPrototypeOf(this),i=ro.get(t)||[],r=new Set,n=[],s=[],a=new Set,o=Object.getPrototypeOf(t);ro.has(o)&&(o.stateDiagram.forEach(c=>r.add(c)),o.allStates.forEach(c=>a.add(c))),i.forEach(c=>{let{from:d,to:h,action:m}=c;typeof d=="string"?n.push({from:d,to:h,action:m}):d.length?d.forEach(p=>{n.push({from:p,to:h,action:m})}):s.push({to:h,action:m})}),n.forEach(c=>{let{from:d,to:h,action:m}=c;a.add(d),a.add(h),a.add(m+"ing"),r.add("".concat(d," --> ").concat(m,"ing : ").concat(m)),r.add("".concat(m,"ing --> ").concat(h," : ").concat(m," 🟢")),r.add("".concat(m,"ing --> ").concat(d," : ").concat(m," 🔴"))}),s.forEach(c=>{let{to:d,action:h}=c;r.add("".concat(h,"ing --> ").concat(d," : ").concat(h," 🟢")),a.forEach(m=>{m!==d&&r.add("".concat(m," --> ").concat(h,"ing : ").concat(h))})});let l=[...r];return Object.defineProperties(t,{stateDiagram:{value:l},allStates:{value:a}}),l}static get(t){let i;return typeof t=="string"?(i=jt.instances.get(t),i||jt.instances.set(t,i=new jt(t,void 0,Object.create(jt.prototype)))):(i=jt.instances2.get(t),i||jt.instances2.set(t,i=new jt(t.constructor.name,void 0,Object.create(jt.prototype)))),i}static getState(t){var i;return(i=jt.get(t))===null||i===void 0?void 0:i.state}updateDevTools(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};FB(jt.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(t){no.call(this,t)}};re.STATECHANGED="stateChanged",re.UPDATEAFSM="updateAFSM",re.INIT="[*]",re.ON="on",re.OFF="off",re.instances=new Map,re.instances2=new WeakMap;var Of=typeof window<"u",XC=Of&&window.requestIdleCallback||function(e){let t=Date.now();return setTimeout(()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})},1e3)},BB=Of&&window.cancelIdleCallback||function(e){clearTimeout(e)},QC=Of&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),so=class _t{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=x(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=W(x({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,_t.isBreakLoop(t)},t.delay)}static intervalInWorker(t){_t.sharedWorker||(_t.sharedWorker=new Worker(URL.createObjectURL(new Blob([`
|
||
const timers = new Map();
|
||
self.onmessage = function(e) {
|
||
const { taskId, delay, type } = e.data;
|
||
if (type === 'start') {
|
||
timers.set(taskId, setInterval(() => {
|
||
self.postMessage({ type: 'tick', taskId });
|
||
}, delay));
|
||
} else if (type === 'stop') {
|
||
clearInterval(timers.get(taskId));
|
||
timers.delete(taskId);
|
||
}
|
||
};
|
||
`],{type:"application/javascript"}))),_t.sharedWorker.onmessage=i=>{var r;if(i.data.type==="tick"){let n=_t.workerTasks.get(i.data.taskId);n&&(_t.isBreakLoop(n)?((r=_t.sharedWorker)==null||r.postMessage({type:"stop",taskId:n.taskID}),_t.workerTasks.delete(n.taskID)):(n.callback(),n.loopCount+=1))}}),_t.workerTasks.set(t.taskID,t),_t.sharedWorker.postMessage({taskId:t.taskID,delay:t.delay,type:"start"})}static timeout(t){let i=()=>{if(t.callback(),t.loopCount+=1,!_t.isBreakLoop(t))return t.timeoutID=setTimeout(i,t.delay)};return t.timeoutID=setTimeout(i,t.delay)}static ric(t){let i,r=J(),n=()=>{if(i=J()-r,i>=t.delay&&(r=J()-Math.floor(i%t.delay),t.callback(),t.loopCount+=1),!_t.isBreakLoop(t))return t.ricID=XC(n,{timeout:t.delay})};return t.ricID=XC(n,{timeout:t.delay})}static raf(t){let i,r=J(),n=()=>document.hidden&&t.backgroundTask?(i=J()-r,r=J(),t.callback(),t.loopCount+=1,_t.isBreakLoop(t)?void 0:t.timeoutID=setTimeout(n,t.delay-Math.floor(i%t.delay))):(i=J()-r,i>=t.delay&&(r=J()-Math.floor(i%t.delay),t.callback(),t.loopCount+=1),_t.isBreakLoop(t)?void 0:t.rafID=requestAnimationFrame(n));if(t.rafID=requestAnimationFrame(n),t.backgroundTask){let s=()=>{if(document.hidden){let a=J()-r;a>=t.delay?n():t.timeoutID=setTimeout(n,t.delay-a)}};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:a}=this.taskMap.get(t);return i&&clearInterval(i),r&&clearTimeout(r),n&&QC&&QC(n),s&&BB(s),a&&document.removeEventListener("visibilitychange",a),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)}};u(so,"taskMap",new Map),u(so,"currentTaskID",1),u(so,"sharedWorker",null),u(so,"workerTasks",new Map);var _e=so,z={LOAD_START:_.LOADSTART,LOADED_DATA:_.LOADEDDATA,LOADED_META_DATA:_.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",RESIZE:_.RESIZE,TIME_UPDATE:"time-update",LEAVE_PICTURE_IN_PICTURE:_.LEAVE_PICTURE_IN_PICTURE,ENTER_PICTURE_IN_PICTURE:_.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"},Mf={};Ni(Mf,{create:()=>Wt,remove:()=>mt});var ao=new WeakMap;function Wt(e,t){ao.has(e)||ao.set(e,[]);let i=ao.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 mt(e){let t=ao.get(e);t&&(t.forEach(i=>i()),ao.delete(e))}var ue=new class{constructor(){u(this,"_roomIdMap",new Map),u(this,"_configs"),typeof registerProcessor>"u"&&(this._configs={sdkAppId:"",userId:"",version:ei,env:zr.QCLOUD,browserVersion:Tr.name+Tr.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){tn||!P.isAbleToUpload||this._configs.env===zr.QCLOUD&&this.uploadEventToKibana(W(x({},e),{result:"success"}))}logFailedEvent(e){if(tn||!P.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==null?void 0:r.extraCode)||(r==null?void 0:r.code)||C.UNKNOWN};this._configs.env===zr.QCLOUD&&this.uploadEventToKibana(W(x({},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:cA(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:ei,log:t};r&&(n.errorInfo=r.message,r.stack&&(n.errorInfo+=`
|
||
`.concat(r.stack)));let s=Ya.enable?us(n,2002,Number(this._configs.sdkAppId)):JSON.stringify(n);this.sendRequest(os(this._configs.sdkAppId,va.LOG),s)}sendRequest(e,t){setTimeout(()=>Va({url:e,body:t,priority:"low"}).catch(()=>{}),2e3)}},_i=new WeakMap;function vr(e){let{settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:n}=e;return function(s,a,o){let l=Fa({retryFunction:o.value,settings:t,onError(c){let{error:d,retry:h,reject:m,retryFuncArgs:p}=c;var f;i?i.call(this,d,()=>{var T;(T=_i.get(s))!=null&&T.has(a)?h():m(d)},m,p):(f=_i.get(s))!=null&&f.has(a)?h():m(d)},onRetrying(c,d){var h;Qr(r)&&r.call(this,c,d),(h=_i.get(s))!=null&&h.has(a)&&(_i.get(s).get(a).stopRetry=d)},onRetryFailed:n});return o.value=function(){let c=_i.get(s);for(var d=arguments.length,h=new Array(d),m=0;m<d;m++)h[m]=arguments[m];return c?c.set(a,{args:h}):_i.set(s,new Map([[a,{args:h}]])),l.apply(this,h).finally(()=>{var p;return(p=_i.get(s))==null?void 0:p.delete(a)})},o}}function Xc(e){let{fnName:t,callback:i,validateArgs:r=!0}=e;return function(n,s,a){let o=a.value;return a.value=function(){for(var l,c,d=arguments.length,h=new Array(d),m=0;m<d;m++)h[m]=arguments[m];if((l=_i.get(n))!=null&&l.has(t)){let{stopRetry:p,args:f}=_i.get(n).get(t),T=!0;if(r){for(let E of f)if(!h.find(v=>v===E)){T=!1;break}}T&&(i&&i.apply(this,h),p&&p(),(c=_i.get(n))==null||c.delete(t))}return o.apply(this,h)},a}}var on=class extends re{constructor(e,t){super(e.id,"".concat(t,"-player")),this.options=e,this.kind=t,u(this,"id"),u(this,"element",null),u(this,"track"),u(this,"url"),u(this,"attr"),u(this,"mode"),u(this,"muted"),u(this,"_log"),u(this,"isPausedByUserCall",!1),u(this,"_pausedRetryCount"),u(this,"_isElementPlayingFired",!1),u(this,"_interval"),u(this,"_delayDestroyTimeoutId",0),u(this,"_playSuccessResolve"),u(this,"_isReplayByRecreateMediaStreamCalled",!1),u(this,"isPlayCalled",!1),u(this,"isInAutoPlayFailedState",!1),u(this,"isBindAutoPlayEvent",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Kr,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 g(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=Y({key:K.PLAY_FAILED,data:{media:this.kind,error:e}});if(this._log.warn(e),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new O({code:C.PLAY_NOT_ALLOWED,message:t})}})}stop(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;var t;this.isPlayCalled=!1,this.isPausedByUserCall=!1,this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!en?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(_.ENDED),this._interval>0&&_e.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():fR?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 Wt(this.element,this.element).add(_.PLAYING,e).add(_.ENDED,e).add(_.PAUSE,e).add(_.ERROR,e).add(_.LOADSTART,e).add(_.LOADEDDATA,e).add(_.LOADEDMETADATA,e)}}bindTrackEvents(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.track;if(e){let t=this.handleTrackEvent.bind(this);Mf==null||Mf.create(e,e).add(_.ENDED,t).add(_.MUTE,t).add(_.UNMUTE,t),e.readyState===_.ENDED&&this.handleTrackEvent({type:_.ENDED}),e.muted&&this.handleTrackEvent({type:_.MUTE})}}bindAutoPlayEvent(){this.isBindAutoPlayEvent||(R.on(b.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!0)}unbindTrackEvents(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.track;e&&mt(e)}unbindEvents(){this.element&&mt(this.element),this.unbindTrackEvents(),R.off(b.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!1}handleElementEvent(e){switch(e.type){case _.PLAYING:lo()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(_.PLAYING),this._interval&&(_e.clearTask(this._interval),this._interval=-1);break;case _.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(_.ENDED);break;case _.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(_.PAUSE);break;case _.ERROR:if(this.element&&this.element.error){this.handlePaused(_.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)),ue.uploadEvent({log:"stat-".concat(this.kind,"-").concat(Qe.PLAYER_ERROR,"-").concat(t,"-").concat(navigator.userAgent),error:this.element.error}),hR||rf?this.emit(z.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case _.LOADEDDATA:this.kind===_.VIDEO&&this.emit(z.LOADED_DATA);break;case _.LOADEDMETADATA:this.kind===_.VIDEO&&this.emit(z.LOADED_META_DATA);break;case _.LOADSTART:this.emit(z.LOAD_START)}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),ue.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),w.addSuccessEvent({key:this.kind===_.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),ue.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),w.addFailedEvent({key:this.kind===_.AUDIO?506700:516700,error:(t=this.element)==null?void 0:t.error}),this.emit(z.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn("delay ".concat(e,"ms to recreate mediaStream")),new Promise((t,i)=>{mi(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)}),mi(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 g(this,null,function*(){let t=e.type;switch(this.options.enableLogTrackState&&this._log[t===_.UNMUTE?"info":"warn"]("track ".concat(t)),t){case _.ENDED:this.handleStopped(_.ENDED);break;case _.MUTE:this.handlePaused(_.MUTE);break;case _.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(_.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}};u(on,"PlayerEvent",z),M([vr({settings:{retries:2,timeout:0},onError(e,t,i,r){r[0]=(r[0]||1e3)+1e3,t()}})],on.prototype,"doReplayByRecreateMediaStream"),M([Ke([],"PLAYING",{sync:!0,success(e){this.emit(z.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}})],on.prototype,"handlePlaying"),M([Ke("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(e){this.emit(z.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}})],on.prototype,"handlePaused"),M([Ke([],"STOPPED",{sync:!0,success(e){this.emit(z.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}})],on.prototype,"handleStopped");var Bi="trtc_autoplay",Lf="".concat(Bi,"_mask"),oo="".concat(Bi,"_wrapper"),ZC="".concat(Bi,"_header"),xf="".concat(Bi,"_content"),Qc="".concat(Bi,"_action_wrapper"),Uf="".concat(Bi,"_question"),Vf="".concat(Bi,"_collapse"),Zc="".concat(Bi,"_action_confirm"),$C="".concat(Bi,"_detail"),eb="#2473E8",Ff="dialog",HB="".concat(Ff,"-show"),WB="".concat(Ff,"-1"),GB="".concat(Ff,"-2"),tb=!1,Bf=!1,lo=()=>Bf,ib="".concat(Pi,"/").concat(Mi()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),rb="<br><a href='".concat(ib,"' target='_blank'>").concat(Mi()?"其他方案?":"Any other solution?","</a>"),jB="".concat(Mi()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(rb):"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(rb)),zB=class{constructor(){if(u(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),u(this,"_dialogNode",null),u(this,"_bodyPosition",""),u(this,"_showDetail",!1),u(this,"_isCollapseClicked",!1),u(this,"_isQuestionClicked",!1),Mi()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!tb){let e=document.createElement("style");e.innerHTML=".".concat(Lf,"{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(Lf," div:not(.").concat(Qc,"){display:block !important;}.").concat(oo,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(oo," a{color:").concat(eb,";}.").concat(ZC,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(xf,"{margin:8px 0;}.").concat(Qc,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(Vf,"{margin-right:auto;cursor:pointer}.").concat(Uf,"{height:100%;line-height:16px;cursor:pointer;}.").concat(Zc,"{margin-left:8px;color:#fff;background:").concat(eb,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(Zc,":hover{opacity:0.9;}.").concat(Vf,",.").concat(Zc,",.").concat(xf,",.").concat(Uf,"{font-size:14px;}@media screen and (max-width:750px){.").concat(oo,"{width:80vw;}}"),document.head.appendChild(e),tb=!0}this.addDiaLog()}createDiaLog(){let e=document.createElement("template");e.innerHTML='<div class="'.concat(Lf,`"><div class='`).concat(oo,"'><div class='").concat(ZC,"'>").concat(location.host,"</div><div class='").concat(xf,"'>").concat(this.content,"</div><div class='").concat($C,`' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">`).concat(jB,"</div><div class='").concat(Qc,"'></div></div></div>").trim();let t=document.createElement("button");t.className=Zc,t.innerText=Mi()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);let i=document.createElement("div");i.className=Uf,i.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
||
<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">
|
||
<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"/>
|
||
<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"/>
|
||
<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"/>
|
||
</svg>
|
||
`,i.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=Vf,r.innerText="".concat(Mi()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);let n=e.content.firstChild,s=n.querySelector(".".concat(Qc));return s.appendChild(r),s.appendChild(i),s.appendChild(t),n}addDiaLog(){lo()||(Bf=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(oo)).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",P.info("show autoplay dialog"),ue.uploadEvent({log:HB}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,Bf=!1),co=null}onConfirm(){P.warn("confirm clicked, try resume stream"),R.emit(b.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){let e=this._dialogNode.querySelector(".".concat($C));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||ue.uploadEvent({log:WB}),this._isCollapseClicked=!0}onQuestionClick(){window.open(ib,"_blank"),this._isQuestionClicked||ue.uploadEvent({log:GB}),this._isQuestionClicked=!0}},co=null;function Hf(){co||(co=new zB)}var uo,gi=class Ek extends on{constructor(t){super(t,_.VIDEO),u(this,"stat",{}),u(this,"_calculateTimeout",-1),u(this,"viewMirror",!1),u(this,"objectFit","cover"),u(this,"container"),u(this,"canvas"),u(this,"shouldRenderAlpha",!1),u(this,"_preSize",{width:0,height:0}),u(this,"posterImg"),u(this,"pipWindow"),u(this,"enterPIPPromise"),u(this,"_originContainerPosition"),u(this,"_isResettingSrcObject",!1),u(this,"_wrapper",null),u(this,"_useWrapper",!1),this.mode=t.canvas?1:0,this.container=t.container,this.canvas=t.canvas,I(t.viewMirror)||(this.viewMirror=t.viewMirror),I(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(){let t=document.createElement(_.VIDEO);this.track&&this.mode!==2&&(t.srcObject=new MediaStream([this.track])),t.muted=!0,t.setAttribute("id","video_".concat(this.id)),t.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.element=t,Oe&&(t.poster="data:,"),this._appendToWrapper(),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let t=this._useWrapper?"grid-area:1/1;width:100%;height:100%;object-fit:".concat(this.objectFit,";").concat(this.shouldRenderAlpha?"":"background-color:black",";"):"width:100%;height:100%;object-fit:".concat(this.objectFit,";").concat(this.shouldRenderAlpha?"":"background-color:black",";");return this.viewMirror&&(t+="transform:scaleX(-1);"),t}setLiveMode(t){if(this._useWrapper!==t&&(this._useWrapper=t,this.elementToRender&&this.elementToRender.setAttribute("style",this.styleAttribute),this.container&&this.elementToRender))if(t){let i=this._getOrCreateWrapper();i.insertBefore(this.elementToRender,i.firstChild)}else this.container.appendChild(this.elementToRender),this._cleanupWrapper()}setContainer(t){if(this.container===t)return;let i=this._wrapper,r=this.container;this.container=t,this._pausedRetryCount=Kr,this.track&&this.elementToRender&&this._appendToWrapper(),i&&r&&r!==this.container&&i.isConnected&&i.children.length===0&&i.remove()}_getOrCreateWrapper(){if(!this.container)throw new Error("[VideoPlayer] container is required");let t=this.container.querySelector("[data-trtc-video-wrapper]");return t||(t=document.createElement("div"),t.setAttribute("data-trtc-video-wrapper","true"),t.style.cssText="display:grid;width:100%;height:100%;",this.container.appendChild(t)),this._wrapper=t,t}_appendToWrapper(t){let i=t??this.elementToRender;if(this.container&&i)if(this._useWrapper){let r=this._getOrCreateWrapper();r.insertBefore(i,r.firstChild)}else this.container.appendChild(i)}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(_.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(_.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(_.RESIZE,this.handleElementEvent),this.element&&(this.element.addEventListener(_.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===_.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(z.ENTER_FULL_SCREEN)):(this._log.info("leave fullscreen"),this.emit(z.LEAVE_FULL_SCREEN))}handleVolumeChange(){var t;(this.isPictureInPicture()||this.isFullscreen())&&this.emit(z.VOLUME_CHANGE,{muted:(t=this.element)==null?void 0:t.muted})}handleElementEvent(t){var i,r,n,s,a,o;if(this.mode===2)return;super.handleElementEvent(t);let l=t.type,c=this.isPictureInPicture(),d=this.isFullscreen(),h=t.isTrusted&&(c&&Ze||d);if(l===_.PLAYING&&h&&!this._isResettingSrcObject&&(this._log.warn("user resume in ".concat(d?"fullscreen":"pip")),this.emit(z.USER_RESUME_IN_PIP_OR_FULL_SCREEN)),l===_.PAUSE&&(h&&(this._log.warn("user pause in ".concat(d?"fullscreen":"pip")),this.emit(z.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)),mi(500).then(()=>{var m;(m=this.container)!=null&&m.isConnected&&(this._pausedRetryCount=Kr,this._log.info("view container ".concat(this.container.id," is in dom, reset pausedRetryCount")))})),this._pausedRetryCount>0&&!lo()&&!this.isPausedByUserCall&&!h&&(this._log.info("[".concat(Kr-this._pausedRetryCount+1,"/").concat(Kr,"] ").concat(this.kind," player auto resume when paused")),this.doResume(),this._pausedRetryCount--),be&&!h&&(this._interval=_e.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 m=this.element.style.transform;l===_.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=m.replace("scaleX(-1)",""):l===_.LEAVE_PICTURE_IN_PICTURE&&!m.includes("scaleX")&&(this.element.style.transform="".concat(m," scaleX(-1)"))}l===_.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=((a=this.element)==null?void 0:a.videoHeight)||0,this._preSize.width=((o=this.element)==null?void 0:o.videoWidth)||0,this.emit(z.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height})),l===_.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(z.LEAVE_PICTURE_IN_PICTURE)),l===_.ENTER_PICTURE_IN_PICTURE&&this.emit(z.ENTER_PICTURE_IN_PICTURE)}resetSrcObjectToReplay(){Oe&&ps&&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;this.canvas!==t&&((r=this.canvas)==null||r.remove(),t==null||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(),this._appendToWrapper(t)):this.element&&this._appendToWrapper(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||!Ze&&!me))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),a=s.objectFit||this.objectFit,o=1;if(this._useWrapper){let l=parseInt(s.zIndex,10);isNaN(l)||(o=l+1)}n.style.cssText=this._useWrapper?"grid-area:1/1;z-index:".concat(o,";width:100%;height:100%;object-fit:").concat(a,";"):"position:absolute;top:0;left:0;width:100%;height:100%;object-fit:".concat(a,";"),n.onload=()=>g(this,null,function*(){try{n.decode&&(yield n.decode()),this.container&&!this._useWrapper&&window.getComputedStyle(this.container).position==="static"&&(this._originContainerPosition=this.container.style.position,this.container.style.position="relative"),this.posterImg=n;let l=this._useWrapper?this._wrapper:this.container;l==null||l.appendChild(n),Ba()&&Rt<=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&&(Ba()&&Rt<=17&&this.elementToRender&&(this.elementToRender.style.visibility=""),this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),!this._useWrapper&&this.container&&!I(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 g(this,null,function*(){Et(Ek.prototype,this,"pause").call(this),!this.isPictureInPicture()&&!this.hasPoster&&(ps||t&&(me||Ze))&&(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&&ps&&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(_.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(),this._useWrapper&&this._cleanupWrapper()}_cleanupWrapper(){this._wrapper&&this._wrapper.children.length===0&&this._wrapper.remove(),this._wrapper=null}play(t){if(I(t==null?void 0:t.isLiveStream)||this.setLiveMode(t.isLiveStream),this.element){if(this.elementToRender&&this.container)if(this._useWrapper){let i=this._getOrCreateWrapper();this.elementToRender.parentElement!==i&&i.insertBefore(this.elementToRender,i.firstChild)}else this.elementToRender.parentElement!==this.container&&this.container.append(this.elementToRender)}else this.initializeElement();return 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(z.MEDIA_TRACK_CHANGED,t),t!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([t]),this.element.remove()),this._appendToWrapper()))}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(io()&&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 a;return(a=this.element)==null?void 0:a.requestVideoFrameCallback(r)},2e3))};this.element.requestVideoFrameCallback(r)}}catch(t){this._log.warn("init stat failed",t)}}enterFullscreen(){return g(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(be&&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 g(this,null,function*(){try{if(!this.isFullscreen())return;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 g(this,null,function*(){this.isFullscreen()?yield this.exitFullscreen():yield this.enterFullscreen()})}enterPictureInPicture(){return g(this,null,function*(){this.enterPIPPromise=this._enterPictureInPicture();try{return yield this.enterPIPPromise}finally{delete this.enterPIPPromise}})}_enterPictureInPicture(){return g(this,null,function*(){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:t}=this;if(t.requestPictureInPicture){this._log.info("requestPictureInPicture");let i=yield t.requestPictureInPicture();return this.pipWindow=i,this._log.info("entered pip mode"),this.elementToRender===this.canvas&&(this.canvas.remove(),this._appendToWrapper(this.element)),i}if(t.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),yield t.webkitSetPresentationMode("picture-in-picture"),this._log.info("entered pip mode (webkit)"),{};throw new Error("pip API not supported")}catch(t){throw this._log.error("failed to enter pip:",t.name,t.message),t}})}exitPictureInPicture(){return g(this,null,function*(){var t;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=Kr,this._appendToWrapper(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(i){throw this._log.error("failed to exit pip:",i),i}})}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 g(this,null,function*(){this.isPictureInPicture()?yield this.exitPictureInPicture():yield this.enterPictureInPicture()})}};function $c(e,t){return g(this,null,function*(){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield e.audioWorklet.addModule(t),P.info("worklet addModule success")}catch(i){throw P.info("worklet addModule catch error. ".concat(i.message)),i}})}typeof AudioContext<"u"?uo=AudioContext:typeof webkitAudioContext<"u"?uo=webkitAudioContext:typeof mozAudioContext<"u"&&(uo=mozAudioContext);var st,JB=1500,nb=-1,eu=0,ho=-1,Wf=!1,sb=0,ab=-1,ob=-1;(function e(){try{if(st)return;(st=new uo({sampleRate:48e3})).onstatechange=()=>{P.info("context state: ".concat(st.state).concat(st.state!=="running"?" visibilityState: ".concat(document.visibilityState):"")),vs()},clearTimeout(nb)}catch(t){P.error("initAudioContext failed: ".concat(t," typeof AudioContextClass: ").concat(typeof uo)),nb=setTimeout(e,1e3)}})();var vs=()=>{st.state==="suspended"?(eu=J(),ho===-1&&(ho=setTimeout(()=>{st.state==="suspended"&&(Wf=!0,R.emit("155",{isSuspended:!0}))},JB)),mo(),document.addEventListener("click",vs)):st.state==="interrupted"?mo():(eu&&(w.addNumber({key:507800,value:J()-eu,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),eu=0),ho!==-1&&(clearTimeout(ho),ho=-1,Wf&&(Wf=!1,R.emit("155",{isSuspended:!1}))),document.removeEventListener("visibilitychange",vs),document.removeEventListener("click",vs))},Gf=0,jf=-1;function mo(){return new Promise((e,t)=>{if(st.state==="running")return e();Date.now()-Gf<1e3?(clearTimeout(jf),jf=setTimeout(()=>{Gf=Date.now(),st.resume().then(e,t)},1e3)):(clearTimeout(jf),Gf=Date.now(),st.resume().then(e,t))}).catch(e=>{P.warn("context resume failed: ".concat(e)),document.addEventListener("visibilitychange",vs)})}document.addEventListener("click",vs);var et=e=>st,tt=class{constructor(e){this.name=e,u(this,"node"),u(this,"node2"),u(this,"pre",new Set),u(this,"next",new Set),u(this,"context"),u(this,"connectedNodes",new Set),u(this,"nextInputChannelMap",new Map),u(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){P.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(),w.addSuccessEvent({key:502701})}catch(r){P.error(r),w.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(),w.addSuccessEvent({key:502702})}catch(t){P.error(t),w.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}},KB=class extends tt{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:256;super(),this.fftSize=e,u(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}},lb=class{constructor(){u(this,"source",new tt),u(this,"gain",new tt),u(this,"destination",new tt)}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(et().createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){let t=tu(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}},cb=class extends lb{constructor(e){super(),this.context=e,u(this,"aec",new tt("aec")),u(this,"mixNode",new tt("mixNode")),u(this,"silentNode",new tt("silentNode")),u(this,"denoiser",new tt("denoiser")),u(this,"voiceChanger",new tt("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(){if(this.context.inputs.has(this))return;let e=this.context.inputs.size;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),e<=1&&this.context.inputs.size>1&&this.context.onAudioMixedChanged(!0)}disconnect(){if(!this.context.inputs.has(this))return;let e=this.context.inputs.size;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),e>1&&this.context.inputs.size<=1&&this.context.onAudioMixedChanged(!1)}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()}},qB=class{constructor(){u(this,"audioContext",et()),u(this,"destination",this.audioContext.createMediaStreamDestination()),u(this,"inputs",new Set),u(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]}},ub=new WeakMap;function tu(e){try{let t=ub.get(e);if(t)return t;let i=et();if(e instanceof HTMLAudioElement)t=i.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=i.createMediaStreamSource(new MediaStream([e]))}return ub.set(e,t),t}catch(t){if(!(me&&t instanceof Error&&t.name==="NotSupportedError"))throw t;P.warn(t)}}var iu=class qi{constructor(t){u(this,"_volume",0),u(this,"_volumeDb",0),u(this,"_log"),u(this,"_scriptProcessorNode",null),u(this,"_audioWorkletNode",null),u(this,"_interval",200),u(this,"ready",this.preload());let{log:i}=t;this._log=i,R.on(b.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-qi.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!qi.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);';qi.workletReady=$c(qi.audioContext,URL.createObjectURL(new Blob([t],{type:"application/javascript"})))}return qi.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(qi.audioContext,"volume-meter");let t=!1;this._audioWorkletNode.port.onmessage=i=>{qi.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)),ue.logFailedEvent({userId:this._log.userId,eventType:Qe.LOAD_WORKLET,error:t}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=et().createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=t=>{qi.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,R.off(b.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})}};u(iu,"lastMessageTime",0),u(iu,"audioContext",et()),u(iu,"workletReady");var db=iu,hb=class extends tt{constructor(e){super(),u(this,"_volumeMeter"),this._volumeMeter=new db(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return g(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()}}},ru=db,YB=Ge(it(),1),mb=e=>t=>t.deviceId===e,zf=class{constructor(e,t){u(this,"kind"),u(this,"type"),u(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&&po(this.devices[0])||t&&(i.forEach(r=>{if(r.deviceId&&!this.devices.find(mb(r.deviceId))){let n="".concat(this.kind).concat(this.type,"Added");P.warn("".concat(n,": ").concat(JSON.stringify(r))),t.emit(n,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!i.find(mb(r.deviceId))){let n="".concat(this.kind).concat(this.type,"Removed");P.warn("".concat(n,": ").concat(JSON.stringify(r))),t.emit(n,r)}})),this.devices=i}hasDevice(e){return!!this.devices.find(t=>t.deviceId===e)}},XB=class extends YB.EventEmitter{constructor(){super(),u(this,"audioInputs",new zf(_.AUDIO,"Input")),u(this,"videoInputs",new zf(_.VIDEO,"Input")),u(this,"audioOutputs",new zf(_.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||_e.run("interval",()=>{this.update()},{delay:1e4}))}init(){nu().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return g(this,arguments,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return(function*(){let i=yield nu(t);return e.audioInputs.update(i,e),e.videoInputs.update(i,e),e.audioOutputs.update(i,e),e})()})}hasBlueTooth(){var e;if(1e3*((e=et())==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)))}},He=np||dc?null:new XB;function po(e){return e.deviceId===e.groupId&&e.groupId===""}function nu(){return g(this,arguments,function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return(function*(){if(sn()||!Tf())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(e!==0){let i={audio:!1,video:!1};if(t.forEach(r=>{po(r)&&(r.kind===_.AUDIO_INPUT?i.audio=!0:r.kind===_.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&&mo()}catch(n){P.debug("capture before getDevices failed: ",n)}t=yield navigator.mediaDevices.enumerateDevices(),r==null||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&&Jf.add("".concat(i.deviceId,"_").concat(i.kind)),i.getCapabilities&&(n.getCapabilities=()=>i.getCapabilities()),n})})()})}function Hi(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return He.update(e?1:0).then(t=>t.audioInputs.devices)}function Wi(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return He.update(e?2:0).then(t=>t.videoInputs.devices)}var pb=!1;function ln(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return g(this,null,function*(){return(be||Ze)&&(e=!1),He.update(e?1:0).then(t=>t.audioOutputs.devices)})}var Jf=new Set;function fb(e,t){return g(this,null,function*(){let i=(yield Hi()).find(r=>r.deviceId===Ra);return!t&&(i==null?void 0:i.groupId)===e||(i==null?void 0:i.groupId)===e&&i.label===t})}var su,QB=class extends lb{constructor(e){super(),this.log=e,u(this,"volumeMeter"),u(this,"volumeMeterAfter3A"),u(this,"volumeDestination"),u(this,"analyser",new KB),this.volumeMeter=new hb({log:this.log}),this.volumeMeterAfter3A=new hb({log:this.log}),this.volumeDestination=new tt,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},Kf=class vk extends on{constructor(t){super(t,_.AUDIO),u(this,"_outputDeviceId"),u(this,"_floatVolume",1),u(this,"_destination"),u(this,"pipeline"),u(this,"volumeMeterMode","worklet"),u(this,"enableVolumeControlInIOS"),this.enableVolumeControlInIOS=t.enableVolumeControlInIOS,this.mode=0,t.url&&(this.url=t.url),this.pipeline=new QB(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((rt==="15.2"||rt==="15.3"||rt==="15.4")&&this.muted)return void this._log.info("audioElement is muted.");let i=su||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(le(t)?t/100:this._floatVolume),i===su&&(su=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(z.TIME_UPDATE,this.currentTime)),this.bindElementEvents(),this._log.info("initializeElement")}play(t){return g(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==null?void 0: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(et().createAnalyser()),(function(){g(this,null,function*(){try{pb||(pb=!0,P.info("speakers:".concat((yield ln()).map(i=>" ".concat(i.deviceId.slice(0,8),": ").concat(i.label)))))}catch{}})})()}catch(i){throw this._log.warn("audio play error: ".concat(i)),Ui(rt,"18.7",!0)&&this.bindAutoPlayEvent(),i}return Et(vk.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 g(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()}},ZB=class extends Kf{setTrack(e){this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(z.MEDIA_TRACK_CHANGED,e),e&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]))))}},_b=class extends Kf{constructor(e){super(e),u(this,"_sourceElement"),u(this,"_output",new tt),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(et().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(z.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&&!Ba();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(Ba()){if(!this.enableVolumeControlInIOS)return;(function(){if(!be||ob!==-1)return;let r=()=>{J()-sb<500||(st&&st.state==="running"&&st.currentTime===ab&&(P.warn("context is fake running, auto resume"),st.suspend().catch(n=>{P.warn("context suspend failed: ".concat(n))})),ab=st.currentTime,sb=J())};ob=setInterval(()=>{r()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&r()})})()}if(me&&!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=et().createMediaStreamDestination()),this.pipeline.destination.setNode(this._destination),mt(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play().catch(r=>{this.emit(z.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&&en&&(su=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},qf=class extends re{constructor(e){let{userId:t,sdkAppId:i,mediaType:r,room:n,PlayerClass:s=r===1?_b:gi}=e;var a;super(),u(this,"id",RR()),u(this,"userId",""),u(this,"isRemote"),u(this,"mediaType"),u(this,"room"),u(this,"user"),u(this,"_log"),u(this,"_inputTrack"),u(this,"_outputTrack"),u(this,"isPlayCalled"),u(this,"container",null),u(this,"player"),u(this,"subVideoPlayerMap"),u(this,"muted",!1),u(this,"abortCtrl"),u(this,"objectFit","cover"),u(this,"mirror"),u(this,"rotation"),u(this,"isScreen",!1),u(this,"manager"),u(this,"trackSettings"),u(this,"isFirstVideoFrameEmitted",!1),this.userId=t||"",this.mediaType=r,this._log=P.createLogger({parent:n==null?void 0:n.getLogger(),id:"".concat(this.kind[0],"t"),userId:(a=n||this.room)==null?void 0:a.userId,remoteUserId:this instanceof yo?void 0:this.userId,sdkAppId:i,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof yo}),this.player=new s({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:n==null?void 0:n.enableVolumeControlInIOS}),this.player.on(z.PLAYER_STATE_CHANGED,o=>{if(R.emit(b.PLAYER_STATE_CHANGED,x({track:this},o)),this.emit("player-state-changed",o),o.state==="PLAYING"&&this.room){let l=!0;for(let{remoteAudioTrack:c,remoteVideoTrack:d,remoteAuxiliaryTrack:h}of[...this.room.remotePublishedUserMap.values()])if(c.isAvailable&&!c.player.isPlaying||d.isAvailable&&!d.player.isPlaying||h.isAvailable&&!h.player.isPlaying){l=!1;break}l&&lo()&&co&&co.deleteDialog()}}),this.kind===_.VIDEO&&(this.player.on(z.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(z.LOADED_DATA),R.emit(b.VIDEO_LOADED_DATA,{track:this})}),this.player.on(z.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(z.LOADED_META_DATA)}),this.player.on(z.MEDIA_TRACK_CHANGED,o=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(c=>c.setTrack(o))}),this.player.on(z.RESIZE,o=>{this.emitFirstVideoFrameEvent(z.RESIZE),this.emit("video-size-changed",x({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},o))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(z.ERROR,this.onPlayerError.bind(this)),this.player.on(z.AUTOPLAY_FAILED,this.handleAutoPlayFailed,this)}get log(){return this._log||P}get kind(){return this.mediaType===1?_.AUDIO:_.VIDEO}get isAudio(){return this.kind===_.AUDIO}get strMediaType(){return this.mediaType===4?_.VIDEO:this.mediaType===2?_.SCREEN:_.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 g(this,null,function*(){let i=Ue(e)?e[0]:e;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!I(t.muted)&&this.setPlayerMute(t.muted),t&&!I(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof gi&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(Ue(e)&&e.length>=1&&this.container&&e.includes(this.container)&&this.container.contains(this.player.elementToRender)?(e.splice(e.indexOf(this.container),1),e.unshift(this.container)):(this.container=i,this.player.setContainer(i))),Ue(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t))));if(t&&!I(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===_.VIDEO)&&this.setPlayerMute(!0),t&&!I(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof gi&&(I(t==null?void 0:t.isLiveStream)||this.player.setLiveMode(t.isLiveStream),this.player.setObjectFit(this.objectFit),t&&!I(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof gi&&this.player.setContainer(i)),R.emit(b.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),Ue(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!==_.VIDEO||I(e)||e===this.mirror)return;this.mirror=e;let i=this.player;t&&(i=t);let r=this.manager;if(Se(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 g(this,null,function*(){if(!this._outputTrack||this.kind===_.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((r,n)=>{var s;e.find(a=>n===a)||(r.stop(),(s=this.subVideoPlayerMap)==null||s.delete(n))});for(let[r,n]of e.entries()){let s=this.subVideoPlayerMap.get(n);s?t&&(I(t.objectFit)||s.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new gi({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(Bp(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(t=>{t.stop()}),this.container=null)}resume(){return g(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),R.emit(e?b.TRACK_MUTED:b.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){Wt(e,e).add(_.MUTE,this.onTrackMuted).add(_.UNMUTE,this.onTrackUnmuted).add(_.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===_.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){mt(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 Bp(this)&&this.isAudio&&(t=this.user)!=null&&t.muteState.hasAudio&&(i=this.user)!=null&&i.muteState.audioMuted?void 0:(this.player.stop(Bp(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 g(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(($r||_r)&&(yield mi(100),(t=this.player)!=null&&t.isPlaying))return;Hf()}else document.addEventListener("click",i,!0);R.once(b.LOCAL_TRACK_CAPTURE_SUCCESS,r=>{let{track:n}=r;n.kind==="audio"&&lo()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&i()}),this.emit("error",e)})}getVideoFrame(){return this.player instanceof gi?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==null?void 0:n.width)||((i=this.player.element)==null?void 0:i.videoWidth)||0,a=(n==null?void 0:n.height)||((r=this.player.element)==null?void 0:r.videoHeight)||0;e===z.RESIZE&&!s&&!a||e===z.LOADED_META_DATA&&!s&&!a||(e===z.LOADED_DATA&&!s&&!a&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,fr(this.rotation)&&([s,a]=[a,s]),this.emit("first-video-frame",{width:s,height:a,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"))}};M([Ke([],re.INIT,{sync:!0})],qf.prototype,"_toInitState");var $B=Object.prototype.hasOwnProperty,Gi=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(Ut(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($B.call(e,t))return!1;return!0}return!1},e5=Fa({retryFunction:function(e){return g(this,null,function*(){let t=(function(s){return{audio:t5(s),video:i5(s)}})(e);P.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let i=[],r=[],n=["label","deviceId","groupId"];if(t.audio&&(i=yield Hi(),P.info("microphones: ".concat(ti(i.map(s=>W(x({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:n})))),t.video&&(r=yield Wi(),P.info("cameras: ".concat(ti(r,{keysToInclude:n}))),!Se(t.video)&&t.video.facingMode==="user"&&!t.video.deviceId)){let s=r.filter(a=>!a.label.includes("infrared")).find(a=>a.label.includes("facing front"));s&&(t.video.deviceId=s.deviceId,P.info("exclude infrared camera: ".concat(JSON.stringify(t))))}try{let s=yield navigator.mediaDevices.getUserMedia(t);return LC&&s.getTracks().forEach(a=>{var o;let l=a.getCapabilities();P.info("".concat(a.kind," capabilities: ").concat(ti(l,{keysToInclude:gp}))),!I(e.echoCancellation)&&((o=l.echoCancellation)==null?void 0:o.indexOf(e.echoCancellation))===-1&&P.warn("Invalid argument for 'echoCancellation'. Expected one of [".concat(JSON.stringify(l.echoCancellation),"], but received '").concat(e.echoCancellation,"'"))}),t.audio&&mo(),s}catch(s){let{message:a}=s;throw s.name==="NotFoundError"&&(e.video&&r&&r.length===0&&(a=Y({key:K.CAMERA_NOT_FOUND})),e.audio&&i&&i.length===0&&(a=Y({key:K.MICROPHONE_NOT_FOUND}))),new O({code:C.INITIALIZE_FAILED,name:s.name,message:a,constraint:s.constraint})}})},settings:{retries:3,timeout:500},onError:e=>{let{error:t,retry:i,reject:r,retryFuncArgs:n,retriedCount:s}=e,a=s+1;t.name==="NotReadableError"||t.name==="OverconstrainedError"||t.name==="AbortError"?(a===1?(n[0].video&&(n[0].maxResolution=!1,(!Ze||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)):a===2?n[0].useDeviceIdOnly=!0:a===3&&!n[0].useExactDeviceId&&(n[0].useTrueAsConstraint=!0),i()):r(t),n[0].microphoneId&&gb(n[0].microphoneId,!1),n[0].cameraId&&gb(n[0].cameraId,!0)},onRetrying:e=>{P.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:e=>{ue.logFailedEvent({eventType:Qe.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{ue.logSuccessEvent({eventType:Qe.GET_USER_MEDIA_RETRY}),ue.uploadEvent({log:"stat-".concat(Qe.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function gb(e,t){return g(this,null,function*(){let i=(t?yield Wi():yield Hi()).find(r=>r.deviceId===e);i&&Pe(i.getCapabilities)&&P.warn(ti(i.getCapabilities(),{keysToInclude:gp}))})}function t5(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!Gi(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(le(e.channelCount)&&(t.channelCount=e.channelCount),(Se(e.echoCancellation)||e.echoCancellation==="remote-only"||e.echoCancellation==="all")&&(t.echoCancellation=e.echoCancellation),Se(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),Se(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!Gi(t)||t)}function i5(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&&!Gi(i)?i:(e.width&&(i.width={ideal:e.width},t&&!me&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!me&&(i.height.max=e.height)),me&&gr&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!Gi(i)||i)}var r5=e5;function Tb(e){return ge((t,i)=>function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];return g(this,null,function*(){return yield e.apply(this,n),t.apply(this,n)})})}function cn(e){return ge((t,i)=>function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];return g(this,null,function*(){let a=yield t.apply(this,n);return yield e.call(this,...n),a})})}function Eb(e){return ge((t,i)=>function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];return g(this,null,function*(){try{return yield t.apply(this,n)}catch(a){e.call(this,a)}})})}function ge(e){return function(t,i,r){return r.value=e(r.value,i),r}}var n5=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&P.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",()=>{P.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState}),e=!0)}})(),s5=0,vb=class{constructor(e){u(this,"log"),u(this,"isRunning",!1),u(this,"queue",[]);let t="fq".concat(++s5);e&&(t+="|".concat(e)),this.log=P.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=x({},e),s=new Promise((a,o)=>{n.resolve=a,n.reject=o});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==null?void 0:e.funcName,e==null?void 0: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()})}},au=new WeakMap,ou=new WeakMap;function fo(){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=au.get(this)||new vb;for(var a=arguments.length,o=new Array(a),l=0;l<a;l++)o[l]=arguments[l];return au.set(this,s),s.push({fn:n,args:o,context:this,funcName:i},e)},r}}function yb(e){return function(t,i,r){let n=r.value;return r.value=function(){var s,a,o;let l=[];for(var c=arguments.length,d=new Array(c),h=0;h<c;h++)d[h]=arguments[h];return(a=(s=au.get(this))==null?void 0:s.queue)==null||a.forEach(m=>l.push(m)),(o=ou.get(this))==null||o.forEach(m=>m==null?void 0:m.queue.forEach(p=>l.push(p))),l.forEach(m=>{m.reject(new O({code:C.API_CALL_ABORTED,message:e}))}),au.delete(this),ou.delete(this),n.apply(this,d)},r}}function yr(e,t){return function(i,r,n){let s=n.value,a=o=>e(...o);return n.value=function(){for(var o=arguments.length,l=new Array(o),c=0;c<o;c++)l[c]=arguments[c];let d=ou.get(this)||new Map,h=d.get(a(l))||new vb(t==null?void 0:t(...l));return d.set(a(l),h),ou.set(this,d),h.push({fn:s,args:l,context:this,funcName:r})},n}}function Sr(e,t){return ge((i,r)=>function(){let n=e;try{for(var s=arguments.length,a=new Array(s),o=0;o<s;o++)a[o]=arguments[o];let l=i.apply(this,a),c=J();return Pa(l)?l.then(d=>(t?w.addSuccessEvent({key:n,cost:J()-c}):w.addSuccessEvent({key:n}),d)).catch(d=>{throw w.addFailedEvent({key:n,error:d}),d}):(w.addSuccessEvent({key:n}),l)}catch(l){throw w.addFailedEvent({key:n,error:l}),l}})}var Sb={};function we(){}Ni(Sb,{Events:()=>Fe,Inspect:()=>Ir,LastSink:()=>lu,Sink:()=>ee,Subscribe:()=>cu,TimeoutError:()=>Rb,audit:()=>j5,bindCallback:()=>b5,bindNodeCallback:()=>k5,buffer:()=>f5,bufferCount:()=>p5,bufferTime:()=>mH,call:()=>Ib,catchError:()=>jb,combineLatest:()=>kb,concat:()=>c5,concatMap:()=>rH,concatMapTo:()=>nH,count:()=>N5,create:()=>ce,debounce:()=>J5,debounceTime:()=>K5,defer:()=>Db,delay:()=>pH,deliver:()=>te,dispose:()=>Yf,elementAt:()=>q5,empty:()=>e_,every:()=>$5,exhaustMap:()=>cH,exhaustMapTo:()=>uH,expand:()=>_H,filter:()=>un,find:()=>Y5,findIndex:()=>X5,first:()=>Q5,fromAnimationFrame:()=>R5,fromArray:()=>E5,fromEvent:()=>ye,fromEventPattern:()=>v5,fromFetch:()=>y5,fromIterable:()=>S5,fromPromise:()=>Ob,fromReadableStream:()=>A5,fromReader:()=>I5,groupBy:()=>dH,identity:()=>a5,ignoreElements:()=>L5,iif:()=>d5,inspect:()=>Ab,interval:()=>Pb,last:()=>Z5,map:()=>i_,mapTo:()=>tH,max:()=>P5,merge:()=>Xf,mergeMap:()=>aH,mergeMapTo:()=>oH,min:()=>O5,never:()=>D5,nothing:()=>we,of:()=>T5,pairwise:()=>eH,pipe:()=>Ie,race:()=>bb,range:()=>C5,reduce:()=>Mb,retry:()=>vH,scan:()=>Ub,setAsapScheduler:()=>g5,share:()=>_o,shareReplay:()=>u5,skip:()=>V5,skipUntil:()=>F5,skipWhile:()=>t_,startWith:()=>Qf,subject:()=>Ti,subscribe:()=>ze,sum:()=>M5,switchMap:()=>du,switchMapTo:()=>mu,take:()=>Ss,takeLast:()=>U5,takeUntil:()=>pt,takeWhile:()=>x5,tap:()=>r_,throttle:()=>W5,throwError:()=>w5,timeInterval:()=>hH,timeout:()=>EH,timer:()=>$f,toPromise:()=>gH,toReadableStream:()=>TH,withLatestFrom:()=>m5,zip:()=>h5});var Ib=e=>e(),a5=e=>e;function Yf(){this.dispose()}var Ab=()=>typeof __FASTRX_DEVTOOLS__<"u",o5=1,Ir=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(e){let t=new l5(e,this,this.streamId++);return Fe.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},lu=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=we,this.error=we,this.next=we,this.dispose=we,this.subscribe=we,this.doDefer()}subscribe(e){return e instanceof Ir?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(Ib),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}},ee=class extends lu{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)}},cu=class extends lu{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:we,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:we,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:we;if(super(),this._next=t,this._error=i,this._complete=r,this.then=we,e instanceof Ir){let n={toString:()=>"subscribe",id:0,source:e};this.defer(()=>{Fe.defer(n,0)}),Fe.create(n),Fe.pipe(n),this.sourceId=n.id,this.subscribe(e),Fe.subscribe({id:n.id,end:!0}),t==we?this._next=s=>Fe.next(n,0,s):this.next=s=>{Fe.next(n,0,s),t(s)},r==we?this._complete=()=>Fe.complete(n,0):this.complete=()=>{this.dispose(),Fe.complete(n,0),r()},i==we?this._error=s=>Fe.complete(n,0,s):this.error=s=>{this.dispose(),Fe.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 Ie(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 ce(e,t,i){if(Ab()){let r=Object.defineProperties(Object.setPrototypeOf(e,Ir.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}});Fe.create(r);for(let n=0;n<i.length;n++){let s=i[n];typeof s=="function"&&s instanceof Ir&&Fe.addSource(r,s)}return r}return e}function te(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 Ir){let a=ce(o=>{let l=new e(o,...r);l.sourceId=a.id,l.subscribe(s)},t,arguments);return a.source=s,Fe.pipe(a),a}return a=>s(new e(a,...r))}}}function Ar(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var l5=class extends ee{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer(()=>{Fe.defer(this.source,this.id)})}next(e){Fe.next(this.source,this.id,e),this.sink.next(e)}complete(){Fe.complete(this.source,this.id),this.sink.complete()}error(e){Fe.complete(this.source,this.id,e),this.sink.error(e)}},Fe={addSource(e,t){Ar("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){Ar("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe(e,t){let{id:i,end:r}=e;Ar("subscribe",{id:i,end:r,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(e,t,i){Ar("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){Ar("defer",{id:e.id,streamId:t})},pipe(e){Ar("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){Ar("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=o5++),Ar("create",{name:e.toString(),id:e.id})}},Rb=class extends Error{constructor(e){super("timeout after ".concat(e,"ms")),this.timeout=e}},Cb=class extends lu{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 _o(){return e=>{let t=new Cb(e);if(e instanceof Ir){let i=ce(r=>{t.add(r)},"share",arguments);return t.sourceId=i.id,i.source=e,Fe.pipe(i),i}return ce(t.add.bind(t),"share",arguments)}}function Xf(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ce(r=>{let n=new ee(r),s=t.length;n.complete=()=>{--s===0&&r.complete()},t.forEach(n.bindSubscribe)},"merge",arguments)}function bb(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ce(r=>{let n=new Map;t.forEach(s=>{let a=new ee(r);n.set(s,a),a.complete=()=>{n.delete(s),n.size===0?r.complete():a.dispose()},a.next=o=>{n.delete(s),n.forEach(l=>l.dispose()),a.resetNext(),a.resetComplete(),a.next(o)}}),t.forEach(s=>n.get(s).subscribe(s))},"race",arguments)}function c5(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ce(r=>{let n=0,s=t.length,a=new ee(r);a.complete=()=>{n<s&&!a.disposed?(a.doDefer(),a.subscribe(t[n++])):r.complete()},a.complete()},"concat",arguments)}function u5(e){return t=>{let i=new Cb(t),r=[];return i.next=function(n){r.push(n),r.length>e&&r.shift(),this.sinks.forEach(s=>s.next(n))},ce(n=>{n.defer(()=>i.remove(n)),r.forEach(s=>n.next(s)),i.add(n)},"shareReplay",arguments)}}function d5(e,t,i){return ce(r=>e()?t(r):i(r),"iif",arguments)}function kb(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ce(r=>{let n=t.length,s=n,a=n,o=new Array(n),l=()=>{--a===0&&r.complete()};t.forEach((c,d)=>{let h=new ee(r);h.next=m=>{s--,h.next=p=>{o[d]=p,s===0&&r.next(o)},h.next(m)},h.complete=l,h.subscribe(c)})},"combineLatest",arguments)}function h5(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ce(r=>{let n=t.length,s=n,a=new Array(n),o=()=>{--s===0&&r.complete()};t.forEach((l,c)=>{let d=new ee(r),h=[];a[c]=h,d.next=m=>{h.push(m),a.every(p=>p.length)&&r.next(a.map(p=>p.shift()))},d.complete=o,d.subscribe(l)})},"zip",arguments)}function Qf(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return r=>ce(function(n){let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:t.length;for(;s<a&&!n.disposed;)n.next(t[s++]);n.disposed||n.subscribe(r)},"startWith",arguments)}var m5=te(class extends ee{constructor(e){super(e);let t=new ee(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=we,t.subscribe(kb(...r))}next(e){this.buffer&&this.sink.next([e,...this.buffer])}},"withLatestFrom"),p5=te(class extends ee{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"),f5=te(class extends ee{constructor(e,t){super(e),this.buffer=[];let i=new ee(e);i.next=r=>{e.next(this.buffer),this.buffer=[]},i.complete=we,i.subscribe(t)}next(e){this.buffer.push(e)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},"buffer"),_5=function(e,t,i,r){return new(i||(i=Promise))(function(n,s){function a(c){try{l(r.next(c))}catch(d){s(d)}}function o(c){try{l(r.throw(c))}catch(d){s(d)}}function l(c){c.done?n(c.value):(function(d){return d instanceof i?d:new i(function(h){h(d)})})(c.value).then(a,o)}l((r=r.apply(e,[])).next())})};function Ti(e){let t=arguments,i=_o()(ce(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=we,i.complete=we,i.error=we,i}function Db(e){return ce(t=>t.subscribe(e()),"defer",arguments)}var ys={promise:e=>{Promise.resolve().then(e)},setImmediate:typeof setImmediate<"u"?e=>setImmediate(e):null,setTimeout:e=>setTimeout(e,0)},Zf=typeof Promise<"u"?ys.promise:ys.setImmediate?ys.setImmediate:ys.setTimeout,wb=e=>t=>{Zf(()=>e(t))},g5=e=>{typeof e=="function"?Zf=e:ys[e]&&(Zf=ys[e])},Nb=e=>wb(t=>{for(let i=0;!t.disposed&&i<e.length;i++)t.next(e[i]);t.complete()});function T5(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ce(Nb(t),"of",arguments)}function E5(e){return ce(Nb(e),"fromArray",arguments)}function Pb(e){return ce(t=>{let i=0,r=setInterval(()=>t.next(i++),e);return t.defer(()=>{clearInterval(r)}),"interval"},"interval",arguments)}function $f(e,t){return ce(i=>{let r=0,n=setTimeout(()=>{if(i.removeDefer(s),i.next(r++),t){let a=setInterval(()=>i.next(r++),t);i.defer(()=>{clearInterval(a)})}else i.complete()},e),s=()=>clearTimeout(n);i.defer(s)},"timer",arguments)}function uu(e,t){return i=>{let r=n=>i.next(n);i.defer(()=>t(r)),e(r)}}function v5(e,t){return ce(uu(e,t),"fromEventPattern",arguments)}function ye(e,t){if("on"in e&&"off"in e)return ce(uu(i=>e.on(t,i),i=>e.off(t,i)),"fromEvent",arguments);if("addListener"in e&&"removeListener"in e)return ce(uu(i=>e.addListener(t,i),i=>e.removeListener(t,i)),"fromEvent",arguments);if("addEventListener"in e)return ce(uu(i=>e.addEventListener(t,i),i=>e.removeEventListener(t,i)),"fromEvent",arguments);throw"target is not a EventDispachter"}function Ob(e){return ce(t=>{e.then(i=>{t.next(i),t.complete()},t.error.bind(t))},"fromPromise",arguments)}function y5(e,t){return ce(Db(()=>Ob(fetch(e,t))),"fromFetch",arguments)}function S5(e){return ce(wb(t=>{try{for(let i of e){if(t.disposed)return;t.next(i)}t.complete()}catch(i){t.error(i)}}),"fromIterable",arguments)}function I5(e){let t=i=>_5(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 ce(i=>{t(i)},"fromReader",arguments)}function A5(e){return ce(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 R5(){return ce(e=>{let t=requestAnimationFrame(function i(r){e.disposed||(e.next(r),t=requestAnimationFrame(i))});e.defer(()=>cancelAnimationFrame(t))},"fromAnimationFrame",arguments)}function C5(e,t){return ce(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 b5(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 ce(s=>{let a=r.concat(o=>(s.next(o),s.complete()));e.apply(t,a)},"bindCallback",arguments)}function k5(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 ce(s=>{let a=r.concat((o,l)=>o?s.error(o):(s.next(l),s.complete()));e.apply(t,a)},"bindNodeCallback",arguments)}function D5(){return ce(()=>{},"never",arguments)}function w5(e){return ce(t=>t.error(e),"throwError",arguments)}function e_(){return ce(e=>e.complete(),"empty",arguments)}var go=class extends ee{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)}},Mb=te(go,"reduce"),N5=e=>te(go,"count")((t,i)=>e(i)?t+1:t,0),P5=()=>te(go,"max")(Math.max),O5=()=>te(go,"min")(Math.min),M5=()=>te(go,"sum")((e,t)=>e+t,0),un=te(class extends ee{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"),L5=te(class extends ee{next(e){}},"ignoreElements"),Ss=te(class extends ee{constructor(e,t){super(e),this.count=t}next(e){this.sink.next(e),--this.count===0&&(this.doDefer(),this.complete())}},"take"),pt=te(class extends ee{constructor(e,t){super(e);let i=new ee(e);i.next=()=>{i.doDefer(),e.complete()},i.complete=Yf,i.subscribe(t)}},"takeUntil"),x5=te(class extends ee{constructor(e,t){super(e),this.f=t}next(e){this.f(e)?this.sink.next(e):(this.doDefer(),this.complete())}},"takeWhile"),U5=e=>Mb((t,i)=>(t.push(i),t.length>e&&t.shift(),t),[]),V5=te(class extends ee{constructor(e,t){super(e),this.count=t}next(e){--this.count===0&&(this.next=super.next)}},"skip"),F5=te(class extends ee{constructor(e,t){super(e),e.next=we;let i=new ee(e);i.next=()=>{i.doDefer(),e.resetNext()},i.complete=Yf,i.subscribe(t)}},"skipUntil"),t_=te(class extends ee{constructor(e,t){super(e),this.f=t}next(e){this.f(e)||(this.next=super.next,this.next(e))}},"skipWhile"),B5={leading:!0,trailing:!1},H5=class extends ee{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)}},Lb=class extends ee{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:B5;super(e),this.durationSelector=t,this.config=i,this._throttle=new H5(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=we,this._throttle.complete(),super.complete()}},W5=te(Lb,"throttle"),G5={leading:!1,trailing:!0},j5=e=>te(Lb,"audit")(e,G5),z5=class extends ee{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},xb=class extends ee{constructor(e,t){super(e),this.durationSelector=t,this._debounce=new z5(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()}},J5=te(xb,"debounce"),K5=e=>te(xb,"debounceTime")(t=>$f(e)),q5=te(class extends ee{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"),Y5=e=>t=>Ss(1)(t_(i=>!e(i))(t)),X5=te(class extends ee{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"),Q5=te(class extends ee{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"),Z5=te(class extends ee{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"),$5=te(class extends ee{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"),Ub=te(class extends ee{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"),eH=te(class extends ee{constructor(){super(...arguments),this.hasLast=!1}next(e){this.hasLast?this.sink.next([this.last,e]):this.hasLast=!0,this.last=e}},"pairwise"),Vb=class extends ee{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},i_=te(Vb,"map"),tH=e=>te(Vb,"mapTo")(t=>e),To=class extends ee{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()}},Eo=class yk extends ee{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===yk.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()}},Fb=class extends To{},Bb=class extends Eo{next(e){this.subInner(e,Fb),this.next=t=>{this.currentSink.dispose(),this.subInner(t,Fb)}}},du=te(Bb,"switchMap");function hu(e){return(t,i)=>e(()=>t,i)}var mu=hu(te(Bb,"switchMapTo")),iH=class extends To{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Hb=class extends Eo{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(),iH),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},rH=te(Hb,"concatMap"),nH=hu(te(Hb,"concatMapTo")),sH=class extends To{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Wb=class extends Eo{constructor(){super(...arguments),this.inners=new Set}next(e){this.subInner(e,sH),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(e=>e.resetComplete()):this.dispose()}},aH=te(Wb,"mergeMap"),oH=hu(te(Wb,"mergeMapTo")),lH=class extends To{dispose(){this.context.resetNext(),super.dispose()}},Gb=class extends Eo{next(e){this.next=we,this.subInner(e,lH)}},cH=te(Gb,"exhaustMap"),uH=hu(te(Gb,"exhaustMapTo")),dH=te(class extends ee{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=Ti(),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"),hH=te(class extends ee{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"),mH=te(class extends ee{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"),pH=te(class extends ee{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"),jb=te(class extends ee{constructor(e,t){super(e),this.selector=t}error(e){this.dispose(),this.selector(e)(this.sink)}},"catchError"),fH=class extends To{tryComplete(){let e=this.context.inners.delete(this);super.dispose(),e&&this.context.checkComplete()}next(e){this.sink.next(e),this.context.expandValue(e)}},_H=te(class extends Eo{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 fH(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"),gH=()=>e=>new Promise((t,i)=>{let r;new cu(e,n=>r=n,i,()=>t(r))}),TH=()=>e=>{let t;return new ReadableStream({start(i){t=new cu(e,i.enqueue.bind(i),i.error.bind(i),i.close.bind(i))},cancel(){t.dispose()}})},ze=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:we,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:we,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:we;return r=>new cu(r,e,t,i)},r_=te(class extends ee{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"),EH=te(class extends ee{constructor(e,t){super(e),this.timeout=t,this.id=setTimeout(()=>this.error(new Rb(this.timeout)),this.timeout)}next(e){super.next(e),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},"timeout"),vH=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1/0;return t=>{if(t instanceof Ir){let i=ce(r=>{let n=e,s=new ee(r);s.error=a=>{n-- >0?s.subscribe(t):r.error(a)},s.sourceId=i.id,s.subscribe(t)},"retry",[e]);return i.source=t,Fe.pipe(i),i}return i=>{let r=e,n=new ee(i);n.error=s=>{r-- >0?t(n):i.error(s)},t(n)}}},n_=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(n_||{}),vo=class Sk extends qf{constructor(t,i,r){super({mediaType:t,PlayerClass:i,room:r}),u(this,"isRemote",!1),u(this,"deviceId"),u(this,"groupId",""),u(this,"label",""),u(this,"sourceTrack"),u(this,"enableAutoSwitchWhenRecapturing",!0),u(this,"_isRecapturing",!1),u(this,"_lastRecaptureTime",0),u(this,"_onMuteTimeoutId",-1),u(this,"_encodeCheckTimeoutId",-1),u(this,"recaptureMode",0),u(this,"profile"),u(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(_.MUTE,this.onTrackMuted),t.addEventListener(_.UNMUTE,this.onTrackUnmuted),t.addEventListener(_.ENDED,this.onTrackEnded),t.muted&&this.onTrackMuted(),t.readyState===_.ENDED&&this.onTrackEnded()}uninstallTrackEvent(t){t.removeEventListener(_.MUTE,this.onTrackMuted),t.removeEventListener(_.UNMUTE,this.onTrackUnmuted),t.removeEventListener(_.ENDED,this.onTrackEnded)}setStateToReady(){}capture(t){let i=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return g(this,null,function*(){var r,n;let s=this.sourceTrack;try{let a,o=J();R.emit(b.LOCAL_TRACK_CAPTURE_START,{track:this}),t.customSource?(a=new MediaStream,a.addTrack(t.customSource)):(i||(r=this.sourceTrack)==null||r.stop(),a=yield r5(t));let l=a.getTracks()[0];return yield this.setInputMediaStreamTrack(l),t.customSource||(this.sourceTrack=l,this.updateDeviceIdInUse(),this.listenDeviceChange()),R.emit(b.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:J()-o,profile:this.profile,room:(n=this.manager)==null?void 0:n.room}),a}catch(a){throw R.emit(b.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:a}),this.log.error("getUserMedia error observed ".concat(a)),a}finally{i&&(s==null||s.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=Yr(((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 g(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)=>g(this,null,function*(){var n,s,a,o,l;let c=()=>r(new O({code:C.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?i():((this.state===re.INIT||this.state==="ready")&&c(),Ie(ye(t,"local-publish-flag-changed"),un(()=>this.hasFlag),pt(Xf(ye(this,re.INIT),ye(this,"ready"))),ze(i,r,c))),(a=(s=(n=this.room)==null?void 0:n.networkQuality)==null?void 0:s.hadRecentBadUplink)!=null&&a.call(s,2))return i();let d=t.heartbeatCount,h=((l=(o=this.mediaTrack)==null?void 0:o.stats)==null?void 0:l.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(()=>g(this,null,function*(){var m,p,f,T,E,v,y,D;if((f=(p=(m=this.room)==null?void 0:m.networkQuality)==null?void 0:p.hadRecentBadUplink)!=null&&f.call(p,2)||t.heartbeatCount-d<3)return i();if(this.isPublished||this.isPublishing){let N=this.kind===_.AUDIO;if((T=this.mediaTrack)!=null&&T.stats){let A=this.mediaTrack.stats.totalFrames||0;A-h===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",A)}if(!this.isMediaTrackActive)return this.emit("6",this),r(new O({message:"".concat(this.strMediaType," encode failed, track is not active"),code:N?C.AUDIO_ENCODE_FAILED:C.VIDEO_ENCODE_FAILED}));let S=this.stat.bytesSent>0;if(w[S?"addSuccessEvent":"addFailedEvent"]({key:N?503700:513702}),!N){let A={H264:513704,H265:513705,VP8:513706}[((v=(E=this.room)==null?void 0:E.videoCodec)==null?void 0:v.toUpperCase())||"H264"];A&&w[S?"addSuccessEvent":"addFailedEvent"]({key:A})}if(!S){if(w.addEnum({key:N?503701:513703,value:Gc()}),ue.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(nn()||Er()),userId:this.userId}),this.log.warn(N?"encode failed":"".concat((D=(y=this.room)==null?void 0:y.videoCodec)==null?void 0:D.toUpperCase()," encode failed")),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield mi(5e3),this.stat.bytesSent>0||this.hasFlag)))return i();this.emit("6",this),r(new O({message:"".concat(this.strMediaType," encode failed"),code:N?C.AUDIO_ENCODE_FAILED:C.VIDEO_ENCODE_FAILED}))}}}),1e4)}))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),R.emit(b.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return g(this,null,function*(){if(this.sourceTrack&&Es){let{deviceId:t,groupId:i}=this.sourceTrack.getSettings(),{label:r}=this.sourceTrack;(yield(function(n){return g(this,arguments,function(s){let{newDeviceId:a,oldDeviceId:o,oldGroupId:l,oldLabel:c,kind:d}=s;return(function*(){return a===o&&(d!==_.AUDIO||a!==Ra||(yield fb(l,c)))})()})})({newDeviceId:t,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=t,this.label=r,i&&(this.groupId=i),nu().then(n=>{let s=n.find(a=>{let o=a.deviceId===t;return i&&(o=o&&a.groupId===i),o});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===_.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==null?void 0:i.getSettings())||{}).deviceId,"_").concat(_.AUDIO_INPUT);return!!Jf.has(n)})(this.sourceTrack)||this.kind===_.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==null?void 0:i.getSettings())||{}).deviceId,"_").concat(_.VIDEO_INPUT);return!!Jf.has(n)})(this.sourceTrack)||this._isRecapturing||t&&gr&&Ze)}onTrackMuted(){if(super.onTrackMuted(),n5(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<ba)return void setTimeout(()=>this.onTrackMuted(),ba);this._onMuteTimeoutId=setTimeout(()=>g(this,null,function*(){var t;if((t=this.sourceTrack)!=null&&t.muted){if((be||Oe)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return g(this,null,function*(){if(Et(Sk.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTime<ba)return void setTimeout(()=>this.onTrackEnded(),ba);this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(t){let i=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return g(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 a;(this.kind==="audio"?yield Hi():yield Wi()).find(o=>o.deviceId===t)&&(a=t),s.deviceId=a}return this.capture(s,i).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),R.emit(b.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(a=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(a.message)),this.emit("5",a),R.emit(b.LOCAL_TRACK_RECAPTURE,{track:this,error:a})}).finally(()=>{i&&(n==null||n.stop())})})}getRecoverCaptureDeviceId(){return g(this,null,function*(){let t=this instanceof ji;if(t&&this.facingMode)return this.facingMode;let{deviceId:i}=this;if(i){let r=(So.get(i)||0)+1;if(So.set(i,r),r>=3&&this.enableAutoSwitchWhenRecapturing){let n=t?(yield Wi()).find(s=>!So.has(s.deviceId)):(yield Hi()).find(s=>!So.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(),R.emit(b.LOCAL_TRACK_STOPPED,{track:this}),this.uninstallTrackEvent(this.sourceTrack)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),(t=this.manager)==null||t.removeInput(this),this._onMuteTimeoutId&&clearTimeout(this._onMuteTimeoutId)}close(){super.close(),this.stopCapture()}};M([Ke(re.INIT,"ready",{ignoreError:!0,sync:!0})],vo.prototype,"setStateToReady"),M([fo()],vo.prototype,"capture"),M([Ke("ready","publish",{ignoreError:!0,success(){R.emit(b.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 O?e:e.cause instanceof O?e.cause:e,n=!1;r instanceof O&&(r.message.includes("timeout")?i="timeout":r.code===C.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)}}),Sr(521714,!1)],vo.prototype,"publish"),M([ge(e=>function(){return g(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)})}),Ke([],"ready",{sync:!0})],vo.prototype,"unpublish");var yo=vo,So=new Map;R.on(b.SWITCH_DEVICE_SUCCESS,e=>{e.track.deviceId&&So.delete(e.track.deviceId)});var dn=class Lo extends yo{constructor(t){super(1,ZB,t.room),u(this,"mediaType",1),u(this,"volume",0),u(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),u(this,"playerMuted",!0),u(this,"pipeline"),u(this,"earMonitorGainNode",new tt),u(this,"_output",new tt),u(this,"codecPipeline",[]),u(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),u(this,"mixedAudioReferenceMap",new Map),u(this,"isAudioContextLongSuspended",!1),u(this,"after3aSilenceStartTime",0),u(this,"muteMicOnly",!1),u(this,"_volumeDetectionTrack",null),u(this,"_volumeDetectionSource",new tt),this.manager=t,this.pipeline=new cb(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._volumeDetectionSource.pipeTo(this.player.pipeline.volumeMeter),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this),R.on(b.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return ru.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){I(t)||(t!==0||this.after3aSilenceStartTime?t>0&&(this.after3aSilenceStartTime=0):this.after3aSilenceStartTime=J())}setInputMediaStreamTrack(t){return g(this,null,function*(){let i=this.trackSettings||{};w.addEnum({key:501701,value:i.channelCount||0,useUV:!1}),w.addEnum({key:501702,value:i.sampleRate||0,useUV:!1}),w.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 Et(Lo.prototype,this,"setInputMediaStreamTrack").call(this,t),this.updatePlayingState(!!t)})}capture(t){return g(this,arguments,function(i){var r=this;let{deviceId:n,customSource:s,useExactDeviceId:a=!0,retryWhenExactFailed:o}=i,l=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return(function*(){let c=yield Et(Lo.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:a,retryWhenExactFailed:o,customSource:s},l);return mo(),c})()})}switchDevice(t){return g(this,null,function*(){if(this.mediaTrack){if(this.deviceId===t&&!this.isUseCustomSource&&(t!==Ra||(yield fb(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}),R.emit(b.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(){He&&!He.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&He.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(t){return g(this,null,function*(){if(t.deviceId===this.deviceId){let i=this.recaptureMode===1;if(this.log.warn("RecaptureMode: ".concat(n_[this.recaptureMode],". Current microphone is lost: ").concat(JSON.stringify(t))),this.recaptureMode===0){Le(this.userId,{eventId:2003,param1:6,streamType:1});let r=yield Hi();r[0]?this.recapture(r[0].deviceId):i=!0}i&&He.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(t){this.recaptureMode===1&&t.deviceId!==this.deviceId||(He.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn("microphone added: ".concat(JSON.stringify(t))),this.recapture(t.deviceId))}update3A(t){return g(this,arguments,function(i){var r=this;let{echoCancellation:n,noiseSuppression:s,autoGainControl:a}=i;return(function*(){let o=r.sourceTrack||r.mediaTrack;if(!o)return;let l=o.getConstraints(),c=!1;!I(n)&&n!==r.profile.echoCancellation&&(r.profile.echoCancellation=n,l.echoCancellation=n,c=!0),!I(s)&&s!==r.profile.noiseSuppression&&(r.profile.noiseSuppression=s,l.noiseSuppression=s,c=!0),!I(a)&&a!==r.profile.autoGainControl&&(r.profile.autoGainControl=a,l.autoGainControl=a,c=!0),c&&(me||Ze?yield o.applyConstraints(l).catch(d=>r._log.warn("update3A failed: ",d)):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&&w.addEnum({key:502700,value:2})}setMute(t,i){var r;this._cleanupVolumeDetectionTrack(),t==="microphone"?(this.muteMicOnly=!0,this.sourceTrack&&(this.sourceTrack.enabled=!1),i&&this._setupVolumeDetectionTrack(),(r=this.manager)!=null&&r.isAudioMixed?this._outputTrack&&(this._outputTrack.enabled=!0):(this.muted=!0,this._inputTrack&&(this._inputTrack.enabled=!1),this._outputTrack&&(this._outputTrack.enabled=!1)),this.emit("mute",this),R.emit(b.TRACK_MUTED,{track:this})):t===!0?(this.muteMicOnly=!1,this.muted=!0,this.sourceTrack&&(this.sourceTrack.enabled=!1),this._inputTrack&&(this._inputTrack.enabled=!1),this._outputTrack&&(this._outputTrack.enabled=!1),i&&this._setupVolumeDetectionTrack(),this.emit("mute",this),R.emit(b.TRACK_MUTED,{track:this})):(this.muteMicOnly=!1,this.muted=!1,this.sourceTrack&&(this.sourceTrack.enabled=!0),this._inputTrack&&(this._inputTrack.enabled=!0),this._outputTrack&&(this._outputTrack.enabled=!0),this.emit("unmute",this),R.emit(b.TRACK_UNMUTED,{track:this}))}_setupVolumeDetectionTrack(){let t=this.sourceTrack||this.mediaTrack;if(!t)return;this._volumeDetectionTrack=t.clone(),this._volumeDetectionTrack.enabled=!0;let i=tu(this._volumeDetectionTrack);i&&this._volumeDetectionSource.setNode(i)}_cleanupVolumeDetectionTrack(){this._volumeDetectionTrack&&(this._volumeDetectionTrack.stop(),this._volumeDetectionTrack=null),this._volumeDetectionSource.deleteNode()}setAudioVolume(t){super.setAudioVolume(0),be&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(et().createGain()),this._output.setNode(et().destination)),this.earMonitorGainNode.node.gain.value=t}enableTrackANS(t){return this.update3A({noiseSuppression:t})}enableTrackAEC(t){if(this.sourceTrack&&!Ze&&!be)return this.update3A({echoCancellation:t})}addDenoiser(t){var i;Ht<=92&&((i=this.trackSettings)==null?void 0:i.sampleRate)!==48e3?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(w.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=tu(t);if(!r)return;let n=new tt,s=et().createGain();s.gain.value=1;let a=new tt;n.pipeTo(a).pipeTo(this.pipeline.mixNode),n.setNode(r),a.setNode(s),this.mixedAudioReferenceMap.set(i,[n,a])}unMixAudioReference(t){let[i,r]=this.mixedAudioReferenceMap.get(t)||[];i&&(this.log.info("unMixAudioReference() => ".concat(t)),i.deleteNode(),r==null||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._cleanupVolumeDetectionTrack(),this.mixedAudioReferenceMap.forEach(t=>{let[i,r]=t;i.deleteNode(),r.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),He.off("audioInputAdded",this.handleMicrophoneAdded,this),He.off("audioInputRemoved",this.handleMicrophoneRemoved,this),R.off(b.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(t){let i=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return g(this,null,function*(){try{yield Et(Lo.prototype,this,"recapture").call(this,t,i)}catch(r){let n=(yield Hi()).find(s=>s.deviceId!==t);if(!n)throw r;yield Et(Lo.prototype,this,"recapture").call(this,n.deviceId)}})}encodeFrame(t){return this.manager?this.manager.encodePipeline.reduceRight((i,r)=>r?r({frame:i,ntp:Ta()}):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(en?"":", 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){var i;if(this.isAudioContextLongSuspended){let r=this.sourceTrack||this.mediaTrack;r&&(t=r)}super.setOutputMediaStreamTrack(t),this.muteMicOnly&&(i=this.manager)!=null&&i.isAudioMixed&&(t.enabled=!0)}onAudioMixedChanged(t){this.log.info("onAudioMixedChanged() isAudioMixed: ".concat(t)),this.muteMicOnly&&(t?(this.muted=!1,this._outputTrack&&this._outputTrack!==this._inputTrack&&(this._outputTrack.enabled=!0)):this.muted=!0,this.emit("mute",this),R.emit(b.TRACK_MUTED,{track:this}))}};function pu(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 zb(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=pu(i,n);if(s===0){n+=1;continue}let a=-1;for(let h=n+s;h<i.byteLength;h+=1)if(pu(i,h)>0){a=h;break}let o=a===-1?i.byteLength:a,l=o-n,c=new ArrayBuffer(l),d=new DataView(c);for(let h=0;h<l;h+=1)d.setUint8(h,i.getUint8(n+h));r.push(new fu(d,t)),n=o}return r}var fu=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 a=this.dataView.getInt8(s);switch(a){case 0:case 1:case 2:case 3:r===2&&(i.push(3),r=0),a===0?r+=1:r=0,i.push(a);break;default:r=0,i.push(a)}}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 a=this.dataView.getUint8(s);if(t+=1,a!==255){e+=a;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}},yH=class{constructor(){u(this,"_seiMessageList",[]),u(this,"_smallSeiMessageList",[]),u(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 a=0;a<i;a++)n.push(255);n.push(r);let s=new DataView(e);return n.push(...new Uint8Array(s.buffer)),n.push(128),new fu(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((d,h)=>d+h.dataView.byteLength,0),a=new ArrayBuffer(s+e.data.byteLength),o=new DataView(a),l=new DataView(e.data),c=0;for(let d=0;d<n.length;d++)for(let h=0;h<n[d].dataView.byteLength;h++)o.setInt8(c++,n[d].dataView.getInt8(h));for(let d=0;d<e.data.byteLength;d++)o.setInt8(c++,l.getInt8(d));return e.data=a,n.length}return 0}},Jb=class In extends yo{constructor(t){super(arguments.length>1&&arguments[1]!==void 0?arguments[1]:4,gi,t==null?void 0:t.room),u(this,"profile",x({},ya)),u(this,"avoidCropping",!1),u(this,"_scaleResolutionDownBy"),u(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0}),u(this,"small"),u(this,"isNeedToSetBandwidth"),u(this,"muteImage"),u(this,"manager"),u(this,"_seiCodec",new yH),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=pr(((r=this.room)==null?void 0:r.sdkAppId)||0)?op:ap;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(n)),this.setProfile(W(x({},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(Es&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get contentHint(){var t,i;return((t=this._inputTrack)==null?void 0:t.contentHint)||((i=this.outMediaTrack)==null?void 0:i.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 g(this,null,function*(){var i,r,n;if(he(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,Et(In.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(n=this.manager)==null?void 0:n.deleteWatermark("mute"),this.muteImage=void 0),Et(In.prototype,this,"setMute").call(this,t)})}capture(t){return g(this,arguments,function(i){var r=this;let{deviceId:n,facingMode:s,useExactDeviceId:a=!0,customSource:o,retryWhenExactFailed:l=!0}=i;return(function*(){let c={audio:!1,video:!0,facingMode:s||r.facingMode,cameraId:n,width:r.profile.width,height:r.profile.height,frameRate:r.profile.frameRate,useExactDeviceId:a,retryWhenExactFailed:l,customSource:o};if(c.facingMode==="environment"){let d=yield r.getDeviceIdWhenUsingBackCamera();d&&(c.cameraId=d)}return Et(In.prototype,r,"capture").call(r,c)})()})}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=pr(((i=this.room)==null?void 0:i.sdkAppId)||0)?op:ap;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(n)),super.setProfile(W(x({},this.profile),{width:1920,height:1080}))}}applyProfile(){return g(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,a=s.height!==this.profile.height||s.width!==this.profile.width||s.frameRate!==this.profile.frameRate;if(a&&(Rt===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:o=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),c=o*l;return a&&c&&n&&c===n?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:_.VIDEO,videoType:_.BIG})}})}get settings(){let t={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},i=this.sourceTrack||this.mediaTrack;return Es&&i&&Object.assign(t,i.getSettings()),t}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:Rc(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 g(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),R.emit(b.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 g(this,null,function*(){let t;try{if(rf&&!Ka&&xC){let i=(yield Wi(!0)).map(n=>{var s;return W(x({},n),{capabilities:(s=n.getCapabilities)==null?void 0:s.call(n)})}).filter(n=>{var s,a;return(a=(s=n.capabilities)==null?void 0:s.facingMode)==null?void 0:a.includes("environment")}),r=i[0];i.forEach(n=>{var s,a,o,l;let{capabilities:c}=n;((s=c.width)!=null&&s.max&&(a=c.height)!=null&&a.max?c.width.max*c.height.max:0)>((o=r.capabilities.width)!=null&&o.max&&(l=r.capabilities.height)!=null&&l.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 g(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=x({},t);return t.width*t.height<=19200&&Oe&&Bt&&(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&&_R&&(n.width=r?1280:720,n.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),cf(rt,"14.3")&&Ui(rt,"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&&(Bt||me)&&!Hc()&&t.width*t.height<=230400&&t.width/t.height===16/9&&(this._scaleResolutionDownBy=1280/t.width,n.width=1280,n.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(){He&&!He.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&He.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(t){return g(this,null,function*(){if(t.deviceId===this.deviceId){let i=this.recaptureMode===1;if(this.log.warn("RecaptureMode: ".concat(n_[this.recaptureMode],". Current camera is lost: ").concat(JSON.stringify(t))),this.recaptureMode===0){Le(this.userId,{eventId:2003,param1:7,streamType:2});let r=yield Wi();r[0]?this.recapture(r[0].deviceId):i=!0}i&&He.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(t){return g(this,null,function*(){this.recaptureMode===1&&t.deviceId!==this.deviceId||(He.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 I(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(t,i)}close(){He.off("videoInputAdded",this.handleCameraAdded,this),He.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(t){return g(this,null,function*(){try{yield Et(In.prototype,this,"recapture").call(this,t)}catch(i){let r=(yield Wi()).find(n=>n.deviceId!==t);if(!r)throw i;yield Et(In.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||I(t)||t!==this.rotation&&(this.rotation=t,this.manager.rotation=t))}setOutputMediaStreamTrack(t){let i=this._outputTrack;if(!(this instanceof In&&Xr(i,this.room)))return super.setOutputMediaStreamTrack(t)}};M([cn(function(e){this.setContentHint(e.contentHint||"motion")})],Jb.prototype,"capture");var ji=Jb,Kb={};Ni(Kb,{REPORT_TYPE:()=>Lp,buildSSOPackage:()=>us,bytes2ms:()=>BA,calculateScaleResolutionDownNumber:()=>Rc,concatArrayBuffers:()=>xp,convertObjectNumberToInt:()=>Ac,copyProperties:()=>FA,deepClone:()=>cs,deepCloneBasic:()=>Cc,deepMerge:()=>Li,delay:()=>mi,fibonacci:()=>ls,formatedTime:()=>ZA,getConstructorName:()=>vc,getContainerFromElement:()=>QA,getEnv:()=>MA,getFirst16Bits:()=>eR,getInternalVersion:()=>qA,getLast16Bits:()=>Up,getLoggerUrl:()=>os,getMediaStreamTrackInfo:()=>Mp,getMuteStateFromFlag:()=>Yr,getNetworkType:()=>Ec,getNumNetworkType:()=>Na,getReconnectionTimeout:()=>qr,getStringByteLength:()=>Ic,getTestSignalDomain:()=>LA,getTurnServer:()=>XA,getUint32Version:()=>Np,getValueType:()=>Je,getVersionFromInternalVersion:()=>YA,getViewListFromView:()=>xa,glog:()=>WA,ipv4ToUint32:()=>La,isArray:()=>Ue,isAudioWorkletSupported:()=>zA,isBoolean:()=>Se,isConstructor:()=>Oa,isEmpty:()=>yc,isFunction:()=>Pe,isLangChinese:()=>Mi,isMediaStreamTrack:()=>GA,isNumber:()=>le,isObject:()=>hi,isOverseaSdkAppId:()=>pr,isPlainObject:()=>Ut,isPortrait:()=>wp,isPromise:()=>Pa,isRemoteTrack:()=>jA,isRotate90Or270:()=>fr,isSetSinkIdSupported:()=>JA,isString:()=>he,isUndefined:()=>I,isVideoMixerOutputTrack:()=>Xr,loadImage:()=>Ua,loadVideo:()=>$A,ms2bytes:()=>HA,ms2samples:()=>Dp,normalizeUrl:()=>Op,performanceNow:()=>J,promiseAny:()=>Ma,samples2ms:()=>kp,setNetworkTypeFromWebRTC:()=>bp,stringify:()=>ti,stringifyIncludeValue:()=>Sc,throttlePromise:()=>Pp});var SH=[-1,-1,1,-1,-1,1,1,1],IH=[0,0,1,0,0,1,1,1],Io=class U_ extends re{constructor(t,i){if(super(),this.context=t,u(this,"name"),u(this,"input"),u(this,"output"),u(this,"texture"),u(this,"ctx2d",null),u(this,"fbo"),u(this,"width",0),u(this,"height",0),u(this,"x",0),u(this,"y",0),u(this,"program"),u(this,"vertexShader"),u(this,"fragmentShader"),u(this,"totalFrames",0),u(this,"dropFrames",0),u(this,"matchInputSize",!0),u(this,"texCoordBuffer"),u(this,"positionBuffer"),u(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),u(this,"cost",0),u(this,"_canvas",null),u(this,"_image"),u(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 Ei)t.ctx&&i.create2d&&(typeof OffscreenCanvas=="function"&&Rt!==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(IH),this.positionBuffer=this.createBuffer(SH),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 O({code:C.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 Gt&&this.render(t)||this.context instanceof Ei&&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 Gt){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,a)=>{s&&(t.activeTexture(t.TEXTURE0+a),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,a)=>{t.enableVertexAttribArray(a),t.bindBuffer(t.ARRAY_BUFFER,s),t.vertexAttribPointer(a,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,a,o,l,c){let d=!(I(a)||I(o)||I(l)||I(c));return!(!this.ctx2d||!t)&&(t instanceof ImageData?(d?this.ctx2d.putImageData(t,i,r,a,o,l,c):this.ctx2d.putImageData(t,i,r),this.emit(U_.RENDER,this.ctx2d.canvas)):(d?this.ctx2d.drawImage(t,a,o,l,c,i,r,n,s):this.ctx2d.drawImage(t,i,r,n,s),this.emit(U_.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:a,name:o,cost:l}=this,c=Date.now(),d=(i-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:i,x:r,y:n,width:s,height:a,timestamp:c,fps:d,name:o,cost:l},x({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}};u(Io,"RENDER","render"),M([Ke(re.INIT,"connected",{sync:!0})],Io.prototype,"connect"),M([Ke("connected",re.INIT,{ignoreError:!0,sync:!0})],Io.prototype,"disconnect"),M([Ke([],"closed",{sync:!0})],Io.prototype,"close");var Ct=Io,AH=Ie(Pb(250),i_(()=>performance.now()),_o()),RH=[0,1,1,1,0,0,1,0],s_=class extends Ct{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),u(this,"_intervalId",0),u(this,"_sequence",0),u(this,"checkGLError",!1),u(this,"checkVisibilityChange"),e instanceof Ei?this.ctx2d=e.ctx||null:e.available&&t!=null&&t.mirrorUpAndDown&&this.setTexBuffer(RH)}start(e){this.log.info("".concat(this.name," start render ").concat(e," fps")),_e.clearTask(this._intervalId),this._intervalId=_e.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(_e.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Gt){let t=this.context.ctx.getError();t&&this.context.destroy(new O({code:C.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(Ct.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&&(_e.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),_e.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),_e.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},a_=class extends s_{constructor(e,t){super(e,t),u(this,"_videoTrack"),u(this,"_muteOb"),u(this,"_closedOb",ye(this,"closed")),u(this,"_subscription"),u(this,"_canvasContainer"),Number(xi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=ye(this._videoTrack,"mute"),Ie(ye(this._videoTrack,"ended"),pt(this._closedOb),ze(()=>{this.context.destroy(new O({code:C.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){var e;this._subscription=Ie(this._muteOb,pt(this._closedOb),mu((e=5e3,t=>{let i=performance.now();Ie(AH,t_(r=>r-i<e),Ss(1))(t)})),un(()=>{var t;return!((t=this._videoTrack)==null||!t.muted||document.hidden)}),ze(()=>{this.context.destroy(new O({code:C.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()}},CH=class extends a_{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(Ct.RENDER,this.context._canvas2d)}else this.emit(Ct.RENDER,this.context._canvas);return i}},bH=class extends a_{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))}},qb=class extends Ct{constructor(e,t){super(e,x({name:"imageSource"},t)),u(this,"_lastImage"),u(this,"_totalFrames",0),u(this,"_autoResize",!1),u(this,"_canvasRendered"),u(this,"videoCallbackId",0),u(this,"waitingFirstFrame",!0),u(this,"shouldUpdate",!0),this._autoResize=(t==null?void 0:t.autoResize)!==!1,Rt===16&&(this._canvasRendered=Ti(),Ie(this._canvasRendered,Qf(this._image),du(i=>i instanceof HTMLCanvasElement?ye(i,"rendered"):e_()),pt(ye(this,"closed")),ze(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),io()&&!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 a=this.context.ctx;a.texSubImage2D(a.TEXTURE_2D,0,0,0,a.RGBA,a.UNSIGNED_BYTE,s)}}else{if(t){this.useTexture();let a=this.context.ctx;a.texImage2D(a.TEXTURE_2D,0,a.RGBA,a.RGBA,a.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)}},Yb=class extends qb{constructor(e,t,i){super(e,i),this._player=t,this.name="videoPlayerSource",Ie(ye(this._player,z.PLAYER_STATE_CHANGED),pt(ye(this,"closed")),un(r=>{let{state:n}=r;return n==="PLAYING"}),ze(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},Is=class extends Yb{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(e,t,i){super(e,new gi({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()}},kH=class extends Ct{constructor(e,t,i){super(e,W(x({name:"textSource"},i),{create2d:!0})),u(this,"hasChange",!0),u(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,a=this.content.split(`
|
||
`);for(let o=0;o<a.length;o++)this.ctx2d.fillText(a[o],e,t+o*s)}},Ao=class extends re{constructor(e){super(),u(this,"frameRate"),u(this,"_canvas"),u(this,"log"),u(this,"hasAlpha",!1),u(this,"name"),u(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 Is(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new a_(this,e)}createVideoImageSource(e,t){return new qb(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new Yb(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new kH(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};u(Ao,"_ids",0);var Ro=class extends Ao{constructor(){super(...arguments),u(this,"defaultProgam"),u(this,"defaultVShader"),u(this,"defaultFShader"),u(this,"ctx"),u(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(Ao._ids++)),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",wA),!this.ctx)throw new O({code:C.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,`
|
||
// 顶点着色器
|
||
attribute vec4 a_position;
|
||
attribute vec2 a_texCoord;
|
||
varying vec2 v_texCoord;
|
||
|
||
void main() {
|
||
gl_Position = a_position;
|
||
v_texCoord = a_texCoord;
|
||
}
|
||
`),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,`
|
||
// 片元着色器
|
||
precision mediump float;
|
||
varying vec2 v_texCoord;
|
||
uniform sampler2D u_texture;
|
||
|
||
void main() {
|
||
gl_FragColor = texture2D(u_texture, v_texCoord);
|
||
} `),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new O({code:C.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,w.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}};u(Ro,"UNAVAILABLE","unavailable"),M([Ke(re.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),w.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),w.addSuccessEvent({key:512700})}})],Ro.prototype,"create"),M([Ke("created",re.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(Ro.UNAVAILABLE,e),this.removeAllListeners()}})],Ro.prototype,"destroy");var Gt=Ro,Ei=class extends Ao{constructor(){super(...arguments),u(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(Ao._ids++),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha,willReadFrequently:e.willReadFrequently}),!this.ctx)throw new O({code:C.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,w.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(),w.addSuccessEvent({key:512703})}};function DH(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 a=Math.min(i/e,r/t);s.dWidth=e*a,s.dHeight=t*a,s.dx=(i-s.dWidth)/2,s.dy=(r-s.dHeight)/2;break}case"cover":{let a=Math.max(i/e,r/t),o=i/a,l=r/a;s.sx=(e-o)/2,s.sy=(t-l)/2,s.sWidth=o,s.sHeight=l;break}}return s}M([Ke(re.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),w.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),w.addSuccessEvent({key:512701})}})],Ei.prototype,"create"),M([Ke("created",re.INIT,{ignoreError:!0,sync:!0})],Ei.prototype,"destroy");var wH=class{constructor(e,t){this.node=e,this.layout=t,u(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}},Xb=class extends Ct{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t}),u(this,"inputs",[]),u(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 wH(e,t);this.inputs.splice(i,0,n)}changeInputLayout(e,t){let i=this.inputs.findIndex(m=>m.node===e);if(i<0)return;let{x:r,y:n,width:s,height:a,zIndex:o,fillMode:l,rotation:c,hidden:d}=t;if(!I(o)&&this.inputs.some(m=>m.layout.zIndex===o&&m.node!==e))throw new Error("input already exists at zIndex ".concat(t.zIndex));let h=this.inputs[i];I(r)||(h.layout.x=r),I(n)||(h.layout.y=n),I(s)||(h.layout.width=s),I(a)||(h.layout.height=a),I(c)||(h.layout.rotation=c),I(d)||(h.layout.hidden=d),l&&(h.layout.fillMode=l),!I(o)&&o!==h.layout.zIndex&&(h.layout.zIndex=o,this.inputs.sort((m,p)=>m.layout.zIndex-p.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 Gt&&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=DH(i.node.width,i.node.height,i.width,i.height,i.fillMode,fr(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,a=Date.now(),o=(e-this.lastInfo.totalFrames)/((a-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:e,x:t,y:i,width:r,height:n,timestamp:a,fps:o,name:s},x({parent:this.inputs.filter(l=>l).map(l=>l.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(e=>{var t;if(e.node.disconnect(),e.positionBuffer&&this.context instanceof Gt)try{(t=this.context.ctx)==null||t.deleteBuffer(e.positionBuffer)}catch{}})}close(){super.close(),this.removeAllInputs()}},NH=[1,0,0,0,1,1,0,1],Rr=class extends Ct{constructor(e,t,i,r){if(super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t}),u(this,"mirror",!1),u(this,"rotation",0),i&&(this.mirror=i),r&&(this.rotation=r),e instanceof Gt)try{this.setTexBuffer(NH)}catch(n){e.destroy(new O({code:C.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){fr(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}},o_=class extends yo{constructor(e){super(arguments.length>1&&arguments[1]!==void 0?arguments[1]:4,gi,e==null?void 0:e.room),u(this,"inputLocalVideoTracks",new Map),u(this,"inputLocalScreenTracks",new Map),u(this,"cameraNodeMap",new Map),u(this,"screenNodeMap",new Map),u(this,"textNodeMap",new Map),u(this,"imageNodeMap",new Map),u(this,"videoNodeMap",new Map),u(this,"endedIds",new Set),u(this,"videoContext"),u(this,"mixNode"),u(this,"destination"),u(this,"manager"),u(this,"stat"),u(this,"_checkId",0),u(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(Ct.RENDER,t=>{this.emit("render",t)}),this.mixNode=new Xb(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=_e.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new Ei({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 a=this.cameraNodeMap.get(n);a&&a.image.cancelVideoFrameCallback(a.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 a=this.screenNodeMap.get(n);a&&a.image.cancelVideoFrameCallback(a.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 g(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),en&&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,Wt(this,He).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=Rt===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 screenSource failed");t.on("output-media-track-changed",()=>{this.updateScreenSource(e,i,t.mediaTrack)});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 a=this.videoContext.createTextSource({content:i,font:r,color:n});a.resize(s.width,s.height),this._connectMix(a,s),this.textNodeMap.set(t,a)}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.inputLocalVideoTracks.get(e);n&&i&&i!==n.mediaTrack&&(this.log.debug("updateCameraSource mixerLocalVideoTrack newTrack:",i,"oldTrack:",n.mediaTrack),n.setInputMediaStreamTrack(i));let s=this.cameraNodeMap.get(e);if(s){if(i){if(Rt===16&&i instanceof CanvasCaptureMediaStreamTrack)if(s instanceof Is){let l=s.output;s.close(),s=this.videoContext.createVideoImageSource(i.canvas,{name:"cameraCanvasSource",logger:this.log}),s.connect(l),this.cameraNodeMap.set(e,s)}else s.image=i.canvas;else if(s instanceof Is)s.replaceTrack(i);else{let l=s.output;s.close(),s=this.videoContext.createVideoTrackSource(i,"cameraNodeSource"),s.connect(l),this.cameraNodeMap.set(e,s)}let{width:a,height:o}=i.getSettings();a&&o&&s.resize(a,o)}r&&s.resize(r.width,r.height),(r||i)&&this.setFpsAuto(),this._changeMixLayout(s,t)}}updateScreenSource(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,r=this.inputLocalScreenTracks.get(e);this.log.debug("updateScreenSource mixerLocalScreenTrack",r,i),r&&i&&i!==r.mediaTrack&&r.setInputMediaStreamTrack(i);let n=this.screenNodeMap.get(e);n&&(i&&n.replaceTrack(i),this._changeMixLayout(n,t))}updateTextSource(e){let{id:t,content:i,font:r,color:n,layout:s}=e,a=this.textNodeMap.get(t);a&&(I(i)||(a.content=i),I(r)||(a.font=r),I(n)||(a.color=n),a.resize(s.width,s.height),this._changeMixLayout(a,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 Rr(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 Rr&&(I(i)||(n.mirror=i),I(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 Rr&&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 Rr&&i.output.close(),i.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof Rr&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof Rr&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof Rr&&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(),_e.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(),mt(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")}},l_=RR();if(typeof navigator<"u"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:l_,exposeOrigin:!0,permittedOrigins:["*"]})}catch{}var PH=function(e){return g(this,null,function*(){let t=null,i=(function(s){let a={preferCurrentTab:s.preferDisplaySurface==="current-tab"||!!s.captureElement,systemAudio:"include",selfBrowserSurface:s.selfBrowserSurface||"include",surfaceSwitching:"include"},o={width:Ze?{max:s.width}:{ideal:s.width,max:s.width},height:Ze?{max:s.height}:{ideal:s.height,max:s.height},frameRate:s.frameRate,displaySurface:s.preferDisplaySurface||"monitor"};if(a.video=o,s.systemAudio){let{echoCancellation:l=!0,noiseSuppression:c=!1,autoGainControl:d=!1}=s;a.audio={echoCancellation:l,noiseSuppression:c,autoGainControl:d,sampleRate:48e3}}return a})(e);P.info("getDisplayMedia with constraints: ".concat(JSON.stringify(i)));let r=yield navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&r.getAudioTracks().length===0&&(Bc&&Ht<74||Ze||me)&&P.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){P.warn("screen applyConstraints failed: ".concat(s))}e.captureElement&&(yield(function(s,a){return g(this,null,function*(){var o;if("CropTarget"in window&&"fromElement"in CropTarget&&Pe(s.cropTo))try{if(((o=s.getCaptureHandle())==null?void 0:o.handle)!==l_)return;let l=yield CropTarget.fromElement(a);yield s.cropTo(l)}catch(l){P.warn("cropTo target failed ".concat(l))}})})(n,e.captureElement))}if(e.audio){let s=(function(a){let o={echoCancellation:a.echoCancellation,autoGainControl:a.autoGainControl,noiseSuppression:a.noiseSuppression,sampleRate:a.sampleRate,channelCount:a.channelCount};return I(a.microphoneId)||(o.deviceId=a.microphoneId),{audio:o,video:!1}})(e);P.info("getUserMedia with constraints: ".concat(JSON.stringify(s))),t=yield navigator.mediaDevices.getUserMedia(s),r.addTrack(t.getAudioTracks()[0])}return r})},hn=class extends ji{constructor(e){super(e,2),u(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),u(this,"objectFit","contain"),u(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}get isShareCurrentTab(){var e,t;try{return l_===((t=(e=this.mediaTrack)==null?void 0:e.getCaptureHandle())==null?void 0:t.handle)}catch{return}}capture(e){return g(this,arguments,function(t){var i=this;let{systemAudio:r=!1,autoGainControl:n,echoCancellation:s,noiseSuppression:a,audioTrack:o,videoTrack:l,captureElement:c,preferDisplaySurface:d,selfBrowserSurface:h}=t;return(function*(){var m;try{let p,f=J();return l||o?(p=new MediaStream,l&&p.addTrack(l),o&&p.addTrack(o)):(p=yield PH({audio:!1,systemAudio:r,width:i.profile.width,height:i.profile.height,frameRate:i.profile.frameRate,autoGainControl:n,echoCancellation:s,noiseSuppression:a,captureElement:c,preferDisplaySurface:d,selfBrowserSurface:h}),i.sourceTrack=p.getVideoTracks()[0]),yield i.setInputMediaStreamTrack(p.getVideoTracks()[0]),R.emit(b.LOCAL_TRACK_CAPTURE_SUCCESS,{track:i,cost:J()-f,profile:i.profile,room:(m=i.manager)==null?void 0:m.room}),p}catch(p){throw i.log.error("getDisplayMedia error observed ".concat(p)),p instanceof O?p:new O({code:C.INITIALIZE_FAILED,name:p.name,message:p.message})}})()})}switchDevice(e){return g(this,null,function*(){throw new Error("Method not implemented.")})}};M([cn(function(e){this.setContentHint(e.contentHint||"detail")})],hn.prototype,"capture");var c_,_u=class extends dn{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 u_(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 g(this,null,function*(){let n=et();c_||(c_=$c(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 c_;let s=n.sampleRate,a=new AudioWorkletNode(n,"dumper",{numberOfInputs:e.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:s,targetSampleRate:t}});return a.channelCountMode="explicit",a.channelCount=i,r&&a.port.postMessage({port:r},[r]),e.forEach((o,l)=>o.connect(a,0,l)),new ReadableStream({start(o){a.port.onmessage=l=>{o.enqueue(l.data)}},cancel(){e.forEach(o=>o.disconnect(a)),a.port.close()}})})}var OH=class extends qB{constructor(e){super(),this.room=e,u(this,"_localAudioTrack"),u(this,"_localScreenAudioTrack"),u(this,"log"),u(this,"denoiser"),u(this,"voiceChanger"),u(this,"mixChangedDebounce"),u(this,"audioProcessor"),u(this,"encodePipeline",[]),u(this,"decodePipeline",[]),u(this,"getPCMAbortCtrlMap",new Map),u(this,"audioFrameEventConfigMap",new Map),u(this,"audioReferenceMap",new Map),u(this,"isLocalAudioNeedAudioProcess",!1),u(this,"isScreenAudioNeedAudioProcess",!1),this.log=P.createLogger({parent:e==null?void 0:e.getLogger(),id:"am",userId:e==null?void 0:e.userId,sdkAppId:e==null?void 0:e.sdkAppId}),this.installEvent()}get isAudioMixed(){return this.inputs.size>1}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,a=[],o=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},1e3*e),l=()=>{for(let d=0;d<n.length;d++){let h=URL.createObjectURL(new Blob(a[d])),m=document.createElement("a");m.href=h,m.download="".concat(n[d],".pcm"),m.style.display="none",document.body.appendChild(m),m.click(),URL.revokeObjectURL(h),m.remove()}clearTimeout(o),s.abort("download")},c=u_(r).then(d=>d.pipeTo(new WritableStream({write(h){h.forEach((m,p)=>a[p]=a[p]?a[p].concat(m[0]):[m[0]])}}),s).catch(h=>l));return{then:c.then.bind(c),download:l}}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:a=48e3,channelCount:o=1,port:l}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!s)return;this.log.info("getPCM ".concat(t||"local"));let c,d,h=Math.floor(.04*a),m=new Float32Array(h),p=new Float32Array(h),f=0,T=new AbortController,E=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(E)return u_([et().createMediaStreamSource(new MediaStream([E]))],a,o,l).then(v=>v.pipeTo(new WritableStream({write(y){y[0][0]&&(f+y[0][0].length>h?(m.set(y[0][0].subarray(0,h-f),f),c=y[0][0].subarray(h-f),y[0][1]&&(p.set(y[0][1].subarray(0,h-f),f),d=y[0][1].subarray(h-f)),f+=h-f):(c&&(m.set(c,f),f+=c.length,c=void 0),d&&(p.set(d,f),d=void 0),m.set(y[0][0],f),y[0][1]&&p.set(y[0][1],f),f+=y[0][0].length),f>=h&&(f=0,e({userId:t,sampleRate:a,channelCount:o,data:o===1?m:[m,p]}),m=new Float32Array(h),p=new Float32Array(h)))}}),T).catch(y=>this.log.warn("stop getPCM reason:".concat(y)))),T;this.log.info("getPCM failed: ".concat(t||"local"," has no audio track"))}get hasScreenAudioTrack(){return!I(this._localScreenAudioTrack)}get hasAudioTrack(){return!I(this._localAudioTrack)}changeInput(e){var t,i;return e instanceof _u?(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 dn?(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 Tu?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}onAudioMixedChanged(e){var t;(t=this._localAudioTrack)==null||t.onAudioMixedChanged(e)}removeInput(e){e instanceof _u?delete this._localScreenAudioTrack:e instanceof dn&&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,a)=>{var o;(o=this._localAudioTrack)==null||o.mixAudioReference(s,a)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&r&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(r,e,t),this.audioReferenceMap.forEach((s,a)=>{var o;(o=this._localScreenAudioTrack)==null||o.mixAudioReference(s,a)}))}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==null?void 0:e.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor(e){let{processor:t,type:i}=e;var r;this.encodePipeline.includes(t)||(this.encodePipeline[i]=t,(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 a;(a=this.room)==null||a.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(a=>{var o;(o=this.room)==null||o.emit("audio-frame",a)},""),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(){R.on("113",this.handleLocalTrackStarted,this),R.on("114",this.handleLocalTrackStopped,this),R.on("115",this.handleRemoteTrackStarted,this),R.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){R.off("113",this.handleLocalTrackStarted),R.off("114",this.handleLocalTrackStopped),R.off("115",this.handleRemoteTrackStarted),R.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||I(n))return;this.setAudioReferenceVolume(r,n)}}};function gu(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:30,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2;return ge((i,r)=>function(){for(var n=arguments.length,s=new Array(n),a=0;a<n;a++)s[a]=arguments[a];return new Promise((o,l)=>{let c=setTimeout(()=>{let d=new O({code:C.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(r,"() timeout ").concat(e,"s")});(this.log||this._log||P).warn(d),t===2?l(d):t===1&&o()},1e3*e);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(c),i.apply(this,s).then(o,l).finally(()=>{clearTimeout(c),this._checkPendingPromiseSet&&c&&this._checkPendingPromiseSet.delete(c)})})})}var mn=class V_ extends qf{constructor(t,i,r){super({userId:i.userId,sdkAppId:t.sdkAppId,mediaType:r,room:t}),this.room=t,this.user=i,u(this,"tinyId"),u(this,"isRemote",!0),u(this,"jitterBufferDelay",0),u(this,"availableState"),u(this,"remotePublishState"),u(this,"_triggerCheckDecodeSubject",Ti(ye(this,V_.STATE_SUBSCRIBE))),u(this,"ignoreUpdatePlayingState"),this.tinyId=i.tinyId,this.availableState=new re("".concat(i.userId,"-").concat(this.mediaType,"-available"),"remote-track-available"),this.remotePublishState=new re("".concat(i.userId,"-").concat(this.mediaType,"-remote-publish"),"remote-track-publish"),Ie(Xf(ye(this,re.STATECHANGED),ye(this.remotePublishState,re.STATECHANGED)),i_(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),ze(o=>{this.availableState.state!==(o?re.ON:re.OFF)&&(this.availableState.state=o?re.ON:re.OFF),(!this.isRemotePublished||!this.ignoreUpdatePlayingState)&&this.updatePlayingState(o)}));let n=Ie(ye(this.player,z.ERROR),un(o=>o.code===MediaError.MEDIA_ERR_DECODE)),s=Ie($f(5e3),un(()=>!!(!this.ignoreDecodeError&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived&&this.isRemotePublished)&&(!this.player.isPlaying&&!(this.kind===_.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)||(this.reportDecodeResult(!0),!1)))),a=Ie(bb(n,s),pt(ye(this,re.INIT)));Ie(this._triggerCheckDecodeSubject,un(()=>!this.ignoreDecodeError),mu(a),ze(o=>{this.reportDecodeResult(!1,o)}))}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===V_.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===re.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===_.AUDIO;if(w[t?"addSuccessEvent":"addFailedEvent"]({key:s?504700:514702}),!s){let a=((r=this.room)==null?void 0:r.downlinkVideoCodec.toUpperCase())||"H264";w[t?"addSuccessEvent":"addFailedEvent"]({key:RC["DECODE_".concat(a,"_RESULT")]}),t||this.log.warn("".concat((n=this.room)==null?void 0:n.downlinkVideoCodec," decode failed"))}t||(w.addEnum({key:s?504701:514703,value:Gc()}),ue.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(nn()||Er()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===_.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?re.ON:re.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};u(mn,"STATE_SUBSCRIBE","subscribe"),M([gu(5,1)],mn.prototype,"waitHasMediaTrack"),M([Ke(re.INIT,mn.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),R.emit(b.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),Sr(521716,!1)],mn.prototype,"subscribe"),M([Ke(mn.STATE_SUBSCRIBE,re.INIT,{sync:!0,success(){this.log.info("unsubscribed"),R.emit(b.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],mn.prototype,"unsubscribe");var Qb=mn,Tu=class extends Qb{constructor(e,t){super(e,t,1),u(this,"volume",0),u(this,"mediaType",1),u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=e.audioManager}get dbVolume(){return ru.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&&wf().AudioDecoder&&an)}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:a,frame:o,hasLeavingTag:l}=s;this.emit("audio-frame-with-ntp",{ntp:a,frame:o,hasLeavingTag:l})}),t=r(n),!t)return}return t}getAudioLevel(){if(!this.isAvailable)return 0;let e=this.volume||super.getAudioLevel();return e>1?1:e}getInternalAudioLevel(){return this.isAvailable?super.getInternalAudioLevel():0}get isRemotePublished(){return this.user.muteState.audioAvailable}},MH=class extends Ct{constructor(e,t,i,r,n){super(e,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:t}),this.setContainer=r,u(this,"initStat",{alphaStitchingType:1}),u(this,"end",Ti()),u(this,"minSize",320),u(this,"maxSize",1280),u(this,"draggable",!1),u(this,"startDragX",0),u(this,"startDragY",0),u(this,"left",0),u(this,"top",0),u(this,"baseWidth",320),u(this,"baseRatio"),u(this,"container"),this.initStat=n,this.draggable=i,this.bindDragEvents(),w.addEnum({key:515700,value:1}),this.draggable&&w.addEnum({key:515700,value:11})}bindDragEvents(){let e=this.context._canvas;if(e)if(this.draggable){let t=pt(this.end);Ie(ye(e,"mousedown"),r_(this.startDrag.bind(this)),du(()=>Ie(ye(window,"mousemove"),pt(ye(window,"mouseup")))),t,ze(this.doDrag.bind(this))),Ie(ye(e,"dblclick"),t,ze(this.resetPosition.bind(this))),Ie(ye(e,"wheel"),t,ze(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:a}=this,o=this.context._canvas;if(!a||!o)return!1;let l=super.draw2d(e,t,i,r,n),c=a.getImageData(0,0,r,n),{data:d}=c,h=!1;if(this.initStat.alphaStitchingType===1){let m=Math.floor(r/2);for(let p=0;p<n;p++)for(let f=0;f<m;f++){let T=4*(p*r+f),E=4*(p*r+(f+m)),v=d[E];d[E+3]=0;let y=v>=100;d[T+3]=y?255:0}h=super.draw2d(c,0,0,0,0,m,n),o.width=m}else if(this.initStat.alphaStitchingType===2){let m=Math.floor(n/2);for(let p=0;p<m;p++)for(let f=0;f<r;f++){let T=4*(p*r+f),E=4*((p+m)*r+f),v=d[E];d[E+3]=0;let y=v>=100;d[T+3]=y?255:0}h=super.draw2d(c,0,0,0,0,r,m),o.height=m}return(s=this.context.ctx)==null||s.clearRect(0,0,r,n),l&&h}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}},Co=class extends Qb{constructor(e,t){super(e,t,arguments.length>2&&arguments[2]!==void 0?arguments[2]:4),u(this,"mediaType",4),u(this,"source"),u(this,"shouldRenderAlpha",!1),u(this,"alphaNode"),u(this,"shouldBeDraggable",!0),u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0,keyFramesDecoded:0}),u(this,"_keyFrameCountLogged",!1),u(this,"_keyFrameStartTimestamp",0),u(this,"_keyFrameStartCount",0),u(this,"_keyFrameIntervals",[]),u(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(),R.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=_f[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 Ei({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 s_(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 MH(t,this.log,this.shouldBeDraggable,r,{alphaStitchingType:e});this.source.connect(n),n.connect(i),this.alphaNode=n}else this.source.connect(i);io()||(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;!le(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==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),R.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,a="".concat(n," keyframes in 16s ").concat(s," [").concat(this._keyFrameIntervals.map(l=>l.toFixed(1)).join(","),"] keyFramesDecoded ").concat(e),o=s<=2.5?"debug":"info";this.log[o](a),this._keyFrameCountLogged=!0}}},Zb=class extends Co{constructor(e,t){super(e,t,2),u(this,"mediaType",2),u(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}},As=new Map;function Le(e,t){let i=W(x({},t),{timestamp:Ta()});As.has(e)?As.get(e).push(i):As.set(e,[i])}function $b(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ge((r,n)=>function(){for(var s=arguments.length,a=new Array(s),o=0;o<s;o++)a[o]=arguments[o];return LH.call(this,t,a,n,this._name),r.apply(this,a)})}function LH(e,t,i,r){try{if(Ue(e))for(let n=0;n<e.length;n++)Eu.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else Eu.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}catch(n){throw P.error(n),n}}function Eu(e){let{rule:t,value:i,key:r,fnName:n,className:s}=e;if(I(i)){if(t.required)throw new O({code:C.INVALID_PARAMETER,message:Y({key:K.INVALID_PARAMETER_REQUIRED,data:{key:r,rule:t,fnName:n,value:i},link:{className:s,fnName:n}})});if(I(t.defaultValue))return;i=t.defaultValue}if(Array.isArray(t.type)){let l=!1;for(let c=0;c<t.type.length;c++)t.type[c]===null&&i===null&&(l=!0),Pe(t.type[c])&&i instanceof t.type[c]&&(l=!0),he(t.type[c])&&Je(i)===t.type[c].toLowerCase()&&(l=!0);if(!l)throw new O({code:C.INVALID_PARAMETER,message:Y({key:K.INVALID_PARAMETER_TYPE,data:{key:r,rule:{type:t.type.map(c=>Oa(c)?vc(c):he(c)?c:Je(c))},fnName:n,value:i},link:{className:s,fnName:n}})})}else if(!I(t.type)&&Je(i)!==t.type)throw new O({code:C.INVALID_PARAMETER,message:Y({key:K.INVALID_PARAMETER_TYPE,data:{key:r,rule:t,fnName:n,value:i},link:{className:s,fnName:n}})});if(t.allowEmpty===!1){let l=le(i)&&(i===0||Number.isNaN(i)),c=he(i)&&i.trim()==="";if(l||c)throw new O({code:C.INVALID_PARAMETER,message:Y({key:K.INVALID_PARAMETER_EMPTY,data:{key:r,rule:t,fnName:n,value:i},link:{className:s,fnName:n}})})}if(t.notLessThanZero&&le(i)&&i<0)throw new O({code:C.INVALID_PARAMETER,message:Y({key:K.CANNOT_LESS_THAN_ZERO,data:{key:r,rule:t,fnName:n,value:i},link:{className:s,fnName:n}})});if(!I(t.min)&&le(i)&&i<t.min)throw new O({code:C.INVALID_PARAMETER,message:Y({key:K.INVALID_PARAMETER_MIN,data:{key:r,rule:t,fnName:n,value:i},link:{className:s,fnName:n}})});if(!I(t.max)&&le(i)&&i>t.max)throw new O({code:C.INVALID_PARAMETER,message:Y({key:K.INVALID_PARAMETER_MAX,data:{key:r,rule:t,fnName:n,value:i},link:{className:s,fnName:n}})});if(he(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new O({code:C.INVALID_PARAMETER,message:Y({key:K.INVALID_PARAMETER_INSTANCE,data:{key:r,rule:t,fnName:n,value:i},link:{className:s,fnName:n}})})}else if(Pe(t.instanceOf)&&!(i instanceof t.instanceOf))throw new O({code:C.INVALID_PARAMETER,message:Y({key:K.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 O({code:C.INVALID_PARAMETER,message:Y({key:K.INVALID_PARAMETER_RANGE,data:{key:r,rule:t,fnName:n,value:i},link:{className:s,fnName:n}})});let{properties:a}=t;Ut(a)&&hi(i)&&Object.keys(a).forEach(l=>{Eu.call(this,{rule:a[l],value:i&&i[l],key:"".concat(r,".").concat(l),fnName:n,className:s})});let{arrayItem:o}=t;Ut(o)&&Ue(i)&&i.forEach((l,c)=>{Eu.call(this,{rule:o,value:l,key:"".concat(r,"[").concat(c,"]"),fnName:n,className:s})}),Pe(t.validate)&&t.validate.call(this,i,r,n,s,this)}R.on(b.JOIN_SUCCESS,e=>{let{room:t}=e;Le(t.userId,{eventId:32788})}),R.on(b.LEAVE_START,e=>{let{room:t}=e;Le(t.userId,{eventId:32789})}),R.on(b.LOCAL_TRACK_PUBLISHED,e=>{let{track:t}=e;if(t.room){let i=32769;t.mediaType===4?i=32768:t.mediaType===2&&(i=32805),Le(t.room.userId,{eventId:i})}}),R.on(b.LOCAL_TRACK_UNPUBLISHED,e=>{let{track:t}=e;if(t.room){let i=32771;t.mediaType===4?i=32770:t.mediaType===2&&(i=32806),Le(t.room.userId,{eventId:i})}}),R.on(b.TRACK_MUTED,e=>{let{track:t}=e;t.room&&(t.kind===_.AUDIO?Le(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):Le(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))}),R.on(b.TRACK_UNMUTED,e=>{let{track:t}=e;t.room&&(t.kind===_.AUDIO?Le(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):Le(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))}),R.on(b.REMOTE_TRACK_SUBSCRIBED,e=>{let{track:t}=e;t.room&&(t.mediaType===1&&Le(t.room.userId,{eventId:32777,remoteUserId:t.userId}),t.mediaType===4&&Le(t.room.userId,{eventId:32776,remoteUserId:t.userId}),t.mediaType===8&&Le(t.room.userId,{eventId:32803,remoteUserId:t.userId}))}),R.on(b.REMOTE_TRACK_UNSUBSCRIBED,e=>{let{track:t}=e;t.room&&(t.mediaType===1&&Le(t.room.userId,{eventId:32779,remoteUserId:t.userId}),t.mediaType===4&&Le(t.room.userId,{eventId:32778,remoteUserId:t.userId}),t.mediaType===8&&Le(t.room.userId,{eventId:32804,remoteUserId:t.userId}))}),R.on(b.SWITCH_DEVICE_SUCCESS,e=>{let{track:t}=e;t.room&&Le(t.room.userId,{eventId:t.kind===_.VIDEO?32780:32781})}),R.on(b.LOCAL_TRACK_REPLACED,e=>{let{track:t}=e;t.room&&Le(t.room.userId,{eventId:t.kind===_.VIDEO?32782:32783})}),R.on(b.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&&Le(i.userId,{eventId:t})}),R.on(b.PEER_CONNECTION_STATE_CHANGED,e=>{let t,{room:i,prevState:r,state:n,remoteUserId:s}=e,a=!!s;switch(n){case"CONNECTED":t=r==="RECONNECTING"?a?32801:32798:a?32793:32792;break;case"DISCONNECTED":r==="RECONNECTING"&&(t=a?32802:32799);break;case"RECONNECTING":t=a?32800:32797}t&&Le(i.userId,{eventId:t,remoteUserId:s})}),R.on(b.VIDEO_CODEC_IMPLEMENTATION_CHANGED,e=>{let{implementation:t,userId:i,remoteUserId:r,codec:n,isHWCodec:s,prevImplementation:a,streamType:o}=e,l=s?1:0;a||(l=s?3:2);let c={H264:0,H265:1,VP8:2}[n.toUpperCase()],d={eventId:4004,param1:l,param2:c,streamType:o||2};r&&(d.remoteUserId=r,d.eventId=4005),Le(i,d),w.addEnum({key:r?514701:513701,value:l}),w.addEnum({key:r?514700:513700,value:c})}),R.on(b.LOCAL_TRACK_RECAPTURE,e=>{let{track:t,error:i}=e;if(t.userId){let r={eventId:2003,param1:0};t.kind===_.AUDIO?(r.streamType=1,i&&(r.param1=2)):(r.streamType=t.streamType==="auxiliary"?7:2,i&&(r.param1=8)),Le(t.userId,r)}});var xH=Ge(it(),1),UH=class extends xH.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,u(this,"userMap",new Map),u(this,"remotePublishedUserMap",new Map),u(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===Tc)return void this.addAsrRobotUser(e);if(this.userMap.has(t))return;let a={userId:i,tinyId:r,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}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,"]");I(t)||(r+=":".concat(DA[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:a,fromType:o}=t,l=Yr(n,s),c=(i=this.remotePublishedUserMap.get(r))==null?void 0:i.muteState;if(c){let d=this.remotePublishedUserMap.get(r);d&&d.flag!==n&&(d.flag=n,this._log.info("remote publish updated: ".concat(JSON.stringify(d.muteState))),this.emit("6",{prevMuteState:c,muteState:l,flag:n}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(l))),this.addUser({userId:s,tinyId:a,role:20,fromType:o}),this.emit("3",t),this.emit("6",{prevMuteState:Yr(0,s),muteState:l,flag:n})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}},VH=Ge(it(),1),FH=class extends VH.default{constructor(){super(...arguments),u(this,"_connectionTimeoutCount",0),u(this,"_isFirewallRestrictionEventEmitted",!1)}increaseTimeoutCount(){this._connectionTimeoutCount+=1,this.checkAndEmitFirewallRestriction()}resetTimeoutCount(){this._connectionTimeoutCount=0}checkAndEmitFirewallRestriction(){this._connectionTimeoutCount>=3&&!this._isFirewallRestrictionEventEmitted&&(this._isFirewallRestrictionEventEmitted=!0,this.emit("firewall-restriction"))}destroy(){this._connectionTimeoutCount=0,this._isFirewallRestrictionEventEmitted=!1,this.removeAllListeners()}};function e0(e){let{timesInSecond:t,maxSizeInSecond:i,getSize:r}=e;return ge((n,s)=>{let a=new WeakMap;return R.on(b.ROOM_DESTROY,o=>{let{room:l}=o;return a.delete(l)}),function(){let o=a.get(this);for(var l=arguments.length,c=new Array(l),d=0;d<l;d++)c[d]=arguments[d];if(o||(o={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},a.set(this,o)),o.timestamp===0?o.timestamp=Date.now():Date.now()-o.timestamp>1e3&&(o.timestamp=Date.now(),o.callCountInSecond=0,o.totalSizeInSecond=0),r&&(o.totalSizeInSecond+=r(...c)),o.timestamp!==0&&Date.now()-o.timestamp<1e3&&(o.callCountInSecond>=t||o.totalSizeInSecond>i))throw new O({code:C.INVALID_OPERATION,message:Y({key:K.CALL_FREQUENCY_LIMIT,data:{isTimes:o.callCountInSecond>=t,isSize:o.totalSizeInSecond>i,name:s,timesInSecond:t,maxSizeInSecond:i}})});o.callCountInSecond++,n.call(this,...c)}})}var k,t0=!0,bo={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"},G={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},vu=((k=vu||{})[k.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",k[k.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",k[k.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",k[k.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",k[k.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",k[k.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",k[k.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",k[k.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",k[k.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",k[k.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",k[k.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",k[k.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",k[k.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",k[k.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",k[k.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",k[k.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",k[k.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",k[k.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",k[k.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",k[k.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",k[k.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",k[k.INVALID_OPERATION=5100]="INVALID_OPERATION",k[k.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",k[k.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",k[k.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",k[k.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",k[k.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",k[k.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",k[k.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",k[k.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",k[k.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",k[k.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",k[k.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",k[k.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",k[k.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",k[k.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",k[k.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",k[k.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",k[k.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",k[k.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",k[k.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",k[k.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",k[k.DEVICE_ERROR=5300]="DEVICE_ERROR",k[k.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",k[k.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",k[k.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",k[k.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",k[k.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",k[k.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",k[k.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",k[k.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",k[k.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",k[k.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",k[k.SERVER_ERROR=5400]="SERVER_ERROR",k[k.NEED_TO_BUY=5401]="NEED_TO_BUY",k[k.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",k[k.OPERATION_FAILED=5500]="OPERATION_FAILED",k[k.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",k[k.REJOIN_FAILED=5502]="REJOIN_FAILED",k[k.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",k[k.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",k[k.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",k[k.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",k[k.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",k[k.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",k[k.OPERATION_ABORT=5998]="OPERATION_ABORT",k[k.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",k),i0=W(x({},ii),{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),a="";return a=Array.isArray(i.type)?i.type.join("|"):i.type,"'".concat(s,"' must be type of ").concat(a," when calling ").concat(r,"(), received type: ").concat(Je(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),a="".concat(i.instanceOf.name||i.instanceOf);return"'".concat(s,"' must be instanceof ").concat(a," when calling ").concat(r,"(), received type: ").concat(Je(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=pn(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=pn(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=pn(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=pn(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=pn(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=pn(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=pn(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==null?void 0:t.name)||"",": ").concat((t==null?void 0:t.originMessage)||(t==null?void 0:t.message))},MICROPHONE_RECOVER_FAILED(e){let{error:t}=e;return"microphone recover capture failed ".concat((t==null?void 0:t.name)||"",": ").concat((t==null?void 0:t.originMessage)||(t==null?void 0:t.message))},OPERATION_FAILED(e){let{fnName:t,error:i}=e;return"'".concat(t,"' failed, reason: ").concat(i==null?void 0:i.toString())},FIREWALL_RESTRICTION:()=>"media connection failure due to firewall restrictions, please try to change your network.",EVENT_HANDLER_ERROR(e){let{eventName:t}=e;return"an error was caught on trtc.on('".concat(t,"', handler), please check your code on 'handler'.")},VIDEO_CONTEXT_ERROR(e){let{reason:t,error:i}=e;return"video context error ".concat(t," ").concat((i==null?void 0:i.name)||""," ").concat((i==null?void 0:i.message)||"")},SERVER_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' got server error: ").concat(i==null?void 0:i.toString(),", please check the SDK documentation.")},NEED_TO_BUY(e){let{value:t,url:i}=e;return"You need to buy packages for ".concat(t,". Refer to: ").concat(i)},ACCOUNT_NO_MONEY:e=>{let{fnParams:t}=e;return"your TRTC account run out of credit, please recharge.".concat(t.sdkAppId?" SDKAppId: ".concat(t.sdkAppId):"")},OPERATION_ABORT(e){let{fnName:t}=e;return"'".concat(t,"' abort")},UNKNOWN_ERROR(e){let{fnName:t,error:i}=e;return"'".concat(t,"' throw unknown exception").concat(i?", error: ".concat(i.toString(),"."):".")}});function pn(e){if(!e)return"camera";let t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var BH=class ju extends Error{constructor(t){let{code:i,extraCode:r,message:n="",messageParams:s,fnName:a="",originError:o,data:l}=t;var c;let d;d=n||(function(h){let m,{code:p,params:f,enableDocLink:T=!1}=h,E="",v=vu[p];try{m=i0[v]}catch{m=i0.UNKNOWN_ERROR}return Pe(m)?E=m(f):he(m)&&(E=m),f.fnName&&!E.includes(f.fnName)&&(E[E.length-1]!=="."&&(E+="."),E+=" thrown from ".concat(f.fnName,"()")),T&&(E+=" doc:"),E})({code:i===G.SERVER_ERROR?i:r||i,params:x({fnName:a,error:o},s)}),super(d),u(this,"name","RtcError"),u(this,"code"),u(this,"extraCode"),u(this,"functionName"),u(this,"message"),u(this,"data"),u(this,"handler"),u(this,"originError"),this.name=vu[i],this.code=i,this.extraCode=r,this.functionName=a,this.originError=o,this.message=d,this.data=l,this.extraCode===5302&&(c=this.originError)!=null&&c.message.includes("system")&&(this.handler=()=>{let h=document.createElement("a");ms?h.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):gr&&(h.href="x-apple.systempreferences:com.apple.preference.security?Privacy_".concat({startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"}[this.functionName])),h.href.length>0&&h.click()})}static convertFrom(t,i,r){let n=t;if(t instanceof O){let{stack:s}=t,a={code:G.UNKNOWN_ERROR,fnName:i,originError:t};switch(t.getCode()){case C.INVALID_PARAMETER:a.code=G.INVALID_PARAMETER,a.message=t.message;break;case C.INVALID_OPERATION:a.code=G.INVALID_OPERATION,a.message=t.message;break;case C.NOT_SUPPORTED:case C.NOT_SUPPORTED_H264:a.code=G.ENV_NOT_SUPPORTED,t.getCode()===C.NOT_SUPPORTED_H264&&(a.extraCode=t.message.includes(ii.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case C.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case C.SERVER_TIMEOUT:case C.SWITCH_ROLE_FAILED:case C.SWITCH_ROOM_FAILED:a.code=G.SERVER_ERROR,a.extraCode=t.getExtraCode();break;case C.API_CALL_ABORTED:a.code=G.OPERATION_ABORT;break;case C.DEVICE_NOT_FOUND:case C.DEVICE_AUTO_RECOVER_FAILED:case C.INITIALIZE_FAILED:a.code=5300,t.name&&(a.extraCode=(function(o){let l;switch(o){case"NotFoundError":l=5301;break;case"NotAllowedError":l=5302;break;case"NotReadableError":l=5303;break;case"OverconstrainedError":l=5304;break;case"InvalidStateError":l=5305;break;case"SecurityError":l=5306;break;case"AbortError":l=5307;break;default:l=5300}return l})(t.name));break;case C.VIDEO_ENCODE_FAILED:a.extraCode=5505;case C.AUDIO_ENCODE_FAILED:a.extraCode=5506,a.code=G.OPERATION_FAILED;break;case C.UNKNOWN:break;default:a.code=G.OPERATION_FAILED}n=new ju(a),s&&(n.stack+=s.substr(s.indexOf(`
|
||
`)))}else{if(t instanceof ju)return t;n=new ju({code:G.UNKNOWN_ERROR,fnName:i,originError:t})}return n}},j=BH;function bt(e){return e==="sub"?"auxiliary":e==="auxiliary"?"sub":"main"}function Rs(e){return e===bo.QOS_PREFERENCE_CLEAR?"detail":e===bo.QOS_PREFERENCE_SMOOTH?"motion":""}function yu(e,t){let i=t?gA:ya;return sR(e)?x(x({},i),e):Oi[e]?Oi[e]:i}var r0={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}}},n0={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}}},Cs={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(e,t,i){if(he(e)&&!document.getElementById(e))throw new j({code:G.INVALID_PARAMETER,extraCode:5009,fnName:i,messageParams:{key:t}})}},s0={name:"userId",required:!0,type:"string"},a0={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 bs(e,t){if(!e)throw new j({code:G.INVALID_OPERATION,extraCode:5101,fnName:t})}function o0(e,t,i){if(!e)throw new j({code:G.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:i}})}function l0(e,t,i){if(!(/^[1-9]\d*$/.test(String(e))&&e<4294967295))throw new j({code:G.INVALID_PARAMETER,extraCode:5013,fnName:t,messageParams:{key:i}})}function c0(e,t,i){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e))throw new j({code:G.INVALID_PARAMETER,extraCode:5012,fnName:t,messageParams:{key:i}})}function u0(e){var t;if((t=e==null?void 0:e.option)==null||!t.small)return;if(!Cf())return P.warn("small stream is not supported"),void delete e.option.small;let i=yu(e.option.profile),r=yu(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:(P.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 HH={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 j({code:G.INVALID_OPERATION,extraCode:5104,fnName:i});if(e.roomId){if(he(e.roomId))throw new j({code:G.INVALID_PARAMETER,extraCode:5016,fnName:i,messageParams:{key:t}});l0(e.roomId,i,t)}else{if(!e.strRoomId)throw new j({code:G.INVALID_PARAMETER,extraCode:5015,fnName:i});c0(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:Cs,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:r0},validate(e){var t,i;if(((t=e==null?void 0:e.option)==null||!t.videoTrack)&&sn())throw new j({code:G.ENV_NOT_SUPPORTED,extraCode:5201});(i=e==null?void 0:e.option)!=null&&i.small&&u0(e)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:W(x({},Cs),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:r0},validate(e){var t;(t=e==null?void 0:e.option)!=null&&t.small&&u0(e)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},mute:{type:["boolean","string"],values:[!0,!1,"microphone"]},muteKeepVolumeDetection:{type:"boolean"},option:a0},validate(e){var t;if(((t=e==null?void 0:e.option)==null||!t.audioTrack)&&sn())throw new j({code:G.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:["boolean","string"],values:[!0,!1,"microphone"]},muteKeepVolumeDetection:{type:"boolean"},option:a0}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Cs,publish:{type:"boolean"},option:n0},validate(e,t,i,r,n){var s;if((s=e==null?void 0:e.option)==null||!s.videoTrack){if(sn())throw new j({code:G.ENV_NOT_SUPPORTED,extraCode:5201});if(!zc())throw new j({code:G.ENV_NOT_SUPPORTED,fnName:i,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Cs,publish:{type:"boolean"},option:n0}},muteRemoteAudio:[s0,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[s0,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Cs,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){bs(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(o0(!!r,i,e),r&&(e.streamType==="main"&&!r.muteState.videoAvailable||e.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new j({code:G.INVALID_OPERATION,extraCode:5103,fnName:i,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:W(x({},Cs),{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){bs(this._room.isJoined,i);let r=this._room.remotePublishedUserMap.get(e.userId);if(o0(!!r,i,e),r){if(e.streamType==="main"&&!r.muteState.videoAvailable||e.streamType==="sub"&&!r.muteState.hasAuxiliary)throw new j({code:G.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 j({code:G.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!=="*"&&I(e.streamType))throw new j({code:G.INVALID_PARAMETER,extraCode:5014,fnName:i})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(e,t,i){bs(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(!kf)throw new j({code:G.ENV_NOT_SUPPORTED,fnName:i,extraCode:5207});if(!this._room.enableSEI)throw new j({code:G.INVALID_OPERATION,fnName:i,extraCode:5108});if(e.byteLength>1e3)throw new j({code:G.INVALID_PARAMETER,extraCode:5018,fnName:i});if(e.byteLength===0)throw new j({code:G.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:i});bs(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 j({code:G.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 j({code:G.INVALID_PARAMETER,extraCode:5018,fnName:i});if(e.byteLength===0)throw new j({code:G.INVALID_PARAMETER,extraCode:5017,fnName:i,messageParams:{key:t}})}}},validate(e,t,i){if(bs(this._room.isJoined,i),this._room.scene==="live"&&this._room.role==="audience")throw new j({code:G.INVALID_OPERATION,extraCode:5107,fnName:i,messageParams:{key:t}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(e,t,i){if(bs(this._room.isJoined,i),this._room.useStringRoomId&&e.strRoomId===this._room.roomId||!this._room.useStringRoomId&&e.roomId===Number(this._room.roomId))throw new j({code:G.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 j({code:G.INVALID_PARAMETER,extraCode:5019,fnName:i,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(e.roomId)l0(e.roomId,i,t);else{if(!e.strRoomId)throw new j({code:G.INVALID_PARAMETER,extraCode:5015,fnName:i});c0(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}}}},qe={TRTC:HH},kt=class extends Error{};function WH(e,t){let i=cs(e);for(let r=0;r<t.length;r++)Li(i[r],t[r]);return i}function GH(e){this._resolve=Promise.resolve(e)}function jH(e){this._reject=Promise.reject(e)}var d0=class Ps{constructor(t,i){this.instance=t,this.group=i,u(this,"started",!1),u(this,"ops",[]),u(this,"startSame",()=>!0),u(this,"mergeUpdate",WH);let r=Ps.instances.get(t);r?r.set(i,this):Ps.instances.set(t,new Map([[i,this]]))}static get(t,i){if(!i)return;let r=Ps.instances.get(t);return r&&r.get(i)||new Ps(t,i)}static gets(t,i){let r=Ps.instances.get(t),n=[];return r&&r.forEach((s,a)=>{i.test(a)&&n.push(s)}),n}action(t,i,r){let n=o=>{var l;return t===0?this.started=!0:t===3&&(this.started=!1),this.ops.shift(),(l=this.currentOp)==null||l.action(),o},s=o=>{var l,c;throw this.ops.shift(),t===0&&((l=this.currentOp)==null?void 0:l.type)===2&&this.ops.shift().reject(new kt("start failed")),(c=this.currentOp)==null||c.action(),o},a={type:t,action:()=>i(...a.args).then(n,s),args:r,resolve:GH,reject:jH};try{switch(this.state){case 1:if(t===0)throw new kt("already started");break;case 4:if(t===2)throw new kt("not started");break;default:return this.cacheOp(a)}}catch(o){return Promise.reject(o)}return this.ops.push(a),a.promise=i(...a.args).then(n,s)}cacheOp(t){if(this.ops.length===1)switch(this.state){case 0:case 2:if(t.type===0)throw new kt("already start");break;case 3:switch(t.type){case 2:throw new kt("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new kt("unknown state")}else switch(t.type){case 3:if(this.lastOpType===3)return this.lastOp.promise;{let r=new kt("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 kt("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new kt("start not allowed after update");case 0:throw new kt("duplicate start");case 3:if(this.startSame(this.currentOp.args,t.args))throw this.ops.pop().reject(new kt("keep start")),new kt("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}};u(d0,"instances",new WeakMap);var ko=d0,Su=new WeakMap,Iu=(e,t)=>{if(t instanceof kt){let{stack:i}=t;t=new j({code:G.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),i&&(t.stack+=i.substr(i.indexOf(`
|
||
`)))}throw t};function fn(e,t){return ge((i,r)=>function(){for(var n=arguments.length,s=new Array(n),a=0;a<n;a++)s[a]=arguments[a];let o=ko.get(this,typeof e=="string"?e:e.call(this,...s));return o?(t&&(o.startSame=t.bind(this)),o.action(0,i.bind(this),s).catch(Iu.bind(null,r))):i.apply(this,s)})}function ks(e,t){let{merge:i,debounce:r}=t||{};return ge((n,s)=>function(){for(var a=arguments.length,o=new Array(a),l=0;l<a;l++)o[l]=arguments[l];let c=ko.get(this,typeof e=="string"?e:e.call(this,...o));if(!c)return n.apply(this,o);if(i&&(c.mergeUpdate=i.bind(this)),r&&r.isNeedToDebounce.apply(this,o)){let{delay:d,getKey:h}=r;return new Promise((m,p)=>{var f,T;let E=(f=Su.get(this))==null?void 0:f.get(h(...o));if(E){let{timeoutId:y,resolve:D}=E;clearTimeout(y),D()}let v=setTimeout(()=>{if(c.state===3||c.state===4)return m();c.action(2,n.bind(this),o).catch(Iu.bind(null,s)).then(m,p)},d);Su.has(this)?(T=Su.get(this))==null||T.set(h(...o),{timeoutId:v,resolve:m}):Su.set(this,new Map([[h(...o),{timeoutId:v,resolve:m}]]))})}return c.action(2,n.bind(this),o).catch(Iu.bind(null,s))})}function _n(e){return ge((t,i)=>function(){for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];let a=typeof e=="function"?e.call(this,...n):e;if(a instanceof RegExp)return Promise.all(ko.gets(this,a).map(l=>l.action(3,()=>Promise.resolve(),n))).then(()=>t.call(this,...n));let o=ko.get(this,a);return o?o.action(3,t.bind(this),n).catch(Iu.bind(null,i)):t.apply(this,n)})}function gn(){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(Pi,"/en/TRTC.html#.").concat(t);r.warn(n)},i}}var F={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"},zH=new Set([F.AUDIO_VOLUME,F.AUDIO_FRAME,F.NETWORK_QUALITY,F.STATISTICS,F.SEI_MESSAGE,F.CUSTOM_MESSAGE,F.LAYER_DATA]),h0={};Ni(h0,{ScheduleRequestType:()=>f0,getAbilityConfig:()=>qH,getScheduleDomain:()=>h_,isNeedToSchedule:()=>wo,scheduleProxy:()=>zi,sendScheduleRequest:()=>p0,setIsNeedToSchedule:()=>ni,setScheduleProxy:()=>d_});var Tn=null,Au=0,JH=1728e5,KH=36e5,Do="trtc_schedule_cache",wo=!0;function m0(e){var t;if(typeof window<"u"&&typeof localStorage<"u")try{if((t=e.config)!=null&&t.scheduleCache){let i=Date.now()+KH;localStorage.setItem(Do,JSON.stringify({result:e,expireIn:i})),Au=i}else localStorage.removeItem(Do)}catch(i){P.error("saveScheduleToLocalStorage error",i)}}function ni(e){Se(e)&&e!==wo&&(wo=e,P.info("setIsNeedToSchedule ".concat(e)),e?(function(){if(typeof window<"u"&&typeof localStorage<"u")try{localStorage.removeItem(Do)}catch(t){P.error("clearScheduleCache error",t)}})():Au=Date.now()+JH)}function p0(e){return g(this,null,function*(){let{userId:t,sdkAppId:i,useStringRoomId:r,roomId:n,userSig:s,version:a,frameWorkType:o,role:l,latencyLevel:c}=e;if(!wo&&Tn&&Au>Date.now())return(function(h){g(this,null,function*(){let{sdkAppId:m}=h;try{let p=yield _0(h),f=yield g0(Ji(m,"cloudconfig",_.MAIN),p,{timeout:5e3});f&&f.config&&Tn&&(P.info("update cloud config success"),Tn.config=x({},f.config),ni(!f.config.scheduleCache),m0(Tn))}catch(p){P.warn("update cloud config failed",p)}})})(e),{isCached:!0,result:Tn};let d={delta:0,count:[1,1],msg:[],detail:[]};try{let h=yield _0(e),m=J(),p=yield(function(T,E,v){return new Promise((y,D)=>{let N=null;Ma([T0(S=>E.count[0]=S+1,S=>{let{error:A,retry:L,retriedCount:U,retryFuncArgs:q}=S;E.msg[0]=A.message,N||(U>=1&&(q[0]=Ji(v,"config",_.MAIN,!0)),L())})(Ji(v,"config",_.MAIN),T,{get timeout(){return 1e3*ls(2+E.count[0])}}),T0(S=>E.count[1]=S+1,S=>{let{error:A,retry:L,retriedCount:U,retryFuncArgs:q}=S;E.msg[1]=A.message,N||(U>=2&&(q[0]=Ji(v,"config",_.BACKUP,!0)),L())})(Ji(v,"config",_.BACKUP),T,{get timeout(){return 1e3*ls(2+E.count[1])}})]).then(S=>{N=S,y(N)}).catch(D)})})(h,d,i);p.config&&(p.config.loggerDomain&&Ea(p.config.loggerDomain),Se(p.config.scheduleCache)&&ni(!p.config.scheduleCache)),d.delta=J()-m;let f=(function(T,E,v){let y={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let D=performance.getEntriesByType("resource"),N=Ji(T,"config",_.MAIN),S=Ji(T,"config",_.BACKUP);for(let A of D)if(A.startTime>=v&&(A.name===N||A.name===S)&&A.transferSize>0){let L=A.name===N?_.MAIN:_.BACKUP,U=Math.round(A.duration),q=Math.round(A.domainLookupStart-A.startTime),fe=A.redirectStart>0?Math.round(A.redirectEnd-A.redirectStart):0,Re=A.fetchStart>0?Math.round(A.domainLookupStart-A.fetchStart):0,ne=Math.round(A.domainLookupEnd-A.domainLookupStart),ft=Math.round(A.requestStart-A.secureConnectionStart),xe=Math.round(A.secureConnectionStart-A.connectStart),yt=Math.round(A.responseStart-A.requestStart),Wu=Math.round(A.responseEnd-A.responseStart),x_=[ne,ft,xe,yt,Wu];ue.uploadEvent({log:"stat-schedule-net:".concat(U,"(").concat(q,"(").concat(fe,"->").concat(Re,")->").concat(x_.join("->"),") ").concat(L),userId:E}),y=W(x({},y),{totalCost:U,local:q,dns:ne,tcp:xe,tls:ft,request:yt,response:Wu});break}}catch(D){P.error("getScheduleDetailCost error",D)}return y})(Number(i),t,m);return Tn=p,m0(p),{isCached:!1,result:p,detailCost:f}}catch(h){let m=Ue(h)?h[0]:h,p=le(m.code)?m.code:0,f="schedule failed".concat(m.message?": ".concat(m.message):""),T=new O({code:C.SCHEDULE_FAILED,extraCode:p,message:Y({key:K.JOIN_ROOM_FAILED,data:{error:f,code:p}})});throw P.error(f,p),T}})}typeof document<"u"&&document.head.insertAdjacentHTML("beforeend",Object.values(mr).map(e=>'<link rel="dns-prefetch" href="https://'.concat(e,'">')).join(`\r
|
||
`)),(function(){if(typeof window<"u"&&typeof localStorage<"u")try{let e=localStorage.getItem(Do);if(e){let{result:t,expireIn:i}=JSON.parse(e);i>Date.now()?(Tn=t,Au=i,wo=!1):localStorage.removeItem(Do)}}catch(e){P.error("loadScheduleFromLocalStorage error",e)}})(),R.on("28",()=>ni(!0)),R.on("63",()=>ni(!0)),R.on("84",()=>ni(!0)),R.on("201",e=>{e.state==="RECONNECTING"&&ni(!0)}),R.on("202",e=>{e.state==="RECONNECTING"&&ni(!0)});var zi={main:"",backup:""};function d_(e){Ue(e)?(zi.main=e[0],zi.backup=e[1]):(zi.main=e,zi.backup=e)}var f0=(e=>(e.CONFIG="config",e.TRTC_AUTO_CONF="trtcAutoConf",e.AUDIO_AI_AUTH="audioAiAuth",e.CLOUD_CONFIG="cloudconfig",e))(f0||{});function _0(e){return g(this,null,function*(){var t;let{userId:i,sdkAppId:r,useStringRoomId:n,roomId:s,userSig:a,version:o,frameWorkType:l,role:c,latencyLevel:d}=e,h=new FormData;h.append("userId",String(i)),h.append("sdkAppId",String(r)),h.append("isStrGroupId",String(n)),h.append("groupId",String(s)),h.append("sdkVersion",o),h.append("userSig",String(a));let m=((t=yield Wc())==null?void 0:t.model)||df();m&&h.append("model",m);let p=Er();p&&h.append("osString",p);let f=fs();return f&&h.append("gpu",f),c&&h.append("role",String(c)),d&&h.append("latencyLevel",String(d)),l&&h.append("frameWorkType",String(l)),h})}function Ji(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:_.MAIN,r=arguments.length>3&&arguments[3]!==void 0&&arguments[3];return"https://".concat(zi[i]||h_(e,i,r),"/api/v1/").concat(t)}function qH(e,t,i){let r=Ji(e,t),n=Ji(e,t,_.BACKUP),s=new URLSearchParams(i).toString(),a=fetch("".concat(r,"?").concat(s)).then(l=>l.json()),o=fetch("".concat(n,"?").concat(s)).then(l=>l.json());return Ma([a,o])}function h_(e){let t,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:_.MAIN,r=arguments.length>2&&arguments[2]!==void 0&&arguments[2];return t=pr(e)?r?i===_.MAIN?mr.MAIN_OVERSEA_BACKUP:mr.BACKUP_OVERSEA:i===_.MAIN?mr.MAIN_OVERSEA:mr.BACKUP_OVERSEA:i===_.MAIN?mr.MAIN:mr.BACKUP,t}function g0(e,t,i){return new Promise((r,n)=>{Va({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 T0=(e,t)=>Fa({retryFunction:g0,settings:{retries:3,timeout:0},onError:t,onRetrying:e}),m_=class{constructor(){u(this,"_log"),this._log=P.createLogger({id:"fd"})}download(e,t){return g(this,null,function*(){let{type:i="blob"}=t||{};e=Op(e);try{let r,n=J();if(r=Pe(fetch)?yield this.downloadWithFetch(e,i):yield this.downloadWithXHR(e,i),!r||!r.data)throw new Error("data is empty");let s=J()-n;return this._log.info("downloaded: ".concat(e,", return type: ").concat(i,", cost: ").concat(s,"ms")),w.addSuccessEvent({key:522700,cost:J()-n}),r.data}catch(r){throw this._log.error("failed to download: ".concat(e,", error: ").concat(r)),w.addFailedEvent({key:522700,error:r}),r}})}downloadWithFetch(e,t){return g(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 g(this,null,function*(){this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t)));let i=J(),r=null,n=null;if(Pe(WebAssembly.instantiateStreaming)&&!e.startsWith("data:application/octet-stream;base64,")&&!(s=>s.startsWith("file://"))(e)&&Pe(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=J()-i;return this._log.info("loadedWasm ".concat(e,", cost: ").concat(s,"ms")),w.addSuccessEvent({key:522701,cost:s}),r}throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(n)),w.addFailedEvent({key:522701,error:n}),n})}loadScript(e){this._log.info("loadScript ".concat(e));let t=J();return new Promise((i,r)=>{let n=document.createElement("script");n.type="text/javascript",n.onload=()=>{this._log.info("loadedScript ".concat(e,", cost: ").concat(J()-t,"ms")),w.addSuccessEvent({key:522702,cost:J()-t,split:1e3}),i(n)},n.onerror=s=>{this._log.error("failed to loadScript ".concat(e,", error: ").concat((s==null?void 0:s.message)||JSON.stringify(s))),w.addFailedEvent({key:522702}),r(s)},n.crossOrigin="anonymous",n.src=e,document.head.append?document.head.append(n):document.getElementsByTagName("head")[0].appendChild(n)})}};M([vr({settings:{timeout:0,retries:3},onError(e,t,i){var r;(e==null?void 0:e.status)===404||(r=e==null?void 0: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))}})],m_.prototype,"download"),M([vr({settings:{timeout:3e3,retries:3},onRetrying(e){this._log.warn("loadScript retrying: ".concat(e))}})],m_.prototype,"loadScript");var p_=new m_;function E0(e){let[t,i]=e,r=i.byteLength,n=parseInt(String(r/255),10),s=r%255,a=[];a.push(0,0,0,1,6,t);for(let l=0;l<n;l++)a.push(255);a.push(s);let o=new DataView(i);return a.push(...new Uint8Array(o.buffer)),a.push(128),new fu(new DataView(new Uint8Array(a).buffer),!0)}function v0(e){return e.type==="empty"||e.data.byteLength===0}function y0(e){let t=new DataView(e),i=0;for(;i<t.byteLength;){let r=pu(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 S0(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 I0(e){let{frame:t,seiMessageList:i}=e;if(!i||i.length===0||t.data.byteLength===0)return t;let r=9-S0(t.data);if(r<=0)return t;let n=i.splice(0,r).reverse().map(E0),s=n.reduce((d,h)=>d+h.dataView.byteLength,0),a=new ArrayBuffer(s+t.data.byteLength),o=new DataView(a),l=new DataView(t.data),c=0;for(let d=0;d<n.length;d++)for(let h=0;h<n[d].dataView.byteLength;h++)o.setInt8(c++,n[d].dataView.getInt8(h));for(let d=0;d<t.data.byteLength;d++)o.setInt8(c++,l.getInt8(d));return t.data=a,t}function A0(e){let{frame:t,onSEI:i}=e;try{if(v0(t)||!y0(t.data))return t;let r=zb(t.data,!1).filter(n=>n.isSEI);i==null||i(r.reverse())}catch{}return t}function R0(e){let{seiMessageList:t,isAudio:i,getNtpTime:r,isMain:n}=e;return new TransformStream({transform(s,a){let o=s;i?audioEncodePipeline.forEach(l=>{o=l({frame:o,ntp:r(),onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:o.data,userId:""})}})}):videoEncodePipeline.forEach(l=>{o=l({frame:o,seiMessageList:t,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:o.data,userId:"",streamType:n?"main":"auxiliary"})}})}),a.enqueue(o)}})}function C0(e){let{userId:t,streamType:i,isAudio:r}=e;return new TransformStream({transform(n,s){let a=n;r?(audioDecodePipeline.forEach(o=>{a=o({frame:a,onAudioFrameNTPTime:l=>{self.postMessage({type:"audio-ntp",data:l,userId:t,streamType:i})},onDump:()=>{self.postMessage({type:"dump",isAudio:r,data:a.data,userId:t})}})}),s.enqueue(a)):videoDecodePipeline.forEach(o=>{a=o({frame:a,onSEI:l=>{l.forEach(c=>{self.postMessage({type:"sei",seiPayloadType:c.seiPayloadType,data:c.seiPayload.buffer,userId:t,streamType:i})})},onDump:()=>{self.postMessage({type:"dump",isAudio:r,data:a.data,userId:t,streamType:i})}})}),s.enqueue(a)}})}function b0(e){let t=[fu],i=[S0,v0,zb,y0,E0,R0,C0,Up,xp,pu],r="const videoEncodePipeline=[".concat(e.videoEncodePipeline.toString(),`];
|
||
const videoDecodePipeline=[`).concat(e.videoDecodePipeline.toString(),`];
|
||
const audioEncodePipeline = [`).concat(e.audioEncodePipeline.toString(),`];
|
||
const audioDecodePipeline = [`).concat(e.audioDecodePipeline.toString(),"];"),n="(()=>{".concat(t.map(l=>"const ".concat(l.name,"=(()=>").concat(l.toString(),")()")).join(`
|
||
`),`
|
||
`).concat(i.map(l=>l.toString()).join(`
|
||
`),";(").concat(()=>{let l=[],c=[],d=[],h=0;self.onmessage=m=>{switch(m.data.type){case"sei":m.data.isMain?(l.push(m.data.data),m.data.small&&d.push(m.data.data)):c.push(m.data.data);break;case"ntp-offset":h=m.data.data}},self.onrtctransform=m=>{let{options:p}=m.transformer,f=p.isReceiver?C0({userId:p.userId,streamType:p.streamType,isAudio:p.isAudio}):R0({getNtpTime:()=>Date.now()+h,isAudio:p.isAudio,isMain:p.isMain,seiMessageList:p.isMain?p.small?d:l:c});m.transformer.readable.pipeThrough(f).pipeTo(m.transformer.writable)}},")();").concat(r,"})()"),s=new Blob([n],{type:"text/javascript"}),a=URL.createObjectURL(s),o=new Worker(a);return URL.revokeObjectURL(a),o}var k0,f_=class{constructor(e){u(this,"audioPlayer"),u(this,"videoPlayer"),u(this,"log"),this.audioPlayer=e.audioPlayer,this.videoPlayer=e.videoPlayer,this.log=e.log.createChild({id:"pip"}),this.videoPlayer.on(z.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.on(z.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.on(z.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(z.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(z.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.on(z.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.on(z.VOLUME_CHANGE,this.handleVolumeChange,this)}handleUserResumeInPIPOrFullScreen(){this.audioPlayer.isPaused&&(this.log.warn("resume audio in ".concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.doResume()),Oe&&ps&&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"),Oe&&ps?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(z.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.off(z.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.off(z.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(z.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(z.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.off(z.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.off(z.VOLUME_CHANGE,this.handleVolumeChange,this)}},D0=!1;function YH(e){var t=this;let{TRTC:i,room:r,errorModule:n,assetsPath:s}=e;return{TRTC:i,LocalMixVideoTrack:o_,LocalVideoTrack:ji,LocalScreenTrack:hn,room:r,assetsPath:s,fileDownloader:p_,innerEmitter:R,INNER_EVENT:b,constants:uA,environment:aR,utils:Kb,eventLogger:ue,log:this.room.getLogger(),loggerManager:P,errorModule:n,kvStatManager:w,rtcDectection:_s,trtc:this,rx:Sb,enums:CR,schedule:h0,getDevices:nu,initVisionTaskRegistry:function(a,o){let l=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"/mediapipe/vision.js";return g(t,null,function*(){!window.VisionTaskRegistry&&!D0&&(D0=!0,k0=p_.loadScript("".concat(a,"/").concat(l).replace(/([^:]\/)\/+/g,"$1"))),yield k0,yield(yield window.VisionTaskRegistry.getInstance(a)).preloadModels(o)})},audioContext:et(),deviceDetector:He,AudioPlayer:Kf,RemoteAudioPlayer:_b,VideoPlayer:gi,showAutoPlayDialog:Hf,Timer:_e,clearStarted:(a,o)=>{let l=a.getAlias(),c=ko.instances.get(this);if(c)if(o){let d=c.get(l+o);if(!d)return;d.started=!1}else c.forEach((d,h)=>{h.startsWith(l)&&(d.started=!1)})},startGetPCM:u_,createAudioNode:tu,getNetworkTimeOffset:M3,validateSourceNode:()=>{var a;if(me&&((a=this.room.audioManager._localAudioPipline)==null||!a.source.node))throw new j({code:G.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:b0,AVPlayerStateSyncManager:f_,PlayerEvent:z}}var Ds=new WeakMap,w0="5.16.0";function at(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ge((r,n)=>function(){for(var s=arguments.length,a=new Array(s),o=0;o<s;o++)a[o]=arguments[o];try{__.call(this,t,a,n,this._name)}catch(l){return Promise.reject(l)}return r.apply(this,a)})}function N0(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return ge((r,n)=>function(){for(var s=arguments.length,a=new Array(s),o=0;o<s;o++)a[o]=arguments[o];try{__.call(this,t,a,n,this._name)}catch(l){throw l}return r.apply(this,a)})}function __(e,t,i,r){if(Ue(e))for(let n=0;n<e.length;n++)Ru.call(this,{rule:e[n],value:t[n],key:e[n].name,fnName:i,className:r});else Ru.call(this,{rule:e,value:t[0],key:e.name,fnName:i,className:r})}function Ru(e){let{rule:t,value:i,key:r,fnName:n,className:s}=e;function a(c){return{code:G.INVALID_PARAMETER,extraCode:c,fnName:n,messageParams:{key:r,rule:t,value:i}}}if(I(i)){if(t.required)throw new j(a(5001));if(I(t.defaultValue))return void(Pe(t.validate)&&t.validate.call(this,i,r,n,s,this));i=t.defaultValue}if(Array.isArray(t.type)){let c=!1;for(let d=0;d<t.type.length;d++)t.type[d]===null&&i===null&&(c=!0),Pe(t.type[d])&&i instanceof t.type[d]&&(c=!0),he(t.type[d])&&Je(i)===t.type[d].toLowerCase()&&(c=!0);if(!c)throw new j({code:G.INVALID_PARAMETER,extraCode:5002,fnName:n,messageParams:{key:r,rule:{type:t.type.map(d=>Oa(d)?vc(d):he(d)?d:Je(d))},value:i}})}else if(!I(t.type)&&Je(i)!==t.type)throw new j(a(5002));if(t.allowEmpty===!1){let c=le(i)&&(i===0||Number.isNaN(i)),d=he(i)&&i.trim()==="";if(c||d)throw new j(a(5003))}if(t.notLessThanZero&&le(i)&&i<0)throw new j(a(5006));if(!I(t.min)&&le(i)&&i<t.min)throw new j(a(5007));if(!I(t.max)&&le(i)&&i>t.max)throw new j(a(5008));if(he(t.instanceOf)){if(!i||i._name!==t.instanceOf)throw new j(a(5004))}else if(Pe(t.instanceOf)&&!(i instanceof t.instanceOf))throw new j(a(5004));if(Array.isArray(t.values)&&!t.values.includes(i))throw new j(a(5005));let{properties:o}=t;Ut(o)&&hi(i)&&Object.keys(o).forEach(c=>{Ru.call(this,{rule:o[c],value:i&&i[c],key:"".concat(c),fnName:n,className:s})});let{arrayItem:l}=t;Ut(l)&&Ue(i)&&i.forEach((c,d)=>{Ru.call(this,{rule:l,value:c,key:"".concat(r,"[").concat(d,"]"),fnName:n,className:s})}),Pe(t.validate)&&t.validate.call(this,i,r,n,s,this)}var XH=0;function Ae(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{getRemoteId:t=()=>"",replaceArg:i,getKVReportKey:r,ignoreLog:n,ignoreErrorLog:s}=e;return ge((a,o)=>function(){for(var l=arguments.length,c=new Array(l),d=0;d<l;d++)c[d]=arguments[d];var h,m,p;function f(D,N,S){if(S&&S.includes(D))return"hided";if(i){let A=i(...c);if(c[A.argIndex]===N)return A.value}if(N===c||D in c)return N;try{return N instanceof HTMLElement?"id: ".concat(N.id," type:").concat(Je(N)):N instanceof MediaStreamTrack?Mp(N):(JSON.stringify(N),N)}catch{return"type:".concat(Je(N))}}let T=(this==null?void 0:this._log)||P,E=++XH;if(n!=null&&n(...c))return a.apply(this,c);c.length>0?T.info("".concat(o,"() ").concat(E," ").concat(JSON.stringify(c,(D,N)=>f(D,N,["userSig","privateMapKey"])))):T.info("".concat(o,"() ").concat(E));let v=r?r(...c):yC[o],y=(s==null?void 0:s(...c))||!1;try{let D=a.apply(this,c),N=J();if(Pa(D)){let S="".concat(o.includes("Plugin")?"".concat(((m=(h=c[0]).getName)==null?void 0:m.call(h))||""," "):" ");return D.then(A=>(T.info("".concat(o,"() success ").concat(E," ").concat(S).concat(t.call(this,...c))),w.addSuccessEvent({key:v,cost:J()-N}),A)).catch(A=>{var L;let U=(A=j.convertFrom.call(this,A,o,c.length===1?c[0]:c)).extraCode||A.code,q=(L=A.message)!=null&&L.includes(U)?"":" code:".concat(U),fe=(A==null?void 0:A.code)===G.OPERATION_ABORT;throw y||T[fe?"warn":"error"]("".concat(o,"() failed ").concat(E," ").concat(S).concat(t.call(this,...c)," ").concat(A).concat(q," params: ").concat(JSON.stringify(c,f))),w.addFailedEvent({key:v,error:A}),A})}return w.addSuccessEvent({key:v}),D}catch(D){let N=(D=j.convertFrom.call(this,D,o)).extraCode||D.code,S=(p=D.message)!=null&&p.includes(N)?"":" code:".concat(N),A=(D==null?void 0:D.code)===G.OPERATION_ABORT;throw y||T[A?"warn":"error"]("".concat(o,"() failed ").concat(E," ").concat(D).concat(S," params: ").concat(JSON.stringify(c,f))),w.addFailedEvent({key:v,error:D}),D}})}var g_,T_=e=>ge((t,i)=>function(r,n){return g(this,null,function*(){let s=this._plugins.get(r);if(!s)throw this._log.error("plugin ".concat(String(r)," is not found")),new j({code:G.OPERATION_ABORT,message:"plugin ".concat(String(r)," is not found"),fnName:i});if(Pe(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error("plugin ".concat(String(r)," is not supported")),new j({code:G.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(r)," is not supported"),extraCode:5210,fnName:i});return __.call(this,s.getValidateRule(e),[n],i,"TRTC"),t.call(this,s,n)})}),E_=0,Cu=class xo{constructor(t){this.core=t,u(this,"log"),u(this,"customAudioReferenceMap",new Map),u(this,"audioRefId",0),u(this,"audioContext",et()),u(this,"localAudioWorkletNode"),u(this,"screenAudioWorkletNode"),u(this,"mixNode"),u(this,"silentNode"),E_+=1,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(E_)}),this.log.info("created id=".concat(this.getAlias()).concat(E_)),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 j({code:G.INVALID_OPERATION,extraCode:5106,fnName:n})}}}preload(t){return g_||(g_=this.doPreload(t)),g_}doPreload(t){return g(this,null,function*(){let i=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(i);try{yield $c(this.audioContext,r)}catch(n){this.log.error("preload audioProcessor failed. ".concat(n))}finally{URL.revokeObjectURL(r)}})}getName(){return xo.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return xo.getStartValidateRule(this.core);case"update":return xo.updateValidateRule;case"stop":return xo.stopValidateRule}}start(t){return g(this,null,function*(){var i,r,n,s;let{room:a}=this.core,{sdkAppId:o,userId:l,userSig:c,assetsPath:d=this.core.assetsPath,audioReference:h,processLevel:m,enableDump:p,isLocalAudioNeedAudioProcess:f=!0,isScreenAudioNeedAudioProcess:T=!1}=t;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=f,this.core.room.audioManager.isScreenAudioNeedAudioProcess=T,!d)throw new j({code:G.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(d,"/audioProcessor-wasm.js")),f&&!this.localAudioWorkletNode){let{sign:E,status:v,timestamp:y}=yield this.getAuthData(o,l,c);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",o,l,y,E,v,a)}if(T&&!this.screenAudioWorkletNode){let{sign:E,status:v,timestamp:y}=yield this.getAuthData(o,l,c);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",o,l,y,E,v,a)}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"}),a.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),I(h)||h.forEach(E=>{this.customAudioReferenceMap.set(E,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:E,refId:"o-".concat(this.audioRefId++)})}),I(m)||(n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:m}}),I(p)||(s=this.localAudioWorkletNode)==null||s.port.postMessage({type:"dump",data:{enable:p}})})}update(t){return g(this,null,function*(){var i,r,n;let{audioReference:s,enableDump:a,processLevel:o}=t;I(s)||(this.customAudioReferenceMap.forEach((l,c)=>{this.customAudioReferenceMap.delete(c),this.core.room.audioManager.updateAudioReference({type:"remove",refId:l})}),s.forEach(l=>{this.customAudioReferenceMap.set(l,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:l,refId:"o-".concat(this.audioRefId++)})})),I(o)||(i=this.localAudioWorkletNode)==null||i.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:o}}),I(a)||((r=this.localAudioWorkletNode)==null||r.port.postMessage({type:"dump",data:{enable:a}}),(n=this.screenAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:a}}))})}stop(){return g(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 g(this,null,function*(){let n=String(Date.now()).slice(0,-3),{auth:s,sign:a,status:o,message:l}=yield(function(c){return g(this,arguments,function(d){let{sdkAppId:h,userId:m,userSig:p,timestamp:f}=d;return(function*(){let T="".concat((function(U){let q=arguments.length>1&&arguments[1]!==void 0?arguments[1]:_.MAIN;return"https://".concat(zi[q]||h_(U,q),"/api/v1/audioAiAuth")})(h),"?sdkAppId=").concat(h,"&userId=").concat(m,"&userSig=").concat(p,"×tamp=").concat(f),E=yield fetch(T),{data:{errCode:v,errMsg:y,sign:D,status:N}}=yield E.json();if(N==="1")return{auth:!0,sign:D,status:N,message:y};let S=pr(h)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",A="Init RTCAudioProcessor failed.",L="";switch(v){case 1:L="Please check your params.";break;case 2:L="You need to buy packages. Refer to: ".concat(S);break;case 3:L="Server is invalid. Please contact our engineer. ";break;case 4:L="Your packages is not active. Refer to: ".concat(S);break;case 5:L="Your packages is expired. Refer to: ".concat(S);break;case 6:L="Your version is not supported."}return{auth:!1,status:N,message:y?"".concat(A," Reason: ").concat(y,". ").concat(L):"".concat(A,", ").concat(L)}})()})})({sdkAppId:t,userSig:r,userId:i,timestamp:n});if(!s)throw this.log.info("audioProcessor: ".concat(i," auth result: ").concat(s,". Message: ").concat(l)),new j({code:G.INVALID_PARAMETER,message:l});return{sign:a,status:o,timestamp:n}})}initWorkletNode(t,i,r,n,s,a,o,l){t.port.postMessage({type:"init",data:{sdkAppId:String(r),userId:n,timestamp:s,sign:a,status:o}}),t.port.onmessage=c=>{var d;let{data:h}=c;switch(h.type){case"cost":let m=(h==null?void 0:h.value)>10?"info":"debug";return void this.log[m]("".concat(i==="localAudio"?"":"[".concat(i,"] "),"avg cost: ").concat(h.value," max: ").concat(h==null?void 0:h.max,"(").concat(ip(new Date(h==null?void 0:h.maxCostTimestamp)),") hist: ").concat((d=h==null?void 0:h.hist)==null?void 0:d.join(" ")));case"log":return void this.log[h.logLevel]("".concat(i==="localAudio"?"":"[".concat(i,"] ")).concat(h.value));case"dump":return void R.emit("265",{room:l,data:h.value,type:i==="localAudio"?"dump":"dump-screen-audio"});case"detectEcho":return void this.log.warn("".concat(i==="localAudio"?"":"[".concat(i,"] "),"detect echo: ").concat(Hc()?nn():Er()))}}}handleLocalAudioStarted(t){return g(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 g(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}};u(Cu,"updateValidateRule",{type:"object"}),u(Cu,"stopValidateRule",{type:"object"}),u(Cu,"Name","AudioProcessor");var QH=Cu,v_=0,ZH=class{constructor(e,t){u(this,"audioObjectURL"),u(this,"player"),u(this,"publisher"),u(this,"mixInput"),this.mixInput=new cb(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&&(I(e.volume)||(this.volume=e.volume),I(e.loop)||(this.loop=e.loop),I(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 g(this,null,function*(){if(e.url){let t=yield p_.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 ws(e,t){if(t&&typeof t!="function")throw new j({code:G.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(e," should be a function.")})}var No=class Uo{constructor(t){this.core=t,u(this,"log"),u(this,"mixedMusicMap",new Map),u(this,"cacheMusicMap",new Map),v_+=1,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(v_)}),this.log.info("created id=".concat(this.getAlias()).concat(v_))}getName(){return Uo.Name}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return Uo.startValidateRule;case"update":return Uo.updateValidateRule;case"stop":return Uo.stopValidateRule}}start(t){return g(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 ZH(t,i.audioManager),this.cacheMusicMap.set(r,s)),s.updateListener(t),s.updateSettings(t);try{yield s.play()}catch(a){yield this.handleAutoPlayFailed(s,t,a)}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.")),w.addEnum({key:502700,value:3}),this.kvUpload(t)})}handleAutoPlayFailed(t,i,r){return g(this,null,function*(){let{id:n}=i;if(r.name==="NotSupportedError"){if(this.log.error("play failed, try to reload source. error: ".concat(r)),yield t.reload(i),!this.mixedMusicMap.has(n))return void this.log.warn("music ".concat(n," has been stopped, skip play after reload."));yield t.play()}else{if(r.name!=="NotAllowedError")throw r;if(this.core.room.enableAutoPlayDialog){let s=()=>{var a;(a=t.play())==null||a.finally(()=>{R.off("154",s,this)})};R.on("154",s,this),Hf()}else this.core.trtc.emit(F.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>g(this,null,function*(){return t.play()})})}})}update(t){return g(this,null,function*(){let{id:i,operation:r,seekFrom:n,playbackRate:s}=t;this.log.info("update music source, ".concat(JSON.stringify(t)));let a=this.mixedMusicMap.get(i);a?(a.updateSettings(t),a.updateListener(t),I(r)||a.setOperation(r),I(n)||a.seek(n),this.kvUpload(t)):this.log.warn("update music source failed, music id: ".concat(i," not found."))})}stop(t){return g(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==null||s.stop(),r.mixedMusicMap.delete(n)}n==="*"&&r.destroyAllMusic()})()})}kvUpload(t){let{track:i,loop:r,volume:n,playbackRate:s,operation:a,seekFrom:o,onTimeUpdate:l,onDurationChange:c,onEnded:d}=t;i&&w.addCount({key:502009}),r&&w.addCount({key:502001}),n&&w.addCount({key:502002}),s&&w.addCount({key:502003}),a&&w.addCount({key:502004}),o&&w.addCount({key:502005}),typeof l!="function"&&w.addCount({key:502007}),typeof d!="function"&&w.addCount({key:502008}),typeof c!="function"&&w.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()}};u(No,"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(),a=n.indexOf(s)>=0||n.indexOf(e.url.split(".").pop())>=0,o=r.startsWith("blob"),l=r.startsWith("data");if(!(a||o||l))throw new j({code:G.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:i})}if(!e.url&&!e.track)throw new j({code:G.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:i});ws("onTimeUpdate",e.onTimeUpdate),ws("onEnded",e.onEnded),ws("onDurationChange",e.onDurationChange)}}),u(No,"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){ws("onTimeUpdate",e.onTimeUpdate),ws("onEnded",e.onEnded),ws("onDurationChange",e.onDurationChange)}}),u(No,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(No,"Name","AudioMixer");var y_,$H=No,S_=0,bu=class Vo{constructor(t){this.core=t,u(this,"log"),u(this,"audioContext",et()),u(this,"workletNode"),u(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5}),S_+=1,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(S_)}),this.log.info("created id=".concat(this.getAlias()).concat(S_))}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 j({code:G.INVALID_OPERATION,extraCode:5106,fnName:n})}}}preload(t){return y_||(y_=this.doPreload(t)),y_}doPreload(t){return g(this,null,function*(){let i=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(i);try{yield $c(this.audioContext,r)}catch(n){throw this.log.error("load worklet failed",n),n}finally{URL.revokeObjectURL(r)}})}getName(){return Vo.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(t){switch(t){case"start":return Vo.startValidateRule(this.core);case"update":return Vo.updateValidateRule;case"stop":return Vo.stopValidateRule}}start(t){return g(this,null,function*(){let{room:i,schedule:r}=this.core,{assetsPath:n=this.core.assetsPath}=t;if(!n)throw new j({code:G.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(FC()?"":"-nosimd",".js")),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:a,sign:o,status:l,message:c}=yield(function(d,h){return g(this,arguments,function(m,p){let{sdkAppId:f,userId:T,userSig:E,timestamp:v}=p;return(function*(){try{let{data:{errCode:y,errMsg:D,sign:N,status:S}}=yield m.getAbilityConfig(f,m.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:f,userId:T,userSig:E,timestamp:v});if(S==="1")return{auth:!0,sign:N,status:S,message:D};let A=pr(f)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",L="Init RTCAIDenoiser failed.",U="";switch(y){case 1:U="Please check your params.";break;case 2:U="You need to buy packages. Refer to: ".concat(A);break;case 3:U="Server is invalid. Please contact our engineer. ";break;case 4:U="Your packages is not active. Refer to: ".concat(A);break;case 5:U="Your packages is expired. Refer to: ".concat(A);break;case 6:U="Your version is not supported."}return{auth:!1,status:S,message:D?"".concat(L," Reason: ").concat(D,". ").concat(U):"".concat(L,", ").concat(U)}}catch(y){return{auth:!1,status:"0",message:"Init RTCAIDenoiser failed. All requests failed. ".concat(y)}}})()})})(r,W(x({},t),{timestamp:s}));if(!a)throw this.log.info("RTCAIDenoiser: ".concat(t.userId," auth result: ").concat(a,". Message: ").concat(c)),new j({code:G.INVALID_PARAMETER,message:c});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:o,status:l}}),this.workletNode.port.onmessage=d=>{var h;let{data:m}=d;if(m.type==="cost"){let p=(m==null?void 0:m.max)>20?"warn":(m==null?void 0:m.max)>10?"info":"debug";this.log[p]("avg cost: ".concat(m.value," max: ").concat(m==null?void 0:m.max,"(").concat(ip(new Date(m==null?void 0:m.maxCostTimestamp)),") hist: ").concat((h=m==null?void 0:m.hist)==null?void 0:h.join(" ")))}else m.type==="log"&&this.log[m.logLevel]("".concat(m.value))}}this.updateConfig(t),this.workletNode.port.postMessage({type:"enable"}),i.audioManager.addDenoiser(this.workletNode),i.sendAbilityStatus({ai_denoise:1})})}update(t){return g(this,null,function*(){this.updateConfig(t)})}stop(){return g(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;I(t.mode)||(t.mode===0?this.config.enableFarFieldReduce=!1:t.mode===1&&(this.config.enableFarFieldReduce=!0),i=!0),I(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)}};u(bu,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),u(bu,"stopValidateRule",{type:"object"}),u(bu,"Name","AIDenoiser");var e4=bu,t4=Ge(it(),1),i4=class extends t4.EventEmitter{constructor(){super(),u(this,"observer"),u(this,"state","nominal"),u(this,"_loafObserver",null),u(this,"_loafBuffer",[]),u(this,"_loafFlushTimer",null),u(this,"_totalBlockingDuration",0),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}}get totalBlockingDuration(){return this._totalBlockingDuration}start(){this.startCPUObserver(),this.startLoAFDetection()}startCPUObserver(){return g(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!Oe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){ue.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}startLoAFDetection(){var e;try{if(!("PerformanceObserver"in window)||(e=PerformanceObserver.supportedEntryTypes)==null||!e.includes("long-animation-frame")||this._loafObserver)return;this._loafObserver=new PerformanceObserver(t=>{this.processLoAFEntries(t.getEntries())}),this._loafObserver.observe({type:"long-animation-frame",buffered:!0}),this._loafFlushTimer=setInterval(()=>this.flushLoAFBuffer(),1e4)}catch{}}processLoAFEntries(e){try{for(let t of e){if(t.duration<100)continue;let i={time:new Date(performance.timeOrigin+t.startTime).toLocaleTimeString("en-GB",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3}),duration:Math.round(t.duration),scripts:(t.scripts||[]).map(r=>({duration:Math.round(r.duration),invoker:r.invoker||"",invokerType:r.invokerType||"",sourceURL:r.sourceURL||"",sourceFunctionName:r.sourceFunctionName||""}))};this._totalBlockingDuration+=i.duration,i.duration>=200&&this._loafBuffer.push(i)}}catch{}}flushLoAFBuffer(){if(this._loafObserver&&this.processLoAFEntries(this._loafObserver.takeRecords()),this._loafBuffer.length!==0)try{let e=this._loafBuffer.splice(0),t=new Map,i=o=>o?(t.has(o)||t.set(o,t.size+1),"[".concat(t.get(o),"]")):"",r=new Map;for(let o of e){let l=o.scripts.length>0?o.scripts.map(d=>"".concat(d.invokerType,":").concat(d.invoker," ").concat(d.sourceFunctionName," ").concat(i(d.sourceURL))).join(" | "):"no script info",c=r.get(l);c?(c.count+=1,c.timeRange.push(o.time),c.duration.push(o.duration)):r.set(l,{count:1,timeRange:[o.time],duration:[o.duration]})}let n=" count | duration(avg) | time range | scripts",s=[...r.entries()].map(o=>{let[l,c]=o,d=Math.round(c.duration.reduce((m,p)=>m+p,0)/c.count),h=c.count===1?c.timeRange[0]:"".concat(c.timeRange[0],"~").concat(c.timeRange[c.timeRange.length-1]);return" ".concat(String(c.count).padStart(5)," | ").concat(String(d).padStart(13),"ms | ").concat(h.padEnd(27)," | ").concat(l)}),a=t.size>0?`
|
||
sources: `.concat([...t.entries()].map(o=>{let[l,c]=o;return"[".concat(c,"]").concat(l)}).join(" ")):"";P.warn("[LoAF] ".concat(e.length," long frames (>").concat(100,"ms) in last ").concat(10,"s:").concat(a,`
|
||
`).concat(n,`
|
||
`).concat(s.join(`
|
||
`)))}catch{}}onPressureChange(e){let t=this.stateNum,i=e[e.length-1];this.state=i.state,(this.stateNum>3||t>3)&&P.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){ue.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}this._loafObserver&&(this._loafObserver.disconnect(),this._loafObserver=null),this._loafFlushTimer&&(clearInterval(this._loafFlushTimer),this._loafFlushTimer=null),this.flushLoAFBuffer()}},I_=new i4,A_=0,R_=class Ik{constructor(t){this.core=t,u(this,"log"),u(this,"_seiMessageList",[]),u(this,"_smallSeiMessageList",[]),u(this,"_subStreamSeiMessageList",[]),A_++,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(A_)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(A_)),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode(t){let{frame:i,mediaType:r}=t;try{return I0({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 A0({frame:i,onSEI:n=>{n.forEach(s=>{r!=null&&r.userId?this.core.trtc.emit(F.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:an?this.encode:I0,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:an?this.decode:A0,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],a=!!r.small;r.toSubStream?this._subStreamSeiMessageList.push(s):(this._seiMessageList.push(s),a&&this._smallSeiMessageList.push(s)),(n=this.core.room.scriptTransformWorker)==null||n.postMessage({type:"sei",data:s,isMain:!r.toSubStream,small:a})}getName(){return Ik.Name}getAlias(){return"sei"}getGroup(){return"sei"}};u(R_,"autoStart",!0),u(R_,"Name","SEI");var ku,r4=R_,n4=0,C_=class Ak{constructor(t){this.core=t,u(this,"_core"),u(this,"log"),u(this,"dialog"),this._core=t,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(++n4)}),this.log.info("created")}getName(){return Ak.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 g(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 g(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 g(this,null,function*(){var t;if(!this.dialog)try{if(ku)yield ku;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(ei,"/assets/debug-dialog.js");ku=this._core.fileDownloader.loadScript(i),yield ku}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)}};u(C_,"Name","Debug"),u(C_,"autoStart",!0);var s4=C_,P0=e=>{switch(e){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},O0=class{constructor(e,t,i){u(this,"trackDoneOB"),u(this,"startOB"),u(this,"stopOB"),u(this,"inputFrameCount",0),u(this,"decodedFrameCount",0),u(this,"type","auto"),u(this,"config"),u(this,"decoder"),u(this,"_decodeSink");let{kvStatManager:r,trtc:n}=e;this.config=i.config,this.trackDoneOB=ye(t,re.INIT),this.stopOB=Ti(),this.startOB=Ti(),i.type==="auto"?this.type="webCodecs":this.type=i.type;let s=Ti();Ie(this.startOB,Qf(0),du(a=>{let o=this.pipe(t);return s.next("STARTING"),t.log.info("decoder type: ".concat(this.type)),Ie(o,pt(this.stopOB),ze(()=>{},l=>{t.log.error(l),r.addFailedEvent({key:P0(this.type),error:l}),a>4?this.startOB.error(l):this.startOB.next(a+1)})),Ie(o,Ss(1),jb(e_))}),pt(this.stopOB),ze(()=>{t.player.setOutput(),s.next("STARTED")},a=>{s.next("FAILED")},()=>{r.addSuccessEvent({key:P0(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 _o()(t=>g(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"}))}},a4={type:"object"},M0=class F_{constructor(t){this.core=t,u(this,"log"),u(this,"contextMap",new Map),u(this,"decodeProcessorMap",new WeakMap),this.log=t.log.createChild({id:"".concat(this.getAlias())})}getAlias(){return F_.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return F_.Name}getValidateRule(t){return a4}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 O0(this.core,n,t);return Ie(s.trackDoneOB,Ss(1),ze(()=>{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 O0(this.core,t.track,t))}}};u(M0,"Name","TRTCAudioDecoder");var L0=M0,o4={rttPoorLimit:150,lossPoorLimit:20,rttGoodLimit:100,lossGoodLimit:10,fpsPoorLimit:5,cooldownTime:1e4,poorCount:3,goodCount:5,maxUpgradeFailCount:3},l4=class{constructor(){u(this,"log"),u(this,"autoMode",{enabled:!1,instance:null,config:o4,sortedStreamList:[],currentQualityIndex:0}),u(this,"switchControl",{isInternal:!1,isSwitching:!1,lastSwitchTime:0,boundOnStatistics:null}),u(this,"networkMetrics",{frameRate:0,rtt:0,loss:0}),u(this,"counters",{rttUnder:0,lossUnder:0,downgradeCondition:0,upgradeFail:0}),u(this,"onStatistics",e=>{var t,i;if(!this.autoMode.instance)return;let{config:r}=this.autoMode;if(this.networkMetrics.rtt=e.rtt,this.networkMetrics.loss=e.downLoss,this.counters.rttUnder=e.rtt<r.rttGoodLimit?this.counters.rttUnder+1:0,this.counters.lossUnder=e.downLoss<r.lossGoodLimit?this.counters.lossUnder+1:0,(t=e==null?void 0:e.remoteStatistics)==null||!t.length)return;let n=this.getCurrentPlayingStream(this.autoMode.instance);if(!n)return;let{userId:s,streamType:a}=n,o=e.remoteStatistics.find(d=>d.userId===s);if((i=o==null?void 0:o.video)==null||!i.length)return;let l=a==="sub"?"sub":"big",c=o.video.find(d=>d.videoType===l);c?(this.networkMetrics.frameRate=c.frameRate||0,this.checkAndSwitchQuality()):this.log.warn("onStatistics: videoStat not found for userId=".concat(s,", streamType=").concat(a))}),this.log=P.createLogger({id:"pqs"})}getCurrentPlayingStream(e){var t,i;let r=e,n=r._playbackQualityList;if(!n||n.length===0)return this.log.warn("getCurrentPlayingStream: streamList is empty"),null;for(let s of n){let a=e.room.remotePublishedUserMap.get(s.userId);if(!a)continue;let o=(t=s.streamType)!=null?t:"main";if((o==="sub"?a.remoteAuxiliaryTrack:a.remoteVideoTrack).isPlayCalled){let l=(i=r._remoteVideoConfigMap.get("".concat(s.userId,"_").concat(o)))==null?void 0:i.config;if(l)return{userId:s.userId,streamType:o,config:l}}}return null}switchPlaybackQuality(e){return g(this,null,function*(){var t;let{trtcInstance:i,streamList:r,quality:n,_internalSwitch:s=!1}=e;this.log.info("switchPlaybackQuality quality: ".concat(n,", streamList: ").concat(JSON.stringify(r)));let a=i;if(r&&r.length>0&&(a._playbackQualityList=r.map(f=>{var T;return W(x({},f),{streamType:(T=f.streamType)!=null?T:"main"})})),n==="auto")return void(yield this.startAutoMode(i));if(this.autoMode.enabled&&n&&!this.switchControl.isInternal&&this.stopAutoMode(),!n)return;if(!a._playbackQualityList||a._playbackQualityList.length<=0)return void this.log.warn("switchPlaybackQuality: streamList is empty, please call with streamList first");let o=a._playbackQualityList.find(f=>f.name===n);if(!o)return void this.log.warn('switchPlaybackQuality: quality "'.concat(n,'" not found in streamList'));let l=this.getCurrentPlayingStream(i);if(this.log.info("currentPlaying userId: ".concat(l==null?void 0:l.userId,", streamType: ").concat(l==null?void 0:l.streamType)),!l)return;let c=(t=o.streamType)!=null?t:"main";if(l.userId===o.userId&&l.streamType===c)return void this.log.info("switchPlaybackQuality: already playing target stream");if(this.switchControl.isSwitching&&!s)return void this.log.info("switchPlaybackQuality: switching in progress, skip");s||(this.switchControl.isSwitching=!0);let d,h=x({},l.config),m=h.streamType==="main"&&c==="main",p=new Promise(f=>{d=setTimeout(()=>f("timeout"),1e4)});try{let f=i.startRemoteVideo(W(x({},l.config),{userId:o.userId,streamType:c,option:W(x({},l.config.option),{isLiveStream:!0})}));if((yield Promise.race([f,p]))==="timeout"){this.log.error("switchPlaybackQuality: VIDEO_PLAY_STATE_CHANGED timeout, rollback");try{yield i.stopRemoteVideo({userId:o.userId,streamType:c})}catch(E){this.log.warn("switchPlaybackQuality: rollback stopRemoteVideo failed",E)}throw new O({code:C.SUBSCRIPTION_TIMEOUT,message:Y({key:K.SWITCH_PLAYBACK_QUALITY_TIMEOUT,data:{userId:o.userId}})})}let T=i.stopRemoteVideo(h);m?yield Promise.all([i.muteRemoteAudio(o.userId,!1).catch(E=>{this.log.warn("muteRemoteAudio(new, false) failed",E)}),i.muteRemoteAudio(h.userId,!0).catch(E=>{this.log.warn("muteRemoteAudio(old, true) failed",E)}),T]):yield T,a._currentLiveUserId=o.userId,a._currentLiveStreamType=c}finally{clearTimeout(d),s||(this.switchControl.isSwitching=!1)}})}startAutoMode(e){return g(this,null,function*(){if(this.autoMode.enabled)return void this.log.info("auto mode already enabled");let t=e;if(!t._playbackQualityList||t._playbackQualityList.length<=1)return void this.log.warn("startAutoMode: need at least 2 streams in streamList for auto mode");this.autoMode.enabled=!0,this.autoMode.instance=e,this.counters.rttUnder=0,this.counters.lossUnder=0,this.counters.downgradeCondition=0,this.counters.upgradeFail=0,this.switchControl.lastSwitchTime=0;let i=t._playbackQualityList||[];this.autoMode.sortedStreamList=[...i].sort((n,s)=>s.bitrate-n.bitrate),this.log.info("auto mode streams: ".concat(this.autoMode.sortedStreamList.map(n=>"".concat(n.name,"(").concat(n.bitrate,"kbps)")).join(" > ")));let r=this.getCurrentPlayingStream(e);if(r){let{userId:n,streamType:s}=r,a=this.autoMode.sortedStreamList.findIndex(o=>{var l;return o.userId===n&&((l=o.streamType)!=null?l:"main")===s});this.autoMode.currentQualityIndex=a>=0?a:0}else this.autoMode.currentQualityIndex=0;this.switchControl.boundOnStatistics=this.onStatistics,e.on(F.STATISTICS,this.switchControl.boundOnStatistics),this.log.info("auto mode started")})}stopAutoMode(){this.autoMode.enabled&&(this.autoMode.instance&&this.switchControl.boundOnStatistics&&this.autoMode.instance.off(F.STATISTICS,this.switchControl.boundOnStatistics),this.switchControl.boundOnStatistics=null,this.autoMode.enabled=!1,this.autoMode.instance=null,this.autoMode.sortedStreamList=[],this.autoMode.currentQualityIndex=0,this.counters.rttUnder=0,this.counters.lossUnder=0,this.counters.downgradeCondition=0,this.counters.upgradeFail=0,this.networkMetrics.frameRate=0,this.networkMetrics.rtt=0,this.networkMetrics.loss=0,this.switchControl.isSwitching=!1,this.log.info("auto mode stopped"))}checkAndSwitchQuality(){var e;if(!this.autoMode.enabled||!this.autoMode.instance||this.switchControl.isSwitching)return;let{config:t}=this.autoMode,i=Date.now()-this.switchControl.lastSwitchTime<t.cooldownTime,r=((e=this.autoMode.sortedStreamList[this.autoMode.currentQualityIndex])==null?void 0:e.name)||"unknown",n=this.autoMode.currentQualityIndex<this.autoMode.sortedStreamList.length-1,s=this.autoMode.currentQualityIndex>0,a=this.networkMetrics.frameRate<=t.fpsPoorLimit,o=this.networkMetrics.loss>=t.lossPoorLimit||this.networkMetrics.rtt>=t.rttPoorLimit,l=a&&o;this.counters.downgradeCondition=l?this.counters.downgradeCondition+1:0;let c=this.counters.rttUnder>=t.goodCount&&this.counters.lossUnder>=t.goodCount,d=this.counters.upgradeFail<t.maxUpgradeFailCount;if(this.log.debug("[check] stream=".concat(r,", fps=").concat(this.networkMetrics.frameRate,", rtt=").concat(this.networkMetrics.rtt,", loss=").concat(this.networkMetrics.loss,", fpsLow=").concat(a,", networkPoor=").concat(o,", downgradeCount=").concat(this.counters.downgradeCondition,"/").concat(t.poorCount,", rttUnder=").concat(this.counters.rttUnder,", lossUnder=").concat(this.counters.lossUnder,", goodCondition=").concat(c,", canDowngrade=").concat(n,", canUpgrade=").concat(s&&d,", inCooldown=").concat(i)),!i){if(this.counters.downgradeCondition>=t.poorCount&&n){let h=this.autoMode.sortedStreamList[this.autoMode.currentQualityIndex+1];return this.log.info("auto mode downgrade: ".concat(r," → ").concat(h==null?void 0:h.name,", fps=").concat(this.networkMetrics.frameRate,", rtt=").concat(this.networkMetrics.rtt,", loss=").concat(this.networkMetrics.loss)),void this.switchToQualityIndex(this.autoMode.currentQualityIndex+1)}if(c&&s&&d){let h=this.autoMode.sortedStreamList[this.autoMode.currentQualityIndex-1];this.log.info("auto mode upgrade: ".concat(r," → ").concat(h==null?void 0:h.name,", rttUnder=").concat(this.counters.rttUnder,", lossUnder=").concat(this.counters.lossUnder)),this.switchToQualityIndex(this.autoMode.currentQualityIndex-1,!0)}}}switchToQualityIndex(e){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return g(this,null,function*(){if(!this.autoMode.instance||e<0||e>=this.autoMode.sortedStreamList.length||this.switchControl.isSwitching)return;this.switchControl.isSwitching=!0;let i=this.autoMode.sortedStreamList[e];this.log.info("auto mode: switching to quality index ".concat(e,", stream: ").concat(i.name,", isUpgrade: ").concat(t));try{this.switchControl.isInternal=!0,yield this.switchPlaybackQuality({trtcInstance:this.autoMode.instance,quality:i.name,_internalSwitch:!0}),this.autoMode.currentQualityIndex=e,this.switchControl.lastSwitchTime=Date.now(),this.counters.rttUnder=0,this.counters.lossUnder=0,this.counters.downgradeCondition=0,t&&(this.counters.upgradeFail=0),this.log.info("auto mode switch success: now playing ".concat(i.name))}catch(r){this.log.warn("auto mode switch failed: ".concat(i.name),r),t&&(this.counters.upgradeFail+=1,this.log.info("auto mode upgrade failed, upgradeFailCount=".concat(this.counters.upgradeFail,"/").concat(this.autoMode.config.maxUpgradeFailCount)))}finally{this.switchControl.isInternal=!1,this.switchControl.isSwitching=!1}})}},b_=class{constructor(){u(this,"log"),this.log=P.createLogger({id:"exp"})}call(e,t){return g(this,null,function*(){return Pe(this[e])?this[e](t):Promise.reject(new O({code:C.INVALID_PARAMETER,message:Y({key:K.API_NOT_EXIST,data:{name:e}})}))})}enableAudioFrameEvent(e){return g(this,null,function*(){let{trtcInstance:t,enable:i,userId:r,sampleRate:n=48e3,channelCount:s=1,port:a}=e,{audioManager:o}=t.room,{getPCMAbortCtrlMap:l,audioFrameEventConfigMap:c}=o;if(c.set(r,{enable:i,sampleRate:n,channelCount:s,port:a}),i)if(r==="*")t.room.remotePublishedUserMap.forEach(d=>{if(d.remoteAudioTrack.isAvailable){if(l.get(d.userId))return;let h=o.getPCM(m=>{t.emit(F.AUDIO_FRAME,m)},d.userId);l.set(d.userId,h)}});else{if(l.get(r))return;let d=o.getPCM(h=>{t.emit(F.AUDIO_FRAME,h)},r);l.set(r,d)}else if(r==="*")t.room.remotePublishedUserMap.forEach(d=>{if(d.remoteAudioTrack.isSubscribed){let{userId:h}=d,m=l.get(h);m==null||m.abort("disable"),l.delete(h)}});else{let d=l.get(r);d==null||d.abort("disable"),l.delete(r)}})}resumeRemotePlayer(e){return g(this,null,function*(){if(e.userId==="*"){let i=[];return e.trtcInstance.room.remotePublishedUserMap.forEach(r=>{let{remoteAudioTrack:n,remoteVideoTrack:s,remoteAuxiliaryTrack:a}=r;e.streamType?e.streamType==="main"?(n.isAvailable&&i.push(n.player.resume()),s.isAvailable&&i.push(s.player.resume())):a.isAvailable&&i.push(a.player.resume()):(n.isAvailable&&i.push(n.player.resume()),s.isAvailable&&i.push(s.player.resume()),a.isAvailable&&i.push(a.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))}}requestPictureInPicture(e){let t=[...e.trtcInstance.room.remotePublishedUserMap.values()].find(i=>i.remoteVideoTrack.isAvailable);return t?e.enable?t.remoteVideoTrack.player.enterPictureInPicture():t.remoteVideoTrack.player.exitPictureInPicture():Promise.reject(new O({code:C.INVALID_OPERATION,message:"no available remote video"}))}requestFullScreen(e){let t=[...e.trtcInstance.room.remotePublishedUserMap.values()].find(i=>i.remoteVideoTrack.isAvailable);return t?e.enable?t.remoteVideoTrack.player.enterFullscreen():t.remoteVideoTrack.player.exitFullscreen():Promise.reject(new O({code:C.INVALID_OPERATION,message:"no available remote video"}))}switchPlaybackQuality(e){return g(this,null,function*(){let t=e.trtcInstance;return t._playbackQualitySwitcher||(t._playbackQualitySwitcher=new l4),t._playbackQualitySwitcher.switchPlaybackQuality(e)})}preconnect(e){return g(this,null,function*(){let{trtcInstance:t}=e;return e.enable?t.room.preconnect(e.sdkAppId,e.userId,e.userSig,Oo.frameWorkType,e.roomId,e.strRoomId):t.room.closePreconnect()})}};M([$b({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"}}})],b_.prototype,"enableAudioFrameEvent"),M([$b({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!1,type:"string"},sdkAppId:{required:!1,type:"number"},userSig:{required:!1,type:"string"},roomId:{required:!1,type:"number"},strRoomId:{required:!1,type:"string"}}})],b_.prototype,"preconnect");var c4=new b_,u4=Ge(it(),1),d4=class extends u4.EventEmitter{constructor(){super(),u(this,"states",{}),u(this,"permissionChangeHandler"),u(this,"log"),this.log=P.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 g(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 g(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==null||e.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},Du=new d4,x0=0,Po=new Set,Ye=null;dA(w0),mf.checkStorage();var Q=class Yi extends O3.EventEmitter{constructor(t,i){super(),u(this,"_room"),u(this,"_eventListened",new Set),u(this,"_localVideoTrack",null),u(this,"_localAudioTrack",null),u(this,"_localScreenTrack",null),u(this,"_localScreenAudioTrack",null),u(this,"_localVideoConfig",null),u(this,"_localScreenConfig",null),u(this,"_localAudioConfig",null),u(this,"_remoteVideoConfigMap",new Map),u(this,"_remoteAudioConfigMap",new Map),u(this,"_remoteAudioVolumeMap",new Map),u(this,"_remoteAudioMuteMap",new Map),u(this,"_mediaTrackMap",new WeakMap),u(this,"_log",P.createLogger({id:"t".concat(++x0)})),u(this,"_plugins",new Map),u(this,"_networkQuality",null),u(this,"_speakerId"),u(this,"enterRoomParams"),u(this,"_enableAutoSwitchWhenRecapturing",!0),u(this,"_autoSubscribeDataChannel",!1),u(this,"_playbackQualityList",[]),this._room=new t(x({logger:this._log,frameWorkType:Yi.frameWorkType},i)),this._room.videoDecodeFallbackType=i.videoDecodeFallback,Se(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($H,i.assetsPath),this._use(QH,i.assetsPath),this._use(e4,i.assetsPath),this._use(L0,i.assetsPath),this._use(s4),i.enableSEI&&kf&&this._use(r4),this._room.on("audio-volume",r=>{var n,s;!r.find(a=>a.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(a=>{var o;let l=a.userId===""?this._localAudioTrack:(o=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:o.remoteAudioTrack;l&&(a.volume=l.dbVolume)}),i.enableDbVolume&&r.forEach(a=>{var o;let l=a.userId===""?this._localAudioTrack:(o=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:o.remoteAudioTrack;l&&(a.volume=l.dbVolume)}),this.emit(F.AUDIO_VOLUME,{result:r.sort((a,o)=>o.volume-a.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new j({code:G.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),((r,n)=>{let{emit:s}=r;r.emit=function(){for(var a=arguments.length,o=new Array(a),l=0;l<a;l++)o[l]=arguments[l];try{return s.apply(r,o)}catch(c){let d=Y({key:K.CATCH_HANDLER_ERROR,data:{name:n,event:o[0]},addDocLink:!1});return P.warn("".concat(d,`
|
||
|
||
`).concat(c.stack)),!1}}})(this,"trtc")}static create(t){}static _create(t,i){(function(){var n;if(t0){t0=!1,P.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(Pi,"/en/index.html")),console.info("* Changelog: ".concat(Pi,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),P.info("TRTC Web SDK Version:",ei),tn||P.debug("Build Time:","2026-03-13 18:37:25");let s="UA: ".concat(navigator.userAgent,`
|
||
CPU core: `).concat(navigator.hardwareConcurrency,", GPU: ").concat(fs());if(be&&window.screen&&(window.screen.width||window.screen.height)){let o="".concat(window.screen.width,"x").concat(window.screen.height,"@").concat(window.devicePixelRatio);s+=", screen: ".concat(o)}let a=navigator.deviceMemory;a&&(s+=", minRAM: ".concat(a,"GB")),P.info(s),P.info("URL: ".concat(location.href).concat(((n=self.frameElement)==null?void 0:n.tagName)==="IFRAME"?" in iframe":"")),Wc().then(o=>{o&&P.info(Vi),P.info("OS: ".concat(Er()))})}})();let r=new Yi(t,i||{});return Po.add(r),r.__v_skip=!0,r}get room(){return this._room}_listenEvents(){Wt(this,this._room).add("peer-join",t=>{let{userId:i}=t;this.emit(F.REMOTE_USER_ENTER,{userId:i})}).add("peer-leave",t=>{let{userId:i,reason:r}=t;this.emit(F.REMOTE_USER_EXIT,{userId:i,reason:r})}).add("banned",t=>{ni(!0),this._exitRoom().finally(()=>{this.emit(F.KICKED_OUT,{reason:t.reason})})}).add("error",t=>{this._exitRoom().finally(()=>{this.emit(F.ERROR,j.convertFrom(t))})}).add("signal-connection-state-changed",t=>{this.emit(F.CONNECTION_STATE_CHANGED,t)}).add("network-quality",t=>{this._networkQuality=t;let i=W(x({},t),{uplinkRTT:Math.min(t.uplinkRTT,gc),downlinkRTT:Math.min(t.downlinkRTT,gc)});this.emit(F.NETWORK_QUALITY,i)}).add("remote-published",t=>{[t.remoteAudioTrack,t.remoteVideoTrack,t.remoteAuxiliaryTrack].forEach(i=>{Wt(i,i).add("player-state-changed",r=>{let n=W(x({},r),{userId:t.userId});i.kind===_.VIDEO&&(n.streamType=bt(i.streamType)),this.emit(i.kind===_.AUDIO?F.AUDIO_PLAY_STATE_CHANGED:F.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",r=>{r.getCode()===C.PLAY_NOT_ALLOWED&&this.emit(F.AUTOPLAY_FAILED,{userId:i.userId,mediaType:i.strMediaType,resume:()=>i.player.resume()})})})}).add("remote-unpublished",t=>{[t.remoteAudioTrack,t.remoteVideoTrack,t.remoteAuxiliaryTrack].forEach(i=>{mt(i)})}).add("remote-publish-state-changed",t=>{let{prevMuteState:i,muteState:r}=t,{userId:n}=r,s=i.audioAvailable,a=i.videoAvailable,{audioAvailable:o,videoAvailable:l}=r;o||this._remoteAudioConfigMap.delete(n),l||this._removeRemoteVideoConfig(n,"main"),r.hasAuxiliary||this._removeRemoteVideoConfig(n,"sub"),a!==l&&(l?this._onVideoAvailable({userId:n,streamType:"main"}):this._onVideoUnavailable({userId:n,streamType:"main"}),this.emit(l?F.REMOTE_VIDEO_AVAILABLE:F.REMOTE_VIDEO_UNAVAILABLE,{userId:n,streamType:"main"})),s!==o&&(o?this._onAudioAvailable({userId:n}):this._onAudioUnavailable({userId:n,muteState:r}),this.emit(o?F.REMOTE_AUDIO_AVAILABLE:F.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?F.REMOTE_VIDEO_AVAILABLE:F.REMOTE_VIDEO_UNAVAILABLE,{userId:n,streamType:"sub"})),i.hasDatachannel!==r.hasDatachannel&&r.hasDatachannel&&this._onDataChannelAvailable()}).add("sei-message",t=>{this.emit(F.SEI_MESSAGE,W(x({},t),{streamType:bt(t.streamType)}))}).add("firewall-restriction",()=>{this.emit(F.ERROR,new j({code:G.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",t=>{var i,r,n,s,a,o,l;let c={2:"big",3:"small",7:"sub"},d={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,gc),upLoss:((s=this._networkQuality)==null?void 0:s.uplinkLoss)||0,downLoss:((a=this._networkQuality)==null?void 0:a.downlinkLoss)||0,bytesSent:t.bytes_sent||0,bytesReceived:t.bytes_received||0,localStatistics:{audio:{bitrate:(((o=t.msg_up_stream_info.msg_audio_status)==null?void 0:o.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((l=t.msg_up_stream_info.msg_audio_status)==null?void 0:l.uint32_audio_level)||0)/fi},video:t.msg_up_stream_info.msg_video_status.filter(h=>c[h.uint32_video_stream_type]).map(h=>({bitrate:(h.uint32_video_codec_bitrate||0)/1e3,width:h.uint32_video_width,height:h.uint32_video_height,frameRate:h.uint32_video_enc_fps,videoType:c[h.uint32_video_stream_type]}))},remoteStatistics:t.msg_down_stream_info.map(h=>({userId:h.msg_user_info.str_identifier,audio:{bitrate:(h.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(h.msg_audio_status.uint32_audio_level||0)/fi,point2pointDelay:(h.msg_audio_status.uint32_audio_p2p_delay||0)+(h.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:h.msg_audio_status.uint32_audio_cache_ms||0},video:h.msg_video_status.map(m=>({bitrate:(m.uint32_video_codec_bitrate||0)/1e3,width:m.uint32_video_width,height:m.uint32_video_height,frameRate:m.uint32_video_dec_fps,videoType:c[m.uint32_video_stream_type],point2pointDelay:(m.uint32_video_p2p_delay||0)+(m.uint32_video_cache_ms||0),jitterBufferDelay:m.uint32_video_cache_ms||0,codec:m.uint32_video_codec}))}))};this.emit(F.STATISTICS,d)}).add("custom-message",t=>{this.emit(F.CUSTOM_MESSAGE,t)}).add("layerData",t=>this.emit(F.LAYER_DATA,t)).add("first-video-frame",t=>{this.emit(F.FIRST_VIDEO_FRAME,W(x({},t),{streamType:bt(t.streamType)}))}).add("audio-frame",t=>{this.emit(F.AUDIO_FRAME,t)}).add("data-channel-message",t=>{var i,r,n,s,a;let{data:o}=t;if(o.sender==="")return;let l={segmentId:(i=o.payload)==null?void 0:i.roundid,speakerUserId:o.sender,sourceText:(r=o.payload)==null?void 0:r.text,translationTexts:(n=o.payload)==null?void 0:n.translate_msg,timestamp:(s=o.payload)==null?void 0:s.start_utc_ms,isCompleted:(a=o.payload)==null?void 0:a.end,robotId:o.robotid};l.sourceText!==""&&this.emit(F.REALTIME_TRANSCRIBER_MESSAGE,l)}).add("asr-robot-peer-join",t=>{this.emit(F.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"started",roomId:this.room.roomId,transcriberRobotId:t.userId})}).add("asr-robot-peer-leave",t=>{this.emit(F.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"stopped",roomId:this.room.roomId,transcriberRobotId:t.userId})}),Wt(this,He).add("audioInputAdded",t=>{this.emit(F.DEVICE_CHANGED,{type:"microphone",action:"add",device:t})}).add("audioInputRemoved",t=>{this.emit(F.DEVICE_CHANGED,{type:"microphone",action:"remove",device:t})}).add("videoInputAdded",t=>{this.emit(F.DEVICE_CHANGED,{type:"camera",action:"add",device:t})}).add("videoInputRemoved",t=>{this.emit(F.DEVICE_CHANGED,{type:"camera",action:"remove",device:t})}).add("audioOutputAdded",t=>g(this,null,function*(){if(this.emit(F.DEVICE_CHANGED,{type:"speaker",action:"add",device:t}),Ye&&Ye.deviceId===_c){let i=(yield ln()).find(r=>r.deviceId===_c);i&&Ye.groupId!==i.groupId&&(Ye=i,this.emit(F.DEVICE_CHANGED,{type:"speaker",action:"active",device:i}))}})).add("audioOutputRemoved",t=>g(this,null,function*(){this.emit(F.DEVICE_CHANGED,{type:"speaker",action:"remove",device:t});let i=(yield ln())[0];if(!i||!Ye||Ye.groupId===i.groupId)return;let r=Ye.deviceId===t.deviceId,n=Ye.deviceId===_c&&Ye.deviceId===i.deviceId;(r||n)&&(Ye=i,this.emit(F.DEVICE_CHANGED,{type:"speaker",action:"active",device:i}))})),Wt(this,Du).add("permission-state-change",t=>{this.emit(F.PERMISSION_STATE_CHANGE,t)}),this.room.enableSEI&&this.on(F.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 Ta()}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(YH.call(this,{TRTC:Yi,room:this._room,assetsPath:i,errorModule:{RtcError:j,ErrorCode:G,CoreErrorCode:C,ErrorCodeDictionary:vu}}));return this._plugins.set(t.Name,n),n.__v_skip=!0,t.autoStart&&this.startPlugin(t.Name),n}enterRoom(t){return g(this,null,function*(){var i,r;this.enterRoomParams=t;let{scene:n="rtc",enableAutoPlayDialog:s=!0,autoReceiveAudio:a=!0,autoReceiveVideo:o=!1}=t;t.proxy&&(this._room.setProxyServer(t.proxy),!he(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=a,this._room.autoReceiveVideo=o,Se(t.preferHW)&&(this._room.preferHW=t.preferHW),t.playoutDelay&&(this._room.playoutDelay=t.playoutDelay),t.jitterBufferDelay&&(this._room.jitterBufferDelay=t.jitterBufferDelay);let l={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(l,n,Yi.frameWorkType),this._checkTrackToPublish(),I_.start()})}exitRoom(){return g(this,null,function*(){return yield this._exitRoom()})}switchRoom(t){return g(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(t)}catch(i){if(!(i instanceof aA)||i.code!==C.API_CALL_TIMEOUT&&i.code!==C.SWITCH_ROOM_FAILED)throw i;this._log.warn("switchRoom ".concat(i.code===C.API_CALL_TIMEOUT?"timeout":"failed",", fallback to exitRoom() and enterRoom()")),yield this._rejoinRoom(t)}else yield this._rejoinRoom(t)})}_rejoinRoom(t){return g(this,null,function*(){yield this.exitRoom();let i=x(x({},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=Ds.get(t);i&&(i.forEach(r=>clearTimeout(r)),Ds.delete(t))})(this),this._room.remotePublishedUserMap.forEach(t=>{mt(t.remoteAudioTrack),mt(t.remoteVideoTrack),mt(t.remoteAuxiliaryTrack)})}switchRole(t,i){return g(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(),mt(this),this.removeAllListeners(),this._room.destroy(),Po.delete(this),Po.size===0&&I_.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),R.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return g(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,muteKeepVolumeDetection:s,option:a}=i,o=new dn(t._room.audioManager),l={},c={muted:!0};a&&(I(a.microphoneId)?I(a.audioTrack)||(l.customSource=a.audioTrack):l.deviceId=a.microphoneId,a&&le(a.captureVolume)&&o.setCaptureVolume(a.captureVolume),I(a.profile)||(he(a.profile)?cp[a.profile]&&o.setProfile(cp[a.profile]):o.setProfile(a.profile)),le(a.earMonitorVolume)&&(c.muted=!(a.earMonitorVolume>0),c.volume=a.earMonitorVolume),I(a.echoCancellation)||(o.profile.echoCancellation=a.echoCancellation),I(a.noiseSuppression)||(o.profile.noiseSuppression=a.noiseSuppression),I(a.autoGainControl)||(o.profile.autoGainControl=a.autoGainControl),Se(t._enableAutoSwitchWhenRecapturing)&&(o.enableAutoSwitchWhenRecapturing=t._enableAutoSwitchWhenRecapturing)),o.on("5",d=>{t.emit(F.ERROR,new j({code:G.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),o.on("2",d=>{t.emit(F.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),o.on("4",d=>{let h;d.error&&(h=j.convertFrom(d.error)),t.emit(F.PUBLISH_STATE_CHANGED,W(x({},d),{error:h}))}),o.on("6",()=>{}),t._listenOutputTrackChanged(o),t._speakerId&&o.setAudioOutput(t._speakerId),yield o.capture(l),I(n)||o.setMute(n,s),Wt(o,o).add("player-state-changed",d=>{t.emit(F.AUDIO_PLAY_STATE_CHANGED,W(x({},d),{userId:""}))}),r&&t._room.isJoined&&t._room.publish(o).catch(()=>{}),t._localAudioTrack=o,t._room.capturedLocalMainAudioTrack=o,t._localAudioConfig=W(x({},i),{publish:r}),yield t._updateAudioPlayOption({playOption:c,track:o}),R.emit("113",{userId:"",room:t.room})})()})}updateLocalAudio(t){return g(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:i,mute:r,muteKeepVolumeDetection:n,option:s}=t,a={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):I(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),I(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),I(s.earMonitorVolume)||(a.muted=!(s.earMonitorVolume>0),a.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!I(i)&&(i&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!i&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),I(r)||this._localAudioTrack.setMute(r,n),yield this._updateAudioPlayOption({playOption:a,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Li(this._localAudioConfig,t)})}stopLocalAudio(){return g(this,null,function*(){if(!this._localAudioTrack)return;let t;return this._room.isJoined&&(t=this._room.unpublish(this._localAudioTrack).catch(()=>{})),R.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),mt(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,delete this._room.capturedLocalMainAudioTrack,yield t})}startLocalVideo(){return g(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,n,s;if(t._localVideoTrack)return void t._log.warn("local video is already started");let{view:a,publish:o=!0,capture:l=!0,mute:c,option:d,forcePublish:h=!1}=i,m=o||h,p=l,f=new ji(t._room.videoManager),T={},E={};if(d&&(Se(d.avoidCropping)&&(f.avoidCropping=d.avoidCropping),d.cameraId?T.deviceId=d.cameraId:I(d.useFrontCamera)?I(d.videoTrack)||(T.customSource=d.videoTrack):T.facingMode=d.useFrontCamera?_.FACING_MODE_USER:_.FACING_MODE_ENVIRONMENT,I(d.retryWhenExactFailed)||(T.retryWhenExactFailed=d.retryWhenExactFailed),d.qosPreference&&(T.contentHint=Rs(d.qosPreference)),I(d.profile)||(he(d.profile)?Oi[d.profile]&&f.setProfile(Oi[d.profile]):f.setProfile(d.profile)),I(d.fillMode)||(E.objectFit=d.fillMode),I(d.mirror)||(E.mirror=d.mirror),I(d.small)||(I(d.smallMode)||(t._room.smallMode=d.smallMode),Se(d.small)&&d.small===!1?f.stopSmall():f.updateSmallConfig(yu(d.small,!0))),I(d.rotation)||f.setRotation(d.rotation),Se(t._enableAutoSwitchWhenRecapturing)&&(f.enableAutoSwitchWhenRecapturing=t._enableAutoSwitchWhenRecapturing)),f.once("first-video-frame",v=>{t.emit(F.FIRST_VIDEO_FRAME,W(x({},v),{streamType:bt(v.streamType)}))}),f.on("5",v=>{t.emit(F.ERROR,new j({code:G.DEVICE_ERROR,extraCode:5308,messageParams:{error:v}}))}),f.on("2",v=>{t.emit(F.DEVICE_CHANGED,{type:"camera",action:"active",device:v})}),f.on("4",v=>{let y;v.error&&(y=j.convertFrom(v.error)),t.emit(F.PUBLISH_STATE_CHANGED,W(x({},v),{error:y}))}),f.on("6",()=>{}),t._listenOutputTrackChanged(f),T.customSource&&Xr(T.customSource,t._room)?(f.setOutputMediaStreamTrack(T.customSource),d&&d.qosPreference&&f.setContentHint(Rs(d.qosPreference)),p=!1):p?yield f.capture(T):(r=f.manager)==null||r.changeInput(f),I(c)||(yield f.setMute(c)),Wt(f,f).add("player-state-changed",v=>{t.emit(F.VIDEO_PLAY_STATE_CHANGED,W(x({},v),{userId:"",streamType:"main"}))}).add("video-size-changed",v=>{t.emit(F.VIDEO_SIZE_CHANGED,W(x({},v),{streamType:bt(v.streamType)}))}),m){let v=t._localScreenTrack&&((n=t._localScreenConfig)==null?void 0:n.publish)&&t._localScreenConfig.streamType==="main";t._room.isJoined?!v||h?(t._room.publish(f).catch(()=>{}),((s=t._localScreenConfig)==null?void 0:s.streamType)==="main"&&(t._localScreenConfig.publish=!1)):(m=!1,t._log.warn("main stream is already published, local video track will not publish")):v&&(m=!1)}t._localVideoTrack=f,t._room.capturedLocalMainVideoTrack=f,t._localVideoConfig=W(x({},i),{view:a,publish:m,capture:p}),yield t._updateVideoPlayOption({view:a,playOption:E,track:f})})()})}updateLocalVideo(t){return g(this,null,function*(){var i,r,n,s,a,o,l,c;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:d,publish:h=!0,mute:m,capture:p,option:f,forcePublish:T=!1}=t,E=h||T,v=p,y={};if(!this._localVideoConfig.capture&&Xr((i=this.localVideoTrack)==null?void 0:i.outMediaTrack,this._room)&&(f!=null&&f.cameraId||f!=null&&f.videoTrack)&&this._localVideoTrack.outMediaTrack!==(f==null?void 0:f.videoTrack)&&(v=!0),this._localVideoConfig.capture)v!==!1?f!=null&&f.cameraId?yield this._localVideoTrack.switchDevice(f==null?void 0:f.cameraId):I(f==null?void 0:f.useFrontCamera)?I(f==null?void 0:f.videoTrack)||(Xr(f==null?void 0:f.videoTrack,this._room)&&(f==null?void 0:f.videoTrack)!==((r=this.localVideoTrack)==null?void 0:r.outMediaTrack)?(yield this._localVideoTrack.setOutputMediaStreamTrack(f==null?void 0:f.videoTrack),this._localVideoTrack.setContentHint(Rs(f.qosPreference))):yield this._localVideoTrack.setInputMediaStreamTrack(f==null?void 0:f.videoTrack)):yield this._localVideoTrack.switchDevice(f!=null&&f.useFrontCamera?_.FACING_MODE_USER:_.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(v){let D={};D.deviceId=(f==null?void 0:f.cameraId)||((n=this._localVideoConfig.option)==null?void 0:n.cameraId),D.facingMode=f!=null&&f.useFrontCamera||(s=this._localVideoConfig.option)!=null&&s.useFrontCamera?_.FACING_MODE_USER:_.FACING_MODE_ENVIRONMENT,D.customSource=(f==null?void 0:f.videoTrack)||(D.deviceId||Xr((a=this.localVideoTrack)==null?void 0:a.outMediaTrack,this._room)||(o=this._localVideoConfig.option)==null?void 0:o.videoTrack),yield this._localVideoTrack.capture(D)}f&&(I(f.profile)||(he(f.profile)?Oi[f.profile]&&this._localVideoTrack.setProfile(Oi[f.profile]):this._localVideoTrack.setProfile(f.profile),(!f.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(f.cameraId||f.useFrontCamera?_.FACING_MODE_USER:_.FACING_MODE_ENVIRONMENT))&&(yield this._localVideoTrack.applyProfile())),I(f.fillMode)||(y.objectFit=f.fillMode),I(f.mirror)||(y.mirror=f.mirror),I(f.rotation)||this._localVideoTrack.setRotation(f.rotation),f.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Rs(f.qosPreference)),I(f.small)||(Se(f.small)&&!f.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(yu(f.small,!0)))),this._room.isJoined&&I(E)&&this._localVideoConfig.publish&&v&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((E??this._localVideoConfig.publish)||T?this._localScreenTrack&&((l=this._localScreenConfig)!=null&&l.publish)&&this._localScreenConfig.streamType==="main"&&!T?(E=!1,this._log.warn("main stream is already published, local video track will not publish")):(this._room.publish(this._localVideoTrack).catch(()=>{}),((c=this._localScreenConfig)==null?void 0:c.streamType)==="main"&&(this._localScreenConfig.publish=!1)):this._room.unpublish(this._localVideoTrack).catch(()=>{})),I(m)||(yield this._localVideoTrack.setMute(m)),yield this._updateVideoPlayOption({view:d,playOption:y,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Li(this._localVideoConfig,W(x({},t),{publish:E,capture:v}))})}stopLocalVideo(){return g(this,null,function*(){var t;this._localVideoTrack&&(this._room.isJoined&&(t=this._localVideoConfig)!=null&&t.publish&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),mt(this._localVideoTrack),this._localVideoTrack=null,delete this._room.capturedLocalMainVideoTrack,this._localVideoConfig=null)})}startScreenShare(){return g(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,s;if(t._localScreenTrack)return void t._log.warn("screen share is already started");let{view:a=null,publish:o=!0,muteSystemAudio:l,option:c}=i,d=o,h=new hn(t._room.videoManager);h.on("4",E=>{let v;E.error&&(v=j.convertFrom(E.error)),t.emit(F.PUBLISH_STATE_CHANGED,W(x({},E),{error:v}))}),h.once("first-video-frame",E=>{t.emit(F.FIRST_VIDEO_FRAME,W(x({},E),{streamType:bt(E.streamType)}))}),t._listenOutputTrackChanged(h),i.streamType==="main"&&(h.mediaType=4);let m=null,p={},f={};c&&(I(c.profile)||(he(c.profile)?up[c.profile]&&h.setProfile(up[c.profile]):h.setProfile(c.profile)),c.systemAudio&&(p.systemAudio=!0,p.echoCancellation=c.echoCancellation,p.noiseSuppression=c.noiseSuppression,p.autoGainControl=c.autoGainControl),I(c.fillMode)||(f.objectFit=c.fillMode),c.videoTrack&&(p.videoTrack=c.videoTrack),c.audioTrack&&(p.audioTrack=c.audioTrack),c.captureElement&&(p.captureElement=c.captureElement),c.preferDisplaySurface&&(p.preferDisplaySurface=c.preferDisplaySurface),c.selfBrowserSurface&&(p.selfBrowserSurface=c.selfBrowserSurface),c.qosPreference&&(p.contentHint=Rs(c.qosPreference)));let T=yield h.capture(p);if(h.mediaTrack.addEventListener(_.ENDED,()=>{t._stopScreenShare(),t.emit(F.SCREEN_SHARE_STOPPED)}),T.getAudioTracks()[0]){m=new _u(t._room.audioManager);let E=T.getAudioTracks()[0];(r=i.option)!=null&&r.systemAudio&&!((n=i.option)!=null&&n.audioTrack)&&(m.sourceTrack=E),yield m.setInputMediaStreamTrack(E),Se(l)&&m.mediaTrack&&(m.mediaTrack.enabled=!l),t._speakerId&&m.setAudioOutput(t._speakerId)}if(Wt(h,h).add("player-state-changed",E=>{t.emit(F.VIDEO_PLAY_STATE_CHANGED,W(x({},E),{userId:"",streamType:"sub"}))}),d){let E=t._localVideoTrack&&((s=t._localVideoConfig)==null?void 0:s.publish),v=!(i.streamType==="main"&&E);t._room.isJoined?(v?t._room.publish(h).catch(()=>{}):(d=!1,t._log.warn("main stream is already published, screen share main will not publish")),m&&(t._checkScreenAudioEchoCancellation(h,m),t._room.publish(m).catch(()=>{}))):v||(d=!1)}t._localScreenTrack=h,t._room.capturedLocalAuxVideoTrack=h,t._localScreenAudioTrack=m,t._localScreenConfig=W(x({},i),{view:a,publish:d}),yield t._updateVideoPlayOption({view:a,playOption:f,track:h})})()})}updateScreenShare(t){return g(this,null,function*(){var i,r;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:n,publish:s,muteSystemAudio:a,option:o}=t,l=s,c={};if(o){if(I(o.fillMode)||(c.objectFit=o.fillMode),o.qosPreference){let d=Rs(o.qosPreference);this._localScreenTrack.setContentHint(d)}o.videoTrack&&this._localScreenTrack.setInputMediaStreamTrack(o.videoTrack),o.audioTrack&&this._localScreenAudioTrack&&this._localScreenAudioTrack.setInputMediaStreamTrack(o.audioTrack)}if(this._room.isJoined&&!I(l)){if(l&&!this._localScreenConfig.publish){let d=this._localVideoTrack&&((i=this._localVideoConfig)==null?void 0:i.publish);this._localScreenConfig.streamType==="main"&&d?(l=!1,this._log.warn("main stream is already published, screen share main will not publish")):this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})}if(this._localScreenConfig.publish&&!l){let d=[this._localScreenTrack];this._localScreenAudioTrack&&d.push(this._localScreenAudioTrack),d.forEach(h=>this._room.unpublish(h).catch(()=>{}))}}(r=this._localScreenAudioTrack)!=null&&r.mediaTrack&&Se(a)&&(this._localScreenAudioTrack.mediaTrack.enabled=!a),yield this._updateVideoPlayOption({view:n,playOption:c,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Li(this._localScreenConfig,W(x({},t),{publish:l}))})}stopScreenShare(){return g(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(t){return g(this,null,function*(){let{view:i,userId:r,streamType:n,option:s}=t,a="".concat(r,"_").concat(n);if(this._remoteVideoConfigMap.has(a))return void this._log.warn("remote video has already started. userId:".concat(r,", streamType:").concat(n));let o=this._room.remotePublishedUserMap.get(r);if(!o)return;let l={},c=n==="main"?o.remoteVideoTrack:o.remoteAuxiliaryTrack,d=this._bindRemoteVideoTrackEvents(c);this._listenOutputTrackChanged(c),s&&(I(s.fillMode)||(l.objectFit=s.fillMode),I(s.mirror)||(l.mirror=s.mirror),I(s.poster)||(l.poster=s.poster),l.canvasRender=s.canvasRender,n==="main"&&!I(s.small)&&(!o.remoteVideoTrack.isSubscribing&&!o.remoteVideoTrack.isSubscribed&&o.remoteVideoTrack.setMediaType(s.small?8:4),this._room.changeType(s.small,c.user)),I(s.draggable)||c.setDraggable(s.draggable)),l.isLiveStream=!!this._playbackQualityList.find(h=>h.userId===r&&h.streamType===n),yield this._room.subscribe(c),yield this._enableVideoDecodeFallback(c,n),yield this._updateVideoPlayOption({view:i,playOption:l,track:c}),this._emitTrackEvent(c),this._remoteVideoConfigMap.set(a,{config:t,handlers:d}),s&&!I(s.receiveWhenViewVisible)&&this._observeView({remoteTrack:c,view:i,receiveWhenViewVisible:s.receiveWhenViewVisible,viewRoot:s==null?void 0:s.viewRoot})})}updateRemoteVideo(t){return g(this,null,function*(){var i,r;let{view:n,userId:s,streamType:a,option:o,mute:l}=t,c="".concat(s,"_").concat(a),d=this._remoteVideoConfigMap.get(c);if(!d||!this._room.remotePublishedUserMap.has(s))return;let h={};o&&(I(o.fillMode)||(h.objectFit=o.fillMode),I(o.mirror)||(h.mirror=o.mirror));let m=null,p=this._room.remotePublishedUserMap.get(s);if(a==="main"&&p!=null&&p.muteState.hasVideo&&(m=p.remoteVideoTrack),a==="sub"&&p!=null&&p.muteState.hasAuxiliary&&(m=p.remoteAuxiliaryTrack),!m)return;let{config:f}=d;if(a==="main"&&o&&!I(o.small)&&this._room.changeType(o.small,m.user),o&&!I(o.draggable)&&m.setDraggable(o.draggable),o&&(Se(o.pictureInPicture)&&(o.pictureInPicture?yield m.player.enterPictureInPicture():yield m.player.exitPictureInPicture()),Se(o.fullScreen)&&(o.fullScreen?yield m.player.enterFullscreen():yield m.player.exitFullscreen())),Se(l)){m.ignoreUpdatePlayingState=!0;let y="ios14 not call (un)subscribe with mute";l?(yield m.player.pause(),be&&Rt===14?this._log.warn(y):yield this.room.unsubscribe(m)):(be&&Rt===14?this._log.warn(y):yield this.room.subscribe(m),yield m.player.resume(!0))}yield this._updateVideoPlayOption({view:n,playOption:h,track:m,prevConfig:f}),Li(f,t);let T=I(o==null?void 0:o.receiveWhenViewVisible)?(i=f.option)==null?void 0:i.receiveWhenViewVisible:o.receiveWhenViewVisible,E=I(n)?f.view:n,v=I(o==null?void 0:o.viewRoot)?(r=f.option)==null?void 0:r.viewRoot:o.viewRoot;this._observeView({remoteTrack:m,view:E,receiveWhenViewVisible:T,viewRoot:v})})}stopRemoteVideo(t){return g(this,null,function*(){return this._stopRemoteVideo(t)})}_stopRemoteVideo(t){let i=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return g(this,null,function*(){let r=[],n=this._room.remotePublishedUserMap.get(t.userId);if(n){let{muteState:s,remoteVideoTrack:a,remoteAuxiliaryTrack:o}=n;t.streamType==="main"&&(a.stop(),s.hasVideo&&r.push(a)),t.streamType==="sub"&&(o.stop(),s.hasAuxiliary&&r.push(o))}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 a=i==="main"?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._unbindRemoteVideoTrackEvents(a,n.handlers)}}this._remoteVideoConfigMap.delete(r)}_bindRemoteVideoTrackEvents(t){let i={onEnterPIP:()=>g(this,null,function*(){yield t.player.enterPIPPromise,this.emit(F.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:bt(t.streamType),userId:t.userId,isPictureInPicture:!0,pictureInPictureWindow:t.player.pipWindow})}),onLeavePIP:()=>{this.emit(F.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:bt(t.streamType),userId:t.userId,isPictureInPicture:!1})},onEnterFullScreen:()=>{this.emit(F.FULL_SCREEN_STATE_CHANGED,{streamType:bt(t.streamType),userId:t.userId,isFullScreen:!0})},onLeaveFullScreen:()=>{this.emit(F.FULL_SCREEN_STATE_CHANGED,{streamType:bt(t.streamType),userId:t.userId,isFullScreen:!1})},onDecodeFailed:()=>{this.emit(F.ERROR,new j({code:G.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))},onVideoSizeChanged:r=>{this.emit(F.VIDEO_SIZE_CHANGED,W(x({},r),{streamType:bt(r.streamType)}))}};return t.player.on(z.ENTER_PICTURE_IN_PICTURE,i.onEnterPIP),t.player.on(z.LEAVE_PICTURE_IN_PICTURE,i.onLeavePIP),t.player.on(z.ENTER_FULL_SCREEN,i.onEnterFullScreen),t.player.on(z.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(z.ENTER_PICTURE_IN_PICTURE,i.onEnterPIP),t.player.off(z.LEAVE_PICTURE_IN_PICTURE,i.onLeavePIP),t.player.off(z.ENTER_FULL_SCREEN,i.onEnterFullScreen),t.player.off(z.LEAVE_FULL_SCREEN,i.onLeaveFullScreen),t.off("decode-failed",i.onDecodeFailed),t.off("video-size-changed",i.onVideoSizeChanged)}muteRemoteAudio(t,i){return g(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!==G.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 g(this,null,function*(){return t.start(i)})}updatePlugin(t,i){return g(this,null,function*(){return t.update(i)})}stopPlugin(t,i){return g(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(F.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{zH.has(t)||this._log.debug("emit ".concat(t," ").concat(JSON.stringify(r)))}catch{}return super.emit(t,...r)}off(t,i,r){var n,s;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&&((s=(n=this._room).unsubscribeDataChannel)==null||s.call(n)),(t===Yi.EVENT.AUDIO_FRAME||t==="*")&&this.listeners(Yi.EVENT.AUDIO_FRAME).length===0){let{getPCMAbortCtrlMap:a}=this.room.audioManager;a.forEach(o=>{o==null||o.abort("off")}),a.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(he(i)?t=i:(t=i.userId,s=i.processed===!0,i.streamType&&(n=i.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.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 a=this._room.remotePublishedUserMap.get(i);a&&(s=r==="main"?a.remoteVideoTrack:a.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 g(this,null,function*(){(yield ln()).forEach(i=>{i.deviceId===t&&(this._setCurrentSpeaker(t),this.emit(F.DEVICE_CHANGED,{type:"speaker",action:"active",device:i}),Ye=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(Pi,"/en/TRTC.html#.setCurrentSpeaker"))})}_startRemoteAudio(t){return this._doStartRemoteAudio(t)}_doStartRemoteAudio(t){return g(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={},a=n.remoteAudioTrack;a.on("decode-failed",o=>{this.emit(F.ERROR,new j({code:G.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId);try{let o=(i=this._remoteAudioVolumeMap.get(r))!=null?i:this._remoteAudioVolumeMap.get("*"),l=le(o)?o:100;s.volume=l,this._remoteAudioConfigMap.set(r,t),yield this._room.subscribe(a),Ie(ye(a,"decode-failed"),pt(ye(a,re.INIT)),ze(()=>{this.startPlugin(L0.Name,{track:a,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:a}),R.emit("115",{userId:r,room:this.room}),a.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:a.outMediaTrack,refId:"ra-".concat(r)})}catch(o){throw this._remoteAudioConfigMap.delete(r),o}this._emitTrackEvent(a)})}_stopRemoteAudio(t){let i=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return g(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)),R.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),Ie(ye(t,"decode-failed"),pt(ye(t,re.INIT)),r_(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:t,config:{codec:"avc1.420028"},fallback:n})}),mu(ye(t,"decode-downgrade-state-changed")),ze(s=>{r=s.state,this.emit(F.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,W(x({},s),{streamType:i,userId:t.userId}))},s=>{t.log.error("fallback",s)},()=>{r==="STARTED"&&t.log.info("fallback complete")})))}_updateVideoPlayOption(t){return g(this,arguments,function(i){let{view:r,playOption:n,track:s,prevConfig:a}=i;return(function*(){if(s.setMirror(n.mirror),I(r)&&a&&a.view&&!yc(n)){let o=xa(a.view);o.length>0&&(yield s.play(o,n))}if(!I(r)){let o=xa(r);o.length>0?yield s.play(o,n):s.stop()}})()})}_updateAudioPlayOption(t){return g(this,arguments,function(i){var r=this;let{playOption:n={},track:s,prevConfig:a}=i;return(function*(){if(!s.isPlayCalled)try{yield s.play(null,n)}catch{}if(I(n.muted)||s.setPlayerMute(n.muted),I(n.volume)||s.setAudioVolume(n.volume/100),s instanceof dn&&s.mediaTrack){let o=n.muted===!1&&!I(n.volume)&&n.volume>0?"add":"remove";r.room.audioManager.updateAudioReference({type:o,audioReference:s.mediaTrack,refId:"em"})}else if(s instanceof Tu){let o=n.muted?0:n.volume;if(I(o))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(F.TRACK,{userId:r,streamType:bt(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(I(r)||I(n))return;let a=this._remoteVideoConfigMap.get("".concat(i.userId,"_").concat(bt(i.streamType)));if(!a)return;let o=a.observer||void 0;if(r===null||Ue(r)&&r.length===0||!n)return o==null||o.disconnect(),void(i.isSubscribed||(this._log.info("_observeView observer disconnect, resubscribe",i.userId,i.strMediaType),this._room.subscribe(i).catch(()=>{})));let l=a.visibleViewMap||new Map,c=-1;(!o||o.root!==s)&&(o==null||o.disconnect(),l.clear(),o=new IntersectionObserver(h=>{h.forEach(m=>{l.set(m.target,m.isIntersecting),i.log.info("view ".concat(m.target.id," is").concat(m.isIntersecting?"":" not"," visible"))}),clearTimeout(c),c=window.setTimeout(()=>{[...l.values()].find(m=>m)?i.isSubscribed||this._room.subscribe(i).catch(()=>{}):i.isSubscribed&&this._room.unsubscribe(i).catch(()=>{})},200)},{root:s}));let d=new Set(xa(r));l.forEach((h,m)=>{d.has(m)||(o.unobserve(m),l.delete(m))}),d.forEach(h=>{l.set(h,!0),o.observe(h)}),o.takeRecords().forEach(h=>{l.set(h.target,h.isIntersecting)}),a.visibleViewMap=l,a.observer=o}_exitRoom(){return g(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return g(this,null,function*(){var t,i;if(this._localScreenTrack){if(this._room.isJoined){let r=[];(t=this._localScreenConfig)!=null&&t.publish&&r.push(this._localScreenTrack),this._localScreenAudioTrack&&r.push(this._localScreenAudioTrack),yield Promise.all(r.map(n=>this._room.unpublish(n).catch(()=>{})))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(((i=this._localScreenAudioTrack.trackSettings)==null?void 0:i.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),mt(this._localScreenTrack),this._localScreenTrack=null,delete this._room.capturedLocalAuxVideoTrack,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(t,i){return g(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(a){this._log.warn("start audioProcessor plugin failed: ",a)}}})}_onLocalTrackCaptured(t){let{track:i}=t;i.kind==="audio"&&(!Ye||po(Ye))&&(this._initActiveSpeaker(),R.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return g(this,null,function*(){if(Ye&&!po(Ye))this.emit(F.DEVICE_CHANGED,{type:"speaker",action:"active",device:Ye});else{let t=yield ln();t[0]&&!po(t[0])?(Ye=t[0],this.emit(F.DEVICE_CHANGED,{type:"speaker",action:"active",device:t[0]})):R.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,a=[s];this._room.autoReceiveAudio&&n.remoteAudioTrack.isAvailable&&a.push(n.remoteAudioTrack),this._room.subscribe(...a).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:W(x({seiPayloadType:243},i),{small:!((r=this._localVideoTrack)==null||!r.small)})}),w.addCount({key:5e5,useUV:!0}))}sendCustomMessage(t){var i,r;(r=(i=this._room).sendCustomMessage)==null||r.call(i,t),w.addCount({key:500001,useUV:!0})}callExperimentalAPI(t,i){return g(this,null,function*(){return c4.call(t,x({trtcInstance:this},i))})}static setLogLevel(t,i){P.setLogLevel(t),I(i)||(i?P.enableUploadLog():P.disableUploadLog())}static isSupported(){return Sf(Yi.frameWorkType)}static getPermissions(t){return g(this,arguments,function(i){let{request:r=!0,types:n=["camera","microphone"]}=i;return(function*(){r&&(yield Du.request(n).catch(o=>{var l;return P.error("getPermissions request failed, error: ".concat((l=o==null?void 0:o.message)!=null?l:o))}));let[s,a]=yield Promise.all([Du.get("camera"),Du.get("microphone")]);return{camera:s,microphone:a}})()})}static getCameraList(){return Wi(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static getMicrophoneList(){return Hi(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static getSpeakerList(){return ln(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static setCurrentSpeaker(t){return g(this,null,function*(){if(Oe&&(t===bo.SPEAKER||t===bo.HEADSET)){let i=yield Yi.getMicrophoneList(),r="";return i.forEach(n=>{n.label===t&&(r=n.deviceId)}),r?void Po.forEach(n=>g(null,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:r}}))})):void 0}(yield ln()).forEach(i=>{i.deviceId===t&&(Po.forEach(r=>{r._setCurrentSpeaker(t),r.emit(F.DEVICE_CHANGED,{type:"speaker",action:"active",device:i})}),Ye=i)})})}static _addKVStat(t){let{type:i,key:r,value:n,base:s,useUV:a,version:o,max:l}=t;switch(o&&(Qa.version=o),i){case"count":Qa.addCount({key:r,useUV:a});break;case"enum":Qa.addEnum({key:r,value:n,useUV:a});break;case"number":Qa.addNumber({key:r,value:n,split:s,max:l})}}get localVideoTrack(){return this._localVideoTrack}get localScreenTrack(){return this._localScreenTrack}get localScreenAudioTrack(){return this._localScreenAudioTrack}};u(Q,"VERSION",w0),u(Q,"_loggerManager",P),u(Q,"EVENT",F),u(Q,"ERROR_CODE",G),u(Q,"TYPE",bo),u(Q,"frameWorkType",30),M([Ae({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?e==null?void 0:e.assetsPath:"default"}})})],Q.prototype,"use"),M([at(qe.TRTC.enterRoom),fn("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}),ge(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),Ae()],Q.prototype,"enterRoom"),M([Ae()],Q.prototype,"exitRoom"),M([at(qe.TRTC.switchRoom),Ae(),fo()],Q.prototype,"switchRoom"),M([at(qe.TRTC.switchRole),ks("room",{merge:(e,t)=>t}),Ae()],Q.prototype,"switchRole"),M([Ae()],Q.prototype,"destroy"),M([at(qe.TRTC.startLocalAudio),fn("audio",(e,t)=>{let[i]=e,[r]=t;var n,s;return((n=i==null?void 0:i.option)==null?void 0:n.microphoneId)===((s=r==null?void 0:r.option)==null?void 0:s.microphoneId)}),Ae()],Q.prototype,"startLocalAudio"),M([at(qe.TRTC.updateLocalAudio),ks("audio",{debounce:{delay:200,getKey:()=>"".concat(x0,"-localAudio"),isNeedToDebounce:e=>{var t;return!I((t=e.option)==null?void 0:t.captureVolume)}}}),Ae()],Q.prototype,"updateLocalAudio"),M([_n("audio"),Ae()],Q.prototype,"stopLocalAudio"),M([at(qe.TRTC.startLocalVideo),fn("video",(e,t)=>{let[i]=e,[r]=t;var n,s;return((n=i==null?void 0:i.option)==null?void 0:n.cameraId)===((s=r==null?void 0:r.option)==null?void 0:s.cameraId)}),Ae()],Q.prototype,"startLocalVideo"),M([at(qe.TRTC.updateLocalVideo),ks("video"),Ae()],Q.prototype,"updateLocalVideo"),M([_n("video"),Ae()],Q.prototype,"stopLocalVideo"),M([at(qe.TRTC.startScreenShare),fn("screen",()=>!0),Ae()],Q.prototype,"startScreenShare"),M([at(qe.TRTC.updateScreenShare),ks("screen"),Ae()],Q.prototype,"updateScreenShare"),M([Ae()],Q.prototype,"stopScreenShare"),M([at(qe.TRTC.startRemoteVideo),fn(e=>"v".concat(e.userId).concat(e.streamType),()=>!0),Ae({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Q.prototype,"startRemoteVideo"),M([at(qe.TRTC.updateRemoteVideo),ks(e=>"v".concat(e.userId).concat(e.streamType)),Ae({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Q.prototype,"updateRemoteVideo"),M([at(qe.TRTC.stopRemoteVideo),ge(e=>function(t){return g(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)})}),Ae({getRemoteId:e=>"".concat(e.userId,"_").concat(e.streamType)})],Q.prototype,"stopRemoteVideo"),M([_n(e=>"v".concat(e.userId).concat(e.streamType))],Q.prototype,"_stopRemoteVideo"),M([at(...qe.TRTC.muteRemoteAudio),Ae({getRemoteId:e=>e})],Q.prototype,"muteRemoteAudio"),M([N0(...qe.TRTC.setRemoteAudioVolume),(function(e,t){return ge((i,r)=>function(){for(var n=arguments.length,s=new Array(n),a=0;a<n;a++)s[a]=arguments[a];let o=Ds.get(this);o||(o=new Map,Ds.set(this,o));let l=t(...s),c=o.get(l);if(!c||c<=0){i.apply(this,s);let d=setTimeout(()=>{var h;(h=Ds.get(this))==null||h.delete(l)},e);o.set(l,d)}else{clearTimeout(c);let d=window.setTimeout(()=>{var h;i.apply(this,s),(h=Ds.get(this))==null||h.delete(l)},e);o.set(l,d)}})})(200,e=>e),Ae({getRemoteId:e=>e})],Q.prototype,"setRemoteAudioVolume"),M([T_("start"),cn(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),fn((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),Ae({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>SC[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],Q.prototype,"startPlugin"),M([T_("update"),ks((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t),{merge:(e,t)=>(Li(e[1],t[1]),e)}),Ae({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>IC[e.getName()]})],Q.prototype,"updatePlugin"),M([T_("stop"),_n((e,t)=>{if(e.disableRandomCall)return null;let i=e.getGroup(t),r=e.getAlias();return i==="*"?new RegExp("".concat(r,".*")):r+i}),Ae({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>AC[e.getName()]})],Q.prototype,"stopPlugin"),M([N0(...qe.TRTC.enableAudioVolumeEvaluation)],Q.prototype,"enableAudioVolumeEvaluation"),M([Ae()],Q.prototype,"getVideoSnapshot"),M([Ae()],Q.prototype,"_setCurrentSpeaker"),M([fn(e=>"a".concat(e.userId),()=>!0)],Q.prototype,"_startRemoteAudio"),M([ge(e=>function(t){return g(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(i=>this._stopRemoteAudio(W(x({},t),{userId:i.userId})).catch(()=>{}))):e.call(this,t)})}),_n(e=>"a".concat(e.userId))],Q.prototype,"_stopRemoteAudio"),M([_n("room")],Q.prototype,"_exitRoom"),M([_n("screen")],Q.prototype,"_stopScreenShare"),M([at(...qe.TRTC.sendSEIMessage),e0({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}})],Q.prototype,"sendSEIMessage"),M([at(qe.TRTC.sendCustomMessage),e0({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],Q.prototype,"sendCustomMessage"),M([Ae()],Q.prototype,"callExperimentalAPI"),M([gn()],Q,"create"),M([at(qe.TRTC.create)],Q,"_create"),M([gn()],Q,"setLogLevel"),M([gn()],Q,"isSupported"),M([gn(),Ae()],Q,"getPermissions"),M([gn()],Q,"getCameraList"),M([gn()],Q,"getMicrophoneList"),M([gn()],Q,"getSpeakerList");var Oo=Q,h4=class{constructor(){u(this,"_set",new Set),R.on(b.LEAVE_START,this.delete,this),R.on(b.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,role:s}=e;return n.scene!=="rtc"&&s===21&&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 m4(){return g(this,null,function*(){let e,t;try{let p=yield Hi();e=p&&p.length}catch{}try{let p=yield Wi();t=p&&p.length}catch{}let i={microphone:e,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:n,isH264DecodeSupported:s,isVp8DecodeSupported:a,isH265EncodeSupported:o,isH265DecodeSupported:l}=this.checkSystemResult.detail,c=_s.basis(),d={webRTC:c.isWebRTCSupported,getUserMedia:c.isGetUserMediaSupported,webSocket:c.isWebSocketsSupported,screenShare:c.isScreenShareSupported,webAudio:c.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:n,vp8Decode:a,h265Encode:o,h265Decode:l},h={browser:c.browser,os:c.os,trtc:d,devices:i},m={isWebCodecSupported:c.isWebCodecSupported,isMediaSessionSupported:c.isMediaSessionSupported,isWebTransportSupported:c.isWebTransportSupported};ue.uploadEvent({log:"trtcstats-".concat(JSON.stringify(h)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(h))),ue.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(m)),userId:this.userId}),zC()})}var p4=Ge(it()),U0="1",k_="2",Mo="3",f4="4",wu="5",_4="6",Nu="7",V0="8",si={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},g4=[si.UPDATE_REMOTE_MUTE_STAT,si.UPLINK_NETWORK_STATS,si.USER_LIST_RES,si.MUTE_RESULT,si.SERVER_FIRST_PACKAGE_RECEIVED,si.RECEIVE_CUSTOM_MSG,si.UPDATE_NETWORK_TIME_RESULT],X={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"},F0="publish_change",T4="join",E4="leave",v4="quality_report",B0="mute_uplink",H0="publish",D_="publish_state_change",Pu="unpublish",W0="subscribe",w_="unsubscribe",N_="subscribe_change",y4="start_publishing",S4="stop_publishing",I4="start_push_user_cdn",A4="stop_push_user_cdn",R4="start_mcu_mix",C4="stop_mcu_mix",b4="start_publish_cdn_stream",k4="update_publish_cdn_stream",D4="stop_publish_cdn_stream",w4="get_user_list",N4="change_role",P_="update_constraint_config",P4="rebuild_pc",O4="join/v2",G0="publish/v2",j0="subscribe/v3",M4="ability_status_report",L4="reconnect",x4="channel_msg",U4="switch_room",V4="update_network_time",F4=new Set([H0,F0,D_,Pu,W0,N_,w_,G0,j0]),Ou=new Set,B4=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],H4=0,z0=class extends p4.default{constructor(e){var t,i,r;super(),u(this,"room"),u(this,"sdkAppId"),u(this,"userId"),u(this,"userSig"),u(this,"url"),u(this,"backupUrl"),u(this,"destroyed",!1),u(this,"_socketInUse"),u(this,"_socket"),u(this,"_backupSocket"),u(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[],reportToken:void 0}),u(this,"_currentState","DISCONNECTED"),u(this,"_isReconnecting",!1),u(this,"_seq",0),u(this,"_log"),u(this,"_lastMessageTime",-1),u(this,"_connectStartTime",-1),u(this,"_stopConnectRetry"),u(this,"_isFirstConnect",!0),u(this,"bytesSent",0),u(this,"bytesReceived",0),u(this,"keepAlive",!1),u(this,"signalDomainWhenUnifiedProxy"),u(this,"stopKeepAliveTimeout"),u(this,"stopPreconnectTimeout"),u(this,"rtt",0),u(this,"hasPreconnect",!1),u(this,"_preconnectConfig"),this.room=e.room,this.sdkAppId=e.sdkAppId,this.userId=e.userId,this.userSig=e.userSig,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,this.hasPreconnect=e.preconnect||!1;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-Ou.size>0&&this.room.enableSPC&&(this.keepAlive=!0,Ou.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=P.createLogger({parent:this.room.getLogger(),id:"ws".concat(++H4),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))),this.hasPreconnect&&(e+="&prelink=1");let t=new URLSearchParams(location.search);return B4.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 g(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=J();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 Ma(i),e.unbindAndCloseSocket(e._socketInUse===e._socket?_.BACKUP:_.MAIN),e._isFirstConnect&&(w.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((a,o)=>{n.onclose=o,n.onerror=o,n.onopen=()=>a(n),i&&(s=setTimeout(()=>{this.unbindAndCloseSocket(r?_.MAIN:_.BACKUP),o(new O({code:C.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===_.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&&e.code!==4013)&&this.startReconnection(),this.hasPreconnect&&e.code===4013&&this.room.clearNetworkQuality(),this.room.isJoining&&this.emit(wu,new O({code:C.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(_.MAIN),this.unbindAndCloseSocket(_.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(wu,new O({code:C.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;let{isOnline:t}=this;this._lastMessageTime=Date.now(),t||this.emit(V0),this.bytesReceived+=Ic(e.data);let i=JSON.parse(e.data),{cmd:r,data:n}=i,s=Object.values(si),a=Object.keys(si)[s.indexOf(r)],o=X[a]||r;switch(g4.includes(r)||(this._log.debug("received ".concat(r," msg: ").concat(e.data)),o&&this._log.info("Received event: [ ".concat(o," ]"))),r){case si.CHANNEL_SETUP_RESULT:if(i.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&lA(n.svrTime-new Date().getTime()),this._log.info("ChannelSetup Success ".concat(J()-this._connectStartTime)),w.addSuccessEvent({key:521701,cost:J()-this._connectStartTime}),this._connectStartTime=-1,this.room.firewallDetector.resetTimeoutCount(),this.emit(U0,{signalInfo:this._signalInfo});else{let l=new O({code:C.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:i.code,message:Y({key:K.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:i.code,errorMsg:i.message}})});this._log.error("".concat(i.code,", ").concat(i.message)),this.close(),w.addFailedEvent({key:521701,error:l}),this.emit(wu,l)}break;case si.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(o,{data:i});break;default:this.emit(String(o),{data:i})}}reGetSignalChannelUrl(){return g(this,null,function*(){try{if(!this.room.joinParams)return;ni(!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?_.MAIN:_.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return g(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:L4,data:{roomId:e,useStringRoomId:t,relayInnerIp:r,relayOuterIp:i,relayPort:n},responseCommand:X.CHANNEL_RECONNECT_RESULT});s.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),w.addSuccessEvent({key:521702,cost:J()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(w.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),F4.has(e)&&this._log.info("send",e,t),this.bytesSent+=Ic(r),i.seq}}sendWaitForResponse(e){let{command:t,data:i,timeout:r=5e3,responseCommand:n,commandDesc:s,enableLog:a=!0,addReceiveTime:o=!1}=e;return new Promise((l,c)=>{let d=()=>{clearTimeout(h),c(new O({code:C.API_CALL_ABORTED,message:"".concat(t," aborted due to connection closed")}))};this.once(Nu,d);let h=setTimeout(()=>{this.off(n,m),this.off(Nu,d);let f=new O({code:C.API_CALL_TIMEOUT,message:Y({key:K.API_CALL_TIMEOUT,data:{commandDesc:s,command:t}})});a&&this._log.warn(f),c(f)},r),m=f=>{f.data.seq===p&&(clearTimeout(h),this.off(n,m),this.off(Nu,d),o&&(f.data.receiveTime=Date.now()),l(f))};this.on(n,m);let p=this.send(t,i)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:i,retries:r=0,retryTimeout:n=0}=e;return Fa({retryFunction:this.sendWaitForResponse,onError:s=>{let{retry:a,reject:o,error:l}=s;!this.room.isJoined||this.destroyed||l.code===C.API_CALL_ABORTED?o(l):this.isOnline?a():(this._log.warn("retry ".concat(i," when connected")),this.once(V0,a))},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),clearTimeout(this.stopPreconnectTimeout),Ou.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(_.MAIN),this.unbindAndCloseSocket(_.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(Nu)}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(X.JOIN_ROOM_RESULT,t)},1e3*e);let t=i=>{i.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(X.JOIN_ROOM_RESULT,t))};this.on(X.JOIN_ROOM_RESULT,t)}}stopPreconnectIn(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:300;if(this.keepAlive)return;this._log.info("stopPreconnect in ".concat(e,"s")),this.stopPreconnectTimeout=setTimeout(()=>{this._log.info("close preconnect due to not used in ".concat(e,"s")),this.close(),this.room.clearNetworkQuality(),this.off(X.JOIN_ROOM_RESULT,t)},1e3*e);let t=i=>{i.data.code===0&&(this._log.info("stopPreconnect clear timeout"),clearTimeout(this.stopPreconnectTimeout),this.off(X.JOIN_ROOM_RESULT,t))};this.on(X.JOIN_ROOM_RESULT,t)}markPreconnectConnected(e){this._preconnectConfig=W(x({},e),{linkedTime:Date.now()})}isPreconnectValid(e,t,i){return!(!this.hasPreconnect||!this._preconnectConfig)&&(e!==this._preconnectConfig.sdkAppId||t!==this._preconnectConfig.userId||i!==this._preconnectConfig.userSig?(this._log.warn("preconnect params not match"),!1):!!this.isConnected||(this._log.warn("preconnect is not connected"),!1))}consumePreconnect(){this.hasPreconnect=!1,this._preconnectConfig=void 0}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(k_,t),this._currentState=e,e==="CONNECTED"?this.emit(Mo):e==="DISCONNECTED"&&this.emit(_4)}};M([vr({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&(this._isFirstConnect&&(w.addFailedEvent({key:521720,error:e}),this._isFirstConnect=!1),this.room.firewallDetector.increaseTimeoutCount(),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())}})],z0.prototype,"connect");var W4=Ge(it()),J0=!1,Ki=class{constructor(e){u(this,"userId"),u(this,"tinyId"),u(this,"_sdpSemantics"),u(this,"_isUplink"),u(this,"_room"),u(this,"_log"),u(this,"_signalChannel"),u(this,"_isErrorObserved",!1),u(this,"_waitForPeerConnectionConnectedPromise"),u(this,"_waitForPeerConnectionConnectedPromiseReject",null),u(this,"_peerConnection",null),u(this,"_emitter",new W4.default),u(this,"_currentState","DISCONNECTED"),u(this,"_isReconnecting",!1),u(this,"_reconnectionCount",0),u(this,"_reconnectionTimer",-1),u(this,"_isFirstConnection",!0),u(this,"_prevTime",-1),u(this,"_localAddress"),u(this,"_remoteAddress"),u(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=J())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,w.addSuccessEvent({key:521705,cost:Math.min(J()-this._prevTime,3e4)})):this._isReconnecting&&w.addSuccessEvent({key:521706,cost:J()-this._prevTime}),this._prevTime=-1}catch(e){throw this._isFirstConnection?(this._isFirstConnection=!1,w.addFailedEvent({key:521705,error:e})):this._isReconnecting&&this._reconnectionCount>=3&&w.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()}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 O({code:C.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return hr;let e=null;if(this._isUplink){if(!$a()||this._peerConnection.getSenders().length===0)return hr;e=this._peerConnection.getSenders()[0].transport}else{if(!Jc()||this._peerConnection.getReceivers().length===0)return hr;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:hr}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===Be.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===Be.FAILED||e.target.connectionState===Be.CLOSED){let r="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(i),n=new O({message:r,code:C.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(e.target.connectionState===Be.CONNECTED||e.target.connectionState===Be.COMPLETED)&&(this.logSelectedCandidate(),ue.logSuccessEvent({userId:this._room.userId,eventType:Qe.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(e){return e!==this._currentState&&(e==="CONNECTED"&&(this._room.firewallDetector.resetTimeoutCount(),J0=!0),R.emit(b.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 g(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[,t]of e)if(Za(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=a=>{a.state==="CONNECTED"&&(clearTimeout(s),n(),e())},r=a=>{let{room:o}=a;o===this._room&&(clearTimeout(s),n(),t(new O({code:C.API_CALL_ABORTED,message:Y({key:K.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{R.off(b.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",i,this)},s=setTimeout(()=>{n();let a=new O({code:C.API_CALL_TIMEOUT,message:"connection timeout"});this._room.firewallDetector.increaseTimeoutCount(),t(a)},_p);R.on(b.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(Mo,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=ss()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let e=new O({code:this._isUplink?C.UPLINK_RECONNECTION_FAILED:C.DOWNLINK_RECONNECTION_FAILED,message:Y({key:this._isUplink?K.UPLINK_RECONNECTION_FAILED:K.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(Mo,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)}};M([Sr(521712,!1)],Ki.prototype,"setOffer"),M([Sr(521713,!1)],Ki.prototype,"setAnswer");var K0=Ge(nA()),ot=function(e){return K0.default.parse(e)},Cr=function(e){return K0.default.write(e)};function O_(e){return Object.keys(e).filter(t=>e[t])}var Mu=class Rk extends Ki{constructor(t){super(W(x({},t),{isUplink:!1})),u(this,"_flag",0),u(this,"isRobot",!1),u(this,"role","anchor"),u(this,"remoteAudioTrack"),u(this,"remoteVideoTrack"),u(this,"remoteAuxiliaryTrack"),u(this,"avPlayerStateSyncManager"),u(this,"ssrc",{audio:0,video:0,auxiliary:0}),u(this,"_isSDPExchanging",!1),u(this,"_videoCodec"),u(this,"fromType"),this.flag=t.flag,this.isRobot=t.isRobot||!1,this.remoteAudioTrack=t.remoteAudioTrack||new Tu(this._room,this),this.remoteVideoTrack=t.remoteVideoTrack||new Co(this._room,this),this.remoteAuxiliaryTrack=t.remoteAuxiliaryTrack||new Zb(this._room,this),this.avPlayerStateSyncManager=new f_({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 Yr(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===_.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===mc?_.MAIN:_.AUXILIARY;this._log.debug("ontrack ".concat(n," ").concat(r.kind));let s=_.AUDIO;r.kind===_.VIDEO&&(s=n===_.MAIN?_.VIDEO:_.AUXILIARY);let a=this.remoteAudioTrack;s===_.VIDEO?a=this.remoteVideoTrack:s===_.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(r)}addRRTRLine(t){let i=t.split(`\r
|
||
`),r=new Map;i.forEach((s,a)=>{/^a=rtcp-fb:/.test(s)&&i[a+1]&&!/^a=rtcp-fb:/.test(i[a+1])&&r.set(a+1,"".concat(s.match(/^a=rtcp-fb:\d+/)[0]," rrtr"))});let n=[...r];for(let s=0;s<n.length;s++){let[a,o]=n[s];i.splice(a+s,0,o)}return i.join(`\r
|
||
`)}addSPSDescription(t){let i=ot(t);return i.media.forEach(r=>{r.type===_.VIDEO&&r.fmtp.forEach(n=>{n.config+=";sps-pps-idr-in-keyframe=1"})}),Cr(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=ot(t);return r.media.forEach(n=>{n.ext&&(n.ext=n.ext.filter(s=>!i.includes(s.uri)))}),Cr(r)}isSubscriptionStateNotChanged(t){return JSON.stringify(t)===JSON.stringify(this.subscribeState)}subscribe(t,i){return g(this,null,function*(){var r,n;try{if((((r=this._peerConnection)==null?void 0:r.connectionState)===Be.NEW||((n=this._peerConnection)==null?void 0:n.connectionState)===Be.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(a=>a===!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 O({code:C.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):s}})}unsubscribe(t){return g(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 a=x({},r.subscribeState);n.forEach(l=>{switch(l.mediaType){case 1:a.audio=!1;break;case 4:a.video=!1;break;case 8:a.smallVideo=!1;break;case 2:a.auxiliary=!1}});let o="subscribe_change";Object.values(a).find(l=>l===!0)||(o="unsubscribe"),r._log.info("".concat(o==="unsubscribe"?o:"subscribe"," ").concat(s," [").concat(O_(a),"]")),yield r.sendSubscription(o,a),o==="unsubscribe"&&(r.closePeerConnection(),r.emitConnectionStateChangedEvent("DISCONNECTED"))})()})}unsubscribeDataChannel(){return g(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=w_,s=X.UNSUBSCRIBE_RESULT;return t==="subscribe_change"&&(r={audio:i.audio,bigVideo:i.video,auxVideo:i.auxiliary,smallVideo:i.smallVideo,srcTinyId:this.tinyId},n=N_,s=X.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:n,data:r,responseCommand:s,timeout:1e4}).then(a=>{let{data:o}=a;if(o.code!==0){let l=new O({code:o.code,message:Y({key:K.ERROR_MESSAGE,data:{type:t,message:o.message}})});throw this._log.error(l),l}})}connect(){return g(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 g(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:W0,commandDesc:"exchange sdp",data:n,responseCommand:X.SUBSCRIBE_RESULT,timeout:bA});if(!this._peerConnection){let a=new O({code:C.INVALID_OPERATION,message:Y({key:K.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(s),this._isSDPExchanging=!1}catch(i){throw this._isSDPExchanging=!1,i}})}createOffer(){return g(this,null,function*(){let t={voiceActivityDetection:!1};ri()&&this._sdpSemantics===Aa?(this._peerConnection.addTransceiver(_.AUDIO,{direction:oe.RECVONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:oe.RECVONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:oe.RECVONLY})):(t.offerToReceiveAudio=!0,t.offerToReceiveVideo=!0);let i=yield this._peerConnection.createOffer(t);if(i.sdp){let{isH264DecodeSupported:r}=yield yf();r||(this._log.warn("remove h264 desc from sdp"),i.sdp=(function(n){let s=ot(n);return s.media.forEach(a=>{var o,l;if(a.type===_.VIDEO){let c=new Set;a.rtp.forEach(h=>{let{payload:m,codec:p}=h;return p==="H264"&&c.add(m)}),a.fmtp.forEach(h=>{let{payload:m,config:p}=h,f=p.match(/apt=(\d+)/);f&&f[1]&&c.has(Number(f[1]))&&c.add(m)});let d=h=>{let{payload:m}=h;return!c.has(m)};a.rtp=a.rtp.filter(d),a.rtcpFb=(o=a.rtcpFb)==null?void 0:o.filter(d),a.fmtp=a.fmtp.filter(d),a.payloads=(l=a.payloads)==null?void 0:l.split(" ").filter(h=>!c.has(Number(h))).join(" ")}}),Cr(s)})(i.sdp)),i.sdp=this.addRRTRLine(i.sdp),i.sdp=this.addSPSDescription(i.sdp),i.sdp=(function(n){let s=ot(n);return s.media.forEach(a=>{a.type===_.AUDIO&&a.fmtp.forEach(o=>{o.config+=";sprop-stereo=1;stereo=1"})}),Cr(s)})(i.sdp),this._sdpSemantics===Aa&&(i.sdp=this.removeSDESDescription(i.sdp))}yield this.setOffer(i)})}onSubscribeResult(t){return g(this,null,function*(){let{code:i,message:r=""}=t&&t.data||{},{type:n,sdp:s}=t&&t.data&&t.data.data||{};if(i===fc)throw new O({code:C.NOT_SUPPORTED_H264,message:Y({key:K.NOT_SUPPORTED_H264DECODE})});try{if(i!==0)throw new O({code:i,message:Y({key:K.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(a){throw this._log.error(a),a}})}updateSSRC(t){try{ot(t).media.forEach(i=>{if(i.ssrcs)if(i.type===_.AUDIO){let r=i.ssrcs.find(n=>{var s;return(s=n.value)==null?void 0:s.includes(mc)});r&&(this.ssrc.audio=Number(r.id))}else{let r=i.ssrcs.find(s=>{var a;return(a=s.value)==null?void 0:a.includes(mc)}),n=i.ssrcs.find(s=>{var a;return(a=s.value)==null?void 0:a.includes(yA)});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 g(this,null,function*(){if(!(Et(Rk.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch{let i=qr(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}};M([ge(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 a=o=>{this._emitter.off("closed",a),s(new O({code:C.API_CALL_ABORTED,message:Y({key:K.CONNECTION_ABORTED,data:o})}))};this._emitter.on("closed",a),e.apply(this,i).then(n,s).finally(()=>{this._emitter.off("closed",a)})})})],Mu.prototype,"subscribe"),M([Sr(521717,!1)],Mu.prototype,"unsubscribe"),M([cn(Ki.prototype.afterConnect),Tb(Ki.prototype.beforeConnect)],Mu.prototype,"connect");var q0=Mu,Y0={voiceActivityDetection:!1},Lu=class Ck extends Ki{constructor(t){super(W(x({},t),{isUplink:!0})),u(this,"localMainAudioTrack",null),u(this,"localMainVideoTrack",null),u(this,"localAuxAudioTrack",null),u(this,"localAuxVideoTrack",null),u(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),u(this,"_isPublishingAux",!1),u(this,"_publishingLocalAudioTrack"),u(this,"_publishingLocalVideoTrack"),u(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}),u(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)}isTrackReferenced(t){return t===this.localMainAudioTrack||t===this.localMainVideoTrack||t===this.localAuxVideoTrack||t===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 a=this._currentState,o=super.emitConnectionStateChangedEvent(t);return o&&a!==t&&(i?i.emit("connection-state-changed",{prevState:a,state:t}):((r=this.localMainVideoTrack)==null||r.emit("connection-state-changed",{prevState:a,state:t}),(n=this.localAuxVideoTrack)==null||n.emit("connection-state-changed",{prevState:a,state:t}),(s=this._publishingLocalVideoTrack)==null||s.emit("connection-state-changed",{prevState:a,state:t}))),o}publish(t){return g(this,arguments,function(i){var r=this;let{localAudioTrack:n,localVideoTrack:s,isAuxiliary:a}=i;return(function*(){let o;r._peerConnection||r.initialize(),n&&(r._publishingLocalAudioTrack=n),s&&(r._publishingLocalVideoTrack=s),r._isPublishingAux=a,s&&!a&&s.small&&(o=r._room.videoManager.smallTrack),r.sendMediaSettings(),ri()?yield r.publishByTransceiver({localAudioTrack:n,localVideoTrack:s,smallTrack:o,isAuxiliary:a}):yield r.publishByAddTrack({localAudioTrack:n,localVideoTrack:s,smallTrack:o}),r._publishingLocalAudioTrack=null,r._publishingLocalVideoTrack=null,r._isPublishingAux=!1,a?(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 g(this,arguments,function(i){var r=this;let{localAudioTrack:n,localVideoTrack:s,smallTrack:a,isAuxiliary:o}=i;return(function*(){r._log.info("publish by transceiver");let l=new MediaStream,c=s==null?void 0:s.outMediaTrack,d=n==null?void 0:n.outMediaTrack;d&&l.addTrack(d),c&&l.addTrack(c);let h=r._peerConnection.getTransceivers();if(h.length===0)r._peerConnection.addTransceiver(d||_.AUDIO,{direction:oe.SENDONLY,streams:[l]}),r._peerConnection.addTransceiver(o?_.VIDEO:c||_.VIDEO,{direction:oe.SENDONLY,streams:[l]}),r._peerConnection.addTransceiver(a||_.VIDEO,{direction:oe.SENDONLY,streams:[l]}),r._peerConnection.addTransceiver(o&&c||_.VIDEO,{direction:oe.SENDONLY,streams:[l]}),yield r.connect();else{let m=[];if(d&&(h[0].sender.track||m.push(0),yield h[0].sender.replaceTrack(d),yield r.setBandwidth({bandwidth:(n==null?void 0:n.profile.bitrate)||40,type:_.AUDIO})),c){let p=o?3:1;yield h[p].sender.replaceTrack(c),yield r.setBandwidth({bandwidth:s.profile.bitrate,type:_.VIDEO,videoType:o?_.AUXILIARY:_.BIG}),m.push(p),a&&(yield h[2].sender.replaceTrack(a),yield r.setBandwidth({bandwidth:s.small.bitrate,type:_.VIDEO,videoType:_.SMALL}),m.push(2))}yield r.setTransceiverDirection(oe.SENDONLY,m),yield r.doPublishChange(),s==null||s.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),s==null||s.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})()})}publishByAddTrack(t){return g(this,arguments,function(i){var r=this;let{localAudioTrack:n,localVideoTrack:s,smallTrack:a}=i;return(function*(){r._log.info("publish by addtrack");let o=s==null?void 0:s.outMediaTrack,l=n==null?void 0:n.outMediaTrack;if(r._peerConnection&&r._peerConnection.connectionState!=="new")return n&&l&&(yield r.addTrack(n)),void(o&&(yield r.addTrack(s)));let c=new MediaStream;if(l&&c.addTrack(l),o&&c.addTrack(o),l&&r._peerConnection.addTrack(l,c),o&&(r._peerConnection.addTrack(o,c),a)){let d=new MediaStream;d.addTrack(a),r._peerConnection.addTrack(a,d)}yield r.connect()})()})}enableSmall(t){return g(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(oe.SENDONLY,[2])):(yield i[2].sender.replaceTrack(null),yield this.setTransceiverDirection(oe.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==null||n.on("mute",this.sendMutedFlag,this),n==null||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==null||n.off("mute",this.sendMutedFlag,this),n==null||n.off("unmute",this.sendMutedFlag,this))})}unpublish(t){return g(this,arguments,function(i){var r=this;let{localAudioTrack:n,localVideoTrack:s}=i;return(function*(){if(!Ts())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 a=s&&s===r.localAuxVideoTrack,o=s==null?void 0:s.outMediaTrack,l=r._peerConnection.getSenders(),c=[];n&&(a?r.localAuxAudioTrack=null:r.localMainAudioTrack=null,!r.localAuxAudioTrack&&!r.localMainAudioTrack&&(yield l[0].replaceTrack(null),c.push(0))),o&&(a?(yield l[3].replaceTrack(null),r.localAuxVideoTrack=null,r._mediaSettings=W(x({},r._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield l[1].replaceTrack(null),yield l[2].replaceTrack(null),r.localMainVideoTrack=null,r._mediaSettings=W(x({},r._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),r.isMainStreamPublished||r.isAuxStreamPublished?(yield r.setTransceiverDirection(oe.INACTIVE,c),yield r.doPublishChange(!1)):yield r.doUnpublish(),r.uninstallTrackMuteEvents(n,s),s==null||s.emit("connection-state-changed",{prevState:r._currentState,state:"DISCONNECTED"})})()})}doPublishChange(){let t=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return g(this,null,function*(){let i={state:this._room.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponse({command:D_,data:i,responseCommand:X.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:Pu,commandDesc:"unpublish",responseCommand:X.UNPUBLISH_RESULT,enableLog:t}).catch(i=>{if(i.getCode()===C.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),Es){if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=1e3*r.profile.bitrate,this._mediaSettings.audioFs=a.sampleRate||0}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.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 a=s.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.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:P_,data:this._mediaSettings,responseCommand:X.UPDATE_CONSTRAINT_CONFIG_RES}).then(t=>{t.data.code!==0&&this._log.warn(t.data.message)}).catch(()=>{})}addTrack(t){return g(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?_.AUXILIARY:_.MAIN," stream")),ri()?yield this.addTrackByTransceiver(t,i):yield this.addTrackBySender(t)})}addTrackByTransceiver(t,i){return g(this,null,function*(){var r;if(!t.mediaTrack)return;let n=this._peerConnection.getTransceivers();if(t.kind===_.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===oe.INACTIVE&&(yield this.setTransceiverDirection(oe.SENDONLY,[s]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(t){return g(this,null,function*(){if(!t.outMediaTrack)return;let i=t.outMediaTrack;Ts()&&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===_.VIDEO&&t instanceof ji&&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===pc||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:t}=this._peerConnection.localDescription,i=ot(t);for(let r=0;r<i.media.length;r++)if(Number(i.media[r].mid)===0&&i.media[r].type===_.VIDEO)return!0;return!1}removeSender(t){let i=null;Ts()&&(i=this._peerConnection.getTransceivers().find(r=>r.sender&&r.sender.track===t.track)),this._peerConnection.removeTrack(t),i&&Pe(i.stop)&&(this._log.info("stop transceiver"),i.stop())}removeTrack(t){return g(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?_.AUXILIARY:_.MAIN," stream")),ri()?yield this.removeTrackByTransceiver(t,i):yield this.removeTrackBySender(t)})}removeTrackByTransceiver(t,i){return g(this,null,function*(){if(!t.outMediaTrack)return;let r=this._peerConnection.getTransceivers();if(t.kind===_.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(oe.INACTIVE,[n])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(t,i){return g(this,null,function*(){if(!me)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(l=>{s[l].direction!==t&&(s[l].direction=t,r=!0)}),r){this._log.info("updating offer");let l=yield this._peerConnection.createOffer();yield this.setOffer(l)}let a=-1,o=this._peerConnection.remoteDescription.sdp.split(`\r
|
||
`).map(l=>{if(l.match(new RegExp("a=(".concat(oe.INACTIVE,"|").concat(oe.RECVONLY,"|").concat(oe.SENDONLY,")")))&&a++,i.includes(a)){if(t===oe.INACTIVE&&l.includes("a=".concat(oe.RECVONLY)))return n=!0,"a=".concat(t);if(t===oe.SENDONLY&&l.includes("a=".concat(oe.INACTIVE)))return n=!0,"a=".concat(oe.RECVONLY)}return l}).join(`\r
|
||
`);n&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:o}))})}removeTrackBySender(t){return g(this,null,function*(){if(!t.outMediaTrack)return;if(t.kind===_.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===_.VIDEO&&t.small&&this._peerConnection.getSenders().forEach(r=>{r.track&&r.track.kind===_.VIDEO&&this.removeSender(r)})),yield this.updateOffer("remove",t.outMediaTrack)})}replaceTrack(t){return g(this,null,function*(){var i;let r,n=(i=this._peerConnection)==null?void 0:i.getSenders();if(!n||n.length===0||!t.mediaTrack||(r=ri()?t.kind===_.AUDIO?n[0]:n[1]:n.find(a=>a.track&&a.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?_.AUXILIARY:_.MAIN," stream")),t.kind===_.AUDIO?yield r.replaceTrack(t.outMediaTrack):t.kind===_.VIDEO&&(s?n[3]&&(yield n[3].replaceTrack(t.outMediaTrack)):yield r.replaceTrack(t.outMediaTrack)),!0})}updateOffer(t,i){return g(this,null,function*(){try{let r=yield this._peerConnection.createOffer(Y0);me&&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===_.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 a=yield this._signalChannel.sendWaitForResponse({command:F0,data:s,responseCommand:X.UPDATE_OFFER_RESULT,timeout:CA,commandDesc:"update offer"}),{code:o,message:l}=a.data;o!==0&&this.checkPublishResultCode(o,l),yield this.acceptAnswer(a.data.data),r.sdp&&this.updateSSRC(r.sdp)}catch(r){throw this._log.error(r),r}})}setBandwidth(t){return g(this,arguments,function(i){var r=this;let{bandwidth:n,type:s,videoType:a,sdp:o}=i;return(function*(){if(!bf())return o?s===_.VIDEO?r.updateVideoBandwidthRestriction(o,n,a):r.updateAudioBandwidthRestriction(o,n):void 0;let l,c=r._peerConnection.getSenders();if(ri()){let d=0;s===_.VIDEO&&(d=a===_.SMALL?2:a===_.AUXILIARY?3:1),l=c[d]}else l=c.find(d=>d.track&&d.track.kind===s);if(l){let d=l.getParameters();(!d.encodings||d.encodings.length===0)&&(d.encodings=[{}]),d.encodings[0].maxBitrate=1e3*n;try{return yield l.setParameters(d),r._log.info("".concat(a||"").concat(s," bandwidth ").concat(n," kbps")),o}catch(h){if(r._log.info("failed to set bandwidth by setting maxBitrate: ".concat(h)),o)return s===_.VIDEO?r.updateVideoBandwidthRestriction(o,n,a):r.updateAudioBandwidthRestriction(o,n)}}return o})()})}updateVideoBandwidthRestriction(t,i,r){let n="AS";me&&(n="TIAS",i*=1e3);let s=0,a=-1;return r===_.SMALL?s=1:r===_.AUXILIARY&&(s=2),t=t.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,o=>(a+=1,a===s?"".concat(o,"b=").concat(n,":").concat(i,`\r
|
||
`):o)),t}updateAudioBandwidthRestriction(t,i){let r="AS";return me&&(r="TIAS",i*=1e3),t=t.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
|
||
c=IN $2\r
|
||
b=`.concat(r,":").concat(i,`\r
|
||
`))}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 g(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),this.uninstallEvents(),t}})}exchangeSDP(){return g(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 g(this,null,function*(){try{let t=yield this._peerConnection.createOffer(Y0);yield this.setOffer(t),t.sdp&&this.updateSSRC(t.sdp)}catch(t){throw t}})}doExchangeSDP(){let t={command:H0,responseCommand:X.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof hn||this.localAuxVideoTrack instanceof hn,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=ot(t);return n.media.forEach(s=>{(r==="all"||s.type===r)&&(s.direction=i)}),Cr(n)}acceptAnswer(t){return g(this,null,function*(){var i,r,n,s,a;try{let o;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let c=((i=this._publishingLocalVideoTrack)==null?void 0:i.profile.bitrate)||((r=this.localMainVideoTrack)==null?void 0:r.profile.bitrate),d=((n=this._publishingLocalAudioTrack)==null?void 0:n.profile.bitrate)||((s=this.localMainAudioTrack)==null?void 0:s.profile.bitrate);if(c){let h=this._isPublishingAux?_.AUXILIARY:_.BIG;o=yield this.setBandwidth({bandwidth:c,type:_.VIDEO,sdp:o,videoType:h})}d&&(o=yield this.setBandwidth({bandwidth:d,type:_.AUDIO,sdp:o}))}if(o=this.removeVideoOrientation(t.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:c}=this._room;o=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||c.bitrate,type:_.VIDEO,videoType:_.SMALL,sdp:o})}let l={type:t.type,sdp:o};yield this.setAnswer(l),this._log.debug("accepted answer: ".concat(o))}catch(o){throw this._log.error("failed to accept remote answer ".concat(o)),o}})}sendMutedFlag(t){t===this.localAuxAudioTrack||t===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this._room.muteState))),this._signalChannel.send(B0,this._room.muteState))}getIsReconnecting(){return this._isReconnecting}reconnect(){return g(this,null,function*(){if(!(Et(Ck.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:Pu,responseCommand:X.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=qr(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)&&R.emit(b.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(t){try{ot(t).media.forEach((i,r)=>{if(i.type===_.AUDIO){let n=i.ssrcs&&i.ssrcs[0];n&&(this.ssrc.audio=Number(n.id))}else{if(this._sdpSemantics===pc&&i.ssrcGroups)return void i.ssrcGroups.forEach((s,a)=>{let o=Number(s.ssrcs.split(" ")[0]);a===0?this.ssrc.video=o:a===1&&(this.ssrc.small=o)});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]:_.VIDEO;if(this._peerConnection){let i=this._peerConnection.getSenders();if(t===_.AUXILIARY&&i[3]&&i[3].track)return i[3].track.id;if(t===_.VIDEO&&i[1]&&i[1].track)return i[1].track.id}if(this.localMainVideoTrack&&t===_.VIDEO){let i=this.localMainVideoTrack.mediaTrack;if(i)return i.id}if(this.localAuxVideoTrack&&t===_.AUXILIARY){let i=this.localAuxVideoTrack.mediaTrack;if(i)return i.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(t,i){if(t!==0)throw t===fc?(this._log.error(ii.NOT_SUPPORTED_H264ENCODE),new O({code:C.NOT_SUPPORTED_H264,message:Y({key:K.NOT_SUPPORTED_H264ENCODE})})):new O({code:C.UNKNOWN,message:Y({key:K.SIGNAL_RESPONSE_FAILED,data:{signalResponse:X.PUBLISH_RESULT,code:t,message:i}})})}};M([ge(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 a=o=>{this._emitter.off("closed",a),s(new O({code:C.API_CALL_ABORTED,message:Y({key:K.CONNECTION_ABORTED,data:o})}))};this._emitter.on("closed",a),e.apply(this,i).then(n,s).finally(()=>{this._emitter.off("closed",a)})})})],Lu.prototype,"publish"),M([Sr(521715,!1)],Lu.prototype,"unpublish"),M([cn(Ki.prototype.afterConnect),Tb(Ki.prototype.beforeConnect)],Lu.prototype,"connect");var xu=Lu,G4=class{constructor(e,t){this.room=e,u(this,"_log"),u(this,"_prevReportTime",0),u(this,"_prevReport",{}),u(this,"_prevStats",null),u(this,"_prevEncoderImplementation",""),u(this,"_prevAuxEncoderImpl",""),u(this,"_prevQualityLimitationReason",""),u(this,"_prevAuxQualityLimitationReason",""),u(this,"_prevDecoderImplementationMap",new Map),u(this,"_decodeMap",new Map),u(this,"_prevQpSum",0),u(this,"_prevAuxQpSum",0),u(this,"totalBytesSent",0),u(this,"totalBytesReceived",0),u(this,"_spcStats",null),this._log=t}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(e,t){return g(this,null,function*(){var i,r,n;let s={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},a=e==null?void 0:e.getPeerConnection();if(e&&a){let o=e.getSSRC();try{if((this._spcStats||(yield a.getStats())).forEach(l=>{var c,d,h,m,p,f,T,E,v,y,D,N,S;let A,L;if(l.type==="outbound-rtp")if((l.mediaType||l.kind)===_.VIDEO){if(l.ssrc===o.video?(A=_.VIDEO,L=e.localMainVideoTrack):l.ssrc===o.small?A=_.SMALL:l.ssrc===o.auxiliary&&(L=e.localAuxVideoTrack,A=_.AUXILIARY),!A)return;s[A].bytesSent=l.bytesSent,s[A].packetsSent=l.packetsSent,s[A].framesEncoded=l.framesEncoded,I(l.keyFramesEncoded)||(s[A].keyFramesEncoded=l.keyFramesEncoded),I(l.nackCount)||(s[A].nackCount=l.nackCount),I(l.pliCount)||(s[A].pliCount=l.pliCount),I(l.retransmittedPacketsSent)||(s[A].retransmittedPacketsSent=l.retransmittedPacketsSent),I(l.totalEncodeTime)||(s[A].totalEncodeTime=l.totalEncodeTime),I(l.totalPacketSendDelay)||(s[A].totalPacketSendDelay=l.totalPacketSendDelay);let U=0;if(!I(l.qpSum)&&!I(l.framesEncoded)&&l.framesEncoded>0){let q=l.qpSum,fe=l.framesEncoded,Re=A===_.VIDEO?this._prevQpSum:this._prevAuxQpSum,ne=A===_.VIDEO?((d=(c=e.localMainVideoTrack)==null?void 0:c.stat)==null?void 0:d.framesEncoded)||0:((m=(h=e.localAuxVideoTrack)==null?void 0:h.stat)==null?void 0:m.framesEncoded)||0;if(fe>ne&&q>Re){let ft=q-Re,xe=fe-ne;U=Math.round(ft/xe),U>35&&e.videoCodec==="h264"&&this._log.warn("".concat(A===_.AUXILIARY?"aux ":"","video encoder QP is high: ").concat(U,", resolution: ").concat(l.frameWidth,"x").concat(l.frameHeight,", codec: ").concat(e.videoCodec,", "))}A===_.VIDEO?this._prevQpSum=q:A===_.AUXILIARY&&(this._prevAuxQpSum=q)}if(!I(l.encoderImplementation)&&(A===_.VIDEO&&this._prevEncoderImplementation!==l.encoderImplementation||A===_.AUXILIARY&&this._prevAuxEncoderImpl!==l.encoderImplementation)){let q=2,fe=this._prevEncoderImplementation;A===_.AUXILIARY&&(q=7,fe=this._prevAuxEncoderImpl),R.emit("262",{userId:e.userId,streamType:q,prevImplementation:fe,implementation:l.encoderImplementation,codec:e.videoCodec,isHWCodec:l.powerEfficientEncoder}),this[A===_.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=l.encoderImplementation,L==null||L.log.info("encoderImplementation change to ".concat(l.encoderImplementation,"(").concat(e.videoCodec,") HWEncoder: ").concat(l.powerEfficientEncoder))}l.ssrc===o.video?!I(l.qualityLimitationReason)&&l.bytesSent!==0&&this._prevQualityLimitationReason!==l.qualityLimitationReason&&(L==null||L.log.info("qualityLimitationReason change to ".concat(l.qualityLimitationReason)),R.emit("263",{userId:e.userId,reason:l.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(p=e.localMainVideoTrack)==null?void 0:p.isQosClearFirst}),this._prevQualityLimitationReason=l.qualityLimitationReason):l.ssrc===o.auxiliary&&!I(l.qualityLimitationReason)&&l.bytesSent!==0&&this._prevAuxQualityLimitationReason!==l.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(l.qualityLimitationReason)),R.emit("263",{userId:e.userId,reason:l.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(f=e.localAuxVideoTrack)==null?void 0:f.isQosClearFirst}),this._prevAuxQualityLimitationReason=l.qualityLimitationReason)}else s.audio.bytesSent=l.bytesSent,s.audio.packetsSent=l.packetsSent;else if(l.type==="candidate-pair")Za(l)&&(this.totalBytesSent=l.bytesSent,le(l.currentRoundTripTime)&&(s.rtt=Math.floor(1e3*l.currentRoundTripTime)));else if(l.type==="media-source"){if(l.kind===_.AUDIO)s.audio.audioLevel=l.audioLevel||0,s.audio.totalAudioEnergy=l.totalAudioEnergy||0,l.echoReturnLoss,I((v=(E=(T=e.localMainAudioTrack)==null?void 0:T.sourceTrack)==null?void 0:E.stats)==null?void 0:v.deliveredFramesDuration)?l.totalSamplesDuration&&(s.audio.totalSamplesDuration=l.totalSamplesDuration):s.audio.totalSamplesDuration=e.localMainAudioTrack.sourceTrack.stats.deliveredFramesDuration/1e3;else if(l.kind===_.VIDEO)if(l.trackIdentifier===e.getVideoTrackId(_.VIDEO))if((N=(D=(y=e.localMainVideoTrack)==null?void 0:y.sourceTrack)==null?void 0:D.stats)!=null&&N.deliveredFrames){let{deliveredFrames:U}=e.localMainVideoTrack.sourceTrack.stats;s.video.framesCaptured=U,e.localMainVideoTrack.stat.framesCaptured&&e.localMainVideoTrack.stat.framesCaptured>0&&U>=e.localMainVideoTrack.stat.framesCaptured?s.video.fpsCapture=Math.floor((U-e.localMainVideoTrack.stat.framesCaptured)/this.statInterval):s.video.fpsCapture=l.framesPerSecond}else s.video.fpsCapture=l.framesPerSecond;else l.trackIdentifier===e.getVideoTrackId(_.AUXILIARY)?s.auxiliary.fpsCapture=l.framesPerSecond:s.small.fpsCapture=l.framesPerSecond}if(!I(l.audioLevel)&&(S=e.localMainAudioTrack)!=null&&S.mediaTrack&&l.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(s.audio.audioLevel=l.audioLevel||0),!I(l.frameWidth)){let U=_.SMALL;l.trackIdentifier===e.getVideoTrackId(_.VIDEO)||l.ssrc===o.video?U=_.VIDEO:(l.trackIdentifier===e.getVideoTrackId(_.AUXILIARY)||l.ssrc===o.auxiliary)&&(U=_.AUXILIARY),s[U].frameWidth=l.frameWidth,s[U].frameHeight=l.frameHeight,s[U].framesSent=l.framesSent}}),e.localMainAudioTrack){let l=e.localMainAudioTrack.getInternalAudioLevel(),c=e.localMainAudioTrack.getInternalAudioLevelAfter3A();s.audio.audioCaptureEnergyAfter3a=c,s.audio.micAudioLevel=l,s.audio.audioLevel===0&&(s.audio.audioLevel=c??l)}}catch(l){this._log.warn("failed to getStats on sender connection ".concat(l))}}if((e==null||!e.localMainAudioTrack)&&t.capturedLocalMainAudioTrack){let o=t.capturedLocalMainAudioTrack;o&&(s.audio.micAudioLevel=o.getInternalAudioLevel(),s.audio.audioCaptureEnergyAfter3a=o.getInternalAudioLevelAfter3A(),I((r=(i=o.sourceTrack)==null?void 0:i.stats)==null?void 0:r.deliveredFramesDuration)||(s.audio.totalSamplesDuration=o.sourceTrack.stats.deliveredFramesDuration/1e3))}return e!=null&&e.localMainVideoTrack||this.updateVideoCaptureStats(t.capturedLocalMainVideoTrack,s.video),e!=null&&e.localAuxVideoTrack||this.updateVideoCaptureStats(t.capturedLocalAuxVideoTrack,s.auxiliary),this.totalBytesSent||(this.totalBytesSent+=s.audio.bytesSent+s.video.bytesSent+s.auxiliary.bytesSent),Object.keys(s).forEach(o=>{o===_.AUDIO?(t.capturedLocalMainAudioTrack&&(t.capturedLocalMainAudioTrack.stat=s[o]),e!=null&&e.localAuxAudioTrack&&(e.localAuxAudioTrack.stat=s[o])):o===_.VIDEO?t.capturedLocalMainVideoTrack&&(t.capturedLocalMainVideoTrack.stat=s[o]):o===_.AUXILIARY&&t.capturedLocalAuxVideoTrack&&(t.capturedLocalAuxVideoTrack.stat=s[o])}),s.rtt===0&&(s.rtt=((n=this.room.networkQuality)==null?void 0:n.uplinkRTT)||0),s})}getReceiverStats(e){return g(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:a}=e,{muteState:o,subscribeState:l}=e;(this._spcStats||(yield s.getStats())).forEach(h=>{var m,p;if(h.type==="codec"&&this._decodeMap.set(h.id,h),h.type==="inbound-rtp"){let f=(h.mediaType||h.kind)===_.AUDIO;if(f){if(h.ssrc!==a.audio||!o.hasAudio)return;n.audio.packetsReceived=h.packetsReceived,n.audio.bytesReceived=h.bytesReceived,n.audio.packetsLost=h.packetsLost,h.insertedSamplesForDeceleration&&(n.audio.insertedSamplesForDeceleration=h.insertedSamplesForDeceleration),h.removedSamplesForAcceleration&&(n.audio.removedSamplesForAcceleration=h.removedSamplesForAcceleration),h.totalSamplesDuration&&(n.audio.totalSamplesDuration=h.totalSamplesDuration),h.totalSamplesReceived&&(n.audio.totalSamplesReceived=h.totalSamplesReceived),h.concealedSamples&&(n.audio.concealedSamples=h.concealedSamples),h.silentConcealedSamples&&(n.audio.silentConcealedSamples=h.silentConcealedSamples);let{remoteAudioTrack:T}=e;T.stat.packetsReceived=h.packetsReceived,T.stat.bytesReceived=h.bytesReceived,T.stat.packetsLost=h.packetsLost,n.audio.p2pDelay=T.stat.end2EndDelay,n.hasAudio=!0}else{if(me&&h.bytesReceived===0)return;let T;h.ssrc===a.video&&o.hasVideo&&(n.video.packetsReceived=h.packetsReceived,n.video.bytesReceived=h.bytesReceived,n.video.packetsLost=h.packetsLost,n.video.framesReceived=h.framesReceived,n.video.framesDecoded=h.framesDecoded,n.video.fpsDecoded=h.framesPerSecond,n.hasVideo=!0,e.videoCodec=ff[(m=this._decodeMap.get(h.codecId))==null?void 0:m.mimeType.split("/")[1]]||"h264",n.video.codec=e.videoCodec,T=e.remoteVideoTrack,o.hasSmall&&l.smallVideo&&(n.isSmallSubscribed=!0),h.decoderImplementation&&(!this._prevDecoderImplementationMap.has(n.userId)||this._prevDecoderImplementationMap.get(n.userId)!==h.decoderImplementation)&&(T.log.info("decoderImplementation change to ".concat(h.decoderImplementation,"(").concat(e.videoCodec,") HWDecoder: ").concat(h.powerEfficientDecoder)),R.emit("262",{userId:this.room.userId,remoteUserId:n.userId,prevImplementation:this._prevDecoderImplementationMap.get(n.userId),implementation:h.decoderImplementation,codec:e.videoCodec,isHWCodec:h.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(n.userId,h.decoderImplementation)),I(h.keyFramesDecoded)||T.updateKeyFramesDecoded(h.keyFramesDecoded)),h.ssrc===a.auxiliary&&o.hasAuxiliary&&(n.auxiliary.packetsReceived=h.packetsReceived,n.auxiliary.bytesReceived=h.bytesReceived,n.auxiliary.packetsLost=h.packetsLost,n.auxiliary.framesReceived=h.framesReceived,n.auxiliary.framesDecoded=h.framesDecoded,n.auxiliary.fpsDecoded=h.framesPerSecond,T=e.remoteAuxiliaryTrack,n.auxiliary.p2pDelay=T.stat.end2EndDelay,n.hasAuxiliary=!0,n.video.codec=((p=this._decodeMap.get(h.codecId))==null?void 0:p.mimeType.split("/")[1].toLowerCase())||"h264",I(h.keyFramesDecoded)||T.updateKeyFramesDecoded(h.keyFramesDecoded)),T&&(T.stat.packetsReceived=h.packetsReceived,T.stat.bytesReceived=h.bytesReceived,T.stat.packetsLost=h.packetsLost,T.stat.framesReceived=h.framesReceived,T.stat.framesDecoded=h.framesDecoded,h.jitterBufferDelay&&(T.stat.jitterBufferDelay=Math.floor(h.jitterBufferDelay/h.jitterBufferEmittedCount*1e3)),n.video.p2pDelay=T.stat.end2EndDelay)}h.jitterBufferDelay&&(f?(n.audio.totalJitter=h.jitterBufferDelay,n.audio.totalJitterCount=h.jitterBufferEmittedCount,n.audio.estimatedPlayoutTimestamp=h.estimatedPlayoutTimestamp):h.ssrc===a.video&&o.hasVideo?(n.video.totalJitter=h.jitterBufferDelay,n.video.totalJitterCount=h.jitterBufferEmittedCount,n.video.estimatedPlayoutTimestamp=h.estimatedPlayoutTimestamp):h.ssrc===a.auxiliary&&o.hasAuxiliary&&(n.auxiliary.totalJitter=h.jitterBufferDelay,n.auxiliary.totalJitterCount=h.jitterBufferEmittedCount))}else h.type==="candidate-pair"&&Za(h)&&(this.totalBytesReceived=h.bytesReceived,le(h.currentRoundTripTime)&&(n.rtt=Math.floor(1e3*h.currentRoundTripTime)));I(h.frameWidth)||((h.trackIdentifier===e.getMainStreamVideoTrackId()||h.ssrc===a.video)&&(n.video.frameWidth=h.frameWidth,n.video.frameHeight=h.frameHeight,e.remoteVideoTrack.stat.frameWidth=h.frameWidth,e.remoteVideoTrack.stat.frameHeight=h.frameHeight),(h.trackIdentifier===e.getAuxStreamVideoTrackId()||h.ssrc===a.auxiliary)&&(n.auxiliary.frameWidth=h.frameWidth,n.auxiliary.frameHeight=h.frameHeight,e.remoteAuxiliaryTrack.stat.frameWidth=h.frameWidth,e.remoteAuxiliaryTrack.stat.frameHeight=h.frameHeight)),!I(h.audioLevel)&&e.muteState.audioAvailable&&e.remoteAudioTrack.mediaTrack&&h.trackIdentifier===e.remoteAudioTrack.mediaTrack.id&&(n.audio.audioLevel=h.audioLevel||0,n.audio.totalAudioEnergy=h.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),I((t=e.remoteVideoTrack.player.stat)==null?void 0:t.fps)||(n.video.fpsRender=e.remoteVideoTrack.player.stat.fps),I((i=e.remoteAuxiliaryTrack.player.stat)==null?void 0:i.fps)||(n.auxiliary.fpsRender=e.remoteAuxiliaryTrack.player.stat.fps);let c=n.audio.estimatedPlayoutTimestamp,d=n.video.estimatedPlayoutTimestamp;if(c&&d&&e.remoteAudioTrack.isAvailable&&e.remoteVideoTrack.isAvailable){let h=d-c;Math.abs(h)<=1e4&&(n.avSyncDelay=h,Math.abs(h)>150&&this._log.warn("av sync delay",h))}}catch(a){this._log.warn("failed to getStats on receiver connection ".concat(a))}return n.rtt===0&&(n.rtt=((r=this.room.networkQuality)==null?void 0:r.uplinkRTT)||0),n})}getStats(e,t){return g(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 a=J(),o=yield s.getStats(),l=J();l-a>2e3&&this._log.warn("getStats cost ".concat(l-a,"ms"));let c=[],d=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source","codec","media-playout"]);o.forEach(h=>d.has(h.type)&&c.push(h)),this._spcStats=c}(e||this.hasCapturedTracks())&&(r=yield this.getSenderStats(e,this.room));for(let[s,a]of t){let o=yield this.getReceiverStats(a);o&&n.push(o)}return t.size&&(i=this.getMediaPlayoutStats(this._spcStats)),{senderStats:r,receiverStats:n,mediaPlayoutStats:i}})}hasCapturedTracks(){return this.room.capturedLocalMainVideoTrack||this.room.capturedLocalMainAudioTrack||this.room.capturedLocalAuxVideoTrack}getDifferenceValue(e,t){if(Gi(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,a,o,l,c,d,h,m,p,f;if(i.msg_device_info.uint32_task_cost=I_.totalBlockingDuration,!Gi(t.senderStats)){let S={uint32_audio_level:t.senderStats.audio.audioLevel*fi,uint32_audio_energy:1e6*(t.senderStats.audio.totalAudioEnergy||0),uint32_audio_codec_bitrate:t.senderStats.audio.bytesSent};t.senderStats.audio.micAudioLevel&&(S.uint32_mic_audio_level=t.senderStats.audio.micAudioLevel*fi),I(t.senderStats.audio.audioCaptureEnergyAfter3a)||(S.uint32_audio_capture_energy_after3a=t.senderStats.audio.audioCaptureEnergyAfter3a*fi),t.senderStats.audio.totalSamplesDuration&&(i.msg_device_info.uint32_audio_capture_cost=t.senderStats.audio.totalSamplesDuration);let A=[];if(t.senderStats.video.bytesSent||t.senderStats.video.fpsCapture){let U={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};A.push(U)}if(t.senderStats.small.bytesSent){let U={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};A.push(U)}if(t.senderStats.auxiliary.bytesSent||t.senderStats.auxiliary.fpsCapture){let U={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};A.push(U)}let L={uint32_bitrate:0,uint32_lost:0,uint32_rtt:t.senderStats.rtt};i.msg_up_stream_info={msg_audio_status:S,msg_video_status:A,msg_network_status:L}}let{statInterval:T}=this;i.msg_down_stream_info=[],t.receiverStats.forEach(S=>{let A={msg_user_info:{str_identifier:S.userId,uint64_tinyid:S.tinyId},msg_network_status:{uint32_rtt:S.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(S.hasAudio){let L={uint32_audio_p2p_delay:S.audio.p2pDelay,uint32_audio_cache_ms:S.audio.totalJitter,uint32_audio_cache_ms_count:S.audio.totalJitterCount,uint32_audio_codec_bitrate:S.audio.bytesReceived,uint32_audio_total_bitrate:S.audio.bytesReceived,uint32_audio_level:1e8*S.audio.audioLevel,uint32_audio_energy:1e6*S.audio.totalAudioEnergy,uint32_audio_receive:S.audio.packetsReceived,uint32_audio_origin_lost:S.audio.packetsLost};A.msg_audio_status=L}if(S.hasVideo){let L=r.get("".concat(S.userId,"_").concat(SA)),U=L?L.duration:0,q={uint32_video_stream_type:S.isSmallSubscribed?3:2,uint32_video_receive_fps:S.video.framesReceived,uint32_video_width:S.video.frameWidth,uint32_video_height:S.video.frameHeight,uint32_video_codec_bitrate:S.video.bytesReceived,uint32_video_receive:S.video.packetsReceived,uint32_video_origin_lost:S.video.packetsLost,uint32_video_block_time:U,uint32_video_dec_fps:S.video.framesDecoded,uint32_video_codec_fps:S.video.fpsRender,uint32_video_cache_ms:S.video.totalJitter,uint32_video_cache_ms_count:S.video.totalJitterCount,uint32_video_p2p_delay:S.video.p2pDelay,uint32_video_codec:S.video.codec,int32_video_audio_relative_delay:S.avSyncDelay+5e3};A.msg_video_status.push(q)}if(S.hasAuxiliary){let L=r.get("".concat(S.userId,"_").concat(IA)),U=L?L.duration:0,q={uint32_video_stream_type:7,uint32_video_receive_fps:S.auxiliary.framesReceived,uint32_video_width:S.auxiliary.frameWidth,uint32_video_height:S.auxiliary.frameHeight,uint32_video_codec_bitrate:S.auxiliary.bytesReceived,uint32_video_receive:S.auxiliary.packetsReceived+S.auxiliary.packetsLost,uint32_video_origin_lost:S.auxiliary.packetsLost,uint32_video_block_time:U,uint32_video_dec_fps:S.auxiliary.framesDecoded,uint32_video_codec_fps:S.video.fpsRender,uint32_video_cache_ms:S.auxiliary.totalJitter,uint32_video_cache_ms_count:S.auxiliary.totalJitterCount,uint32_video_p2p_delay:S.auxiliary.p2pDelay,uint32_video_codec:S.video.codec};A.msg_video_status.push(q)}i.msg_down_stream_info.push(A)}),t.mediaPlayoutStats&&!Gi(t.mediaPlayoutStats)&&(t.mediaPlayoutStats.synthesizedSamplesDuration*=1e3,t.mediaPlayoutStats.totalSamplesDuration*=1e3);let E=this._prevReport,v=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&&E.msg_up_stream_info.msg_audio_status){let S=E.msg_up_stream_info.msg_audio_status,A=i.msg_up_stream_info.msg_audio_status;if(S.uint32_audio_codec_bitrate===0)A.uint32_audio_codec_bitrate=0;else{let L=this.getDifferenceValue(S.uint32_audio_codec_bitrate,A.uint32_audio_codec_bitrate);A.uint32_audio_codec_bitrate=Math.round(8*L/T),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=A.uint32_audio_codec_bitrate}(s=E.msg_device_info)!=null&&s.uint32_audio_capture_cost?(i.msg_device_info.uint32_audio_capture_cost=2*Math.floor(1e3*this.getDifferenceValue(E.msg_device_info.uint32_audio_capture_cost,i.msg_device_info.uint32_audio_capture_cost)/T),i.msg_device_info.uint32_audio_capture_cost>0&&((o=n==null?void 0:n.localMainAudioTrack)==null||o.updateAfter3aSilenceStartTime((a=t.senderStats.audio.audioCaptureEnergyAfter3a)!=null?a:t.senderStats.audio.micAudioLevel))):delete i.msg_device_info.uint32_audio_capture_cost}!I((l=E.msg_device_info)==null?void 0:l.uint32_task_cost)&&!I(i.msg_device_info.uint32_task_cost)&&(i.msg_device_info.uint32_task_cost=Math.round(this.getDifferenceValue(E.msg_device_info.uint32_task_cost,i.msg_device_info.uint32_task_cost)));let y=E.msg_up_stream_info.msg_video_status;i.msg_up_stream_info.msg_video_status.forEach(S=>{let A=y.find(Re=>Re.uint32_video_stream_type===S.uint32_video_stream_type);if(!A||A.uint32_video_codec_bitrate===0)return S.uint32_video_codec_bitrate=0,S.uint32_video_enc_fps=0,void(S.uint32_video_codec_fps=0);let L=0,U=0,q=0;A&&S.uint32_video_codec_bitrate>=A.uint32_video_codec_bitrate&&(L=A.uint32_video_codec_bitrate,U=A.uint32_video_enc_fps,q=A.uint32_video_codec_fps);let fe=this.getDifferenceValue(L,S.uint32_video_codec_bitrate);S.uint32_video_codec_bitrate=Math.round(8*fe/T),i.msg_up_stream_info.msg_network_status.uint32_bitrate+=S.uint32_video_codec_bitrate,S.uint32_video_enc_fps=Math.round(this.getDifferenceValue(U,S.uint32_video_enc_fps)/T),S.uint32_video_codec_fps=Math.round(this.getDifferenceValue(q,S.uint32_video_codec_fps)/T),A.uint32_video_width===0&&A.uint32_video_height===0&&A.uint32_video_codec_fps===0&&(S.uint32_video_codec_fps=S.uint32_video_enc_fps),I(A.uint32_key_frame_count)||(S.uint32_key_frame_count=Math.round(this.getDifferenceValue(A.uint32_key_frame_count,S.uint32_key_frame_count))),I(A.uint32_nack_count)||(S.uint32_nack_count=Math.round(this.getDifferenceValue(A.uint32_nack_count,S.uint32_nack_count))),I(A.uint32_pli_count)||(S.uint32_pli_count=Math.round(this.getDifferenceValue(A.uint32_pli_count,S.uint32_pli_count))),I(A.uint32_video_arq_packets)||(S.uint32_video_arq_packets=Math.round(this.getDifferenceValue(A.uint32_video_arq_packets,S.uint32_video_arq_packets))),I(A.uint32_encode_cost)||(S.uint32_encode_cost=Math.round(this.getDifferenceValue(A.uint32_encode_cost,S.uint32_encode_cost)/T)),I(A.uint32_send_packet_cost)||(S.uint32_send_packet_cost=Math.round(this.getDifferenceValue(A.uint32_send_packet_cost,S.uint32_send_packet_cost)/T))});let D=E.msg_down_stream_info;i.msg_down_stream_info=i.msg_down_stream_info.filter(S=>D.find(A=>A.msg_user_info.uint64_tinyid===S.msg_user_info.uint64_tinyid));let N=i.msg_down_stream_info;if(N.forEach(S=>{let A=D.find(L=>L.msg_user_info.uint64_tinyid===S.msg_user_info.uint64_tinyid);if(Gi(S.msg_audio_status)||Gi(A.msg_audio_status))S.msg_audio_status={};else{let L=S.msg_audio_status,U=A.msg_audio_status,q=this.getDifferenceValue(U.uint32_audio_cache_ms_count,L.uint32_audio_cache_ms_count);delete L.uint32_audio_cache_ms_count,L.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(U.uint32_audio_cache_ms,L.uint32_audio_cache_ms)/q)||0;let fe=this.room.remotePublishedUserMap.get(S.msg_user_info.str_identifier);fe&&(fe.remoteAudioTrack.stat.jitterBufferDelay=L.uint32_audio_cache_ms),L.uint32_audio_origin_lost=this.getDifferenceValue(U.uint32_audio_origin_lost,L.uint32_audio_origin_lost),L.uint32_audio_receive=this.getDifferenceValue(U.uint32_audio_receive,L.uint32_audio_receive),L.uint32_audio_receive+=L.uint32_audio_origin_lost;let Re=this.getDifferenceValue(U.uint32_audio_codec_bitrate,L.uint32_audio_codec_bitrate);L.uint32_audio_codec_bitrate=Math.round(8*Re/T),L.uint32_audio_total_bitrate=Math.round(8*Re/T)}if(S.msg_video_status&&A.msg_video_status){let L=A.msg_video_status;S.msg_video_status=S.msg_video_status.filter(U=>L.find(q=>q.uint32_video_stream_type===U.uint32_video_stream_type)),S.msg_video_status.forEach(U=>{let q=L.find(vW=>vW.uint32_video_stream_type===U.uint32_video_stream_type),fe=q.uint32_video_receive,Re=q.uint32_video_origin_lost,ne=q.uint32_video_codec_bitrate,ft=q.uint32_video_receive_fps,xe=q.uint32_video_dec_fps;U.uint32_video_origin_lost=this.getDifferenceValue(Re,U.uint32_video_origin_lost),U.uint32_video_receive=this.getDifferenceValue(fe,U.uint32_video_receive)+U.uint32_video_origin_lost;let yt=this.getDifferenceValue(ne,U.uint32_video_codec_bitrate);U.uint32_video_codec_bitrate=Math.round(8*yt/T);let Wu=this.getDifferenceValue(ft,U.uint32_video_receive_fps);U.uint32_video_receive_fps=Math.round(Wu/T),U.uint32_video_dec_fps=Math.round(this.getDifferenceValue(xe,U.uint32_video_dec_fps)/T);let x_=this.getDifferenceValue(q.uint32_video_cache_ms_count,U.uint32_video_cache_ms_count);delete U.uint32_video_cache_ms_count,U.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(q.uint32_video_cache_ms,U.uint32_video_cache_ms)/x_)||0})}}),!I((c=v==null?void 0:v.mediaPlayoutStats)==null?void 0:c.totalSamplesDuration)&&!I((d=t.mediaPlayoutStats)==null?void 0:d.totalSamplesDuration)){let S=2*Math.floor(this.getDifferenceValue((h=v==null?void 0:v.mediaPlayoutStats)==null?void 0:h.synthesizedSamplesDuration,(m=t.mediaPlayoutStats)==null?void 0:m.synthesizedSamplesDuration)/T),A=2*Math.floor(this.getDifferenceValue((p=v==null?void 0:v.mediaPlayoutStats)==null?void 0:p.totalSamplesDuration,(f=t.mediaPlayoutStats)==null?void 0:f.totalSamplesDuration)/T);i.msg_device_info.uint32_audio_play_cost=A-S}return v&&t.receiverStats.forEach(S=>{if(S.audio.concealedSamples&&S.audio.totalSamplesReceived){let A=v.receiverStats.find(L=>L.userId===S.userId);if(A&&A.audio.concealedSamples&&A.audio.totalSamplesReceived){let L=(S.audio.silentConcealedSamples||0)-(A.audio.silentConcealedSamples||0),U=S.audio.concealedSamples-A.audio.concealedSamples,q=S.audio.totalSamplesReceived-A.audio.totalSamplesReceived,fe=Math.floor((U-L)/q*1e3*T);if(fe>1e3*T/5){let Re=N.find(ne=>ne.msg_user_info.str_identifier===S.userId);Re&&(Re.msg_audio_status.uint32_audio_block_time=fe)}}}}),i.msg_down_stream_info.forEach(S=>{S.msg_video_status.forEach(A=>{A.uint32_video_codec_bitrate===0&&A.uint32_video_receive_fps===0&&(A.uint32_video_width=0,A.uint32_video_height=0)})}),i}getStatsReport(e){return g(this,arguments,function(t){var i=this;let{uplinkConnection:r,downlinkConnections:n,freezeMap:s}=t;return(function*(){let a={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}}]},o=yield i.getStats(r,n);return JSON.stringify(i._prevReport)==="{}"&&(i._prevReport=JSON.parse(JSON.stringify(a))),i.prepareReport({stats:o,report:a,freezeMap:s,uplinkConnection:r}),i._prevReportTime=Date.now(),a})()})}getMediaPlayoutStats(e){let t;if(Ue(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}}updateVideoCaptureStats(e,t){var i,r;if((r=(i=e==null?void 0:e.sourceTrack)==null?void 0:i.stats)==null||!r.deliveredFrames)return;let{deliveredFrames:n}=e.sourceTrack.stats;t.framesCaptured=n;let s=e.stat.framesCaptured;s&&s>0&&n>=s&&(t.fpsCapture=Math.floor((n-s)/this.statInterval)),e.stat.framesCaptured=n}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map,[this.room.capturedLocalMainVideoTrack,this.room.capturedLocalAuxVideoTrack].forEach(e=>{e!=null&&e.stat&&(e.stat.framesCaptured=0)})}},j4=Ge(it());function z4(e){return new Promise(t=>g(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(a){let o={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let l=performance.getEntriesByType("resource").reverse();for(let c of l)if(c.name===a){let d=Math.round(c.duration),h=Math.max(Math.round(c.domainLookupStart-c.startTime),0),m=c.redirectStart>0?Math.max(Math.round(c.redirectEnd-c.redirectStart),0):0,p=c.fetchStart>0?Math.max(Math.round(c.domainLookupStart-c.fetchStart),0):0,f=Math.round(c.domainLookupEnd-c.domainLookupStart),T=Math.round(c.requestStart-c.secureConnectionStart),E=Math.round(c.secureConnectionStart-c.connectStart),v=Math.round(c.responseStart-c.requestStart),y=Math.round(c.responseEnd-(c.responseStart||c.startTime));o=W(x({},o),{totalCost:d,local:h,redirect:m,httpCache:p,dns:f,tcp:E,tls:T,request:v,response:y});break}}catch{}return o})(n);s.totalCost===0&&(s.totalCost=Date.now()-r),t(s)}))}var Uu=class Os extends j4.default{constructor(t){let{signalChannel:i,room:r}=t;super(),u(this,"_room"),u(this,"_signalChannel"),u(this,"_log"),u(this,"uplinkRTT",0),u(this,"uplinkLoss",0),u(this,"downlinkRTT",0),u(this,"downlinkLoss",0),u(this,"pingResults",{}),u(this,"_downlinkPrevStatMap",new Map),u(this,"_downlinkLossAndRTTMap",new Map),u(this,"_interval",-1),u(this,"_uplinkNetworkQuality",0),u(this,"_downlinkNetworkQuality",0),u(this,"_uplinkQualityHistory",[]),u(this,"_downlinkQualityHistory",[]),this._room=r,this._signalChannel=i,this._log=P.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>Os.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>Os.HISTORY_SIZE&&this._downlinkQualityHistory.shift()}initialize(){this._signalChannel.on(X.UPLINK_NETWORK_STATS,t=>{this.handleUplinkNetworkQuality(t)}),this._signalChannel.on(k_,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 a=n.expectAudPkg+n.expectVidPkg,o=n.recvAudPkg+n.recvVidPkg,l=a-o;a===0&&o===0||(this.uplinkLoss=l<=0?0:Math.round(l/a*100),this.uplinkRTT=n.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return g(this,null,function*(){if(this._room.remotePublishedUserMap.size===0)return void(this.downlinkNetworkQuality=0);let t=[...this._room.remotePublishedUserMap.values()],i=new Set,r=t.filter(o=>{let l=o.getPeerConnection();return!(!l||i.has(l))&&(i.add(l),!0)}),n=r.filter(o=>{var l;return((l=o.getPeerConnection())==null?void 0:l.connectionState)===Be.CONNECTED});if(r.filter(o=>this.isPeerConnectionDisconnected(o.getPeerConnection())).length===t.length)return void(this.downlinkNetworkQuality=6);for(let o=0;o<n.length;o++){let l=n[o].getPeerConnection();if(!l)return;let{rtt:c,totalPacketsLost:d,totalPacketsReceived:h}=yield this.getStat(l);if(!this._downlinkPrevStatMap.has(l)){this._downlinkPrevStatMap.set(l,{totalPacketsLost:d,totalPacketsReceived:h});continue}let m=0,p=this._downlinkPrevStatMap.get(l),f=d-p.totalPacketsLost,T=h-p.totalPacketsReceived;m=f<=0||T<0?0:Math.round(f/(f+T)*100),this._downlinkPrevStatMap.set(l,{totalPacketsLost:d,totalPacketsReceived:h}),this._downlinkLossAndRTTMap.set(l,{rtt:c,loss:m,userId:n[o].getUserId(),audioDelay:n[o].remoteAudioTrack.stat.end2EndDelay,videoDelay:n[o].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(o=>{this.isPeerConnectionDisconnected(o)&&(this._downlinkPrevStatMap.delete(o),this._downlinkLossAndRTTMap.delete(o))}),this._downlinkLossAndRTTMap.size===0)return this.downlinkRTT=0,this.downlinkLoss=0,void(this.downlinkNetworkQuality=0);let{rtt:s,loss:a}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=s,this.downlinkLoss=a,this.downlinkNetworkQuality=this.getNetworkQuality(a,s)})}getStat(t){return g(this,null,function*(){let i={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!t||!Jc())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"&&le(s.currentRoundTripTime)&&(i.rtt=Math.round(1e3*s.currentRoundTripTime)),s.type==="inbound-rtp"&&(s.mediaType===_.AUDIO||s.mediaType===_.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=1)}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!==Be.DISCONNECTED&&t.connectionState!==Be.FAILED&&t.connectionState!==Be.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=_e.run("ric",()=>{var t;this.handleDownlinkNetworkQuality();let i=[...this._downlinkLossAndRTTMap.values()];R.emit(b.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=W(x({},n),{pingResults:this.uplinkRTT>r.rttThreshold||this.downlinkRTT>r.rttThreshold?this.pingResults:{}})),this.emit(Os.EVENT_NETWORK_QUALITY,n);let s=Date.now();if(r&&(this.uplinkRTT>r.rttThreshold||this.downlinkRTT>r.rttThreshold)&&s-Os.lastPingTime>1e3*r.interval){Os.lastPingTime=Date.now();let a=r.domain.map(o=>z4(o).then(l=>({domain:o,cost:l.totalCost})));Promise.all(a).then(o=>{this.pingResults.isPoorNetwork=o.some(l=>l.cost>700),this.pingResults.timestamp=s,this.pingResults.data=o,o.forEach(l=>{w.addSuccessEvent({key:521718,cost:l.cost})}),this._log.warn("All ping results: ".concat(JSON.stringify(o)))}).catch(o=>{this._log.warn("Error during pinging domains: ".concat(o))})}},{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&&(_e.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:a}=r,o=i.get(n);if(o){let l=this._room.remotePublishedUserMap.get(o);l==null||l.setDelay({videoDelay:s,audioDelay:a})}})}};u(Uu,"HISTORY_SIZE",10),u(Uu,"EVENT_NETWORK_QUALITY","0"),u(Uu,"lastPingTime",0);var X0=Uu,Q0=class{constructor(e){u(this,"_frameWorkType"),u(this,"_component"),u(this,"_language"),u(this,"connectionType"),u(this,"_room"),u(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,reportToken:void 0}),u(this,"_keyPrefix"),u(this,"_log"),u(this,"_intervalId"),u(this,"_firstPublishedUserList"),u(this,"_networkQuality"),u(this,"_basicInfo"),u(this,"_pathJoinRoom"),u(this,"_pathLeaveRoom"),u(this,"_pathMainVideoMap"),u(this,"_pathMainAudioMap"),u(this,"_pathAuxiliaryMap"),u(this,"_remoteStreamStatMap"),u(this,"_localStreamStat"),u(this,"_eventMap",new Map),u(this,"_captureCostSum",0),u(this,"_captureCostCount",0),u(this,"isDestroyed",!1),u(this,"_lastReportData"),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=P.createLogger({parent:this._room.getLogger(),id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(t=>{t.startsWith("handle")&&Pe(this[t])&&(this[t]=(function(i){let{fn:r,context:n}=i;return function(){try{for(var s=arguments.length,a=new Array(s),o=0;o<s;o++)a[o]=arguments[o];let l=r.apply(n,a);return Pa(l)?l.catch(c=>P.error("".concat(r.name,"() error observed ").concat(c))):l}catch(l){P.error("".concat(r.name,"() error observed ").concat(l))}}})({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:ei,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,Wc().then(()=>{this._basicInfo.string_os_version=Er(),this._basicInfo.string_device_name=nn()||this._basicInfo.string_os_version})}addEvent(e,t){return this._eventMap.set(e,t),R.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(b.JOIN_START,this.handleJoinStart).addEvent(b.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(b.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(b.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(b.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(b.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(b.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(b.JOIN_FAILED,this.handleJoinFailed).addEvent(b.LEAVE_START,this.handleLeaveStart).addEvent(b.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(b.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(b.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(b.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(b.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(b.PUBLISH_START,this.handlePublishStart).addEvent(b.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(b.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(b.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(b.PLAY_TRACK_START,this.handlePlayStart).addEvent(b.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(b.PLAYER_STATE_CHANGED,e=>{let{track:t,state:i,type:r}=e;!t.isRemote||!this.hitTest(t.room)||i==="PLAYING"&&(r===_.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(b.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(b.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(b.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(b.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(b.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(b.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(b.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,a=r.hasAudio||r.hasVideo||r.hasSmall,o=r.hasAuxiliary;!n&&a&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&o&&this.handleRemoteStreamAdded(r.userId,"auxiliary")}).addEvent(b.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)=>R.off(t,e)),this._eventMap.clear()}destroy(){this.uninstallEvents(),_e.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&&(I(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),I(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),I(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:a,tls:o,request:l,response:c}=i;this._pathJoinRoom.int32_schedule_cost=r,this._pathJoinRoom.int32_schedule_local=n,this._pathJoinRoom.int32_schedule_dns=s,this._pathJoinRoom.int32_schedule_tcp=a,this._pathJoinRoom.int32_schedule_tls=o,this._pathJoinRoom.int32_schedule_request=l,this._pathJoinRoom.int32_schedule_response=c}}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 O?Number(i.getExtraCode()||i.getCode()):C.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=J()-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._pathJoinRoom.uint64_end_time!==0&&(this._basicInfo.uint32_joining_duration=t-this._pathJoinRoom.uint64_end_time),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 O?Number(i.getExtraCode()||i.getCode()):C.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:W(x({},J4),{msg_user_info:new M_({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:a,role:o}=i,l=new M_({userId:s,tinyId:a,role:o==="anchor"?20:21}),c=Date.now(),d="".concat(s,"_").concat(r),h=this._remoteStreamStatMap.get(d);h&&h.subscribeStartTime===0&&(h.subscribeStartTime=c),r==="main"?(i.muteState.hasVideo&&(n.video||n.smallVideo)&&!this._pathMainVideoMap.has(d)&&this._pathMainVideoMap.set(d,{statsToReport:{msg_user_info:l,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:s,sendSubscribeCMDTime:c}),i.muteState.hasAudio&&n.audio&&!this._pathMainAudioMap.has(d)&&this._pathMainAudioMap.set(d,{statsToReport:{msg_user_info:l,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,sendSubscribeCMDTime:c})):i.muteState.hasAuxiliary&&n.auxiliary&&!this._pathAuxiliaryMap.has(d)&&this._pathAuxiliaryMap.set(d,{sendSubscribeCMDTime:c})}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==null?void 0: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 a=i-this._pathJoinRoom.uint64_start_time;s.uint32_video_render_first=a,w.addNumber({key:516820,value:a})}}(r==null?void 0: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:a}=t,o=this._networkQuality.totalDownlinkRTTAndLossMap.get(n);if(o)o.totalRTT+=i,o.totalLoss+=r,s&&(o.totalVideoDelay=(o.totalVideoDelay||0)+s,o.videoDelayCount=(o.videoDelayCount||0)+1),a&&(o.totalAudioDelay=(o.totalAudioDelay||0)+a,o.audioDelayCount=(o.audioDelayCount||0)+1),o.count++;else{let l,c,d,h;s&&(c=s,d=1),a&&(l=a,h=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(n,{totalRTT:i,totalLoss:r,count:1,totalAudioDelay:l,totalVideoDelay:c,audioDelayCount:h,videoDelayCount:d})}}))}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:a,uint32_video_width:o,uint32_video_height:l}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=s,this._localStreamStat.totalVideoFPS+=a,this._localStreamStat.totalVideoWidth+=o,this._localStreamStat.totalVideoHeight+=l,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:s}=r.msg_audio_status;Math.floor(s/fi*100)>0&&(this._localStreamStat.totalAudioLevel+=s/fi,this._localStreamStat.audioLevelCount++)}n.forEach(s=>{let{msg_user_info:a,msg_audio_status:o,msg_video_status:l}=s,c=a.str_identifier,d=this._room.remotePublishedUserMap.get(c);if(l.forEach(h=>{let m=h.uint32_video_stream_type===2,p=h.uint32_video_stream_type===7,f="".concat(c,"_").concat(m?"main":"auxiliary"),T=this._remoteStreamStatMap.get(f);if(T&&(m&&d!=null&&d.remoteVideoTrack.isSubscribed||p&&d!=null&&d.remoteAuxiliaryTrack)){T.totalVideoFPS+=h.uint32_video_receive_fps,T.totalVideoBitrate+=h.uint32_video_codec_bitrate,T.videoCount++,T.statsToReport.uint32_video_width===0&&(T.statsToReport.uint32_video_width=h.uint32_video_width),T.statsToReport.uint32_video_height===0&&(T.statsToReport.uint32_video_height=h.uint32_video_height);let E=m?d.remoteVideoTrack:d.remoteAuxiliaryTrack;E.stat.jitterBufferDelay&&(T.videoJitterBufferDelay=E.stat.jitterBufferDelay),E.stat.framesReceived&&(T.statsToReport.uint32_video_consume_render_rate=Math.floor(E.stat.framesDecoded/E.stat.framesReceived*ga(10,6)))}}),!yc(o)){let h="".concat(c,"_main"),m=this._remoteStreamStatMap.get(h);this._remoteStreamStatMap.has(h)&&m&&d!=null&&d.remoteAudioTrack.isSubscribed&&(m.totalAudioBitrate+=o.uint32_audio_codec_bitrate,m.audioCount++,d.remoteAudioTrack.stat.jitterBufferDelay&&(m.audioJitterBufferDelay=d.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(o.uint32_audio_level/fi*100)>0&&(m.totalAudioLevel+=o.uint32_audio_level/fi,m.audioLevelCount++),o.uint32_audio_block_time&&(m.statsToReport.uint32_audio_block_time+=o.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 O?i.getExtraCode()||i.getCode():C.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&Sa)>=0}hasAudioFlag(e){return this._firstPublishedUserList.findIndex(t=>t.userId===e&&t.flag&Ia)>=0}hasAuxFlag(e){return this._firstPublishedUserList.findIndex(t=>t.userId===e&&t.flag&hc)>=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._basicInfo.uint32_avg_rtt===0&&this._networkQuality.totalDownlinkRTTAndLossMap.size>0){let e=0,t=0;this._networkQuality.totalDownlinkRTTAndLossMap.forEach(i=>{e+=i.totalRTT,t+=i.count}),t>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(e/t))}if(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:c,count:d,audioDelayCount:h,videoDelayCount:m,totalAudioDelay:p,totalVideoDelay:f}=r;e.statsToReport.uint32_avg_down_loss=Math.floor(c/d),h&&p&&(e.statsToReport.uint32_audio_network_p2p_delay=Math.floor(p/h),e.audioJitterBufferDelay&&(e.statsToReport.uint32_p2p_delay=Math.floor(e.statsToReport.uint32_audio_network_p2p_delay+e.audioJitterBufferDelay))),m&&f&&(e.statsToReport.uint32_video_network_p2p_delay=Math.floor(f/m))}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,_.AUDIO),e.statsToReport.uint32_video_play_time=n.getDuration(t,_.VIDEO)),e.statsToReport.uint32_video_render_first&&(e.statsToReport.uint32_video_render_first=Math.min(e.statsToReport.uint32_video_render_first,En));let{badCaseDetector:s}=this._room,{dataFreeze:a,count:o}=s.getDataFreezeDuration(t),{renderFreeze:l}=s.getRenderFreezeDuration(t);e.statsToReport.uint32_video_block_count=o,e.statsToReport.uint32_video_block_time=Math.min(a,e.statsToReport.uint32_video_play_time),e.statsToReport.uint32_video_external_block_time=Math.min(l,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>En&&(e.statsToReport.uint64_play_first_frame_time=e.statsToReport.uint64_start_enter_time+En):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>En&&(e.statsToReport.uint64_render_first_frame_time=e.statsToReport.uint64_start_enter_time+En):this._pathMainVideoMap.delete(t)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>En&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+En)}getReportData(){this._basicInfo.uint32_networkType=Na();let e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new M_({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:La(this._signalInfo.relayIp),uint32_client_ip:La(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*ga(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:La(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 Ac(e),e}report(){return g(this,null,function*(){try{this.prepareReport();let e=this.getReportData();yield this.upload(e),this._lastReportData=e,this.initData()}catch(e){this._log.warn(e)}finally{this.isDestroyed&&(this._room=null)}})}upload(e){return g(this,null,function*(){if(e.msg_path_enter_room.uint64_start_time===0)return;let t=Number(this._room.sdkAppId),i=Ya.enable?us(e,2001,t):yield rR(e),r=i instanceof ArrayBuffer,n="".concat(os(t,va.KEY_POINT),"&gzip=").concat(+r),s=!1;navigator.sendBeacon&&(s=navigator.sendBeacon(n,i));let a=[this.uploadKVStat(w),this.uploadKVStat(Qa)];s||a.push(Va({url:n,body:i,priority:"low"})),yield Promise.all(a)})}setConnectionType(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}uploadKVStat(e){return g(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 a=t.getReportData((n=i._room)==null?void 0:n.userSig,(s=i._signalInfo)==null?void 0:s.reportToken);if(a.stats_count.length===0&&a.stats_distribution.length===0)return;a.msg_sdk_basic_info=W(x({},a.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(a);let o=Ya.enable?us(a,2003,r):yield rR(a),l=o instanceof ArrayBuffer,c="".concat(os(+r,va.KV_STAT),"&gzip=").concat(+l),d=!1;navigator.sendBeacon&&(d=navigator.sendBeacon(c,o)),d||Va({url:c,body:o})})()})}getLastReportData(){return this._lastReportData}};M([vr({settings:{timeout:500,retries:3}})],Q0.prototype,"upload");var En=5e3,J4={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},M_=class{constructor(e){u(this,"str_identifier"),u(this,"str_tinyid"),u(this,"uint32_role"),this.str_identifier=String(e.userId),this.str_tinyid=String(e.tinyId||0),this.uint32_role=e.role}},K4=Q0,Z0=class{constructor(){u(this,"_startTime"),u(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=J())}stop(){this._endTime===0&&(this._endTime=J())}getDuration(){return this._endTime===0?J()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},q4=class{constructor(e){u(this,"_room",null),u(this,"_durationMap"),u(this,"_eventMap",new Map),this._room=e.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(b.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(b.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(b.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"),_.AUDIO),i.hasVideo&&!r.hasVideo&&this.stopDurationItem("".concat(s,"_main"),_.VIDEO),i.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem("".concat(s,"_auxiliary"),_.VIDEO);let a=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(s);a&&(!i.hasAudio&&r.hasAudio&&a.remoteAudioTrack.isSubscribed&&this.addDuractionItem(s,_.AUDIO,"main"),!i.hasVideo&&r.hasVideo&&a.remoteVideoTrack.isSubscribed&&this.addDuractionItem(s,_.VIDEO,"main"),!i.hasAuxiliary&&r.hasAuxiliary&&a.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(s,_.VIDEO,"auxiliary"))}).set(b.LEAVE_SUCCESS,e=>{let{room:t}=e;this.hitTest(t)&&this.reset()}).set(b.SWITCH_ROOM_SUCCESS,e=>{let{room:t}=e;this.hitTest(t)&&this.reset()}),this._eventMap.forEach((e,t)=>R.on(t,e,this))}uninstallEvents(){this._eventMap.forEach((e,t)=>R.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 Z0,s=this._durationMap.get(r);s?this.isRecording(s[t])||s[t].push(n):this._durationMap.set(r,{userId:e,type:i,audio:t===_.AUDIO?[n]:[],video:t===_.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()}},Y4=class{constructor(){u(this,"renderFreezeMap",new Map),u(this,"dataFreezeMap",new Map)}get(e,t){let i=this.renderFreezeMap.get(e),r=this.dataFreezeMap.get(e);return t?t==="data"?r:i:i&&r?i.duration>r.duration?i:r: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()}},X4=class{constructor(e){u(this,"_room"),u(this,"_renderFreezeMap",new Map),u(this,"_isVideoPlayingEventFiredMap",new Map),u(this,"_dataFreezeMap",new Map),u(this,"_monitorFreezeData",new Y4),u(this,"_eventMap",new Map),u(this,"_videoEncodeFailedCount",0),u(this,"_audioEncodeFailedCount",0),u(this,"_encodeFailedThreshold",3),u(this,"ABNORMAL_TIME_LOWER_LIMIT",3e3),u(this,"ABNORMAL_TIME_UPPER_LIMIT",5e3),u(this,"_videoAbnormalTimestampMap",new Map),u(this,"_remoteVideoAbnormalTimestampMap",new Map),u(this,"_audioAbnormalTimestampMap",new Map),u(this,"eventListenerMap",new Map),this._room=e.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(b.LEAVE_SUCCESS,e=>{let{room:t}=e;this.hitTest(t)&&this.stop()}).set(b.SWITCH_ROOM_SUCCESS,e=>{let{room:t}=e;this.hitTest(t)&&this.stop()}).set(b.PLAY_TRACK_START,this.onPlayTrackStart).set(b.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(b.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",a="".concat(r.userId,"_").concat(s);this.stopDataFreeze({key:a,userId:n,type:s})}if(i.hasAuxiliary&&!r.hasAuxiliary){let s="auxiliary",a="".concat(r.userId,"_").concat(s);this.stopDataFreeze({key:a,userId:n,type:s})}}).set(b.PLAYER_STATE_CHANGED,e=>{let{track:t,state:i,reason:r,type:n}=e;if(t.isRemote&&t.room&&this.hitTest(t.room)&&n===_.VIDEO){if(i==="PLAYING"){let s="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(s,!0)}r===_.MUTE?this.onVideoTrackMuted(t):r===_.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(b.HEARTBEAT_REPORT,this.onHearBeatReport).set(b.REMOTE_VIDEO_PLAY_START,this.onRemoteVideoPlayStart).set(b.REMOTE_VIDEO_PLAY_FINISH,this.onRemoteVideoPlayEnd),this._eventMap.forEach((e,t)=>R.on(t,e,this))}uninstallEvents(){this._eventMap.forEach((e,t)=>R.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 Z0;n?n.durationItemList.push(s):this._dataFreezeMap.set(r,{userId:t,type:i,durationItemList:[s],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.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 a=J();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 o=this._remoteVideoAbnormalTimestampMap.get("".concat(r,"-decode"));o&&a-o>this.ABNORMAL_TIME_LOWER_LIMIT&&a-o<this.ABNORMAL_TIME_UPPER_LIMIT&&ue.uploadEvent({userId:this._room.userId,log:"stat-".concat(Qe.VIDEO_DECODE_FAILED_DURING_CALL)})}else this._remoteVideoAbnormalTimestampMap.set("".concat(r,"-decode"),a);else{let o=this._remoteVideoAbnormalTimestampMap.get("".concat(r,"-decode"));o&&a-o>=this.ABNORMAL_TIME_UPPER_LIMIT&&(ue.uploadEvent({userId:this._room.userId,log:"stat-".concat(Qe.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_stream_type===2&&s.uint32_video_dec_fps<=5||s.uint32_video_stream_type===7&&s.uint32_video_dec_fps===0))if(this._remoteVideoAbnormalTimestampMap.has("".concat(r,"-hardware"))){let o=this._remoteVideoAbnormalTimestampMap.get("".concat(r,"-hardware"));if(o&&a-o>this.ABNORMAL_TIME_LOWER_LIMIT/2&&a-o<2*this.ABNORMAL_TIME_UPPER_LIMIT){ue.uploadEvent({userId:this._room.userId,log:"stat-".concat(Qe.VIDEO_HARDWARE_DECODE_FAILED)});let l=this._room.remotePublishedUserMap.get(r);if(l){let c=s.uint32_video_stream_type===2?l.remoteVideoTrack:l.remoteAuxiliaryTrack;c&&(c.log.warn("decode failed during call"),c.emit("decode-failed-during-call"))}}}else this._remoteVideoAbnormalTimestampMap.set("".concat(r,"-hardware"),a);else{let o=this._remoteVideoAbnormalTimestampMap.get("".concat(r,"-hardware"));o&&a-o>=2*this.ABNORMAL_TIME_UPPER_LIMIT&&(ue.uploadEvent({userId:this._room.userId,log:"stat-".concat(Qe.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==null?void 0:i.stat.bytesSent)||0;if((i==null?void 0:i.isMediaTrackActive)===!1||r<=0||i!=null&&i.isUseCustomSource)return;t.forEach(n=>{let s=J();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 a=this._videoAbnormalTimestampMap.get("local-encode");a&&s-a>this.ABNORMAL_TIME_LOWER_LIMIT&&s-a<this.ABNORMAL_TIME_UPPER_LIMIT&&ue.uploadEvent({userId:this._room.userId,log:"stat-".concat(Qe.VIDEO_ENCODE_FAILED_DURING_CALL)})}else this._videoAbnormalTimestampMap.set("local-encode",s);else{let a=this._videoAbnormalTimestampMap.get("local-encode");a&&s-a>=this.ABNORMAL_TIME_UPPER_LIMIT&&ue.uploadEvent({userId:this._room.userId,log:"stat-".concat(Qe.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==null?void 0:i.stat.bytesSent)||0;if((i==null?void 0:i.isMediaTrackActive)===!1||r<=0||i!=null&&i.isUseCustomSource)return;let n=J();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&&ue.uploadEvent({userId:this._room.userId,log:"stat-".concat(Qe.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&&ue.uploadEvent({userId:this._room.userId,log:"stat-".concat(Qe.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 a=s.getDuration();if(a>fp){let o=this._monitorFreezeData.get(t,"data");this._monitorFreezeData.set(t,{userId:i,type:r,duration:o?o.duration+a:a},"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!==_.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()<fp&&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(!io())return;let n=0,s=()=>{document.hidden||(n=0)};document.addEventListener("visibilitychange",s);let a=(o,l)=>{var c;if(n){let d=t.decodeFPS,h=d>0&&d<=5?600+1e3/d:600,m=l.presentationTime-n;if(m>h){m=Math.min(m,5e3);let p="".concat(t.userId,"_").concat(t.streamType),f=this._monitorFreezeData.get(p,"render");f?f.duration+=m:this._monitorFreezeData.set(p,{userId:t.userId,type:t.streamType,duration:m},"render");let T=this._renderFreezeMap.get(p);T?(T.totalDuration+=m,T.count+=1):this._renderFreezeMap.set(p,{userId:t.userId,type:t.streamType,totalDuration:m,count:1})}}n=l.presentationTime,(c=i.element)==null||c.requestVideoFrameCallback(a)};(r=i.element)==null||r.requestVideoFrameCallback(a),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()}},Q4=Ge(it(),1),Z4=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,u(this,"animationState"),u(this,"originalAspect"),u(this,"totalOffsetX",0),u(this,"totalOffsetY",0),u(this,"defaultScaleRatio",.1),u(this,"isRecovering",!1),u(this,"boundaryY",280),u(this,"lastActionTime",0),u(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?w.addSuccessEvent({key:r.key}):w.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,a=s.originX,o=s.originY,l=s.width,c=s.height;this.vbMode===1?this.dualStageCropping(i,r,a,o,l,c):this.vbMode===2&&this.movingPortrait(i,r,a,o,l,c)}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 a,o,l=arguments.length>6&&arguments[6]!==void 0?arguments[6]:.4,c=e+i/2,d=t+r/2,{min:h,offset:m}=this.calculateBoundary(c,n,e,i),{min:p,offset:f}=this.calculateBoundary(d,s,t,r);return a=2*h+i,o=2*p+r,a/o>this.originalAspect?(a=o*this.originalAspect,m=c-a/2):(o=a/this.originalAspect,f=d-o/2),i/n>l&&(m=0,f=0,a=n,o=s),m=Math.max(0,Math.min(m,n-a)),f=Math.max(0,Math.min(f,s-o)),{sx:m,sy:f,cropWidth:a,cropHeight:o,timestamp:Date.now()}}processFacePositionCrop(e,t,i){if(!this.animationState.current||!this.animationState.target){let a={sx:0,sy:0,cropWidth:t,cropHeight:i,timestamp:Date.now()};return this.animationState.current=a,void(this.animationState.target=a)}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=x({},e),void(this.animationState.target=x({},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)),le(this.animationState.current.scaleOffsetX)&&le(this.animationState.target.scaleOffsetX)&&le(this.animationState.current.scaleOffsetY)&&le(this.animationState.target.scaleOffsetY)){let s=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*i(t);this.animationState.current.scaleOffsetX+=s;let a=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*i(t);this.animationState.current.scaleOffsetY+=a}}t>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(e,t){return Math.sqrt(ga(e.sx-t.sx,2)+ga(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 a=arguments.length>6&&arguments[6]!==void 0?arguments[6]:.3;if(this.isRecovering)return;let o=this.calculateTargetPosition(i,r,n,s,e,t);this.processFacePositionCrop(o,e,t),n*s/o.cropWidth/o.cropHeight>a&&this.recoverOriginal(e,t)}movingPortrait(e,t,i,r,n,s){var a,o,l,c,d,h,m,p,f,T,E,v;let y={sx:i+n/2+this.totalOffsetX,sy:r+s/2+this.totalOffsetY,cropWidth:e,cropHeight:t,scaleRatio:(o=(a=this.animationState.current)==null?void 0:a.scaleRatio)!=null?o:1,scaleOffsetX:(c=(l=this.animationState.current)==null?void 0:l.scaleOffsetX)!=null?c:0,scaleOffsetY:(h=(d=this.animationState.current)==null?void 0:d.scaleOffsetY)!=null?h:0,timestamp:Date.now()};this.animationState.target={sx:e/2,sy:r+s/2,cropWidth:e,cropHeight:t,scaleRatio:(p=(m=this.animationState.target)==null?void 0:m.scaleRatio)!=null?p:1,scaleOffsetX:(T=(f=this.animationState.target)==null?void 0:f.scaleOffsetX)!=null?T:0,scaleOffsetY:(v=(E=this.animationState.target)==null?void 0:E.scaleOffsetY)!=null?v: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(y)}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}},$4=class extends Is{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}),u(this,"_bgTexture"),u(this,"_waterMarkTexture"),u(this,"_lastMaskTexture"),u(this,"_lastMaskFbo"),u(this,"_textureValid",!1),u(this,"_selfieTextureValid",!1),u(this,"_selfieSegmentationHash"),u(this,"wasm"),u(this,"predictReady"),u(this,"_color"),u(this,"_prePrograme"),u(this,"_segmentationMask"),u(this,"_weixin",!1),u(this,"_centerFace"),u(this,"_textureMatrixLocation"),u(this,"_offsetMatrixLocation"),u(this,"_colorLocation"),u(this,"_enableFaceCentering",!1),u(this,"_enableEffectOptimization",!1),u(this,"_mat4"),u(this,"_postProcessing"),u(this,"_onAbort"),u(this,"_visionTaskRegistry"),u(this,"resolvePreditReady"),this.init(t).catch(i=>{e.log.error(i),e.destroy(new O({code:C.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(i.message||i)})),this.resolvePreditReady()})}init(e){return g(this,null,function*(){var t,i,r;this.predictReady=new Promise(o=>{this.resolvePreditReady=o});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:o,y:l,width:c,height:d}=e.waterMark;this.wasm.setWaterMark(o,l,c,d)}if(e.beautyParams){let{beauty:o,brightness:l,ruddy:c}=e.beautyParams;this.wasm.setBeauty(o,l,c,e==null?void 0:e.width,e==null?void 0: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 a=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,a),this._offsetMatrixLocation=s.getUniformLocation(this.program,"u_offsetMatrix"),s.uniformMatrix4fv(this._offsetMatrixLocation,!1,a),this._colorLocation=s.getUniformLocation(this.program,"u_color"),s.uniform1i(s.getUniformLocation(this.program,"lastMask"),4),this._weixin){let o=this.context.createShader(s.FRAGMENT_SHADER,`#version 300 es
|
||
precision highp float;
|
||
uniform sampler2D u_texture;
|
||
uniform sampler2D mask;
|
||
|
||
in vec2 v_texCoord;
|
||
out vec4 outColor;
|
||
void main() {
|
||
outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);
|
||
}`),l=this.context.createShader(s.VERTEX_SHADER,`#version 300 es
|
||
in vec2 a_position;
|
||
in vec2 a_texCoord;
|
||
out vec2 v_texCoord;
|
||
void main() {
|
||
gl_Position = vec4(a_position.x, a_position.y, 0, 1);
|
||
v_texCoord = a_texCoord;
|
||
}`);this._prePrograme=this.context.createProgram(l,o),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:Hc()?(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 g(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 Z4(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(),fr(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(fr(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 a=this.getMaskTexture(this._segmentationMask);t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,a||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 a=this._visionTaskRegistry.getResult(this._selfieSegmentationHash);this.totalFrames===1&&this.context._canvas&&this.resolvePreditReady(),this.onPredict(a)}}catch(a){this._onAbort&&this._onAbort(a)}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:a=0}=t;this._mat4.fromTranslation(r,[-i.offsetX/e.canvas.width+s,a,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:a}=n.canvas,o=this._mat4.create();this._mat4.fromTranslation(o,[e/s,1-(t+r)/a,0]),this._mat4.scale(o,o,[i/s,r/a,1]),n.uniformMatrix4fv(this._textureMatrixLocation,!1,o)}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()}},eW=class extends Ct{constructor(e){super(e,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:e.log,fragmentShaderSource:`
|
||
precision highp float;
|
||
uniform sampler2D ySampler;
|
||
uniform sampler2D uSampler;
|
||
uniform sampler2D vSampler;
|
||
varying highp vec2 textureCoord;
|
||
const mat4 YUV2RGB = mat4(
|
||
1.1643828125, 0, 1.59602734375, -.87078515625,
|
||
1.1643828125, -.39176171875, -.81296875, .52959375,
|
||
1.1643828125, 2.017234375, 0, -1.081390625,
|
||
0, 0, 0, 1);
|
||
void main() {
|
||
vec3 yuv;
|
||
yuv.r = texture2D(ySampler, textureCoord).r;
|
||
yuv.g = texture2D(uSampler, textureCoord).r;
|
||
yuv.b = texture2D(vSampler, textureCoord).r;
|
||
gl_FragColor = vec4(yuv,1) * YUV2RGB;
|
||
}
|
||
`,vertexShaderSource:`
|
||
attribute vec4 vertexPos;
|
||
attribute vec2 texturePos;
|
||
varying vec2 textureCoord;
|
||
void main() {
|
||
gl_Position = vertexPos;
|
||
textureCoord = texturePos;
|
||
}`}),u(this,"yTextureRef"),u(this,"uTextureRef"),u(this,"vTextureRef"),u(this,"Y"),u(this,"U"),u(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)}},$0=(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")},tW=0,iW=class{constructor(e){u(this,"id",tW++),u(this,"trackDoneOB"),u(this,"startOB"),u(this,"stopOB"),u(this,"decoder"),u(this,"videoContext"),u(this,"gop",0),u(this,"gop_helper",0),u(this,"waitFirstKeyFrame",!0),u(this,"startTimestamp",0),u(this,"startTime",0),u(this,"startPerformanceTime",0),u(this,"inputFrameCount",0),u(this,"decodedFrameCount",0),u(this,"decodeFrameCount",0),u(this,"downgradeLevel",0),u(this,"lastDowngradeTime",0),u(this,"lastFrameDiff",0),u(this,"lastDecodeFrameTimestamp",0),u(this,"config"),u(this,"gop_before_configure",[]),u(this,"videoElement"),u(this,"type","wasm"),u(this,"goodType"),u(this,"renderer","2d"),u(this,"wasmOption"),u(this,"createDecoder"),u(this,"_decodeSink"),u(this,"isReported",!1),u(this,"track"),u(this,"stateChangeOB"),u(this,"failedReason");let{track:t,createDecoder:i}=e;if(this.stateChangeOB=Ti(),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=ye(t.availableState,re.OFF),this.stopOB=Ti(),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),Ie(this.stateChangeOB,Ub((r,n)=>(r!==n&&t.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:r,state:n}),n),"INITIALIZED"),pt(this.stopOB),ze()),this.start()}start(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let t=Ie(this.pipe(this.track),pt(this.stopOB),_o());Ie(t,ze(()=>{this.track.stat.framesDecoded++},i=>{if(this.track.log.error("".concat(this.id," play failed: ").concat(i," retryCount: ").concat(e)),w.addFailedEvent({key:$0(this.type,this.renderer),error:i}),e>4)this.failedReason=i,this.stateChangeOB.next("FAILED"),w.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")),w.addSuccessEvent({key:$0(this.type,this.renderer)}),w.addSuccessEvent({key:514704})})),Ie(t,Ss(1),ze(()=>{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"&&!Ef()&&(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 a=!1;switch(31&n[4]){case 5:case 7:a=!0}if(((i=this.decoder)==null?void 0:i.state)!=="configured")return this.track.log.debug("not configured ".concat(this.inputFrameCount)),a&&(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(l=>this.decode(l,!0)),this.gop_before_configure=[]);let{timestamp:o}=e;if(a?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame){if(!a)return void this.track.log.debug("wait first key frame ".concat(this.inputFrameCount," ").concat(n.subarray(0,5).join(" ")));this.waitFirstKeyFrame=!1,this.startTimestamp=o,this.startTime=Date.now(),this.startPerformanceTime=J()}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(o," ").concat((r=e.getMetadata)==null?void 0:r.call(e).rtpTimestamp)),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=o,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=>g(this,null,function*(){this._decodeSink=t;let i,r=e.mediaTrack;t.defer(()=>{var a;r&&(e.player.setCanvas(),e.setInputMediaStreamTrack(r)),i==null||i.close(),(a=this.videoContext)==null||a.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 a=0;if(i.on("videoFrame",o=>{this.decodedFrameCount++,a++,(a<=10||a%500==0)&&e.log.debug("frame ".concat(a," ").concat(this.decodedFrameCount,"/").concat(this.decodeFrameCount," decoded ").concat(o.timestamp)),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(o.timestamp)),t.next(o)}),i.on("error",o=>{e.log.error(o),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 Gt({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create(),this.videoContext.on(Gt.UNAVAILABLE,l=>{e.log.error(l),t.error(7)});let o=new eW(this.videoContext);i.on("videoCodecInfo",l=>o.resize(l.width,l.height)),i.on("videoFrame",l=>{({y:o.Y,u:o.U,v:o.V}=l),this.downgradeLevel===1?this.decodedFrameCount%2==0&&o.render(this.decodedFrameCount):o.render(this.decodedFrameCount)}),e.source=o,e.player.setCanvas(this.videoContext._canvas,2)}else if(n==="videoFrame"){e.player.setCanvas();let o=new MediaStreamTrackGenerator({kind:"video"}),l=o.writable.getWriter();e.setInputMediaStreamTrack(o),i.on("videoFrame",c=>l.write(c))}else{this.videoContext=new Ei({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create({alpha:!1});let o=this.videoContext.createVideoImageSource();i.on("videoFrame",c=>{try{o.image=c,o.update()}catch(d){delete this.goodType,e.log.error(d),t.error(11)}});let l=new s_(this.videoContext,{name:"remotePlayer",logger:e.log});o.connect(l),e.source=o,e.player.setCanvas(this.videoContext._canvas,2)}this.decoder=i}catch(a){e.log.error(a),t.error(s==="webCodecs"?2:6)}})}},ek=Promise.resolve(),tk=class extends Q4.EventEmitter{constructor(e){super(),this.room=e,u(this,"videoContext"),u(this,"_glVideoContext"),u(this,"_2dVideoContext"),u(this,"destination"),u(this,"smallVideoContext"),u(this,"smallDestination"),u(this,"smallTrackSource"),u(this,"smallImageSource"),u(this,"_isMirror",!1),u(this,"_rotation",0),u(this,"cameraTrack"),u(this,"cameraNode"),u(this,"transformNode"),u(this,"mixNode"),u(this,"screenTrack"),u(this,"screenNode"),u(this,"selfModel",!1),u(this,"blurRadius",3),u(this,"arTrack"),u(this,"_enableFaceCentering",!1),u(this,"_enableEffectOptimization",!1),u(this,"onAbort"),u(this,"_color",[0,1,0]),u(this,"Wasm"),u(this,"waterMarkNode"),u(this,"_waterMarkOption"),u(this,"watermarkImageList",[]),u(this,"_beautyParams"),u(this,"isUsingArTrack",!1),u(this,"mixTrack"),u(this,"_isMixScreen",!1),u(this,"_virtualBackground"),u(this,"_virtualBackgroundAbortCallback"),u(this,"virtualBackgroundInstance"),u(this,"_bgAssetPath"),u(this,"log"),u(this,"_mat4"),u(this,"_postProcessing"),u(this,"_checkId",0),u(this,"_use2d",!1),u(this,"_autoSwitchRenderMode",!0),u(this,"encodePipeline",[]),u(this,"decodePipeline",[]),u(this,"updated",ek),u(this,"_updateFlag",!1),this.log=P.createLogger({parent:e==null?void 0:e.getLogger(),id:"vm",userId:e==null?void 0:e.userId,sdkAppId:e==null?void 0:e.sdkAppId}),this.smallVideoContext=new Ei({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 fr(this._rotation)?{width:i,height:t}:{width:t,height:i}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Ei({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 Gt({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(pR<=22),this._glVideoContext.on(Gt.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=_e.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(),_e.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(en||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?w.addFailedEvent({key:t,error:e}):w.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 Gt({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 bH(this.smallVideoContext,e,this.log),this.smallVideoContext.on(Gt.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,i;try{let r=this.cameraTrack,{small:n,player:s}=r;en&&s.setCanvas(e);let a=e&&((t=this.destination)==null?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),a=this.arTrack),this.log.info("set main output ".concat(a?a.label:"no output track")),this.setSmallVideo(n,e),R.emit(b.LOCAL_VIDEO_TRACK_PREPROCESSED,{mediaTrack:a,profile:(i=this.cameraTrack)==null?void 0:i.profile,room:this.room}),r.setOutputMediaStreamTrack(a)}catch(r){this.log.error("set main output failed",r)}}update(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return g(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(Ct.RENDER,n=>{var s;(s=this.cameraTrack)==null||s.emit("render",n)})),Rt===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Is?(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 Is?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 CH(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(Ct.RENDER,o=>{var l;(l=this.cameraTrack)==null||l.emit("render",o)}));let{width:n,height:s}=this.cameraResolution,a=yield this.getWatermarkImage(n,s);this._waterMarkOption={x:0,y:0,width:a.width,height:a.height,image:a},this.cameraNode=new $4(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 Rr(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 Xb(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:a}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(s,a),s&&a&&this.waterMarkNode.resize(s,a)}(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 hn)return this.log.info("change screen input",(t=e.mediaTrack)==null?void 0:t.label),this.setScreenTrack(e);if(e instanceof ji)return this.log.info("change video input",(i=e.mediaTrack)==null?void 0:i.label),this.setCameraTrack(e);if(e instanceof Co){this.log.info("change remote input",(r=e.mediaTrack)==null?void 0:r.label);let a=e.mediaTrack;return e.setOutputMediaStreamTrack(a)}if(e instanceof o_)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 hn?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof ji?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 Co?e.source&&e.source.context.destroy():e instanceof o_&&(delete this.mixTrack,this.update())}setMixTrack(e){this.mixTrack=e}setCameraTrack(e){return this.cameraTrack=e,this.update(!0)}setScreenTrack(e){return g(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 g(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 O({code:C.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:a,y:o,width:l,height:c,fillVideo:d}=n,h=d&&e||l,m=d&&t||c,p=d?0:a,f=d?0:o;r.drawImage(s,p,f,h,m)}),Ua(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 g(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return g(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return g(this,null,function*(){let t;try{t=yield Ua((e==null?void 0:e.imageElement)||e.imageUrl)}catch{throw new O({code:C.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:a="watermark",zIndex:o=2,fillVideo:l=!1}=e;this.watermarkImageList.some(c=>c.type===a)?(this.watermarkImageList=this.watermarkImageList.filter(c=>c.type!==a),this.pushWaterMarkImageList({x:i,y:r,width:n,height:s,image:t,zIndex:o,type:a,imageUrl:e.imageUrl,fillVideo:l}),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:o,type:a,imageUrl:e.imageUrl,fillVideo:l}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(c,d)=>c==="imageUrl"?void 0:d))})}deleteWatermark(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"watermark";return g(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 g(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 g(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 Ua(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:this._color}else delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;if(this.log.info("".concat(this._virtualBackground?"start":"stop"," virtual background, ").concat((e==null?void 0:e.type)||"",", ").concat(this.blurRadius||"")),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new O({code:C.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 g(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 iW(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}};M([Eb(function(e){this.log.error("update failed",e)}),ge(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return g(this,null,function*(){this._updateFlag||(this._updateFlag=!0,yield ek,this.updated=new Promise((n,s)=>{e.apply(this,i).then(n,s),setTimeout(s,5e3,new O({code:C.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],tk.prototype,"update");var rW=0,nW=class extends re{constructor(e){super("room"),u(this,"seq",++rW),u(this,"sdkAppId"),u(this,"userId"),u(this,"userSig"),u(this,"privateMapKey"),u(this,"latencyLevel"),u(this,"tinyId"),u(this,"scene"),u(this,"roomId"),u(this,"useStringRoomId"),u(this,"role","anchor"),u(this,"joinParams",null),u(this,"localPublishFlag",0),u(this,"localTracks",new Set),u(this,"enableAutoPlayDialog",!0),u(this,"autoReceiveAudio",!0),u(this,"autoReceiveVideo",!0),u(this,"proxy_ws"),u(this,"proxy_wt"),u(this,"proxy_unified"),u(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}}),u(this,"keyPointManager"),u(this,"audioManager"),u(this,"videoManager"),u(this,"callDurationCalculator"),u(this,"badCaseDetector"),u(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}),u(this,"videoDecodeFallbackType"),u(this,"smallMode","canvas"),u(this,"preconnectPromise",null),u(this,"enableChorus",!1),u(this,"_isUsingCachedSchedule",!1),u(this,"_log"),u(this,"_joinedTimestamp",0),u(this,"_sdkType"),u(this,"heartbeatReport"),u(this,"heartbeatCount",0),u(this,"quality"),u(this,"enableSEI"),u(this,"isDestroyed",!1),this._log=P.createLogger({parent:e.logger,id:"r".concat(this.seq)}),this.useStringRoomId=!!e.useStringRoomId,Se(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),Se(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),Se(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new K4({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new q4({room:this}),this.badCaseDetector=new X4({room:this}),this.audioManager=new OH(this),this.videoManager=new tk(this)}get videoCodec(){return"h264"}get downlinkVideoCodec(){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 g(this,null,function*(){return this.publish(e)})}removeTrack(e){return g(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return g(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(he(e))/^wss?:\/\//i.test(e)?this.proxy_ws=e:/^https?:\/\//i.test(e)&&(this.proxy_wt=e);else if(Ut(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?(d_([s,s]),Ea("https://".concat(s))):(r&&Ea(r),n&&d_(n))}R.once(b.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:zi.main,sched_back_domain:zi.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return g(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return g(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 g(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 O({code:C.INVALID_OPERATION,message:Y({key:K.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(ii.INVALID_DESTROY),new O({code:C.INVALID_OPERATION,message:Y({key:K.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,R.emit(b.ROOM_DESTROY,{room:this})}schedule(e,t){return g(this,null,function*(){var i,r,n,s;let a=J();try{let{isCached:o,result:l,detailCost:c}=yield p0({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:ei,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=o,this._log.info("schedule cache:".concat(+o," ").concat(ti(l,{keysToExclude:["username","credential"]}))),o&&R.once(b.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=x(x({},this.scheduleResult),l),le((i=l.config)==null?void 0:i.retryCount)&&RA(l.config.retryCount),he((r=l.config)==null?void 0:r.loggerDomain)&&Ea(l.config.loggerDomain),this.videoDecodeFallbackType=((n=l.config)==null?void 0:n.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=((s=l.config)==null?void 0:s.smallMode)||this.smallMode,R.emit(b.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:c}),w.addSuccessEvent({key:521700,cost:J()-a})}catch(o){throw w.addFailedEvent({key:521700,error:o}),o}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}preconnect(e,t,i,r,n,s){return g(this,null,function*(){return Promise.resolve()})}closePreconnect(){return g(this,null,function*(){return Promise.resolve()})}},sW=Ge(it()),ik=Ge(nA());function rk(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==null?void 0:e.rtcpFb)||[]).filter(s=>s.payload===e.rtp[r].payload).map(s=>{let{type:a,subtype:o}=s;return{id:a,params:o?[o]:[]}})})}return i}var aW=(e,t,i)=>g(null,null,function*(){var r;let n=ot(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 a=n.media[0],o=n.media[1];a.ext&&(s.audio.extensions=a.ext.map(c=>({id:c.value,uri:c.uri}))),o.ext&&(s.video.extensions=o.ext.map(c=>({id:c.value,uri:c.uri})));for(let c of a.rtp){if(c.codec!=="opus")continue;let d=a.fmtp.find(m=>m.payload===c.payload);if(!d)continue;let h={codec:c.codec,fmtp:d.config,payload:d.payload,rate:c.rate,channels:c.encoding,rtcpfb:[],rtx:0};(r=a.rtcpFb)==null||r.forEach(m=>{let{payload:p,type:f,subtype:T}=m;if(p===h.payload){let E={id:f,params:[]};T&&E.params.push(T),h.rtcpfb.push(E)}}),s.audio.codecs.push(h);break}let l=["h264","vp8","h265"];return t&&l.shift(),s.video.codecs=[...rk(o)].filter(c=>l.includes(c.codec.toLocaleLowerCase())),s.video.decoders=(yield(function(){return g(this,null,function*(){let c=new RTCPeerConnection;c.addTransceiver(_.VIDEO,{direction:_.TRANSCEIVER_DIRECTION_RECVONLY});let d=yield c.createOffer();if(!d.sdp)return[];let h=rk(ot(d.sdp).media[0]);return c.close(),h})})()).filter(c=>["h264","vp8","h265"].includes(c.codec.toLocaleLowerCase())),s}),nk=(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 o=new RegExp(s,"g");return i.replace(o,"".concat(n,"=").concat(r))}if(!i)return"".concat(n,"=").concat(r);let a=i.endsWith(";")?"":";";return"".concat(i).concat(a).concat(n,"=").concat(r)},oW=e=>{let{serverAbility:t,clientAbility:i,offerSDP:r,enableCustomMessage:n,profileLevelIdConfig:s}=e,a=ot(r),o={extmapAllowMixed:"extmap-allow-mixed",groups:a.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},l={candidates:t.candidates.map(d=>({component:1,foundation:"1",generation:0,ip:d.ip,port:d.port,priority:d.priority,transport:d.foundation,type:d.type})),connection:{version:4,ip:"0.0.0.0"},direction:_.TRANSCEIVER_DIRECTION_RECVONLY,ext:t.audio.extensions.map(d=>({value:d.id,uri:d.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:a.media[0].port,protocol:a.media[0].protocol,type:_.AUDIO,setup:t.dtls.setup,rtcpFb:t.audio.codecs[0].rtcpfb.map(d=>({payload:t.audio.codecs[0].payload,type:d.id,subtype:d.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}]};o.media.push(l);let c=[s==null?void 0:s.big,s==null?void 0:s.small,s==null?void 0:s.aux];return[1,2,3].forEach((d,h)=>{o.media.push(sk({mid:d,serverAbility:t,clientAbility:i,parsedOffer:a,profileLevelId:c[h]}))}),n&&o.media.push(a.media.find(d=>d.mid==="dc")),Cr(o)},sk=e=>{let{mid:t,serverAbility:i,clientAbility:r,parsedOffer:n,isDownlink:s=!1,profileLevelId:a}=e,o={candidates:i.candidates.map(l=>({component:1,foundation:"1",generation:0,ip:l.ip,port:l.port,priority:l.priority,transport:l.foundation,type:l.type})),connection:{version:4,ip:"0.0.0.0"},direction:_.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(l=>({value:l.id,uri:l.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:_.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(s){let l=i.video.decoders;(!l||l.length===0)&&(l=i.video.codecs),(!l||l.length===0)&&(l=r.video.decoders),l.forEach(c=>{vn(o,c)})}else{let l;l=i.useH265?i.video.codecs.findIndex(d=>d.codec.toLowerCase()==="h265"):i.video.codecs.findIndex(d=>d.codec.toLowerCase()===(i.useVp8?"vp8":"h264"));let c=i.video.codecs[l]||r.video.codecs[0];vn(o,c)}if(!s&&a)if(Array.isArray(a)){let l=new Set(a.map(d=>d.toLowerCase())),c=r.video.codecs.filter(d=>{if(d.codec.toLowerCase()!=="h264"||/packetization-mode=0/.test(d.fmtp))return!1;let h=Vu(d.fmtp);return h&&l.has(h)});c.length>0&&(o.payloads="",o.rtp=[],o.fmtp=[],o.rtcpFb=[],c.forEach(d=>vn(o,d)))}else{let l=o.rtp,c=o.fmtp,d=l.find(h=>{var m;return((m=h.codec)==null?void 0:m.toLowerCase())==="h264"});if(d){let h=c.find(m=>String(m.payload)===String(d.payload));h&&(h.config=nk(h.config,a))}}return o},vn=(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}))},lW=(e,t,i)=>{let r=ik.default.parse(e);return r.media.forEach((n,s)=>{var a;if((n.type===_.AUDIO||n.type===_.VIDEO)&&((function(o){if(!o.rtcpFb)return;let l=[];o.rtcpFb.forEach((c,d)=>{var h;l.push(c),o.rtcpFb&&((h=o.rtcpFb[d+1])==null?void 0:h.payload)!==c.payload&&c.type!=="rrtr"&&l.push({payload:c.payload,type:"rrtr"})}),o.rtcpFb=l})(n),(function(o){o.type===_.VIDEO&&o.fmtp&&o.fmtp.forEach(l=>{l.config.includes("apt")||(l.config+=";sps-pps-idr-in-keyframe=1")})})(n),(function(o){o.type===_.AUDIO&&o.fmtp&&o.fmtp.forEach(l=>{l.config+=";sprop-stereo=1;stereo=1"})})(n),(function(o){let l=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"]);o.ext&&(o.ext=o.ext.filter(c=>!l.has(c.uri)))})(n),n.type===_.VIDEO)){if(s<4)n.payloads="",n.fmtp=[],n.rtp=[],n.rtcpFb=[],t.video.codecs.forEach(o=>vn(n,o));else if(i){n.payloads="",n.fmtp=[],n.rtp=[],n.rtcpFb=[];let o=i.video.decoders;(!o||o.length===0)&&(o=i.video.codecs),(!o||o.length===0)&&(o=t.video.decoders),o.forEach(l=>vn(n,l))}}(a=n.payloads)!=null&&a.includes("datachannel")&&r.groups&&n.mid&&(r.groups[0].mids=r.groups[0].mids.replace(n.mid,"dc"),n.mid="dc")}),ik.default.write(r)};function Vu(e){var t,i;let r=/profile-level-id=([0-9a-fA-F]{6})/.exec(e);return(i=(t=r==null?void 0:r[1])==null?void 0:t.toLowerCase())!=null?i:null}function L_(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 Fu(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=Vu(r.fmtp);if(n&&L_(n)===i)return n}return""}var cW=Ge(it()),ak=class extends cW.EventEmitter{constructor(e){super(),this.room=e,u(this,"mainFpsHealth",1),u(this,"mainBitrateHealth",1),u(this,"badMainBitrateHealthCount",0),u(this,"lastEmitBadHealthTime",0),u(this,"log"),!Oe&&Bt&&R.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(){R.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};u(ak,"EVENT_BAD_HEALTH","bad_health");var uW=ak,Ns=(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))(Ns||{}),dW=1,br=class extends sW.default{constructor(e){let{signalChannel:t,room:i,enableDataChannel:r}=e;super(),u(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),u(this,"isDestroyed",!1),u(this,"currentState","DISCONNECTED"),u(this,"_room"),u(this,"_signalChannel"),u(this,"_peerConnection",null),u(this,"_datachannel",null),u(this,"_enableDataChannel"),u(this,"_log"),u(this,"_downlinkMIDMap",new Map),u(this,"_downlinkMIDUserIDMap",new Map),u(this,"_reconnectionTimer",-1),u(this,"reconnectionCount",0),u(this,"clientAbility"),u(this,"_serverAbility",null),u(this,"addDownlinkQueue",new Set),u(this,"removeDownlinkQueue",new Set),u(this,"_parsedAnswer",null),u(this,"_updateSDPPromise",null),u(this,"_waitForPCConnectedPromise"),u(this,"clearWaitForConnectedPromise"),u(this,"clearConnectTimeout"),u(this,"_isSDPLogged",!1),u(this,"enableInsertableStreams",!1),u(this,"insertableStreamsAbortMap",new Map),u(this,"receiverRemoteTrackMap",new WeakMap),u(this,"scriptTransformWorker"),u(this,"_isRelayTried",!1),u(this,"_rttOverCount",0),u(this,"originOffer",null),u(this,"autoSubscribedSsrcGroups",new Map),u(this,"autoSubscribedUserMap",new Map),u(this,"_h265DecodeFailed",!1),this._room=i,this._enableDataChannel=r,this._signalChannel=t,this._log=P.createLogger({parent:this._room.getLogger(),id:"spc".concat(dW++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(an?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}get parsedAnswer(){var e,t;return!this._parsedAnswer&&(t=(e=this._peerConnection)==null?void 0:e.remoteDescription)!=null&&t.sdp&&(this._parsedAnswer=ot(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer}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=ot(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&&!I(r.ssrcs[0].id)){let a=Number(r.ssrcs[0].id),o=Number((s=r.ssrcs.filter(l=>l.attribute==="cname")[1])==null?void 0:s.id);switch(n){case 0:i.audioSsrc=a;break;case 1:i.bigVideoSsrc=a,i.bigVideoRtxSsrc=o;break;case 2:i.smallVideoSsrc=a,i.smallVideoRtxSsrc=o;break;case 3:i.auxVideoSsrc=a,i.auxVideoRtxSsrc=o}}}),i})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth(e){}initScriptTransformWorker(){Kc&&(this.scriptTransformWorker=b0({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 nR(r)&&(i.encodedInsertableStreams=r),this._log.debug("getPeerConnectionConfig",JSON.stringify(i)),i}initialize(e){return g(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(),w.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):r==="failed"&&w.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.info("datachannel close")},this._datachannel.onmessage=r=>{let n=new mW(r.data);this.emit("data_channel_msg",{data:n})},this._datachannel.onerror=r=>{this._log.warn("datachannel error",r)}),this._peerConnection.addTransceiver(_.AUDIO,{direction:_.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:_.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:_.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:_.TRANSCEIVER_DIRECTION_SENDONLY}),i=yield this._peerConnection.createOffer(),this.clientAbility=yield aW(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()))}),w.addSuccessEvent({key:521707}),this.clientAbility}catch(r){throw w.addFailedEvent({key:521707,error:r}),this._log.error("initialize failed ".concat(r,`
|
||
offer: `).concat(i==null?void 0:i.sdp)),r}})}setIceServers(e){return g(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 g(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=J(),a=this.getProfileLevelIdConfig(),o={type:"answer",sdp:oW({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableDataChannel,profileLevelIdConfig:a})};this._serverAbility=e,yield this.setAnswer(o),yield this.waitForPeerConnectionConnected(),this._room.firewallDetector.resetTimeoutCount();let l=((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");l&&this.setPriority(l),t||w.addSuccessEvent({key:521703,cost:J()-s})}catch(s){let a=s instanceof O&&s.code===C.API_CALL_ABORTED;throw a||this._log.error("connect failed: ".concat(s),e),this.reset(),!a&&!this.isReconnecting&&!this.isDestroyed&&(w.addFailedEvent({key:521703,error:s}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),s}})}reconnect(){return g(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(Mo,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=x({ability:t},e),r=yield this._signalChannel.sendWaitForResponse({command:P4,responseCommand:X.REBUILD_PEER_CONNECTION_RES,data:i,enableLog:!1});if(r.data.code!==0)throw new O({code:r.data.code,message:r.data.message});yield this.connect(r.data.data.ability,!0),w.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),R.emit(b.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=qr(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(t/1e3,"s")),yield mi(t,i=>{this._reconnectionTimer=i}),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error("reconnect() failed ".concat(e==null?void 0:e.code," ").concat(e)),w.addFailedEvent({key:521704,error:e}),this.reconnectionCount>=ss()&&this._log.warn("SDK has tried reconnect for ".concat(ss()," 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 g(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(Mo,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===Be.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===Be.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===Be.FAILED||e.target.connectionState===Be.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===Be.CONNECTED||e.target.connectionState===Be.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),R.emit(b.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 hr;let e=null;return $a()&&this._peerConnection.getSenders().length!==0?(e=this._peerConnection.getSenders()[0].transport,Jc()&&this._peerConnection.getReceivers().length!==0&&e?e.state:hr):hr}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(Ns.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return g(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,i]of e)if(Za(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&&bp(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=a=>{a.state==="CONNECTED"&&(clearTimeout(s),n(),e())},r=a=>{let{room:o}=a;o===this._room&&(clearTimeout(s),n(),t(new O({code:C.API_CALL_ABORTED,message:Y({key:K.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{R.off(b.LEAVE_SUCCESS,r,this),this.off(Ns.CONNECTION_STATE_CHANGED,i,this)},s=setTimeout(()=>{n();let a=new O({code:C.API_CALL_TIMEOUT,message:"connection timeout"});this._room.firewallDetector.increaseTimeoutCount(),t(a)},_p);this.clearConnectTimeout=()=>{n(),clearTimeout(s),delete this.clearConnectTimeout},this.clearWaitForConnectedPromise=()=>{this._waitForPCConnectedPromise=null,t(new O({code:C.API_CALL_TIMEOUT,message:"connection timeout"}))},R.on(b.LEAVE_SUCCESS,r,this),this.on(Ns.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 g(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,prevMids:n}=e;var s;if(!this._peerConnection||!this.parsedAnswer)return;this._log.info("updateLocalAndRemoteSDPConfig ".concat(i," ").concat(JSON.stringify(t)));let a,o,l,c=this.parsedAnswer.media.filter(m=>{var p;return(p=m.ssrcs)==null?void 0:p.find(f=>{var T;return(T=f.value)==null?void 0:T.includes(r)})});if(c.length===3)a=c[0],o=c[1],l=c[2];else{let m,p=this._peerConnection.getTransceivers().slice(4);if((n==null?void 0:n.length)===3&&n.every(T=>{var E;return((E=p.find(v=>Number(v.mid)===T))==null?void 0:E.direction)==="inactive"})?(m=n,this._log.info("reusing previous mids for ".concat(i,": ").concat(m.join(","))),p.forEach(T=>{m.includes(Number(T.mid))&&(T.direction=_.TRANSCEIVER_DIRECTION_RECVONLY)})):m=p.filter(T=>T.direction==="inactive").slice(0,3).map(T=>(T.direction=_.TRANSCEIVER_DIRECTION_RECVONLY,Number(T.mid))),m.length===3)a=this.parsedAnswer.media.find(T=>Number(T.mid)===Number(m[0])),o=this.parsedAnswer.media.find(T=>Number(T.mid)===Number(m[1])),l=this.parsedAnswer.media.find(T=>Number(T.mid)===Number(m[2]));else if(m.length===0){this._peerConnection.addTransceiver(_.AUDIO,{direction:_.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:_.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(_.VIDEO,{direction:_.TRANSCEIVER_DIRECTION_RECVONLY}),a=JSON.parse(JSON.stringify(this.parsedAnswer.media[0]));let T=sk({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:ot(this._peerConnection.localDescription.sdp),isDownlink:!0});o=JSON.parse(JSON.stringify(T)),l=JSON.parse(JSON.stringify(T)),a.mid=this.parsedAnswer.media.length,this.parsedAnswer.media.push(a),o.mid=this.parsedAnswer.media.length,this.parsedAnswer.media.push(o),l.mid=this.parsedAnswer.media.length,this.parsedAnswer.media.push(l)}}a.direction=_.TRANSCEIVER_DIRECTION_SENDONLY;let d="".concat(r,"-").concat(t.audio);a.ssrcs=[{id:t.audio,attribute:"cname",value:"".concat(d)},{id:t.audio,attribute:"msid",value:"".concat(d,"-").concat(_.MAIN," ").concat(d,"-audio")}],o.direction=_.TRANSCEIVER_DIRECTION_SENDONLY,o.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(d)},{id:t.video,attribute:"msid",value:"".concat(d,"-").concat(_.MAIN," ").concat(d,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(d)},{id:t.videoRtx,attribute:"msid",value:"".concat(d,"-").concat(_.MAIN," ").concat(d,"-bigvideo")}],o.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],l.direction=_.TRANSCEIVER_DIRECTION_SENDONLY;let h="".concat(d,"-aux");l.ssrcs=[{id:t.auxiliary,attribute:"cname",value:h},{id:t.auxiliary,attribute:"msid",value:"".concat(h," ").concat(d,"-aux").concat(_.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(h," ").concat(d,"-aux").concat(_.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(h," ").concat(d,"-aux").concat(_.VIDEO)}],l.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.auxiliary," ").concat(t.auxiliaryRtx)}],(s=this.parsedAnswer)!=null&&s.groups&&(this.parsedAnswer.groups[0].mids=this.parsedAnswer.media.map(m=>m.mid).join(" ")),this._downlinkMIDMap.set(i,[a.mid,o.mid,l.mid]),this._downlinkMIDUserIDMap.set(a.mid,i),this._downlinkMIDUserIDMap.set(o.mid,i),this._downlinkMIDUserIDMap.set(l.mid,i)}removeDownlink(e){return g(this,null,function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection||!this.parsedAnswer)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;return this._peerConnection.getTransceivers().forEach(r=>{t!=null&&t.includes(Number(r.mid))&&(i=!0,r.direction="inactive")}),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==null||t.forEach(r=>this._downlinkMIDUserIDMap.delete(r)),this._log.info("removeDownlink(".concat(e,") done")),t})}setBandwidth(e){return g(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:i,smallVideo:r,auxVideo:n}=e;try{if(bf()){let s=this._peerConnection.getSenders().slice(0,4);for(let o=0;o<s.length;o++){let l,c=s[o];o===0&&t?l=t:o===1&&i?l=i:o===2&&r?l=r:o===3&&n&&(l=n),l&&(yield this.setSenderMaxBitrate(c,l))}let a=!1;i&&s[1].track&&(a=this.setStartBitrate(1,i)),n&&s[3].track&&(a=this.setStartBitrate(3,n)||a),a&&(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,n;return!((i=this._peerConnection)==null||!i.remoteDescription||(n=(r=this.parsedAnswer)==null?void 0:r.media[e])==null||!n.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||!this.parsedAnswer)return;let s=ot(this._peerConnection.localDescription.sdp),a=me?"TIAS":"AS";t&&(s.media[0].bandwidth=[{type:a,limit:me?1e3*t:t}],this.parsedAnswer.media[0].bandwidth=[{type:a,limit:me?1e3*t:t}]),i&&(s.media[1].bandwidth=[{type:a,limit:me?1e3*i:i}],this.parsedAnswer.media[1].bandwidth=[{type:a,limit:me?1e3*i:i}]),r&&(s.media[2].bandwidth=[{type:a,limit:me?1e3*r:r}],this.parsedAnswer.media[2].bandwidth=[{type:a,limit:me?1e3*r:r}]),n&&(s.media[3].bandwidth=[{type:a,limit:me?1e3*n:n}],this.parsedAnswer.media[3].bandwidth=[{type:a,limit:me?1e3*n:n}]);let o={type:"offer",sdp:Cr(s)};return this.updateSDP({localDescription:o})}setScaleResolutionDownBy(e,t,i){let r=e.getParameters();(!r.encodings||r.encodings.length===0)&&(r.encodings=[{}]);let n=r.encodings[0].scaleResolutionDownBy;if(I(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(Bt&&Ht<83||be&&cf(rt,"12.1")||me&&Dc<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(a=>this._log.warn("".concat(s," failed: ").concat(a)))}updateSDP(){let{localDescription:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!this._parsedAnswer)return Promise.resolve();let t=Cr(this._parsedAnswer);return this._updateSDPPromise=new Promise((i,r)=>g(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(a){this._log.error(a),!this._isSDPLogged&&this._peerConnection&&(this._log.warn("current offer: ".concat(this.filterSDPDirection((n=this._peerConnection.localDescription)==null?void 0:n.sdp),`
|
||
next offer: `).concat(this.filterSDPDirection(e==null?void 0:e.sdp))),this._log.warn("current answer: ".concat(this.filterSDPDirection((s=this._peerConnection.remoteDescription)==null?void 0:s.sdp),`
|
||
next answer: `).concat(this.filterSDPDirection(t))),this._log.warn("offer: ".concat(e==null?void 0:e.sdp)),this._log.warn("answer: ".concat(t)),this._log.warn("transceivers: ".concat(JSON.stringify(this._peerConnection.getTransceivers().map(o=>{let{mid:l,currentDirection:c,direction:d,stopped:h}=o;return{mid:l,currentDirection:c,direction:d,stopped:h}})))),this._log.warn("parsedAnswer: ".concat(JSON.stringify(this._parsedAnswer))),this._isSDPLogged=!0),this._updateSDPPromise=null,r(a)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return g(this,null,function*(){if(!me||!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===oe.INACTIVE&&n===oe.RECVONLY&&(this._parsedAnswer.media[r].direction=e),e===oe.SENDONLY&&n===oe.INACTIVE&&(this._parsedAnswer.media[r].direction=oe.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(){return ot(arguments.length>0&&arguments[0]!==void 0?arguments[0]:"").media.map(e=>e.direction)}setOffer(e){this._log.info("setting offer");let t=lW(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 g(this,null,function*(){if(!this._peerConnection||!this.parsedAnswer||!this._serverAbility)return;let t=!1;this.parsedAnswer.media.forEach(i=>{var r;if(i.type===_.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=[],vn(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=Fp(i==null?void 0:i.big)?i.big:"":e===3?r=Fp(i==null?void 0:i.small)?i.small:"":e===7&&(r=Fp(i==null?void 0:i.aux)?i.aux:""),!r)return"";let n=Fu(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=Fu(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){let s={};return i&&(s.big=i),r&&(s.small=r),n&&(s.aux=n),s}if(be&&(Ui(rt,"26.2",!0)||Ui(xi,"26.2",!0)||_r&&Ui(rt,"18.7",!0))){let s=[],a=Fu("high",this.clientAbility),o=Fu("baseline",this.clientAbility);if(a&&s.push(a),o&&s.push(o),s.length>0)return this._log.warn("use multi profile level ids: ".concat(s.join(", ")," for fallback 26.2 video encode issue")),{big:s,small:s,aux:s}}}catch(e){return void this._log.warn("getProfileLevelIdConfig error: ".concat(e))}}setH264ProfileLevelId(e,t){return g(this,null,function*(){var i;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));let r=e==="main"?1:3,n=(i=this.parsedAnswer)==null?void 0:i.media[r];if(!n||n.type!==_.VIDEO)return;let s=n.rtp||[],a=n.fmtp||[],o=s.find(p=>{var f;return((f=p.codec)==null?void 0:f.toLowerCase())==="h264"});if(!o)return;let l=a.find(p=>String(p.payload)===String(o.payload));if(!l)return;let c=Vu(l.config);if(!c)return;let d=L_(c)==="high";if(t&&d||!t&&!d)return;let h=this._serverAbility.video.codecs.map(p=>Vu(p.fmtp)).filter(Boolean).find(p=>{let f=L_(p);return t?f==="high":f!=="high"});if(!h)return;let m=l.config;l.config=nk(l.config,h),l.config!==m&&(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 g(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let i=!1,r=[];I(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===_.VIDEO){let a;e&&this.is42001fSupported?a=this.clientAbility.video.codecs.find(o=>o.fmtp.includes("42001f")):e||(a=this._serverAbility.video.codecs.find(o=>o.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),a&&((s=n.payloads)==null||!s.includes(String(a.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],vn(n,a),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=>Qr(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._downlinkMIDMap.get(e)||[],i=this._peerConnection.getTransceivers();return t.map(r=>{let n=i.find(s=>Number(s.mid)===r);return n==null?void 0:n.receiver}).filter(Boolean)}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:a,rttThreshold:o}=((r=this._room.scheduleResult.config)==null?void 0:r.useTurnTcpInfo)||{};if(!(a&&o&&n&&s))return;let l=Math.floor(s/n),c=(this._isRelayTried||l>a)&&s>o;c?++this._rttOverCount<5||(this._log.warn("detectTCPAndUDP ws-rtt: ".concat(n," upRTT: ").concat(t," downRTT: ").concat(i," ratio: ").concat(l," over-count: ").concat(this._rttOverCount," isOver: ").concat(c," 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 g(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")),w.addSuccessEvent({key:r,cost:Date.now()-n})}catch(n){this._log.warn("switchRelay ".concat(i," failed"),n),w.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:P_,data:{videoDecCodec:"h264"},responseCommand:X.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)})}};M([yb("reconnect")],br.prototype,"startReconnection"),M([yr(e=>e.userId)],br.prototype,"addDownlink"),M([yr(e=>e)],br.prototype,"removeDownlink"),M([fo(!0)],br.prototype,"updateSDP"),M([Sr(521712,!1),gu(10,0)],br.prototype,"setOffer"),M([Sr(521713,!1),gu(10,0)],br.prototype,"setAnswer"),M([ge((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)})],br.prototype,"close");var hW=class{constructor(e){u(this,"tag"),u(this,"len"),u(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}},mW=class{constructor(e){u(this,"tinyId"),u(this,"data");let t=new DataView(e),i=0,r=[];for(;i<t.byteLength;){let l=t.getUint16(i+2),c=new hW(new Uint8Array(e).slice(i,i+2+2+l).buffer);r.push(c),i+=4+l}let n=[];r.forEach(l=>{l.tag===1?this.tinyId=new TextDecoder().decode(l.data):l.tag===2&&n.push(l.data)});let s=n.reduce((l,c)=>l+c.byteLength,0),a=new Uint8Array(s),o=0;n.forEach(l=>{a.set(new Uint8Array(l),o),o+=l.byteLength}),this.data=a.buffer}},ok=new Set;function ai(){let e=Math.floor(4294967296*Math.random());return ok.has(e)?ai():(ok.add(e),e)}var pW=Ge(it()),lk=class extends pW.default{constructor(e){super(),u(this,"userId"),u(this,"tinyId"),u(this,"_sdpSemantics"),u(this,"_isUplink"),u(this,"_room"),u(this,"_log"),u(this,"_currentState","DISCONNECTED"),u(this,"_prevTime",-1),u(this,"_blackSmallVideoDetectionId"),u(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=P.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&&(R.emit(b.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 ck(e){let{when:t,onSkip:i}=e;return ge((r,n)=>function(){for(var s=arguments.length,a=new Array(s),o=0;o<s;o++)a[o]=arguments[o];return g(this,null,function*(){if(!t.apply(this,a))return r.apply(this,a);i==null||i.call(this,n,...a)})})}var yn=new class{constructor(){u(this,"worker"),u(this,"callbacks",new Map),u(this,"_log"),u(this,"sleep",{}),u(this,"heartbeatListenerCleaner",new Map),u(this,"userIdMap",new Map),this._log=P.createLogger({id:"bvd"})}getWorker(){if(!this.worker){let e=new Blob([`
|
||
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)};
|
||
`],{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:a,count:o}=i.data;if(n==="black")(r=this.callbacks.get(s))==null||r();else if(n==="log")this._log.warn(a);else if(n==="blackCount"){let l=this.userIdMap.get(s);this._log.warn("".concat(l||s," black count: ").concat(o))}}}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),!Ef()||!s||!t||typeof Worker>"u")return void this._log.warn("black video detector not supported");let a=o=>{var l,c,d,h;let m;if(i)m=(c=(l=o.msg_up_stream_info)==null?void 0:l.msg_video_status)==null?void 0:c.filter(p=>p.uint32_video_stream_type===3)[0];else{let p=(d=o.msg_down_stream_info)==null?void 0:d.filter(f=>{var T;return((T=f.msg_user_info)==null?void 0:T.str_identifier)===n})[0];m=(h=p==null?void 0:p.msg_video_status)==null?void 0:h.filter(f=>f.uint32_video_stream_type===3)[0]}if(m){let p=(m.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[t.id]&&this.sleep[t.id]>0)return void(this.sleep[t.id]-=1);p>0&&p<10&&(this.sleep[t.id]=30,this._log.info("track bitrate",p,"start check"),this.checkOnce(t,3e4))}};return r.on("heartbeat-report",a),this.heartbeatListenerCleaner.set(t.id,()=>r.off("heartbeat-report",a)),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)}},Bu=class extends lk{constructor(e){super(W(x({},e),{isUplink:!0})),u(this,"localMainAudioTrack",null),u(this,"localMainVideoTrack",null),u(this,"localAuxAudioTrack",null),u(this,"localAuxVideoTrack",null),u(this,"_isPublishingAux",!1),u(this,"_publishingLocalAudioTrack"),u(this,"_publishingLocalVideoTrack"),u(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}),u(this,"_flag",0),u(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:a}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:i||0,small:r||0,smallRtx:n||0,auxiliary:s||0,auxiliaryRtx:a||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=_e.run("timeout",()=>this.checkPublishState(!0),{delay:1e4,count:1}));w.addCount({key:521e3}),r.forEach(n=>{this._log.warn("".concat(n," publish failed during call ").concat(Er()," ").concat(nn())),w.addEnum({key:521719,value:uk[n]})}),_e.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)}isTrackReferenced(e){return e===this.localMainAudioTrack||e===this.localMainVideoTrack||e===this.localAuxVideoTrack||e===this.localAuxAudioTrack}get serverPublishState(){return{audio:!!(this.flag&Ia),bigVideo:!!(this.flag&Sa),smallVideo:!!(this.flag&hp),auxVideo:!!(this.flag&hc)}}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,a=super.emitConnectionStateChangedEvent(e);return a&&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}))),a}onVideoEncodeFailed(e){return g(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 g(this,arguments,function(t){var i=this;let{localAudioTrack:r,localVideoTrack:n,isAuxiliary:s}=t;return(function*(){var a,o,l,c,d,h,m;if(!i.singlePC)return;if(i.installEvents(),i.installTrackMuteEvents(r,n),n&&(n.retryEncodeFailed=i.onVideoEncodeFailed.bind(i),be&&(Ui(rt,"26.2",!0)||Ui(xi,"26.2",!0)||_r&&Ui(rt,"18.7",!0)))){i._log.warn("detectH264Supported for fallback 26.2 video encode issue");try{yield _s.detectH264SupportedByFakeStreaming(500)}catch{}}if(yield i.singlePC.waitForPeerConnectionConnected(),r&&(i._publishingLocalAudioTrack=r),n){if(!i.singlePC.isH264EncodeSupported&&!i.singlePC.isVP8EncodeSupported)throw new O({code:C.NOT_SUPPORTED_H264,message:Y({key:K.NOT_SUPPORTED_H264ENCODE})});i.singlePC.isUsingH264&&!i.singlePC.isH264EncodeSupported&&i.singlePC.isVP8EncodeSupported&&(i._log.warn("h264 encoder not supported"),yield i.singlePC.switchVideoEncoder("vp8")),Oe&&Fc()===115&&n.profile.width*n.profile.height<=230400&&(i._log.warn("fallback video to defaultBigVideoProfile: ".concat(JSON.stringify(ya))),n.setProfile(ya),yield n.applyProfile()),i._publishingLocalVideoTrack=n}let p;if(i._isPublishingAux=s,n&&!s&&n.small&&(p=i._room.videoManager.smallTrack),yield i._signalChannel.sendWaitForResponseWithRetry({command:G0,responseCommand:X.SPC_PUBLISH_RESULT,data:W(x({},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:p,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:T}=n;yield i.singlePC.setScaleResolutionDownBy(i._peerConnection.getSenders()[s?3:1],T,n.streamType)}r&&(i[s||r instanceof _u?"localAuxAudioTrack":"localMainAudioTrack"]=r),yield i.singlePC.setBandwidth({audio:((a=i.localMainAudioTrack)==null?void 0:a.profile.bitrate)||((o=i.localAuxAudioTrack)==null?void 0:o.profile.bitrate),bigVideo:(l=i.localMainVideoTrack)==null?void 0:l.profile.bitrate,smallVideo:(d=(c=i.localMainVideoTrack)==null?void 0:c.small)==null?void 0:d.bitrate,auxVideo:(h=i.localAuxVideoTrack)==null?void 0:h.profile.bitrate}),i.sendMediaSettings();let f=s?7:2;(i._room.preferHW||(m=i._room.scheduleResult.config)!=null&&m.preferHW)&&n&&n.profile.width*n.profile.height>=921600&&i.singlePC.useHWEncoder(!0,f)})()})}publishByTransceiver(e){let{localAudioTrack:t,localVideoTrack:i,smallTrack:r,isAuxiliary:n}=e;if(!ri())return;this._log.info("publish by transceiver");let s=i==null?void 0:i.outMediaTrack,a=t==null?void 0:t.outMediaTrack,o=this._peerConnection.getTransceivers(),l=[],c=[],d=(m,p,f)=>{var T;let E=o[p].sender.replaceTrack(f);c.push(p),(T=this.singlePC)!=null&&T.enableInsertableStreams&&E.then(()=>this.createEncodedStreams(o[p].sender,m)),this.initSenderTransform(o[p].sender,m),l.push(E)};a&&d(t.mediaType,0,a),s&&d(i.mediaType,n?3:1,s),i!=null&&i.small&&l.push(this.publishSmall(this._room.videoManager.smallMode,i));let h=this.singlePC.setTransceiverDirection(oe.SENDONLY,c);return l.push(h),Promise.all(l)}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:(a,o)=>{var l,c;let d=this.getTrackByMediaType(t);if(!d||!d.encodeFrame)return o.enqueue(a);d.isAudio?o.enqueue(d.enableEncodeFrame?d.encodeFrame(a):a):o.enqueue((l=this.singlePC)!=null&&l.isUsingH264||(c=this.singlePC)!=null&&c.isUsingH265?d.encodeFrame(a,t===8):a)}}),s):n.readable).pipeTo(n.writable,s).catch(a=>{this._log.debug("encoded stream error",a),a!=="destroy"&&this._log.warn(a)})}initSenderTransform(e,t){if(!(this._peerConnection&&this.singlePC&&this.singlePC.scriptTransformWorker&&Kc))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 g(this,null,function*(){e?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()})}publishSmall(e){return g(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"&&!Rf())return void i._log.warn("canvas mode small stream is not supported");let s=i._peerConnection.getTransceivers(),{sender:a}=s[2],o=yield i.doPublishSmall(t,r),l=t==="canvas"?524700:524701;w.addSuccessEvent({key:l}),o?((n=i.singlePC)!=null&&n.enableInsertableStreams&&i.createEncodedStreams(a,8),i.initSenderTransform(a,8),yield i.singlePC.setTransceiverDirection(oe.SENDONLY,[2]),i.updateMediaSettings(),yield i.doPublishChange(),a.track&&(i._blackSmallVideoDetectionId=yn.start({track:a.track,room:i._room,isUplink:!0,userId:i.userId,onBlack:()=>{i._log.warn("small video is black");let c=t==="canvas"?524700:524701;w.addFailedEvent({key:c,error:10002}),yn.stop(i._blackSmallVideoDetectionId),i._blackSmallVideoDetectionId=void 0}}))):w.addFailedEvent({key:l,error:10001})})()})}doPublishSmall(e){return g(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==null?void 0:r.outMediaTrack);let a=s.getParameters(),o=Rc(r==null?void 0:r.profile,r==null?void 0:r.small);return i._log.info("small scaleResolutionDownBy",o),a.encodings[0].scaleResolutionDownBy=o,s.setParameters(a),"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 g(this,null,function*(){this.singlePC&&(this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(oe.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),yn.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)})}checkHighProfile(e){return g(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&&!ER();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==null||r.on("mute",this.sendMutedFlag,this),r==null||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==null||r.off("mute",this.sendMutedFlag,this),r==null||r.off("unmute",this.sendMutedFlag,this))})}unpublish(e){return g(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 a=n&&n===i.localAuxVideoTrack||r&&r===i.localAuxAudioTrack,o=n==null?void 0:n.outMediaTrack,l=i._peerConnection.getSenders(),c=[];r&&(a?i.localAuxAudioTrack=null:i.localMainAudioTrack=null,!i.localMainAudioTrack&&!i.localAuxAudioTrack&&(yield l[0].replaceTrack(null),c.push(0))),o&&(a?(yield l[3].replaceTrack(null),i.localAuxVideoTrack=null,i._mediaSettings=W(x({},i._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield l[1].replaceTrack(null),yield l[2].replaceTrack(null),i.localMainVideoTrack=null,i._mediaSettings=W(x({},i._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),i.isMainStreamPublished||i.isAuxStreamPublished?(yield i.singlePC.setTransceiverDirection(oe.INACTIVE,c),yield i.doPublishChange(!1)):yield i.doUnpublish(),i.uninstallTrackMuteEvents(r,n),n==null||n.emit("connection-state-changed",{prevState:i._currentState,state:"DISCONNECTED"})})()})}doPublishChange(){let e=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return g(this,null,function*(){let t={state:this._room.publishState,constraintConfig:this._mediaSettings},i=yield this._signalChannel.sendWaitForResponseWithRetry({command:D_,data:t,responseCommand:X.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:Pu,commandDesc:"unpublish",responseCommand:X.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===C.API_CALL_TIMEOUT||t.getCode()===C.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),Es){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:a}=r;this._mediaSettings.videoWidth=(s.width||0)/a||0,this._mediaSettings.videoHeight=(s.height||0)/a||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:a}=n;this._mediaSettings.auxVideoWidth=(s.width||0)/a||0,this._mediaSettings.auxVideoHeight=(s.height||0)/a||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:P_,data:this._mediaSettings,responseCommand:X.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return g(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?_.AUXILIARY:_.MAIN," stream")),Ts()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return g(this,null,function*(){var i;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===_.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===oe.INACTIVE&&(yield this.singlePC.setTransceiverDirection(oe.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return g(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?_.AUXILIARY:_.MAIN," stream")),Ts()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return g(this,null,function*(){if(!e.mediaTrack)return;let i=this._peerConnection.getTransceivers();if(e.kind===_.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(oe.INACTIVE,[r])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return g(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?_.AUXILIARY:_.MAIN," stream")),r.kind===_.AUDIO&&i[0]&&(yield i[0].replaceTrack(r)),r.kind===_.VIDEO&&(!n&&i[1]&&(yield i[1].replaceTrack(r)),n&&i[3]&&(yield i[3].replaceTrack(r))),!0})}setBandwidth(e){return g(this,arguments,function(t){var i=this;let{bandwidth:r,type:n,videoType:s}=t;return(function*(){if(i.singlePC){let a={};n===_.AUDIO?a.audio=r:s==="big"?a.bigVideo=r:s==="small"?a.smallVideo=r:a.auxVideo=r,yield i.singlePC.setBandwidth(a)}})()})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this._room.muteState))),this._signalChannel.sendWaitForResponseWithRetry({command:B0,responseCommand:X.MUTE_RESULT,data:this._room.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&R.emit(b.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:_.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===_.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===_.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===_.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===_.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===fc?(this._log.error(ii.NOT_SUPPORTED_H264ENCODE),new O({code:C.NOT_SUPPORTED_H264,message:Y({key:K.NOT_SUPPORTED_H264ENCODE})})):new O({code:C.UNKNOWN,message:Y({key:K.SIGNAL_RESPONSE_FAILED,data:{signalResponse:X.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return g(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}))})}};M([cn(e=>{let{localVideoTrack:t}=e;t==null||delete t.retryEncodeFailed})],Bu.prototype,"unpublish"),M([ck({when(){return this.isDestroyed}})],Bu.prototype,"doPublishChange"),M([ck({when(){return this.isDestroyed}})],Bu.prototype,"doUnpublish");var uk=(e=>(e[e.audio=1]="audio",e[e.bigVideo=2]="bigVideo",e[e.smallVideo=3]="smallVideo",e[e.auxVideo=4]="auxVideo",e))(uk||{}),dk=Bu;function hk(e){return Object.keys(e).filter(t=>e[t])}var Hu=class extends lk{constructor(e){super(W(x({},e),{isUplink:!1})),u(this,"_flag",0),u(this,"isRobot",!1),u(this,"role","anchor"),u(this,"fromType"),u(this,"remoteAudioTrack"),u(this,"remoteVideoTrack"),u(this,"remoteAuxiliaryTrack"),u(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),u(this,"_prevMids"),u(this,"jitterBufferTimeoutId",-1),u(this,"_jitterBufferResolve"),u(this,"_videoCodec"),u(this,"avPlayerStateSyncManager"),u(this,"isDataChannelSubscribed",!1),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.fromType=e.fromType,this.remoteAudioTrack=new Tu(this._room,this),this.remoteVideoTrack=new Co(this._room,this),this.remoteAuxiliaryTrack=new Zb(this._room,this),this.avPlayerStateSyncManager=new f_({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 Yr(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===_.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 a=r.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(a," ").concat(n.kind));let o=_.AUDIO;n.kind===_.VIDEO&&(o=a===_.MAIN?_.VIDEO:_.AUXILIARY);let l=this.remoteAudioTrack;o===_.VIDEO?l=this.remoteVideoTrack:o===_.AUXILIARY&&(l=this.remoteAuxiliaryTrack),(t=this.singlePC)==null||t.receiverRemoteTrackMap.set(s,l),(i=this.singlePC)!=null&&i.scriptTransformWorker&&this.initReceiverTransform(s,a,n.kind===_.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(s),l.setInputMediaStreamTrack(n)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),i=new AbortController,r={abortController:i,enqueue:n=>{var s,a,o;let l=(s=this.singlePC)==null?void 0:s.receiverRemoteTrackMap.get(e);return l&&(l.kind!=="video"||(a=this.singlePC)!=null&&a.isUsingH264||(o=this.singlePC)!=null&&o.isUsingH265)?l.decodeFrame(n):n}};t.readable.pipeThrough(new TransformStream({transform:(n,s)=>{let a=r.enqueue(n);a&&s.enqueue(a)}})).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 g(this,null,function*(){var i,r;try{let n=!0;if(this._log.info("subscribe ".concat(t," ").concat(hk(e))),this.hasSSRC){let o="subscribe_change";Object.values(e).find(l=>l===!0)||(o="unsubscribe"),yield this.sendSubscription(o,e)}else{if(yield this._room.switchRoomSubedReq,(i=this.singlePC)!=null&&i.autoSubscribedUserMap.size){let o=this.singlePC.autoSubscribedUserMap.get(this.userId);if(o){this.singlePC.autoSubscribedUserMap.delete(this.userId);let l=(r=this.singlePC.autoSubscribedSsrcGroups.get(this._room.roomId))==null?void 0:r[o.groupIndex];l&&(this.ssrc={audio:l.audioSsrc,video:l.bigVideoSsrc,videoRtx:l.bigVideoRtxSsrc,auxiliary:l.auxVideoSsrc,auxiliaryRtx:l.auxVideoRtxSsrc},n=!1)}}yield this.doSubscribe(e,n),this.checkTrackEnded(e)}let{user:s,mediaTrack:a}=this.remoteVideoTrack;e.smallVideo&&a?(w.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=yn.start({track:a,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),w.addFailedEvent({key:524702}),yn.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}})):(yn.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 O({code:C.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"),Bt&&Ht<92)return;this.singlePC.startReconnection()}}unsubscribe(e){return g(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 a=x({},i.subscribeState);r.forEach(l=>{switch(l.mediaType){case 1:a.audio=!1;break;case 4:a.video=!1;break;case 8:a.smallVideo=!1;break;case 2:a.auxiliary=!1}});let o="subscribe_change";Object.values(a).find(l=>l===!0)||(o="unsubscribe"),i._log.info("".concat(o==="unsubscribe"?o:"subscribe"," ").concat(n," [").concat(hk(a),"]")),o==="unsubscribe"&&((s=i.singlePC)==null||s.removeDownlinkQueue.add(i.tinyId)),yield i.sendSubscription(o,a),n==="main"&&(yn.stop(i._blackSmallVideoDetectionId),i._blackSmallVideoDetectionId=void 0),o==="unsubscribe"&&(yield i.removeDownlink())})()})}subscribeDataChannel(){return g(this,null,function*(){if(!this.singlePC)return;yield this.singlePC.waitForPeerConnectionConnected();let e=W(x({},this.subscribeState),{datachannel:!0});yield this.doSubscribe(e)})}unsubscribeDataChannel(){return g(this,null,function*(){let e=W(x({},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=w_,n=X.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=N_,n=X.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:r,data:i,responseCommand:n,timeout:1e4,retries:3}).then(s=>{let{data:a}=s;if(a.code!==0){let o=new O({code:a.code,message:Y({key:K.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(o),o}})}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 g(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 g(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:ai(),bigVideoSsrc:ai(),bigVideoRtxSsrc:ai(),auxVideoSsrc:ai(),auxVideoRtxSsrc:ai()},{audioSsrc:a,bigVideoSsrc:o,bigVideoRtxSsrc:l,auxVideoSsrc:c,auxVideoRtxSsrc:d}=s;e.ssrc={audio:a,video:o,videoRtx:l,auxiliary:c,auxiliaryRtx:d},e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc,prevMids:e._prevMids});try{let h=yield e._signalChannel.sendWaitForResponseWithRetry({command:j0,responseCommand:X.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(h.data.code!==0&&h.data.code!==-10036)throw new O({code:h.data.code,message:h.data.message});e.isDataChannelSubscribed=(n=t.datachannel)!=null&&n}catch(h){throw yield e.removeDownlink(),h}return}e.singlePC.addDownlinkQueue.delete(e.tinyId),yield e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc,prevMids:e._prevMids})}finally{if((t.audio||t.video||t.smallVideo||t.auxiliary||!t.datachannel)&&qc){let{main:s,aux:a}=e._room.jitterBufferDelay||{},{jitterDelay:o=s,jitterDelayAux:l=a}=e._room.scheduleResult.config||{};(le(o)||le(l))&&e.setJitterBufferDelay({mainDelay:o,auxDelay:l})}}}})()})}removeDownlink(){return g(this,null,function*(){this.singlePC&&(this.isDataChannelSubscribed=!1,this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId),clearTimeout(this.jitterBufferTimeoutId),this._jitterBufferResolve&&(this._jitterBufferResolve(),this._jitterBufferResolve=void 0),this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),this._prevMids=yield this.singlePC.removeDownlink(this.userId))})}setJitterBufferDelay(e){let{mainDelay:t,auxDelay:i}=e;if(!qc||!this.singlePC||!this._peerConnection||Vt(t)&&Vt(i))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i));let r=this.singlePC.getReceiversByUserId(this.userId);return le(t)&&(this.remoteAudioTrack.jitterBufferDelay=t,this.remoteVideoTrack.jitterBufferDelay=t),le(i)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=i,Vt(t)&&(this.remoteAudioTrack.jitterBufferDelay=i)),new Promise(n=>{this._jitterBufferResolve=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),this._jitterBufferResolve=void 0,n();if(r.forEach(s=>{var a;let o=s.track===this.remoteAuxiliaryTrack.outMediaTrack||Vt(t)&&s.track===this.remoteAudioTrack.outMediaTrack;if(o&&Vt(i)||!o&&Vt(t))return;let l=o?i||0:t,c=(s.jitterBufferTarget||0)+100;c>l||(s.jitterBufferTarget=c,this._log.debug("set ".concat(o?"aux ":"").concat((a=s==null?void 0:s.track)==null?void 0:a.kind," jitterBuffer delay ").concat(c," -> ").concat(l)))}),!r.find(s=>{let a=s.track===this.remoteAuxiliaryTrack.outMediaTrack?i||0:t;return s.jitterBufferTarget<a}))return this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(i," done")),this._jitterBufferResolve=void 0,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),this._jitterBufferResolve=void 0,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()}};M([fo(),ge(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 a=o=>{this.off("closed",a),s(new O({code:C.API_CALL_ABORTED,message:Y({key:K.CONNECTION_ABORTED,data:o})}))};this.on("closed",a),e.apply(this,i).then(n,s).finally(()=>{this.off("closed",a)})})})],Hu.prototype,"subscribe"),M([fo()],Hu.prototype,"unsubscribe"),M([yr(()=>"jitter")],Hu.prototype,"setJitterBufferDelay");var fW=Hu,_W=Ge(it()),mk=class bk extends _W.EventEmitter{constructor(t,i){super(),this.room=t,this.signalChannel=i,u(this,"log"),u(this,"cmdIdSeqMap",new Map),u(this,"messageMap",new Map),this.log=P.createLogger({parent:t.getLogger(),id:"cmm",userId:t.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),i.on(X.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(x4,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),a=this.messageMap.get(s);if(a&&a.lastSeq!==0)if(Math.abs(a.lastSeq-n.seq)>bk.SEQ_INTERVAL)this.messageMap.set(s,{lastSeq:n.seq,cachedMessageMap:new Map}),this.emitMessage(n);else if(n.seq>a.lastSeq){if(n.seq===a.lastSeq+1)this.emitMessage(n);else if(!a.cachedMessageMap.has(n.seq)){let o=setTimeout(()=>this.emitMessage(n,!0),5e3);a.cachedMessageMap.set(n.seq,{message:n,timeoutId:o})}}else this.log.debug("drop message ".concat(n.userId,"-").concat(n.cmdId,"-").concat(n.seq));else a||(a={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(s,a),setTimeout(()=>this.emitMessage(n,!0),100)),a.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),mi(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 o=[...n.cachedMessageMap.values()].sort((l,c)=>l.message.seq-c.message.seq);o[0]&&(s=o[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 a=n==null?void 0:n.cachedMessageMap.get(s.seq+1);a&&this.emitMessage(a.message)}};u(mk,"SEQ_INTERVAL",300);var gW=mk,{isString:pk,isUndefined:Sn,getNetworkType:TW,isEmpty:EW}=$t,kr=class extends nW{constructor(e){super(e),u(this,"_businessInfo"),u(this,"userManager"),u(this,"_version"),u(this,"_heartbeat",-1),u(this,"_lastHeartBeatTime",-1),u(this,"_stats"),u(this,"_joinTimeout",-1),u(this,"_firstPublishedList",null),u(this,"_joinReject",null),u(this,"_isRelayChanged",!1),u(this,"sdpSemantics"),u(this,"signalChannel",null),u(this,"uplinkConnection",null),u(this,"singlePC",null),u(this,"enableSPC",eo),u(this,"_changeBigSmallRecords",new Map),u(this,"networkQuality"),u(this,"_iceTransportPolicy"),u(this,"forceRelay",!1),u(this,"_turnServers",[]),u(this,"_iceServersFromJoin"),u(this,"_syncUserListInterval",-1),u(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160}),u(this,"enableSEI",!1),u(this,"_enableAudioVolumeEvaluation",!1),u(this,"_audioVolumeIntervalId",0),u(this,"_enableMultiAuxStream",!1),u(this,"_pureAudioPushMode",!1),u(this,"_customMessageManager"),u(this,"_enableDataChannel",!1),u(this,"preferHW",!1),u(this,"healthDetector"),u(this,"playoutDelay"),u(this,"jitterBufferDelay"),u(this,"_updateAudioLevelTaskId",-1),u(this,"switchRoomSubedReq"),u(this,"resolveSwitchRoomSubedReq"),u(this,"enableVolumeControlInIOS"),u(this,"capturedLocalMainAudioTrack"),u(this,"capturedLocalMainVideoTrack"),u(this,"capturedLocalAuxVideoTrack"),u(this,"PRECONNECT_EXPIRED_TIME",3e5),u(this,"PRECONNECT_TIMEOUT",1e4),u(this,"preconnectTimeoutId",null),u(this,"firewallDetector"),u(this,"isUsingVideoMixerInternalTrack",!1),this.firewallDetector=new FH,this.firewallDetector.on("firewall-restriction",()=>{this._log.warn("firewall restriction"),this.emit("firewall-restriction")}),this._stats=new G4(this,this._log),this.userManager=new UH(this.userId,this._log),this._version=ei,this.sdpSemantics=pc,Sn(e.sdpSemantics)?_s.isUnifiedPlanDefault()&&(this.sdpSemantics=Aa):this.sdpSemantics=e.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(TW())),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=!Sn(e.enableMultiAuxStream)&&e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&eo,!Sn(e.enableSPC)&&eo&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this._initBusinessInfo(e),this.healthDetector=new uW(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 g(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=iA(r,[]);R.emit(b.REMOTE_PUBLISH_STATE_CHANGED,x({room:this},n)),this.emit("remote-publish-state-changed",x({},n))}),this.joinParams=e,Se(e.enableDataChannel)&&(this._enableDataChannel=e.enableDataChannel),new Promise((r,n)=>g(this,null,function*(){var s,a;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(l){if(!(l instanceof O&&l.code===C.SPC_INITIALIZED_FAILED))return n(l);(s=this.signalChannel)==null||s.destroy(),yield this.initialize()}let o=J();yield this.doJoin(e,(a=this.singlePC)==null?void 0:a.clientAbility),w.addSuccessEvent({key:521708,cost:J()-o}),r(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(o){w.addFailedEvent({key:521708,error:o}),n(o)}this._joinReject=null}))})}initSinglePC(){return g(this,null,function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new br({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 O({code:C.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((i,r)=>g(this,null,function*(){var n,s,a,o,l,c,d,h;if(e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(wu,f=>{this.clearJoinTimeout(),R.emit(b.JOIN_SIGNAL_CONNECTION_END,{room:this,error:f}),r(f)}),Se((s=(n=this.scheduleResult)==null?void 0:n.config)==null?void 0:s.singlePC)&&eo&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),!((o=(a=this.scheduleResult)==null?void 0:a.config)!=null&&o.jitterDelay)&&!((c=(l=this.scheduleResult)==null?void 0:l.config)!=null&&c.jitterDelayAux)||!qc){if(this.scene==="live"&&this.role==="audience"&&!this.jitterBufferDelay&&!this.playoutDelay){let f=this.latencyLevel===2?1e3:700;this._log.debug("set default audience jitterBuffer",f),this.jitterBufferDelay={main:f,aux:f}}t&&this.playoutDelay&&(this._log.info("set playoutDelay",JSON.stringify(this.playoutDelay)),t.playoutDelay=this.playoutDelay)}let m={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:uc,ua:navigator&&navigator.userAgent||"",terminalType:SR(),netType:Na(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0,isChorus:!!this.enableChorus,enableNtpAudioFrame:!!this.enableChorus&&jc(),transcription:this._enableDataChannel,downUseVp8:((d=this.scheduleResult.config)==null?void 0:d.downUseVp8)||!1};this._log.debug("join room signal data: ".concat(JSON.stringify(m)));let p=5e3;(h=this.scheduleResult.config)!=null&&h.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(p=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout(()=>{r(new O({code:C.JOIN_ROOM_FAILED,message:Y({key:K.JOIN_ROOM_TIMEOUT})}))},p),R.emit(b.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?O4:T4,m),this.signalChannel.once(X.JOIN_ROOM_RESULT,f=>g(this,null,function*(){this.clearJoinTimeout();let{code:T,message:E,data:v,tinyId:y}=f.data;R.emit(b.JOIN_RECEIVED_CMD_RES,{room:this,code:T}),T===0?(this._log.info("Join room success, start heartbeat"),y&&(this.tinyId=y),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=v.publishers,this._iceServersFromJoin=v.iceServer?[v.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var D;(D=this.singlePC)==null||D.connect(W(x({},v.ability),{useVp8:v.ability.useVp8||!!e.useVp8,useH265:v.ability.useH265&&!!e.useH265})).catch(()=>{})}),i()):(this._log.error("Join room failed result: ".concat(T," error: ").concat(E)),r(new O({code:C.JOIN_ROOM_FAILED,extraCode:T,message:Y({key:K.JOIN_ROOM_FAILED,data:{error:E,code:T}})})))}))}))}reJoin(){return g(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(W(x({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),ue.logSuccessEvent({userId:this.userId,eventType:Qe.REJOIN}),this.singlePC){let i=r=>{var n;r.state==="CONNECTED"&&((n=this.singlePC)==null||n.off(Ns.CONNECTION_STATE_CHANGED,i),this.uplinkConnection instanceof dk&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(s=>{s.installEvents(),s.onSinglePCReconnected()}))};this.singlePC.on(Ns.CONNECTION_STATE_CHANGED,i),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof xu&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(e){this._log.warn("reJoin fail ".concat(e)),this.reset(),ue.logFailedEvent({userId:this.userId,eventType:Qe.REJOIN,error:e}),this.emit("error",new O({code:C.JOIN_ROOM_FAILED,message:Y({key:K.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")})}initialize(e){return g(this,null,function*(){var t;if(!(e!=null&&e.isPreconnect)&&this.preconnectPromise&&(yield this.preconnectPromise.catch(()=>{})),(t=this.signalChannel)!=null&&t.hasPreconnect){if(this.signalChannel.isPreconnectValid(this.sdkAppId,this.userId,this.userSig))return this._log.info("reuse preconnect signal channel"),void this.signalChannel.consumePreconnect();this.signalChannel.close()}let i,{mainUrl:r,backupUrl:n}=this.getSignalChannelUrl(),s=this.signalChannel||(function(o){return[...Ou.values()].find(c=>c.room.userId===o&&!c.room.isJoined)||null})(this.userId),a=!!(s&&s.isConnected&&s.keepAlive&&s.userId===this.userId);return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(i=this.scheduleResult.domains[0]),this._log.info("".concat(a?"reuse":"setup"," signal channel")),a?(s.url=r,s.backupUrl=n,s.room.setSignalChannel(null),s.room=this,this.signalChannel=s):(s&&s.close(),this.signalChannel=new z0({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:r,backupUrl:n,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?i:void 0,preconnect:e==null?void 0:e.isPreconnect}),this._customMessageManager=new gW(this,this.signalChannel),this._customMessageManager.on("message",o=>{this.emit("custom-message",o)})),this.networkQuality||(this.networkQuality=new X0({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(X0.EVENT_NETWORK_QUALITY,o=>{var l;this.emit("network-quality",o),(l=this.singlePC)==null||l.detectTCPAndUDP(o)})),Wt(this,this.signalChannel).add(k_,o=>{R.emit(b.SIGNAL_CONNECTION_STATE_CHANGED,x({room:this},o)),this.emit("signal-connection-state-changed",o)}).add(f4,o=>{this.reset(),this.emit("error",o)}).add(X.PEER_JOIN,o=>{let{srcTinyId:l,userId:c,role:d,fromType:h}=o.data.data;this.userManager.addUser({userId:c,tinyId:l,role:d,fromType:h})}).add(X.PEER_LEAVE,o=>{let{userId:l,reason:c=0}=o.data.data;this.userManager.deleteUser(l,c)}).add(X.UPDATE_REMOTE_MUTE_STAT,o=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(o.data)}).add(X.CLIENT_BANNED,o=>{let l=o.data.data,{reason:c}=l;if(ue.uploadEvent({log:"stat-banned:".concat(c),userId:this.userId}),c==="user_time_out")return this._log.warn("".concat(c," last heart beat time: ").concat(this._lastHeartBeatTime," interval: ").concat(Date.now()-this._lastHeartBeatTime,", visibility: ").concat(document.visibilityState)),void this.reJoin();this._log[c==="kick"?"error":"info"]("user was banned because of [".concat(c,"]")),this.reset(),this.emit("banned",{reason:c})}).add(X.SEND_SWITCH_ROOM_SUBED_REQ,o=>{if(!this.singlePC)return;let{subList:l}=o.data.data;this._log.info("auto subscribe ".concat(ti(l,{keysToInclude:["userId"]}))),l.forEach(c=>{this.singlePC.autoSubscribedUserMap.set(c.userId,c)}),this.resolveSwitchRoomSubedReq()}).add(X.FALLBACK_CODEC,o=>g(this,null,function*(){var l,c,d,h,m;let p=o.data.data;((l=p.videoControlInfo)==null?void 0:l.enableH265Enc)===0&&((c=this.singlePC)==null?void 0:c.videoCodec)==="h265"&&(this._log.warn("fallback codec enableH265Enc: ".concat((d=p.videoControlInfo)==null?void 0:d.enableH265Enc)),w.addCount({key:513e3}),yield(h=this.singlePC)==null?void 0:h.switchVideoEncoder("h264"),yield(m=this.uplinkConnection)==null?void 0:m.sendMediaSettings())})),this.signalChannel.once(U0,o=>{this.tinyId=o.signalInfo.tinyId,R.emit(b.JOIN_SIGNAL_CONNECTION_END,{room:this})}),R.emit(b.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),a&&R.emit(b.JOIN_SIGNAL_CONNECTION_END,{room:this}),a})}setSignalChannel(e){this.signalChannel=e,e||mt(this)}leave(){return g(this,null,function*(){var e;try{yield this.doHeartbeat()}catch{}this._log.info("leave() => leaving room"),R.emit(b.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(E4),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=_e.run("ric",this.doHeartbeat.bind(this),{delay:2e3}),this.enableChorus&&this.startUpdateNTPTime())}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),_e.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return g(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(As.has(s)){let a=As.get(s).map(o=>({uint32_event_id:o.eventId,uint64_date:o.timestamp,str_userid:o.remoteUserId,uint32_param1:o.param1,uint32_param2:o.param2,uint32_video_stream_type:o.streamType}));return As.delete(s),a}return[]})(this.userId):[],n=W(x({str_sdk_version:uc,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:x({uint32_terminal_type:15,str_device_name:nn(),str_os_version:"",uint32_net_type:Na()},i.msg_device_info)});if(this.heartbeatReport=n,this.heartbeatCount++,R.emit(b.HEARTBEAT_REPORT,{room:this,report:n}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(v4,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",W(x({},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 a of i){if(a.flag===EA)continue;let{userId:o,srcTinyId:l,flag:c,fromType:d}=a;o===this.userId&&(t=!0,this.uplinkConnection&&(this.uplinkConnection.flag=c),this.localPublishFlag!==c&&(this.localPublishFlag=c,this.emit("local-publish-flag-changed",c))),n.push({userId:o,tinyId:l,flag:c,fromType:d})}let s=[...r.map(a=>{let{userId:o,srcTinyId:l,flag:c,mixUserList:d,fromType:h}=a;return{userId:o,tinyId:l,flag:c,isRobot:!0,mixUserList:d,fromType:h}}),...n];s.forEach(a=>{let{userId:o}=a,l=this.remotePublishedUserMap.get(o);l&&this.checkSubscribeBigSmallVideo(l)}),e.data.fakeMixUser&&(e.data.fakeMixUser.tinyId=e.data.fakeMixUser.srcTinyId,s.push(e.data.fakeMixUser)),R.emit(b.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 xu&&(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,a=new(this.singlePC?fW:q0)({userId:t,tinyId:i,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:n,fromType:s});this.userManager.addRemotePublishedUser(a),this.installDownlinkEvents(a,t),this.emit("remote-published",a)}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!==C.ICE_TRANSPORT_ERROR&&(r===C.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",i))}),e.on("connection-state-changed",i=>{this.emit("media-connection-state-changed",W(x({},i),{userId:e.userId}))})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=_e.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){_e.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:w4,responseCommand:X.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:a,srcTinyId:o,role:l,fromType:c}=s;return{userId:a,tinyId:o,role:l,fromType:c}});throw Y({key:K.SIGNAL_RESPONSE_FAILED,data:{signalResponse:X.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||!J0)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)===Be.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(t=>{if(t instanceof Ki&&!t.getIsReconnecting()){let i=t.getPeerConnection();i&&i.connectionState===Be.CLOSED&&(this._log.warn("[".concat(t.getUserId(),"] pc is closed but not reconnect")),t.startReconnection())}})}fallbackToMPC(){return g(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),ue.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 xu({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 q0({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 O({code:C.INVALID_OPERATION,message:Y({key:K.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.firewallDetector.destroy(),this.removeAllListeners(),this.healthDetector.destroy(),_e.clearTask(this._audioVolumeIntervalId))}switchRole(e){return g(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:N4,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:X.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 O({code:C.SWITCH_ROLE_FAILED,message:Y({key:K.SWITCH_ROLE_FAILED,data:{message:n,code:r}})});this.role=e}).catch(i=>{throw i instanceof O&&i.getCode()===C.API_CALL_TIMEOUT&&(i=new O({code:C.SWITCH_ROLE_FAILED,message:Y({key:K.SWITCH_ROLE_TIMEOUT})})),this._log.error(i),i})}subscribeDataChannel(){return g(this,null,function*(){if(this.remotePublishedUserMap.size===0)return;let e=[...this.remotePublishedUserMap.values()].filter(t=>t.fromType===Tc);this._log.info("subscribeDataChannel",e.map(t=>t.userId)),yield Promise.all(e.map(t=>g(this,null,function*(){try{yield t.subscribe(W(x({},t.subscribeState),{datachannel:!0}),"main")}catch(i){this._log.error("subscribeDataChannel failed:",t.userId,i)}})))})}unsubscribeDataChannel(){return g(this,null,function*(){if(this.remotePublishedUserMap.size===0)return;let e=[...this.remotePublishedUserMap.values()].filter(t=>t.fromType===Tc);this._log.info("unsubscribeDataChannel",e.map(t=>t.userId)),yield Promise.all(e.map(t=>t.unsubscribeDataChannel()))})}_initUplinkConnection(){this.uplinkConnection=this.singlePC?new dk({userId:this.userId,tinyId:this.tinyId,room:this}):new xu({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",W(x({},e),{userId:this.userId}))}),this.uplinkConnection.on("error",e=>{let t=e.getCode();t!==C.ICE_TRANSPORT_ERROR&&(t===C.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})}publish(e){return g(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 dn?e:null,localVideoTrack:e instanceof ji?e:null,isAuxiliary:e.streamType==="auxiliary"})})}unpublish(e){return g(this,null,function*(){if((this.scene!=="live"||this.role==="anchor")&&(this.isMainStreamPublished||this.isAuxStreamPublished)&&this.uplinkConnection&&(e.isPublished||e.isPublishing||this.uplinkConnection.isTrackReferenced(e))){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 dn?e:null,localVideoTrack:e instanceof ji?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&&OC()?this.uplinkConnection.replaceTrack(e).then(t=>{t&&R.emit(b.LOCAL_TRACK_REPLACED,{track:e})}):Promise.resolve()}setBandWidth(e){return g(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return g(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:_.VIDEO,videoType:_.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 g(this,null,function*(){if(t=t.filter(a=>!a.isSubscribed),t.length===0)return;let{userId:r}=t[0],n=this.remotePublishedUserMap.get(r);if(!n)return;let s=t.find(a=>a.mediaType===2)?"auxiliary":"main";try{let a=x({},n.subscribeState);t.forEach(l=>{switch(l.mediaType){case 1:a.audio=!0;break;case 4:a.video=!0;break;case 8:a.smallVideo=!0;break;case 2:a.auxiliary=!0}});let o=this._changeBigSmallRecords.get(r);o&&o.options.smallVideo&&n.muteState.hasSmall&&a.video&&(a.video=!1,a.smallVideo=!0),R.emit(b.SUBSCRIBE_START,{room:this,streamType:s,remotePublishedUser:n,subscribeState:a}),this._log.info("subscribe() => ".concat(r," ").concat(s," ").concat(t.map(l=>l.strMediaType).join(",")," [").concat(O_(a),"] prev: [").concat(O_(n.subscribeState),"]")),yield n.subscribe(a,s),this._log.info("subscribe ".concat(r," ").concat(s," done"));for(let l of t)l.mediaTrack||(yield l.waitHasMediaTrack());R.emit(b.SUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:n})}catch(a){let o=a instanceof O?a.getCode():C.UNKNOWN,l=a;throw a instanceof O?o===C.REMOTE_STREAM_NOT_EXIST&&(l=new O({code:C.API_CALL_ABORTED,message:Y({key:K.API_CALL_ABORTED,data:{message:a.message,userId:r,streamType:s}})}),this._log.warn(l)):(l=new O({code:o,message:Y({key:K.SUBSCRIBE_FAILED,data:{message:a.message,userId:r,streamType:s}})}),this._log.error(l)),l}})}unsubscribe(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return g(this,null,function*(){let{userId:r}=t[0],n=this.remotePublishedUserMap.get(r);if(!n)return;let s=t.find(a=>a.mediaType===2)?"auxiliary":"main";this._log.info("unsubscribe() => ".concat(r," ").concat(s," ").concat(t.map(a=>a.strMediaType).join(",")));try{yield n.unsubscribe({remoteTracks:t,streamType:s})}catch(a){this._log.warn("unsubscribe() => failed ".concat(a))}t.forEach(a=>{a.unsubscribe(),a.mediaType===8&&a.setMediaType(4)}),R.emit(b.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 _e.clearTask(this._audioVolumeIntervalId);e=Math.floor(Math.max(e,100)),R.emit(b.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&_e.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=_e.run("intervalInWorker",()=>{var i;ru.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(i=this.remotePublishedUserMap)==null||i.forEach(n=>{if(n.muteState.hasAudio){!ru.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 g(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=_e.run("intervalInWorker",()=>g(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:a}=this.uplinkConnection;s.forEach(o=>{o.type==="media-source"&&o.audioLevel&&(a.volume=o.audioLevel)})}),{delay:n,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),_e.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(!MC||!i)return;let r=(t=i.getSynchronizationSources()[0])==null?void 0:t.audioLevel;le(r)?e.remoteAudioTrack.volume=Math.min(2*r,1):i.getStats().then(n=>{n.forEach(s=>{s.type==="inbound-rtp"&&le(s.audioLevel)&&(e.remoteAudioTrack.volume=s.audioLevel)})})}getLocalAudioStats(){return g(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 g(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 g(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 g(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 g(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($t.getTurnServer(r))):$t.isPlainObject(e)&&i.push($t.getTurnServer(e)),this._turnServers=i,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:R4,data:e,timeout:5e3,responseCommand:X.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"}).catch(t=>{if(t.code!==C.API_CALL_ABORTED)throw t})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:C4,data:e,timeout:5e3,responseCommand:X.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"}).catch(t=>{if(t.code!==C.API_CALL_ABORTED)throw t})}sendStartPublishCDN(e){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?y4:I4,data:e,timeout:5e3,responseCommand:t?X.START_PUBLISH_TENCENT_CDN_RES:X.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"}).catch(i=>{if(i.code!==C.API_CALL_ABORTED)throw i})}sendStopPublishCDN(e){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?S4:A4,data:e,timeout:5e3,responseCommand:t?X.STOP_PUBLISH_TENCENT_CDN_RES:X.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"}).catch(i=>{if(i.code!==C.API_CALL_ABORTED)throw i})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:b4,data:e,timeout:5e3,responseCommand:X.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"}).catch(t=>{if(t.code!==C.API_CALL_ABORTED)throw t})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:k4,data:e,timeout:5e3,responseCommand:X.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"}).catch(t=>{if(t.code!==C.API_CALL_ABORTED)throw t})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:D4,data:e,timeout:5e3,responseCommand:X.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"}).catch(t=>{if(t.code!==C.API_CALL_ABORTED)throw t})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:M4,data:e,timeout:5e3,responseCommand:X.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=$t.getEnv();return t?(e.mainUrl="wss://".concat($t.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},this.clearPreconnectTimeout(),this.preconnectPromise=null}preconnect(e,t,i,r,n,s){return g(this,null,function*(){var a,o;if(!this.isJoined){if(!n&&!s)throw new O({code:C.INVALID_OPERATION,message:"roomId or strRoomId is required"});if(this.preconnectPromise){let l="pending";return(a=this.signalChannel)!=null&&a.isConnected?l="connected":(o=this.signalChannel)!=null&&o.isConnecting&&(l="connecting"),this._log.warn("preconnect is already ".concat(l,", skip duplicate call")),this.preconnectPromise}return this.userId=t,this.sdkAppId=e,this.userSig=i,this.roomId=String(n||s),this.useStringRoomId=!(!s||n),this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.preconnectPromise=Promise.race([this.doPreconnect(e,t,i,r,n,s),new Promise((l,c)=>{this.preconnectTimeoutId=setTimeout(()=>{c(new O({code:C.INVALID_OPERATION,message:"preconnect timeout after ".concat(this.PRECONNECT_TIMEOUT,"ms")}))},this.PRECONNECT_TIMEOUT)})]).then(()=>{this.clearPreconnectTimeout()}).catch(l=>{throw this.clearPreconnectTimeout(),this.closePreconnect().catch(()=>{}),l}),this.preconnectPromise}this._log.warn("already joined room")})}doPreconnect(e,t,i,r,n,s){return g(this,null,function*(){var a,o,l;try{if(!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!$t.getEnv()&&(yield this.schedule({sdkAppId:e,userId:t,userSig:i,roomId:n,strRoomId:s,role:20,privateMapKey:null,businessInfo:null,streamId:null,userDefineRecordId:null},r)),(a=this.scheduleResult.config)==null||!a.prelink)throw new O({code:C.INVALID_OPERATION,message:"preconnect failed: your sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it."});yield this.initialize({isPreconnect:!0}),(o=this.signalChannel)==null||o.markPreconnectConnected({sdkAppId:e,userId:t,userSig:i}),(l=this.signalChannel)==null||l.stopPreconnectIn(this.PRECONNECT_EXPIRED_TIME/1e3),this._log.info("preconnect success")}catch(c){throw this._log.error("preconnect failed",c),c}})}clearPreconnectTimeout(){this.preconnectTimeoutId&&(clearTimeout(this.preconnectTimeoutId),this.preconnectTimeoutId=null)}closePreconnect(){return g(this,null,function*(){var e;if((e=this.signalChannel)!=null&&e.hasPreconnect){if(this.isJoined)return void this._log.warn("close preconnect failed: has joined room");if(this.signalChannel.keepAlive)return void this._log.info("skip close preconnect: use keepAlive");this.clearNetworkQuality(),this.signalChannel&&this.signalChannel.isConnected&&(this.signalChannel.close(),this.setSignalChannel(null)),this.clearPreconnectTimeout(),this.preconnectPromise=null}})}checkSubscribeBigSmallVideo(e){return g(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:a,reSubscribeCount:o}=s;if(a.video&&t.video||a.smallVideo&&t.smallVideo&&r)return;let l={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:a.video,smallVideo:a.smallVideo,datachannel:e.subscribeState.datachannel};try{if(!r&&l.smallVideo&&(l.video=!0,l.smallVideo=!1),l.smallVideo===t.smallVideo&&l.video===t.video)return;s.isSubscribing=!0,s.reSubscribeCount=o-1,yield e.subscribe(l,"main"),e.remoteVideoTrack.setMediaType(l.smallVideo?8:4),this._log.info("change [".concat(i,"] to ").concat(l.smallVideo?"small":"big"," video successfully. count ").concat(Ca-s.reSubscribeCount,".")),s.isSubscribing=!1,s.reSubscribeCount=Ca}catch(c){this._log.info("change [".concat(i,"] to ").concat(l.smallVideo?"small":"big"," video failed. count ").concat(Ca-s.reSubscribeCount,". reason: ").concat(c)),s.isSubscribing=!1,s.reSubscribeCount===0&&this._changeBigSmallRecords.delete(i)}})}changeType(e,t){let i={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:Ca};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(pk(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!Sn(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new O({code:C.INVALID_PARAMETER,message:Y({key:K.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(!Sn(e.userDefineRecordId)){let i=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(i)===null)throw new O({code:C.INVALID_PARAMETER,message:Y({key:K.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!Sn(e.userDefinePushArgs)){if(!(pk(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new O({code:C.INVALID_PARAMETER,message:Y({key:K.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}EW(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){return g(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&an)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 O({code:C.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 g(this,null,function*(){var t;if(!this.signalChannel||!this.singlePC)return;let{roomId:i,strRoomId:r,userSig:n,privateMapKey:s}=e,a=((t=this.scheduleResult.config)==null?void 0:t.autoSubscribeCount)||(e==null?void 0:e.autoSubscribeCount)||1,o=String(this.useStringRoomId?r:i),l=[];for(let m=0;m<a;m++)l.push({audioSsrc:ai(),bigVideoSsrc:ai(),bigVideoRtxSsrc:ai(),auxVideoSsrc:ai(),auxVideoRtxSsrc:ai()});let c={currRoomId:this.roomId,targetRoomId:o,useStringRoomId:this.useStringRoomId,ability:this.singlePC.clientAbility,userSig:n,privateMapKey:s??this.privateMapKey,subscribe:l};this.singlePC.autoSubscribedUserMap.clear(),this.singlePC.autoSubscribedSsrcGroups.clear(),this.singlePC.autoSubscribedSsrcGroups.set(o,l);let d,h=this.roomId;this.roomId=this.useStringRoomId?r:String(i),this.switchRoomSubedReq=new Promise(m=>{this.resolveSwitchRoomSubedReq=m,mi(5e3).then(m)}),R.emit(b.SWITCH_ROOM_START,{room:this}),yield this.singlePC.waitForPeerConnectionConnected();try{this.userManager.clear(),d=yield this.signalChannel.sendWaitForResponse({command:U4,responseCommand:X.SEND_SWITCH_ROOM_RES,data:c});let{code:m,message:p}=d.data;if(m!==0){this._log.error("switch room failed. result: ".concat(m," error: ").concat(p));let f=new O({code:C.SWITCH_ROOM_FAILED,extraCode:m,message:p});throw R.emit(b.SWITCH_ROOM_FAILED,{room:this,error:f}),f}this.userSig=n,Sn(s)||(this.privateMapKey=s),R.emit(b.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:h,targetRoomId:o})}catch(m){throw this.singlePC.autoSubscribedSsrcGroups.clear(),this.roomId=h,this.resolveSwitchRoomSubedReq(),m}})}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(o=>{r=Math.min(o.offset,r),n=Math.max(o.offset,n)});let s=Math.floor(t.reduce((o,l)=>o+l.rtt,0)/t.length),a=Math.floor(t.reduce((o,l)=>o+l.offset,0)/t.length);(n-r>30||s>50)&&setTimeout(()=>this.startUpdateNTPTime(),5e3),lA(a),(i=this.scriptTransformWorker)==null||i.postMessage({type:"ntp-offset",data:a}),this._log.debug("ntp updated offset: ".concat(a)),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:V4,responseCommand:X.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 M([Ke(["left",re.INIT],"joined"),vr({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"),ni(!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())}}),ge(e=>{let t=new h4;return function(i,r,n){return g(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 O({code:C.INVALID_OPERATION,message:Y({key:K.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this,role:i.role}))throw new O({code:C.INVALID_OPERATION,message:Y({key:K.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)),R.emit(b.JOIN_START,{room:this,roomId:s,params:i});let a=$t.getEnv();a||(a=zr.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(dp.OLD_CLOUD_LADDER)?a=zr.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(dp.WEBRTC)&&(a=zr.WEBRTC))),ue.setConfig({env:a,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),_s.checkSystemRequirementsInternal(n).then(o=>{this.checkSystemResult=o,m4.call(this)});try{!this.preconnectPromise&&!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!$t.getEnv()&&(yield this.schedule(i,n));let o=yield e.call(this,i,r,n);return this.roomId=s,this._joinedTimestamp=$t.performanceNow(),R.emit(b.JOIN_SUCCESS,{room:this}),n===30&&!i.component&&ue.uploadEvent({log:"stat-conv-".concat(Number(tn),"-").concat(location.hostname),userId:this.userId}),o}catch(o){throw t.delete({room:this,roomId:s}),R.emit(b.JOIN_FAILED,{room:this,error:o}),o}})}})],kr.prototype,"join"),M([Ke("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),ge(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return g(this,null,function*(){R.emit(b.LEAVE_START,{room:this,roomId:this.roomId}),yield e.call(this,...i),R.emit(b.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})}),yb("leave room"),Xc({fnName:"publish",validateArgs:!1}),Xc({fnName:"unsubscribe",validateArgs:!1})],kr.prototype,"leave"),M([yr(e=>e.mediaType),ge(e=>function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return g(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(s=>s.outMediaTrack&&s.state==="ready"),!i.length))return;R.emit("61",{room:this});let n=e.apply(this,i);return Promise.all(i.map(s=>s.publish(this,n)))})}),vr({settings:{retries:ss,timeout:e=>qr(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),R.emit(b.PUBLISH_FAILED,{room:this}))}})],kr.prototype,"publish"),M([Xc({fnName:"publish"}),yr(e=>e.mediaType),ge(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}),cn(function(){var e,t;this.localTracks.size===0&&$a()&&((t=(e=this.singlePC)==null?void 0:e.getPeerConnection())==null||t.getSenders().forEach(i=>i.track&&i.replaceTrack(null)))})],kr.prototype,"unpublish"),M([Eb(e=>{if(e.code!==C.API_CALL_ABORTED)throw e}),yr(e=>e.userId)],kr.prototype,"replaceTrack"),M([yr(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")}),gu(),ge(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}),vr({settings:{retries:ss,timeout:e=>qr(e)},onError(e,t,i,r){if(e.message.includes("timeout"))this._log.warn("subscribe timeout"),t();else{let n=(e==null?void 0:e.code)===C.API_CALL_ABORTED;this._log[n?"warn":"error"]("subscribe failed ".concat(r.map(s=>s.strMediaType).join(","),": ").concat(e)),i(e),R.emit(b.SUBSCRIBE_FAILED,{room:this,remoteTracks:r})}}})],kr.prototype,"subscribe"),M([Xc({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")})}}),yr(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")})],kr.prototype,"unsubscribe"),Oo.create=Oo._create.bind(Oo,kr),WC(30),Oo})})(Gu)),Gu.exports}var AW=IW();const kW=yW(AW);export{kW as T};
|