1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[4012],{61808:(e,t,i)=>{var r=i(37811),n=i(74137).Buffer;e.exports=function(){let e,t,o,a,s,c,d;var l,h,u,p,_,E,m,f,S,g,T,R,C,v,y,I,A,b,O,w,N,D,P,L,k,M,U,x,V,F,B,j,G,W,H,K,Y,z,q,X,J,Q,Z,$,ee,et,ei,er,en,eo,ea,es,ec,ed,el,eh,eu,ep,e_,eE,em,ef,eS,eg,eT,eR,eC,ev,ey,eI,eA,eb,eO,ew,eN,eD,eP,eL,ek,eM,eU,ex,eV,eF,eB,ej,eG,eW,eH,eK,eY,ez,eq,eX,eJ,eQ,eZ,e$,e0,e1,e2,e3,e5,e4,e6,e8,e9,e7,te,tt,ti,tr,tn,to,ta,ts,tc,td,tl,th,tu,tp,t_,tE,tm,tf,tS,tg,tT,tR,tC,tv,ty,tI,tA,tb,tO,tw,tN,tD,tP,tL,tk,tM,tU,tx,tV,tF,tB,tj,tG,tW,tH,tK,tY,tz,tq,tX,tJ,tQ,tZ,t$,t0,t1,t2,t3,t5,t4,t6,t8,t9,t7,ie,it,ii,ir,io,ia,is,ic,id,il,ih,iu,ip,i_,iE,im,iS,ig,iT,iR,iC,iv,iy,iI,iA,ib,iO,iw,iN,iD,iP,iL,ik,iM,iU,ix,iV,iF,iB,ij,iG,iW,iH,iK,iY,iz,iq,iX,iJ,iQ,iZ,i$,i0,i1,i2,i3,i5,i4,i6,i8,i9,i7,re,rt,ri,rr,rn,ro,ra,rs,rc,rd,rl,rh,ru,rp,r_,rE,rm,rf,rS,rg,rT,rR,rC,rv,ry,rI,rA,rb,rO,rw,rN,rD,rP,rL,rk,rM,rU,rx,rV,rF,rB,rj,rG="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==i.g?i.g:"undefined"!=typeof self?self:{};function rW(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var rH=function(e){try{return!!e()}catch(e){return!0}},rK=!rH(function(){var e=(function(){}).bind();return"function"!=typeof e||e.hasOwnProperty("prototype")}),rY=Function.prototype,rz=rY.call,rq=rK&&rY.bind.bind(rz,rz),rX=rK?rq:function(e){return function(){return rz.apply(e,arguments)}},rJ=rX({}.isPrototypeOf),rQ=function(e){return e&&e.Math===Math&&e},rZ=rQ("object"==typeof globalThis&&globalThis)||rQ("object"==typeof window&&window)||rQ("object"==typeof self&&self)||rQ("object"==typeof rG&&rG)||rQ("object"==typeof rG&&rG)||function(){return this}()||Function("return this")(),r$=Function.prototype,r0=r$.apply,r1=r$.call,r2="object"==typeof Reflect&&Reflect.apply||(rK?r1.bind(r0):function(){return r1.apply(r0,arguments)}),r3=rX({}.toString),r5=rX("".slice),r4=function(e){return r5(r3(e),8,-1)},r6=function(e){if("Function"===r4(e))return rX(e)},r8="object"==typeof document&&document.all,r9=void 0===r8&&void 0!==r8?function(e){return"function"==typeof e||e===r8}:function(e){return"function"==typeof e},r7={},ne=!rH(function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]}),nt=Function.prototype.call,ni=rK?nt.bind(nt):function(){return nt.apply(nt,arguments)},nr={},nn={}.propertyIsEnumerable,no=Object.getOwnPropertyDescriptor;nr.f=no&&!nn.call({1:2},1)?function(e){var t=no(this,e);return!!t&&t.enumerable}:nn;var na,ns,nc=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},nd=Object,nl=rX("".split),nh=rH(function(){return!nd("z").propertyIsEnumerable(0)})?function(e){return"String"===r4(e)?nl(e,""):nd(e)}:nd,nu=function(e){return null==e},np=TypeError,n_=function(e){if(nu(e))throw new np("Can't call method on "+e);return e},nE=function(e){return nh(n_(e))},nm=function(e){return"object"==typeof e?null!==e:r9(e)},nf={},nS=function(e){return r9(e)?e:void 0},ng=function(e,t){return arguments.length<2?nS(nf[e])||nS(rZ[e]):nf[e]&&nf[e][t]||rZ[e]&&rZ[e][t]},nT=rZ.navigator,nR=nT&&nT.userAgent,nC=nR?String(nR):"",nv=rZ.process,ny=rZ.Deno,nI=nv&&nv.versions||ny&&ny.version,nA=nI&&nI.v8;nA&&(ns=(na=nA.split("."))[0]>0&&na[0]<4?1:+(na[0]+na[1])),!ns&&nC&&(!(na=nC.match(/Edge\/(\d+)/))||na[1]>=74)&&(na=nC.match(/Chrome\/(\d+)/))&&(ns=+na[1]);var nb=ns,nO=rZ.String,nw=!!Object.getOwnPropertySymbols&&!rH(function(){var e=Symbol("symbol detection");
1return!nO(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&nb&&nb<41}),nN=nw&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,nD=Object,nP=nN?function(e){return"symbol"==typeof e}:function(e){var t=ng("Symbol");return r9(t)&&rJ(t.prototype,nD(e))},nL=String,nk=function(e){try{return nL(e)}catch(e){return"Object"}},nM=TypeError,nU=function(e){if(r9(e))return e;throw new nM(nk(e)+" is not a function")},nx=function(e,t){var i=e[t];return nu(i)?void 0:nU(i)},nV=TypeError,nF={exports:{}},nB=Object.defineProperty,nj="__core-js_shared__",nG=nF.exports=rZ[nj]||function(e,t){try{nB(rZ,e,{value:t,configurable:!0,writable:!0})}catch(i){rZ[e]=t}return t}(nj,{});(nG.versions||(nG.versions=[])).push({version:"3.46.0",mode:"pure",copyright:"\xa9 2014-2025 Denis Pushkarev (zloirock.ru), 2025 CoreJS Company (core-js.io)",license:"https://github.com/zloirock/core-js/blob/v3.46.0/LICENSE",source:"https://github.com/zloirock/core-js"});var nW=nF.exports,nH=function(e,t){return nW[e]||(nW[e]=t||{})},nK=Object,nY=function(e){return nK(n_(e))},nz=rX({}.hasOwnProperty),nq=Object.hasOwn||function(e,t){return nz(nY(e),t)},nX=0,nJ=Math.random(),nQ=rX(1.1.toString),nZ=function(e){return"Symbol("+(void 0===e?"":e)+")_"+nQ(++nX+nJ,36)},n$=rZ.Symbol,n0=nH("wks"),n1=nN?n$.for||n$:n$&&n$.withoutSetter||nZ,n2=function(e){return nq(n0,e)||(n0[e]=nw&&nq(n$,e)?n$[e]:n1("Symbol."+e)),n0[e]},n3=function(e,t){var i,r;if("string"===t&&r9(i=e.toString)&&!nm(r=ni(i,e))||r9(i=e.valueOf)&&!nm(r=ni(i,e))||"string"!==t&&r9(i=e.toString)&&!nm(r=ni(i,e)))return r;throw new nV("Can't convert object to primitive value")},n5=TypeError,n4=n2("toPrimitive"),n6=function(e,t){if(!nm(e)||nP(e))return e;var i,r=nx(e,n4);if(r){if(void 0===t&&(t="default"),!nm(i=ni(r,e,t))||nP(i))return i;throw new n5("Can't convert object to primitive value")}return void 0===t&&(t="number"),n3(e,t)},n8=function(e){var t=n6(e,"string");return nP(t)?t:t+""},n9=rZ.document,n7=nm(n9)&&nm(n9.createElement),oe=function(e){return n7?n9.createElement(e):{}},ot=!ne&&!rH(function(){return 7!==Object.defineProperty(oe("div"),"a",{get:function(){return 7}}).a}),oi=Object.getOwnPropertyDescriptor;r7.f=ne?oi:function(e,t){if(e=nE(e),t=n8(t),ot)try{return oi(e,t)}catch(e){}if(nq(e,t))return nc(!ni(nr.f,e,t),e[t])};var or=/#|\.prototype\./,on=function(e,t){var i=oa[oo(e)];return i===oc||i!==os&&(r9(t)?rH(t):!!t)},oo=on.normalize=function(e){return String(e).replace(or,".").toLowerCase()},oa=on.data={},os=on.NATIVE="N",oc=on.POLYFILL="P",od=r6(r6.bind),ol=function(e,t){return nU(e),void 0===t?e:rK?od(e,t):function(){return e.apply(t,arguments)}},oh={},ou=ne&&rH(function(){return 42!==Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype}),op=String,o_=TypeError,oE=function(e){if(nm(e))return e;throw new o_(op(e)+" is not an object")},om=TypeError,of=Object.defineProperty,oS=Object.getOwnPropertyDescriptor,og="enumerable",oT="configurable",oR="writable";oh.f=ne?ou?function(e,t,i){if(oE(e),t=n8(t),oE(i),"function"==typeof e&&"prototype"===t&&"value"in i&&oR in i&&!i[oR]){var r=oS(e,t);r&&r[oR]&&(e[t]=i.value,i={configurable:oT in i?i[oT]:r[oT],enumerable:og in i?i[og]:r[og],writable:!1})}return of(e,t,i)}:of:function(e,t,i){if(oE(e),t=n8(t),oE(i),ot)try{return of(e,t,i)}catch(e){}if("get"in i||"set"in i)throw new om("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var oC=ne?function(e,t,i){return oh.f(e,t,nc(1,i))}:function(e,t,i){return e[t]=i,e},ov=r7.f,oy=function(e){var t=function(i,r,n){if(this instanceof t){switch(arguments.length){case 0:return new e;case 1:return new e(i);case 2:return new e(i,r)}return new e(i,r,n)}return r2(e,this,arguments)};return t.prototype=e.prototype,t},oI=function(e,t){var i,r,n,o,a,s,c,d,l,h=e.target,u=e.global,p=e.stat,_=e.proto,E=u?rZ:p?rZ[h]:rZ[h]&&rZ[h].prototype,m=u?nf:nf[h]||oC(nf,h,{})[h],f=m.prototype;for(o in t)r=!(i=on(u?o:h+(p?".":"#")+o,e.forced))&&E&&nq(E,o),s=m[o],r&&(c=e.dontCallGetSet?(l=ov(E,o))&&l.value:E[o]),a=r&&c?c:t[o],(i||_||typeof s!=typeof a)&&(d=e.bind&&r?ol(a,rZ):e.wrap&&r?oy(a):_&&r9(a)?r6(a):a,(e.sham||a&&a.sham||s&&s.sham)&&oC(d,"sham",!0),oC(m,o,d),_&&(nq(nf,n=h+"Prototype")||oC(nf,n,{}),oC(nf[n],o,a),e.real&&f&&(i||!f[o])&&oC(f,o,a)))},oA=Math.ceil,ob=Math.floor,oO=Math.trunc||function(e){var t=+e;return(t>0?ob:oA)(t)},ow=function(e){var t=+e;return t!=t||0===t?0:oO(t)},oN=Math.max,oD=Math.min,oP=function(e,t){var i=ow(e);return i<0?oN(i+t,0):oD(i,t)},oL=Math.min,ok=function(e){var t=ow(e);return t>0?oL(t,0x1fffffffffffff):0},oM=function(e){return ok(e.length)},oU=function(e){return function(t,i,r){var n=nE(t),o=oM(n);if(0===o)return!e&&-1;var a,s=oP(r,o);if(e&&i!=i){for(;o>s;)if((a=n[s++])!=a)return!0}else for(;o>s;s++)if((e||s in n)&&n[s]===i)return e||s||0;return!e&&-1}},ox={includes:oU(!0),indexOf:oU(!1)},oV=ox.includes;oI({target:"Array",proto:!0,forced:rH(function(){return![,].includes()})},{includes:function(e){return oV(this,e,arguments.length>1?arguments[1]:void 0)}});var oF=function(e,t){var i=nf[e+"Prototype"],r=i&&i[t];if(r)return r;var n=rZ[e],o=n&&n.prototype;return o&&o[t]},oB=oF("Array","includes"),oj=n2("match"),oG=function(e){var t;return nm(e)&&(void 0!==(t=e[oj])?!!t:"RegExp"===r4(e))},oW=TypeError,oH={};oH[n2("toStringTag")]="z";var oK="[object z]"===String(oH),oY=n2("toStringTag"),oz=Object,oq="Arguments"===r4(function(){return arguments}()),oX=oK?r4:function(e){var t,i,r;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,t){try{return e[t]}catch(e){}}
1(t=oz(e),oY))?i:oq?r4(t):"Object"===(r=r4(t))&&r9(t.callee)?"Arguments":r},oJ=String,oQ=function(e){if("Symbol"===oX(e))throw TypeError("Cannot convert a Symbol value to a string");return oJ(e)},oZ=n2("match"),o$=function(e){if(oG(e))throw new oW("The method doesn't accept regular expressions");return e},o0=rX("".indexOf);oI({target:"String",proto:!0,forced:!function(e){var t=/./;try{"/./"[e](t)}catch(i){try{return t[oZ]=!1,"/./"[e](t)}catch(e){}}return!1}("includes")},{includes:function(e){return!!~o0(oQ(n_(this)),oQ(o$(e)),arguments.length>1?arguments[1]:void 0)}});var o1=oF("String","includes"),o2=Array.prototype,o3=String.prototype,o5=rW(function(e){var t=e.includes;return e===o2||rJ(o2,e)&&t===o2.includes?oB:"string"==typeof e||e===o3||rJ(o3,e)&&t===o3.includes?o1:t}),o4=TypeError,o6="Reduce of empty array with no initial value",o8=function(e){return function(t,i,r,n){var o=nY(t),a=nh(o),s=oM(o);if(nU(i),0===s&&r<2)throw new o4(o6);var c=e?s-1:0,d=e?-1:1;if(r<2)for(;;){if(c in a){n=a[c],c+=d;break}if(c+=d,e?c<0:s<=c)throw new o4(o6)}for(;e?c>=0:s>c;c+=d)c in a&&(n=i(n,a[c],c,o));return n}},o9={left:o8(!1),right:o8(!0)},o7=function(e,t){var i=[][e];return!!i&&rH(function(){i.call(null,t||function(){return 1},1)})},ae=function(e){return nC.slice(0,e.length)===e},at=ae("Bun/")?"BUN":ae("Cloudflare-Workers")?"CLOUDFLARE":ae("Deno/")?"DENO":ae("Node.js/")?"NODE":rZ.Bun&&"string"==typeof Bun.version?"BUN":rZ.Deno&&"object"==typeof Deno.version?"DENO":"process"===r4(rZ.process)?"NODE":rZ.window&&rZ.document?"BROWSER":"REST",ai="NODE"===at,ar=o9.left;oI({target:"Array",proto:!0,forced:!ai&&nb>79&&nb<83||!o7("reduce")},{reduce:function(e){var t=arguments.length;return ar(this,e,t,t>1?arguments[1]:void 0)}});var an=oF("Array","reduce"),ao=Array.prototype,aa=function(e){var t=e.reduce;return e===ao||rJ(ao,e)&&t===ao.reduce?an:t},as=rW(aa),ac=Array.isArray||function(e){return"Array"===r4(e)},ad=rX([].reverse),al=[1,2];oI({target:"Array",proto:!0,forced:String(al)===String(al.reverse())},{reverse:function(){return ac(this)&&(this.length=this.length),ad(this)}});var ah=oF("Array","reverse"),au=Array.prototype,ap=function(e){var t=e.reverse;return e===au||rJ(au,e)&&t===au.reverse?ah:t},a_=rW(ap),aE=nH("keys"),am=function(e){return aE[e]||(aE[e]=nZ(e))},af=!rH(function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}),aS=am("IE_PROTO"),ag=Object,aT=ag.prototype,aR=af?ag.getPrototypeOf:function(e){var t=nY(e);if(nq(t,aS))return t[aS];var i=t.constructor;return r9(i)&&t instanceof i?i.prototype:t instanceof ag?aT:null},aC=String,av=TypeError,ay=function(e,t,i){try{return rX(nU(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(e){}},aI=function(e){if(nm(e)||null===e)return e;throw new av("Can't set "+aC(e)+" as a prototype")},aA=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=ay(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(e){}return function(i,r){return n_(i),aI(r),nm(i)&&(t?e(i,r):i.__proto__=r),i}}():void 0),ab={},aO={},aw=ox.indexOf,aN=rX([].push),aD=function(e,t){var i,r=nE(e),n=0,o=[];for(i in r)!nq(aO,i)&&nq(r,i)&&aN(o,i);for(;t.length>n;)nq(r,i=t[n++])&&(~aw(o,i)||aN(o,i));return o},aP=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],aL=aP.concat("length","prototype");ab.f=Object.getOwnPropertyNames||function(e){return aD(e,aL)};var ak={};ak.f=Object.getOwnPropertySymbols;var aM=rX([].concat),aU=ng("Reflect","ownKeys")||function(e){var t=ab.f(oE(e)),i=ak.f;return i?aM(t,i(e)):t},ax={},aV=Object.keys||function(e){return aD(e,aP)};ax.f=ne&&!ou?Object.defineProperties:function(e,t){oE(e);for(var i,r=nE(t),n=aV(t),o=n.length,a=0;o>a;)oh.f(e,i=n[a++],r[i]);return e};var aF,aB=ng("document","documentElement"),aj="prototype",aG="script",aW=am("IE_PROTO"),aH=function(){},aK=function(e){return"<"+aG+">"+e+"</"+aG+">"},aY=function(e){e.write(aK("")),e.close();var t=e.parentWindow.Object;return e=null,t},az=function(){try{aF=new ActiveXObject("htmlfile")}catch(e){}az="undefined"!=typeof document?document.domain&&aF?aY(aF):(t=oe("iframe"),i="java"+aG+":",t.style.display="none",aB.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(aK("document.F=Object")),e.close(),e.F):aY(aF);for(var e,t,i,r=aP.length;r--;)delete az[aj][aP[r]];return az()};aO[aW]=!0;var aq=Object.create||function(e,t){var i;return null!==e?(aH[aj]=oE(e),i=new aH,aH[aj]=null,i[aW]=e):i=az(),void 0===t?i:ax.f(i,t)},aX=Error,aJ=rX("".replace),aQ=String(new aX("zxcasd").stack),aZ=/\n\s*at [^:]*:[^\n]*/,a$=aZ.test(aQ),a0=!rH(function(){var e=Error("a");return!("stack"in e)||(Object.defineProperty(e,"stack",nc(1,7)),7!==e.stack)}),a1=function(e,t){if(a$&&"string"==typeof e&&!aX.prepareStackTrace)for(;t--;)e=aJ(e,aZ,"");return e},a2=Error.captureStackTrace,a3={},a5=n2("iterator"),a4=Array.prototype,a6=function(e){return void 0!==e&&(a3.Array===e||a4[a5]===e)},a8=n2("iterator"),a9=function(e){if(!nu(e))return nx(e,a8)||nx(e,"@@iterator")||a3[oX(e)]},a7=TypeError,se=function(e,t){var i=arguments.length<2?a9(e):t;if(nU(i))return oE(ni(i,e));throw new a7(nk(e)+" is not iterable")},st=function(e,t,i){var r,n;oE(e);
1try{if(!(r=nx(e,"return"))){if("throw"===t)throw i;return i}r=ni(r,e)}catch(e){n=!0,r=e}if("throw"===t)throw i;if(n)throw r;return oE(r),i},si=TypeError,sr=function(e,t){this.stopped=e,this.result=t},sn=sr.prototype,so=function(e,t,i){var r,n,o,a,s,c,d,l=i&&i.that,h=!(!i||!i.AS_ENTRIES),u=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),_=!(!i||!i.INTERRUPTED),E=ol(t,l),m=function(e){return r&&st(r,"normal"),new sr(!0,e)},f=function(e){return h?(oE(e),_?E(e[0],e[1],m):E(e[0],e[1])):_?E(e,m):E(e)};if(u)r=e.iterator;else if(p)r=e;else{if(!(n=a9(e)))throw new si(nk(e)+" is not iterable");if(a6(n)){for(o=0,a=oM(e);a>o;o++)if((s=f(e[o]))&&rJ(sn,s))return s;return new sr(!1)}r=se(e,n)}for(c=u?e.next:r.next;!(d=ni(c,r)).done;){try{s=f(d.value)}catch(e){st(r,"throw",e)}if("object"==typeof s&&s&&rJ(sn,s))return s}return new sr(!1)},sa=function(e,t){nm(t)&&"cause"in t&&oC(e,"cause",t.cause)},ss=function(e,t,i,r){a0&&(a2?a2(e,t):oC(e,"stack",a1(i,r)))},sc=n2("toStringTag"),sd=Error,sl=[].push,sh=function(e,t){var i,r=rJ(su,this);aA?i=aA(new sd,r?aR(this):su):oC(i=r?this:aq(su),sc,"Error"),void 0!==t&&oC(i,"message",function(e,t){return void 0===e?arguments.length<2?"":t:oQ(e)}(t)),ss(i,sh,i.stack,1),arguments.length>2&&sa(i,arguments[2]);var n=[];return so(e,sl,{that:n}),oC(i,"errors",n),i};aA?aA(sh,sd):function(e,t,i){for(var r=aU(t),n=oh.f,o=r7.f,a=0;a<r.length;a++){var s=r[a];nq(e,s)||i&&nq(i,s)||n(e,s,o(t,s))}}(sh,sd,{name:!0});var su=sh.prototype=aq(sd.prototype,{constructor:nc(1,sh),message:nc(1,""),name:nc(1,"AggregateError")});oI({global:!0,constructor:!0,arity:2},{AggregateError:sh});var sp,s_,sE,sm=rZ.WeakMap,sf=r9(sm)&&/native code/.test(String(sm)),sS="Object already initialized",sg=rZ.TypeError,sT=rZ.WeakMap;if(sf||nW.state){var sR=nW.state||(nW.state=new sT);sR.get=sR.get,sR.has=sR.has,sR.set=sR.set,sp=function(e,t){if(sR.has(e))throw new sg(sS);return t.facade=e,sR.set(e,t),t},s_=function(e){return sR.get(e)||{}},sE=function(e){return sR.has(e)}}else{var sC=am("state");aO[sC]=!0,sp=function(e,t){if(nq(e,sC))throw new sg(sS);return t.facade=e,oC(e,sC,t),t},s_=function(e){return nq(e,sC)?e[sC]:{}},sE=function(e){return nq(e,sC)}}var sv,sy,sI,sA=sp,sb=function(e){return function(t){var i;if(!nm(t)||(i=s_(t)).type!==e)throw new sg("Incompatible receiver, "+e+" required");return i}},sO=Function.prototype,sw=ne&&Object.getOwnPropertyDescriptor,sN=nq(sO,"name"),sD={EXISTS:sN,PROPER:sN&&"something"===(function(){}).name,CONFIGURABLE:sN&&(!ne||ne&&sw(sO,"name").configurable)},sP=function(e,t,i,r){return r&&r.enumerable?e[t]=i:oC(e,t,i),e},sL=n2("iterator"),sk=!1;[].keys&&("next"in(sI=[].keys())?(sy=aR(aR(sI)))!==Object.prototype&&(sv=sy):sk=!0),r9((sv=!nm(sv)||rH(function(){var e={};return sv[sL].call(e)!==e})?{}:aq(sv))[sL])||sP(sv,sL,function(){return this});var sM=sv,sU=sk,sx=oh.f,sV=oK?({}).toString:function(){return"[object "+oX(this)+"]"},sF=n2("toStringTag"),sB=function(e,t,i,r){var n=i?e:e&&e.prototype;n&&(nq(n,sF)||sx(n,sF,{configurable:!0,value:t}),r&&!oK&&oC(n,"toString",sV))},sj=function(){return this},sG=function(e,t,i,r){var n=t+" Iterator";return e.prototype=aq(sM,{next:nc(+!r,i)}),sB(e,n,!1,!0),a3[n]=sj,e},sW=sD.PROPER,sH=sU,sK=n2("iterator"),sY="keys",sz="values",sq="entries",sX=function(){return this},sJ=function(e,t,i,r,n,o,a){sG(i,t,r);var s,c,d,l=function(e){if(e===n&&E)return E;if(!sH&&e&&e in p)return p[e];switch(e){case sY:case sz:case sq:return function(){return new i(this,e)}}return function(){return new i(this)}},h=t+" Iterator",u=!1,p=e.prototype,_=p[sK]||p["@@iterator"]||n&&p[n],E=!sH&&_||l(n),m="Array"===t&&p.entries||_;if(m&&(s=aR(m.call(new e)))!==Object.prototype&&s.next&&(sB(s,h,!0,!0),a3[h]=sX),sW&&n===sz&&_&&_.name!==sz&&(u=!0,E=function(){return ni(_,this)}),n)if(c={values:l(sz),keys:o?E:l(sY),entries:l(sq)},a)for(d in c)!sH&&!u&&d in p||sP(p,d,c[d]);else oI({target:t,proto:!0,forced:sH||u},c);return a&&p[sK]!==E&&sP(p,sK,E,{name:n}),a3[t]=E,c},sQ=function(e,t){return{value:e,done:t}};oh.f;var sZ="Array Iterator",s$=sb(sZ);sJ(Array,"Array",function(e,t){sA(this,{type:sZ,target:nE(e),index:0,kind:t})},function(){var e=s$(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,sQ(void 0,!0);switch(e.kind){case"keys":return sQ(i,!1);case"values":return sQ(t[i],!1)}return sQ([i,t[i]],!1)},"values"),a3.Arguments=a3.Array;var s0=function(e,t,i){return oh.f(e,t,i)},s1=n2("species"),s2=TypeError,s3=function(e,t){if(rJ(t,e))return e;throw new s2("Incorrect invocation")},s5=rX(Function.toString);r9(nW.inspectSource)||(nW.inspectSource=function(e){return s5(e)});var s4=nW.inspectSource,s6=function(){},s8=ng("Reflect","construct"),s9=/^\s*(?:class|function)\b/,s7=rX(s9.exec),ce=!s9.test(s6),ct=function(e){if(!r9(e))return!1;try{return s8(s6,[],e),!0}catch(e){return!1}},ci=function(e){if(!r9(e))return!1;switch(oX(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return ce||!!s7(s9,s4(e))}catch(e){return!0}};ci.sham=!0;
vendor: 4,899 bytes, line 1
1var cr,cn,co,ca,cs=!s8||rH(function(){var e;return ct(ct.call)||!ct(Object)||!ct(function(){e=!0})||e})?ci:ct,cc=TypeError,cd=function(e){if(cs(e))return e;throw new cc(nk(e)+" is not a constructor")},cl=n2("species"),ch=function(e,t){var i,r=oE(e).constructor;return void 0===r||nu(i=oE(r)[cl])?t:cd(i)},cu=rX([].slice),cp=TypeError,c_=function(e,t){if(e<t)throw new cp("Not enough arguments");return e},cE=/(?:ipad|iphone|ipod).*applewebkit/i.test(nC),cm=rZ.setImmediate,cf=rZ.clearImmediate,cS=rZ.process,cg=rZ.Dispatch,cT=rZ.Function,cR=rZ.MessageChannel,cC=rZ.String,cv=0,cy={},cI="onreadystatechange";rH(function(){cr=rZ.location});var cA=function(e){if(nq(cy,e)){var t=cy[e];delete cy[e],t()}},cb=function(e){return function(){cA(e)}},cO=function(e){cA(e.data)},cw=function(e){rZ.postMessage(cC(e),cr.protocol+"//"+cr.host)};cm&&cf||(cm=function(e){c_(arguments.length,1);var t=r9(e)?e:cT(e),i=cu(arguments,1);return cy[++cv]=function(){r2(t,void 0,i)},cn(cv),cv},cf=function(e){delete cy[e]},ai?cn=function(e){cS.nextTick(cb(e))}:cg&&cg.now?cn=function(e){cg.now(cb(e))}:cR&&!cE?(ca=(co=new cR).port2,co.port1.onmessage=cO,cn=ol(ca.postMessage,ca)):rZ.addEventListener&&r9(rZ.postMessage)&&!rZ.importScripts&&cr&&"file:"!==cr.protocol&&!rH(cw)?(cn=cw,rZ.addEventListener("message",cO,!1)):cn=cI in oe("script")?function(e){aB.appendChild(oe("script"))[cI]=function(){aB.removeChild(this),cA(e)}}:function(e){setTimeout(cb(e),0)});var cN=cm,cD=cf,cP=Object.getOwnPropertyDescriptor,cL=function(e){if(!ne)return rZ[e];var t=cP(rZ,e);return t&&t.value},ck=function(){this.head=null,this.tail=null};ck.prototype={add:function(e){var t={item:e,next:null},i=this.tail;i?i.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item}};var cM,cU,cx,cV,cF,cB=/ipad|iphone|ipod/i.test(nC)&&"undefined"!=typeof Pebble,cj=/web0s(?!.*chrome)/i.test(nC),cG=cN,cW=rZ.MutationObserver||rZ.WebKitMutationObserver,cH=rZ.document,cK=rZ.process,cY=rZ.Promise,cz=cL("queueMicrotask");if(!cz){var cq=new ck,cX=function(){var e,t;for(ai&&(e=cK.domain)&&e.exit();t=cq.get();)try{t()}catch(e){throw cq.head&&cM(),e}e&&e.enter()};cE||ai||cj||!cW||!cH?!cB&&cY&&cY.resolve?((cV=cY.resolve(void 0)).constructor=cY,cF=ol(cV.then,cV),cM=function(){cF(cX)}):ai?cM=function(){cK.nextTick(cX)}:(cG=ol(cG,rZ),cM=function(){cG(cX)}):(cU=!0,cx=cH.createTextNode(""),new cW(cX).observe(cx,{characterData:!0}),cM=function(){cx.data=cU=!cU}),cz=function(e){cq.head||cM(),cq.add(e)}}var cJ=cz,cQ=function(e){try{return{error:!1,value:e()}}catch(e){return{error:!0,value:e}}},cZ=rZ.Promise,c$=cZ&&cZ.prototype,c0=n2("species"),c1=!1,c2=r9(rZ.PromiseRejectionEvent),c3={CONSTRUCTOR:on("Promise",function(){var e=s4(cZ),t=e!==String(cZ);if(!t&&66===nb||!c$.catch||!c$.finally)return!0;if(!nb||nb<51||!/native code/.test(e)){var i=new cZ(function(e){e(1)}),r=function(e){e(function(){},function(){})};if((i.constructor={})[c0]=r,!(c1=i.then(function(){})instanceof r))return!0}return!(t||"BROWSER"!==at&&"DENO"!==at||c2)}),REJECTION_EVENT:c2,SUBCLASSING:c1},c5={},c4=TypeError,c6=function(e){var t,i;this.promise=new e(function(e,r){if(void 0!==t||void 0!==i)throw new c4("Bad Promise constructor");t=e,i=r}),this.resolve=nU(t),this.reject=nU(i)};c5.f=function(e){return new c6(e)};var c8,c9,c7,de=function(e,t){try{1==arguments.length?console.error(e):console.error(e,t)}catch(e){}},dt="Promise",di=c3.CONSTRUCTOR,dr=c3.REJECTION_EVENT,dn=sb(dt),da=cZ&&cZ.prototype,ds=cZ,dc=da,dd=rZ.TypeError,dl=rZ.document,dh=rZ.process,du=c5.f,dp=du,d_=!!(dl&&dl.createEvent&&rZ.dispatchEvent),dE="unhandledrejection",dm=function(e){var t;return!(!nm(e)||!r9(t=e.then))&&t},df=function(e,t){var i,r,n,o=t.value,a=1===t.state,s=a?e.ok:e.fail,c=e.resolve,d=e.reject,l=e.domain;try{s?(a||(2===t.rejection&&dC(t),t.rejection=1),!0===s?i=o:(l&&l.enter(),i=s(o),l&&(l.exit(),n=!0)),i===e.promise?d(new dd("Promise-chain cycle")):(r=dm(i))?ni(r,i,c,d):c(i)):d(o)}catch(e){l&&!n&&l.exit(),d(e)}},dS=function(e,t){e.notified||(e.notified=!0,cJ(function(){for(var i,r=e.reactions;i=r.get();)df(i,e);e.notified=!1,t&&!e.rejection&&dT(e)}))},dg=function(e,t,i){var r,n;d_?((r=dl.createEvent("Event")).promise=t,r.reason=i,r.initEvent(e,!1,!0),rZ.dispatchEvent(r)):r={promise:t,reason:i},!dr&&(n=rZ["on"+e])?n(r):e===dE&&de("Unhandled promise rejection",i)},dT=function(e){ni(cN,rZ,function(){var t,i=e.facade,r=e.value;if(dR(e)&&(t=cQ(function(){ai?dh.emit("unhandledRejection",r,i):dg(dE,i,r)}),e.rejection=ai||dR(e)?2:1,t.error))throw t.value})},dR=function(e){return 1!==e.rejection&&!e.parent},dC=function(e){ni(cN,rZ,function(){var t=e.facade;ai?dh.emit("rejectionHandled",t):dg("rejectionhandled",t,e.value)})},dv=function(e,t,i){return function(r){e(t,r,i)}},dy=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,dS(e,!0))},dI=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);
1try{if(e.facade===t)throw new dd("Promise can't be resolved itself");var r=dm(t);r?cJ(function(){var i={done:!1};try{ni(r,t,dv(dI,i,e),dv(dy,i,e))}catch(t){dy(i,t,e)}}):(e.value=t,e.state=1,dS(e,!1))}catch(t){dy({done:!1},t,e)}}};di&&(dc=(ds=function(e){s3(this,dc),nU(e),ni(c8,this);var t=dn(this);try{e(dv(dI,t),dv(dy,t))}catch(e){dy(t,e)}}).prototype,(c8=function(e){sA(this,{type:dt,done:!1,notified:!1,parent:!1,reactions:new ck,rejection:!1,state:0,value:null})}).prototype=sP(dc,"then",function(e,t){var i=dn(this),r=du(ch(this,ds));return i.parent=!0,r.ok=!r9(e)||e,r.fail=r9(t)&&t,r.domain=ai?dh.domain:void 0,0===i.state?i.reactions.add(r):cJ(function(){df(r,i)}),r.promise}),c9=function(){var e=new c8,t=dn(e);this.promise=e,this.resolve=dv(dI,t),this.reject=dv(dy,t)},c5.f=du=function(e){return e===ds||e===c7?new c9(e):dp(e)}),oI({global:!0,constructor:!0,wrap:!0,forced:di},{Promise:ds}),c7=nf.Promise,sB(ds,dt,!1,!0),l6=ng(dt),ne&&l6&&!l6[s1]&&s0(l6,s1,{configurable:!0,get:function(){return this}});var dA=n2("iterator"),db=!1;try{var dO=0,dw={next:function(){return{done:!!dO++}},return:function(){db=!0}};dw[dA]=function(){return this},Array.from(dw,function(){throw 2})}catch(e){}var dN=c3.CONSTRUCTOR||!function(e,t){try{if(!db)return!1}catch(e){return!1}var i=!1;try{var r={};r[dA]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch(e){}return i}(function(e){cZ.all(e).then(void 0,function(){})});oI({target:"Promise",stat:!0,forced:dN},{all:function(e){var t=this,i=c5.f(t),r=i.resolve,n=i.reject,o=cQ(function(){var i=nU(t.resolve),o=[],a=0,s=1;so(e,function(e){var c=a++,d=!1;s++,ni(i,t,e).then(function(e){d||(d=!0,o[c]=e,--s||r(o))},n)}),--s||r(o)});return o.error&&n(o.value),i.promise}});var dD=c3.CONSTRUCTOR;cZ&&cZ.prototype,oI({target:"Promise",proto:!0,forced:dD,real:!0},{catch:function(e){return this.then(void 0,e)}}),oI({target:"Promise",stat:!0,forced:dN},{race:function(e){var t=this,i=c5.f(t),r=i.reject,n=cQ(function(){var n=nU(t.resolve);so(e,function(e){ni(n,t,e).then(i.resolve,r)})});return n.error&&r(n.value),i.promise}}),oI({target:"Promise",stat:!0,forced:c3.CONSTRUCTOR},{reject:function(e){var t=c5.f(this);return(0,t.reject)(e),t.promise}});var dP=function(e,t){if(oE(e),nm(t)&&t.constructor===e)return t;var i=c5.f(e);return(0,i.resolve)(t),i.promise},dL=c3.CONSTRUCTOR,dk=ng("Promise"),dM=!dL;oI({target:"Promise",stat:!0,forced:!0},{resolve:function(e){return dP(dM&&this===dk?cZ:this,e)}}),oI({target:"Promise",stat:!0,forced:dN},{allSettled:function(e){var t=this,i=c5.f(t),r=i.resolve,n=i.reject,o=cQ(function(){var i=nU(t.resolve),n=[],o=0,a=1;so(e,function(e){var s=o++,c=!1;a++,ni(i,t,e).then(function(e){c||(c=!0,n[s]={status:"fulfilled",value:e},--a||r(n))},function(e){c||(c=!0,n[s]={status:"rejected",reason:e},--a||r(n))})}),--a||r(n)});return o.error&&n(o.value),i.promise}});var dU="No one promise resolved";oI({target:"Promise",stat:!0,forced:dN},{any:function(e){var t=this,i=ng("AggregateError"),r=c5.f(t),n=r.resolve,o=r.reject,a=cQ(function(){var r=nU(t.resolve),a=[],s=0,c=1,d=!1;so(e,function(e){var l=s++,h=!1;c++,ni(r,t,e).then(function(e){h||d||(d=!0,n(e))},function(e){h||d||(h=!0,a[l]=e,--c||o(new i(a,dU)))})}),--c||o(new i(a,dU))});return a.error&&o(a.value),r.promise}});var dx=rZ.Promise,dV=!1;oI({target:"Promise",stat:!0,forced:!dx||!dx.try||cQ(function(){dx.try(function(e){dV=8===e},8)}).error||!dV},{try:function(e){var t=arguments.length>1?cu(arguments,1):[],i=c5.f(this),r=cQ(function(){return r2(nU(e),void 0,t)});return(r.error?i.reject:i.resolve)(r.value),i.promise}}),oI({target:"Promise",stat:!0},{withResolvers:function(){var e=c5.f(this);return{promise:e.promise,resolve:e.resolve,reject:e.reject}}});var dF=cZ&&cZ.prototype;oI({target:"Promise",proto:!0,real:!0,forced:!!cZ&&rH(function(){dF.finally.call({then:function(){}},function(){})})},{finally:function(e){var t=ch(this,ng("Promise")),i=r9(e);return this.then(i?function(i){return dP(t,e()).then(function(){return i})}:e,i?function(i){return dP(t,e()).then(function(){throw i})}:e)}});var dB=rX("".charAt),dj=rX("".charCodeAt),dG=rX("".slice),dW=function(e){return function(t,i){var r,n,o=oQ(n_(t)),a=ow(i),s=o.length;return a<0||a>=s?e?"":void 0:(r=dj(o,a))<55296||r>56319||a+1===s||(n=dj(o,a+1))<56320||n>57343?e?dB(o,a):r:e?dG(o,a,a+2):n-56320+(r-55296<<10)+65536}},dH={codeAt:dW(!1),charAt:dW(!0)},dK=dH.charAt,dY="String Iterator",dz=sb(dY);sJ(String,"String",function(e){sA(this,{type:dY,string:oQ(e),index:0})},function(){var e,t=dz(this),i=t.string,r=t.index;return r>
1=i.length?sQ(void 0,!0):(e=dK(i,r),t.index+=e.length,sQ(e,!1))});var dq=nf.Promise,dX={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};for(var dJ in dX)sB(rZ[dJ],dJ),a3[dJ]=a3.Array;var dQ=rW(dq),dZ=oF("Array","values"),d$=Array.prototype,d0={DOMTokenList:!0,NodeList:!0},d1=rW(function(e){var t=e.values;return e===d$||rJ(d$,e)&&t===d$.values||nq(d0,oX(e))?dZ:t}),d2=TypeError,d3=Math.floor,d5=function(e,t){var i=e.length;if(i<8)for(var r,n,o=1;o<i;){for(n=o,r=e[o];n&&t(e[n-1],r)>0;)e[n]=e[--n];n!==o++&&(e[n]=r)}else for(var a=d3(i/2),s=d5(cu(e,0,a),t),c=d5(cu(e,a),t),d=s.length,l=c.length,h=0,u=0;h<d||u<l;)e[h+u]=h<d&&u<l?0>=t(s[h],c[u])?s[h++]:c[u++]:h<d?s[h++]:c[u++];return e},d4=nC.match(/firefox\/(\d+)/i),d6=!!d4&&+d4[1],d8=/MSIE|Trident/.test(nC),d9=nC.match(/AppleWebKit\/(\d+)\./),d7=!!d9&&+d9[1],le=function(e,t){if(!delete e[t])throw new d2("Cannot delete property "+nk(t)+" of "+nk(e))},lt=[],li=rX(lt.sort),lr=rX(lt.push),ln=rH(function(){lt.sort(void 0)}),lo=rH(function(){lt.sort(null)}),la=o7("sort"),ls=!rH(function(){if(nb)return nb<70;if(!(d6&&d6>3)){if(d8)return!0;if(d7)return d7<603;var e,t,i,r,n="";for(e=65;e<76;
1e++){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++)lt.push({k:t+r,v:i})}for(lt.sort(function(e,t){return t.v-e.v}),r=0;r<lt.length;r++)t=lt[r].k.charAt(0),n.charAt(n.length-1)!==t&&(n+=t);return"DGBEFHACIJK"!==n}});oI({target:"Array",proto:!0,forced:ln||!lo||!la||!ls},{sort:function(e){void 0!==e&&nU(e);var t=nY(this);if(ls)return void 0===e?li(t):li(t,e);var i,r,n=[],o=oM(t);for(r=0;r<o;r++)r in t&&lr(n,t[r]);for(d5(n,function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:oQ(t)>oQ(i)?1:-1}),i=oM(n),r=0;r<i;)t[r]=n[r++];for(;r<o;)le(t,r++);return t}});var lc=oF("Array","sort"),ld=Array.prototype,ll=rW(function(e){var t=e.sort;return e===ld||rJ(ld,e)&&t===ld.sort?lc:t}),lh=RangeError,lu=String.fromCharCode,lp=String.fromCodePoint,l_=rX([].join);oI({target:"String",stat:!0,arity:1,forced:!!lp&&1!==lp.length},{fromCodePoint:function(e){for(var t,i=[],r=arguments.length,n=0;r>n;){if(t=+arguments[n++],oP(t,1114111)!==t)throw new lh(t+" is not a valid code point");i[n]=t<65536?lu(t):lu(55296+((t-=65536)>>10),t%1024+56320)}return l_(i,"")}});var lE=n2("iterator"),lm=!rH(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(e,i){t.delete("b"),r+=i+e}),i.delete("a",2),i.delete("b",void 0),!e.toJSON||!i.has("a",1)||i.has("a",2)||!i.has("a",void 0)||i.has("b")||!t.size||!t.sort||"https://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[lE]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("https://ÑеÑÑ").host||"#%D0%B1"!==new URL("https://a#б").hash||"a1c3"!==r||"x"!==new URL("https://x",void 0).host}),lf=n2("iterator"),lS="URLSearchParams",lg=lS+"Iterator",lT=sA,lR=sb(lS),lC=sb(lg),lv=cL("fetch"),ly=cL("Request"),lI=cL("Headers"),lA=ly&&ly.prototype,lb=lI&&lI.prototype,lO=rZ.TypeError,lw=rZ.encodeURIComponent,lN=String.fromCharCode,lD=ng("String","fromCodePoint"),lP=parseInt,lL=rX("".charAt),lk=rX([].join),lM=rX([].push),lU=rX("".replace),lx=rX([].shift),lV=rX([].splice),lF=rX("".split),lB=rX("".slice),lj=rX(/./.exec),lG=/\+/g,lW=/^[0-9a-f]+$/i,lH=function(e,t){var i=lB(e,t,t+2);return lj(lW,i)?lP(i,16):NaN},lK=function(e){for(var t=0,i=128;i>0&&0!=(e&i);i>>=1)t++;return t},lY=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},lz=function(e){for(var t=(e=lU(e,lG," ")).length,i="",r=0;r<t;){var n=lL(e,r);if("%"===n){if("%"===lL(e,r+1)||r+3>t){i+="%",r++;continue}var o=lH(e,r+1);if(o!=o){i+=n,r++;continue}r+=2;var a=lK(o);if(0===a)n=lN(o);else{if(1===a||a>4){i+="�",r++;continue}for(var s=[o],c=1;c<a&&!(++r+3>t||"%"!==lL(e,r));){var d=lH(e,r+1);if(d!=d){r+=3;break}if(d>191||d<128)break;lM(s,d),r+=2,c++}if(s.length!==a){i+="�";continue}var l=lY(s);null===l?i+="�":n=lD(l)}}i+=n,r++}return i},lq=/[!'()~]|%20/g,lX={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},lJ=function(e){return lX[e]},lQ=function(e){return lU(lw(e),lq,lJ)},lZ=sG(function(e,t){lT(this,{type:lg,target:lR(e).entries,index:0,kind:t})},lS,function(){var e=lC(this),t=e.target,i=e.index++;if(!t||i>=t.length)return e.target=null,sQ(void 0,!0);var r=t[i];switch(e.kind){case"keys":return sQ(r.key,!1);case"values":return sQ(r.value,!1)}return sQ([r.key,r.value],!1)},!0),l$=function(e){this.entries=[],this.url=null,void 0!==e&&(nm(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===lL(e,0)?lB(e,1):e:oQ(e)))};l$.prototype={type:lS,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,i,r,n,o,a,s,c=this.entries,d=a9(e);if(d)for(i=(t=se(e,d)).next;!(r=ni(i,t)).done;){if((a=ni(o=(n=se(oE(r.value))).next,n)).done||(s=ni(o,n)).done||!ni(o,n).done)throw new lO("Expected sequence with length 2");lM(c,{key:oQ(a.value),value:oQ(s.value)})}else for(var l in e)nq(e,l)&&lM(c,{key:l,value:oQ(e[l])})},parseQuery:function(e){if(e)for(var t,i,r=this.entries,n=lF(e,"&"),o=0;o<n.length;)(t=n[o++]).length&&lM(r,{key:lz(lx(i=lF(t,"="))),value:lz(lk(i,"="))})},serialize:function(){for(var e,t=this.entries,i=[],r=0;r<t.length;)lM(i,lQ((e=t[r++]).key)+"="+lQ(e.value));return lk(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)}
1,updateURL:function(){this.url&&this.url.update()}};var l0=function(){s3(this,l1);var e=lT(this,new l$(arguments.length>0?arguments[0]:void 0));ne||(this.size=e.entries.length)},l1=l0.prototype;if(function(e,t,i){for(var r in t)i&&i.unsafe&&e[r]?e[r]=t[r]:sP(e,r,t[r],i)}(l1,{append:function(e,t){var i=lR(this);c_(arguments.length,2),lM(i.entries,{key:oQ(e),value:oQ(t)}),ne||this.length++,i.updateURL()},delete:function(e){for(var t=lR(this),i=c_(arguments.length,1),r=t.entries,n=oQ(e),o=i<2?void 0:arguments[1],a=void 0===o?o:oQ(o),s=0;s<r.length;){var c=r[s];if(c.key!==n||void 0!==a&&c.value!==a)s++;else if(lV(r,s,1),void 0!==a)break}ne||(this.size=r.length),t.updateURL()},get:function(e){var t=lR(this).entries;c_(arguments.length,1);for(var i=oQ(e),r=0;r<t.length;r++)if(t[r].key===i)return t[r].value;return null},getAll:function(e){var t=lR(this).entries;c_(arguments.length,1);for(var i=oQ(e),r=[],n=0;n<t.length;n++)t[n].key===i&&lM(r,t[n].value);return r},has:function(e){for(var t=lR(this).entries,i=c_(arguments.length,1),r=oQ(e),n=i<2?void 0:arguments[1],o=void 0===n?n:oQ(n),a=0;a<t.length;){var s=t[a++];if(s.key===r&&(void 0===o||s.value===o))return!0}return!1},set:function(e,t){var i=lR(this);c_(arguments.length,1);for(var r,n=i.entries,o=!1,a=oQ(e),s=oQ(t),c=0;c<n.length;c++)(r=n[c]).key===a&&(o?lV(n,c--,1):(o=!0,r.value=s));o||lM(n,{key:a,value:s}),ne||(this.size=n.length),i.updateURL()},sort:function(){var e=lR(this);d5(e.entries,function(e,t){return e.key>t.key?1:-1}),e.updateURL()},forEach:function(e){for(var t,i=lR(this).entries,r=ol(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 lZ(this,"keys")},values:function(){return new lZ(this,"values")},entries:function(){return new lZ(this,"entries")}},{enumerable:!0}),sP(l1,lf,l1.entries,{name:"entries"}),sP(l1,"toString",function(){return lR(this).serialize()},{enumerable:!0}),ne&&s0(l1,"size",{get:function(){return lR(this).entries.length},configurable:!0,enumerable:!0}),sB(l0,lS),oI({global:!0,constructor:!0,forced:!lm},{URLSearchParams:l0}),!lm&&r9(lI)){var l2=rX(lb.has),l3=rX(lb.set),l5=function(e){if(nm(e)){var t,i=e.body;if(oX(i)===lS)return l2(t=e.headers?new lI(e.headers):new lI,"content-type")||l3(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),aq(e,{body:nc(0,oQ(i)),headers:nc(0,t)})}return e};if(r9(lv)&&oI({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return lv(e,arguments.length>1?l5(arguments[1]):{})}}),r9(ly)){var l4=function(e){return s3(this,lA),new ly(e,arguments.length>1?l5(arguments[1]):{})};lA.constructor=l4,l4.prototype=lA,oI({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:l4})}}var l6,l8,l9=nf.URLSearchParams,l7=Object.assign,he=Object.defineProperty,ht=rX([].concat),hi=!l7||rH(function(){if(ne&&1!==l7({b:1},l7(he({},"a",{enumerable:!0,get:function(){he(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},i=Symbol("assign detection"),r="abcdefghijklmnopqrst";return e[i]=7,r.split("").forEach(function(e){t[e]=e}),7!==l7({},e)[i]||aV(l7({},t)).join("")!==r})?function(e,t){for(var i=nY(e),r=arguments.length,n=1,o=ak.f,a=nr.f;r>n;)for(var s,c=nh(arguments[n++]),d=o?ht(aV(c),o(c)):aV(c),l=d.length,h=0;l>h;)s=d[h++],ne&&!ni(a,c,s)||(i[s]=c[s]);return i}:l7,hr=function(e,t,i){ne?oh.f(e,t,nc(0,i)):e[t]=i},hn=function(e,t,i,r){try{return r?t(oE(i)[0],i[1]):t(i)}catch(t){st(e,"throw",t)}},ho=Array,ha=/[^\0-\u007E]/,hs=/[.\u3002\uFF0E\uFF61]/g,hc="Overflow: input needs wider integers to process",hd=RangeError,hl=rX(hs.exec),hh=Math.floor,hu=String.fromCharCode,hp=rX("".charCodeAt),h_=rX([].join),hE=rX([].push),hm=rX("".replace),hf=rX("".split),hS=rX("".toLowerCase),hg=function(e){return e+22+75*(e<26)},hT=function(e,t,i){var r=0;for(e=i?hh(e/700):e>>1,e+=hh(e/t);e>455;)e=hh(e/35),r+=36;return hh(r+36*e/(e+38))},hR=function(e){var t,i,r=[],n=(e=function(e){for(var t=[],i=0,r=e.length;i<r;){var n=hp(e,i++);if(n>=55296&&n<=56319&&i<r){var o=hp(e,i++);56320==(64512&o)?hE(t,((1023&n)<<10)+(1023&o)+65536):(hE(t,n),i--)}else hE(t,n)}return t}(e)).length,o=128,a=0,s=72;for(t=0;t<e.length;t++)(i=e[t])<128&&hE(r,hu(i));var c=r.length,d=c;for(c&&hE(r,"-");d<n;){var l=0x7fffffff;for(t=0;t<e.length;t++)(i=e[t])>=o&&i<l&&(l=i);var h=d+1;if(l-o>hh((0x7fffffff-a)/h))throw new hd(hc);for(a+=(l-o)*h,o=l,t=0;t<e.length;t++){if((i=e[t])<o&&++a>0x7fffffff)throw new hd(hc);if(i===o){for(var u=a,p=36;;){var _=p<=s?1:p>=s+26?26:p-s;if(u<_)break;var E=u-_,m=36-_;hE(r,hu(hg(_+E%m))),u=hh(E/m),p+=36}hE(r,hu(hg(u))),s=hT(a,h,d===c),a=0,d++}}a++,o++}return h_(r,"")},hC=function(e){var t=nY(e),i=cs(this),r=arguments.length,n=r>1?arguments[1]:void 0,o=void 0!==n;o&&(n=ol(n,r>2?arguments[2]:void 0));var a,s,c,d,l,h,u=a9(t),p=0;if(!u||this===ho&&a6(u))for(a=oM(t),s=i?new this(a):ho(a);a>p;p++)h=o?n(t[p],p):t[p],hr(s,p,h);else for(s=i?new this:[],l=(d=se(t,u)).next;!(c=ni(l,d)).done;p++)h=o?hn(d,n,[c.value,p],!0):c.value,hr(s,p,h);return s.length=p,s},hv=dH.codeAt,hy=function(e){var t,i,r=[],n=hf(hm(hS(e),hs,"."),".");for(t=0;t<n.length;t++)hE(r,hl(ha,i=n[t])?"xn--"+hR(i):i);return h_(r,".")},hI=sb("URL"),hA=rZ.URL,hb=rZ.TypeError,hO=rZ.parseInt,hw=Math.floor,hN=Math.pow,hD=rX("".charAt),hP=rX(/./.exec),hL=rX([].join),hk=rX(1.1.toString),hM=rX([].pop),hU=rX([].push),hx=rX("".replace),hV=rX([].shift),hF=rX("".split),hB=rX("".slice),hj=rX("".toLowerCase),hG=rX([].unshift),hW="Invalid scheme",hH="Invalid host",hK="Invalid port",hY=/[a-z]/i,hz=/[\d+-.a-z]/i,hq=/\d/,hX=/^0x/i,hJ=/^[0-7]+$/,hQ=/^\d+$/,hZ=/^[\da-f]+$/i,h$=/[\0\t\n\r #%/:<>?@[\\\]^|]/,h0=/[\0\t\n\r #/:<>?@[\\\]^|]/,h1=/^[\u0000-\u0020]+/,h2=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,h3=/[\t\n\r]/g,h5=function(e){var t,i,r,n;if("number"==typeof e){for(t=[],i=0;i<4;i++)hG(t,e%256),e=hw(e/256);return hL(t,".")}if("object"==typeof e){for(t="",r=function(e){for(var t=null,i=1,r=null,n=0,o=0;o<8;o++)0!==e[o]?(n>i&&(t=r,i=n),r=null,n=0):(null===r&&(r=o),++n);return n>i?r:t}(e),i=0;i<8;i++)n&&0===e[i]||(n&&(n=!1),r===i?(t+=i?":":"::",n=!0):(t+=hk(e[i],16),i<7&&(t+=":")));return"["+t+"]"}return e},h4={},h6=hi({},h4,{" ":1,'"':1,"<":1,">":1,"`":1}),h8=hi({},h6,{"#":1,"?":1,"{":1,"}":1}),h9=hi({},h8,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),h7=function(e,t){var i=hv(e,0);return i>32&&i<127&&!nq(t,e)?e:encodeURIComponent(e)},ue={ftp:21,file:null,http:80,https:443,ws:80,wss:443},ut=function(e,t){var i;return 2===e.length&&hP(hY,hD(e,0))&&(":"===(i=hD(e,1))||!t&&"|"===i)},ui=function(e){var t;return e.length>1&&ut(hB(e,0,2))&&(2===e.length||"/"===(t=hD(e,2))||"\\"===t||"?"===t||"#"===t)},ur={},un={},uo={},ua={},us={},uc={},ud={},ul={},uh={},uu={},up={},u_={},uE={},um={},uf={},uS={},ug={},uT={},uR={},uC={},uv={},uy=function(e,t,i){var r,n,o,a=oQ(e);if(t){if(n=this.parse(a))throw new hb(n);this.searchParams=null}else{if(void 0!==i&&(r=new uy(i,!0)),n=this.parse(a,null,r))throw new hb(n);(o=lR(new l0)).bindURL(this),this.searchParams=o}};uy.prototype={type:"URL",parse:function(e,t,i){var r,n,o,a,s,c=t||ur,d=0,l="",h=!1,u=!1,p=!1;for(e=oQ(e),t||(this.scheme="",this.username="",this.password="",this.host=null,this.port=null,this.path=[],this.query=null,this.fragment=null,this.cannotBeABaseURL=!1,e=hx(e,h1,""),e=hx(e,h2,"$1")),r=hC(e=hx(e,h3,""));d<=r.length;){switch(n=r[d],c){case ur:if(!n||!hP(hY,n)){if(t)return hW;c=uo;continue}l+=hj(n),c=un;break;case un:if(n&&(hP(hz,n)||"+"===n||"-"===n||"."===n))l+=hj(n);else{if(":"!==n){if(t)return hW;l="",c=uo,d=0;continue}if(t&&(this.isSpecial()!==nq(ue,l)||"file"===l&&(this.includesCredentials()||null!==this.port)||"file"===this.scheme&&!this.host))return;if(this.scheme=l,t)return void(this.isSpecial()&&ue[this.scheme]===this.port&&(this.port=null));l="","file"===this.scheme?c=um:this.isSpecial()&&i&&i.scheme===this.scheme?c=ua:this.isSpecial()?c=ul:"/"===r[d+1]?(c=us,d++):(this.cannotBeABaseURL=!0,hU(this.path,""),c=uR)}break;case uo:if(!i||i.cannotBeABaseURL&&"#"!==n)return hW;if(i.cannotBeABaseURL&&"#"===n){this.scheme=i.scheme,this.path=cu(i.path),this.query=i.query,this.fragment="",this.cannotBeABaseURL=!0,c=uv;break}c="file"===i.scheme?um:uc;continue;case ua:if("/"!==n||"/"!==r[d+1]){c=uc;continue}c=uh,d++;break;case us:if("/"===n){c=uu;break}c=uT;continue;case uc:if(this.scheme=i.scheme,n===l8)this.username=i.username,this.password=i.password,this.host=i.host,this.port=i.port,this.path=cu(i.path),this.query=i.query;else if("/"===n||"\\"===n&&this.isSpecial())c=ud;else if("?"===n)this.username=i.username,this.password=i.password,this.host=i.host,this.port=i.port,this.path=cu(i.path),this.query="",c=uC;else{if("#"!==n){this.username=i.username,this.password=i.password,this.host=i.host,this.port=i.port,this.path=cu(i.path),this.path.length--,c=uT;continue}this.username=i.username,this.password=i.password,this.host=i.host,this.port=i.port,this.path=cu(i.path),this.query=i.query,this.fragment="",c=uv}break;case ud:if(this.isSpecial()&&("/"===n||"\\"===n))c=uh;else{if("/"!==n){this.username=i.username,this.password=i.password,this.host=i.host,this.port=i.port,c=uT;continue}c=uu}break;case ul:if(c=uh,"/"!==n||"/"!==hD(l,d+1))continue;d++;break;case uh:if("/"!==n&&"\\"!==n){c=uu;continue}break;case uu:if("@"===n){h&&(l="%40"+l),h=!0,o=hC(l);for(var _,E=0;E<o.length;E++){var m=o[E];if(":"!==m||p){var f=h7(m,h9);p?this.password+=f:this.username+=f}else p=!0}l=""}else if(n===l8||"/"===n||"?"===n||"#"===n||"\\"===n&&this.isSpecial()){if(h&&""===l)return"Invalid authority";
1d-=hC(l).length+1,l="",c=up}else l+=n;break;case up:case u_:if(t&&"file"===this.scheme){c=uS;continue}if(":"!==n||u){if(n===l8||"/"===n||"?"===n||"#"===n||"\\"===n&&this.isSpecial()){if(this.isSpecial()&&""===l)return hH;if(t&&""===l&&(this.includesCredentials()||null!==this.port))return;if(a=this.parseHost(l))return a;if(l="",c=ug,t)return;continue}"["===n?u=!0:"]"===n&&(u=!1),l+=n}else{if(""===l)return hH;if(a=this.parseHost(l))return a;if(l="",c=uE,t===u_)return}break;case uE:if(!hP(hq,n)){if(n===l8||"/"===n||"?"===n||"#"===n||"\\"===n&&this.isSpecial()||t){if(""!==l){var S=hO(l,10);if(S>65535)return hK;this.port=this.isSpecial()&&S===ue[this.scheme]?null:S,l=""}if(t)return;c=ug;continue}return hK}l+=n;break;case um:if(this.scheme="file","/"===n||"\\"===n)c=uf;else{if(!i||"file"!==i.scheme){c=uT;continue}switch(n){case l8:this.host=i.host,this.path=cu(i.path),this.query=i.query;break;case"?":this.host=i.host,this.path=cu(i.path),this.query="",c=uC;break;case"#":this.host=i.host,this.path=cu(i.path),this.query=i.query,this.fragment="",c=uv;break;default:ui(hL(cu(r,d),""))||(this.host=i.host,this.path=cu(i.path),this.shortenPath()),c=uT;continue}}break;case uf:if("/"===n||"\\"===n){c=uS;break}i&&"file"===i.scheme&&!ui(hL(cu(r,d),""))&&(ut(i.path[0],!0)?hU(this.path,i.path[0]):this.host=i.host),c=uT;continue;case uS:if(n===l8||"/"===n||"\\"===n||"?"===n||"#"===n){if(!t&&ut(l))c=uT;else if(""===l){if(this.host="",t)return;c=ug}else{if(a=this.parseHost(l))return a;if("localhost"===this.host&&(this.host=""),t)return;l="",c=ug}continue}l+=n;break;case ug:if(this.isSpecial()){if(c=uT,"/"!==n&&"\\"!==n)continue}else if(t||"?"!==n)if(t||"#"!==n){if(n!==l8&&(c=uT,"/"!==n))continue}else this.fragment="",c=uv;else this.query="",c=uC;break;case uT:if(n===l8||"/"===n||"\\"===n&&this.isSpecial()||!t&&("?"===n||"#"===n)){if(".."===(s=hj(s=l))||"%2e."===s||".%2e"===s||"%2e%2e"===s?(this.shortenPath(),"/"===n||"\\"===n&&this.isSpecial()||hU(this.path,"")):"."===(_=l)||"%2e"===hj(_)?"/"===n||"\\"===n&&this.isSpecial()||hU(this.path,""):("file"===this.scheme&&!this.path.length&&ut(l)&&(this.host&&(this.host=""),l=hD(l,0)+":"),hU(this.path,l)),l="","file"===this.scheme&&(n===l8||"?"===n||"#"===n))for(;this.path.length>1&&""===this.path[0];)hV(this.path);"?"===n?(this.query="",c=uC):"#"===n&&(this.fragment="",c=uv)}else l+=h7(n,h8);break;case uR:"?"===n?(this.query="",c=uC):"#"===n?(this.fragment="",c=uv):n!==l8&&(this.path[0]+=h7(n,h4));break;case uC:t||"#"!==n?n!==l8&&("'"===n&&this.isSpecial()?this.query+="%27":this.query+="#"===n?"%23":h7(n,h4)):(this.fragment="",c=uv);break;case uv:n!==l8&&(this.fragment+=h7(n,h6))}d++}},parseHost:function(e){var t,i,r;if("["===hD(e,0)){if("]"!==hD(e,e.length-1)||!(t=function(e){var t,i,r,n,o,a,s,c=[0,0,0,0,0,0,0,0],d=0,l=null,h=0,u=function(){return hD(e,h)};if(":"===u()){if(":"!==hD(e,1))return;h+=2,l=++d}for(;u();){if(8===d)return;if(":"!==u()){for(t=i=0;i<4&&hP(hZ,u());)t=16*t+hO(u(),16),h++,i++;if("."===u()){if(0===i||(h-=i,d>6))return;for(r=0;u();){if(n=null,r>0){if(!("."===u()&&r<4))return;h++}if(!hP(hq,u()))return;for(;hP(hq,u());){if(o=hO(u(),10),null===n)n=o;else{if(0===n)return;n=10*n+o}if(n>255)return;h++}c[d]=256*c[d]+n,2!=++r&&4!==r||d++}if(4!==r)return;break}if(":"===u()){if(h++,!u())return}else if(u())return;c[d++]=t}else{if(null!==l)return;h++,l=++d}}if(null!==l)for(a=d-l,d=7;0!==d&&a>0;)s=c[d],c[d--]=c[l+a-1],c[l+--a]=s;else if(8!==d)return;return c}(hB(e,1,-1))))return hH;this.host=t}else if(this.isSpecial()){if(hP(h$,e=hy(e))||null===(t=function(e){var t,i,r,n,o,a,s,c=hF(e,".");if(c.length&&""===c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(i=[],r=0;r<t;r++){if(""===(n=c[r]))return e;if(o=10,n.length>1&&"0"===hD(n,0)&&(o=hP(hX,n)?16:8,n=hB(n,8===o?1:2)),""===n)a=0;else{if(!hP(10===o?hQ:8===o?hJ:hZ,n))return e;a=hO(n,o)}hU(i,a)}for(r=0;r<t;r++)if(a=i[r],r===t-1){if(a>=hN(256,5-t))return null}else if(a>255)return null;for(s=hM(i),r=0;r<i.length;r++)s+=i[r]*hN(256,3-r);return s}(e)))return hH;this.host=t}else{if(hP(h0,e))return hH;for(t="",i=hC(e),r=0;r<i.length;r++)t+=h7(i[r],h4);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"===this.scheme},includesCredentials:function(){return""!==this.username||""!==this.password},isSpecial:function(){return nq(ue,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"===this.scheme&&1===t&&ut(e[0],!0)||e.length--},serialize:function(){var e=this.scheme,t=this.username,i=this.password,r=this.host,n=this.port,o=this.path,a=this.query,s=this.fragment,c=e+":";return null!==r?(c+="//",this.includesCredentials()&&(c+=t+(i?":"+i:"")+"@"),c+=h5(r),null!==n&&(c+=":"+n)):"file"===e&&(c+="//"),c+=this.cannotBeABaseURL?o[0]:o.length?"/"+hL(o,"/"):"",null!==a&&(c+="?"+a),null!==s&&(c+="#"+s),c},setHref:function(e){var t=this.parse(e);if(t)throw new hb(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"===e)try{return new uI(e.path[0]).origin}catch(e){return"null"}return"file"!==e&&this.isSpecial()?e+"://"+h5(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(oQ(e)+":",ur)},getUsername:function(){return this.username},setUsername:function(e){var t=hC(oQ(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<t.length;i++)this.username+=h7(t[i],h9)}},getPassword:function(){return this.password},setPassword:function(e){var t=hC(oQ(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<t.length;i++)this.password+=h7(t[i],h9)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?h5(e):h5(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,up)},getHostname:function(){var e=this.host;return null===e?"":h5(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,u_)},getPort:function(){var e=this.port;return null===e?"":oQ(e)}
1,setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""===(e=oQ(e))?this.port=null:this.parse(e,uE))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+hL(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,ug))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""===(e=oQ(e))?this.query=null:("?"===hD(e,0)&&(e=hB(e,1)),this.query="",this.parse(e,uC)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!==(e=oQ(e))?("#"===hD(e,0)&&(e=hB(e,1)),this.fragment="",this.parse(e,uv)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var uI=function(e){var t=s3(this,uA),i=c_(arguments.length,1)>1?arguments[1]:void 0,r=sA(t,new uy(e,!1,i));ne||(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())},uA=uI.prototype,ub=function(e,t){return{get:function(){return hI(this)[e]()},set:t&&function(e){return hI(this)[t](e)},configurable:!0,enumerable:!0}};if(ne&&(s0(uA,"href",ub("serialize","setHref")),s0(uA,"origin",ub("getOrigin")),s0(uA,"protocol",ub("getProtocol","setProtocol")),s0(uA,"username",ub("getUsername","setUsername")),s0(uA,"password",ub("getPassword","setPassword")),s0(uA,"host",ub("getHost","setHost")),s0(uA,"hostname",ub("getHostname","setHostname")),s0(uA,"port",ub("getPort","setPort")),s0(uA,"pathname",ub("getPathname","setPathname")),s0(uA,"search",ub("getSearch","setSearch")),s0(uA,"searchParams",ub("getSearchParams")),s0(uA,"hash",ub("getHash","setHash"))),sP(uA,"toJSON",function(){return hI(this).serialize()},{enumerable:!0}),sP(uA,"toString",function(){return hI(this).serialize()},{enumerable:!0}),hA){var uO=hA.createObjectURL,uw=hA.revokeObjectURL;uO&&sP(uI,"createObjectURL",ol(uO,hA)),uw&&sP(uI,"revokeObjectURL",ol(uw,hA))}sB(uI,"URL"),oI({global:!0,constructor:!0,forced:!lm,sham:!ne},{URL:uI});var uN=ng("URL"),uD=lm&&rH(function(){uN.canParse()}),uP=rH(function(){return 1!==uN.canParse.length});oI({target:"URL",stat:!0,forced:!uD||uP},{canParse:function(e){var t=c_(arguments.length,1),i=oQ(e),r=t<2||void 0===arguments[1]?void 0:oQ(arguments[1]);try{return new uN(i,r),!0}catch(e){return!1}}});var uL=ng("URL");oI({target:"URL",stat:!0,forced:!lm},{parse:function(e){var t=c_(arguments.length,1),i=oQ(e),r=t<2||void 0===arguments[1]?void 0:oQ(arguments[1]);try{return new uL(i,r)}catch(e){return null}}});var uk=rW(nf.URL);let uM=!0,uU=!0;function ux(e,t,i){let r=e.match(t);return r&&r.length>=i&&parseInt(r[i],10)}function uV(e,t,i){if(!e.RTCPeerConnection)return;let r=e.RTCPeerConnection.prototype,n=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return n.apply(this,arguments);let o=e=>{let t=i(e);t&&(r.handleEvent?r.handleEvent(t):r(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(r,o),n.apply(this,[e,o])};let o=r.removeEventListener;r.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t]||!this._eventMap[t].has(i))return o.apply(this,arguments);let r=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,r])},Object.defineProperty(r,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function uF(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(uM=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function uB(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(uU=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function uj(){"object"==typeof window&&(uM||"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments))}function uG(e,t){uU&&console.warn(e+" is deprecated, please use "+t+" instead.")}function uW(e){return"[object Object]"===Object.prototype.toString.call(e)}function uH(e,t,i){let r=i?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;let o=[];
vendor: 4,466 bytes, line 1
1return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)}),o.forEach(t=>{e.forEach(i=>{i.type===r&&i.trackId===t.id&&function e(t,i,r){i&&!r.has(i.id)&&(r.set(i.id,i),Object.keys(i).forEach(n=>{n.endsWith("Id")?e(t,t.get(i[n]),r):n.endsWith("Ids")&&i[n].forEach(i=>{e(t,t.get(i),r)})}))}(e,i,n)})}),n}function uK(e,t){let i=e&&e.navigator;if(!i.mediaDevices)return;let r=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;let t={};return Object.keys(e).forEach(i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;let r="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);let n=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==r.ideal){t.optional=t.optional||[];let e={};"number"==typeof r.ideal?(e[n("min",i)]=r.ideal,t.optional.push(e),(e={})[n("max",i)]=r.ideal):e[n("",i)]=r.ideal,t.optional.push(e)}void 0!==r.exact&&"number"!=typeof r.exact?(t.mandatory=t.mandatory||{},t.mandatory[n("",i)]=r.exact):["min","max"].forEach(e=>{void 0!==r[e]&&(t.mandatory=t.mandatory||{},t.mandatory[n(e,i)]=r[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},n=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){let t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=r(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});let a=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||a)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then(i=>{let a=(i=i.filter(e=>"videoinput"===e.kind)).find(e=>t.some(t=>{var i;return o5(i=e.label.toLowerCase()).call(i,t)}));return!a&&i.length&&o5(t).call(t,"back")&&(a=i[i.length-1]),a&&(e.video.deviceId=o.exact?{exact:a.deviceId}:{ideal:a.deviceId}),e.video=r(e.video),uj("chrome: "+JSON.stringify(e)),n(e)})}e.video=r(e.video)}return uj("chrome: "+JSON.stringify(e)),n(e)},o=function(e){return t.version>=64?e:{name:({PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"})[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=(function(e,t,r){n(e,e=>{i.webkitGetUserMedia(e,t,e=>{r&&r(o(e))})})}).bind(i),i.mediaDevices.getUserMedia){let e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return n(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException("","NotFoundError");return e},e=>dQ.reject(o(e))))}}}function uY(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function uz(e){if("object"!=typeof e||!e.RTCPeerConnection||"ontrack"in e.RTCPeerConnection.prototype)uV(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e));else{Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",i=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.track.id):{track:i.track};let n=new Event("track");n.track=i.track,n.receiver=r,n.transceiver={receiver:r},n.streams=[t.stream],this.dispatchEvent(n)}
1),t.stream.getTracks().forEach(i=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.id):{track:i};let n=new Event("track");n.track=i,n.receiver=r,n.transceiver={receiver:r},n.streams=[t.stream],this.dispatchEvent(n)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}}function uq(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){let t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){let n=i.apply(this,arguments);return n||(n=t(this,e),this._senders.push(n)),n};let r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){r.apply(this,arguments);let t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}let i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};let r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach(e=>{let t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function uX(e){if(!e.RTCPeerConnection)return;let t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){let[e,i,r]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0==arguments.length||"function"!=typeof e))return t.apply(this,[]);let n=function(e){let t={};return e.result().forEach(e=>{let i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach(t=>{i[t]=e.stat(t)}),t[i.id]=i}),t},o=function(e){return new Map(Object.keys(e).map(t=>[t,e[t]]))};return arguments.length>=2?t.apply(this,[function(e){i(o(n(e)))},e]):new dQ((e,i)=>{t.apply(this,[function(t){e(o(n(t)))},i])}).then(i,r)}}function uJ(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>uH(t,e.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),uV(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>uH(t,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;let t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){let e,t,i,r=arguments[0];
vendor: 4,283 bytes, line 1
1return this.getSenders().forEach(t=>{t.track===r&&(e?i=!0:e=t)}),this.getReceivers().forEach(e=>(e.track===r&&(t?i=!0:t=e),e.track===r)),i||e&&t?dQ.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):e?e.getStats():t?t.getStats():dQ.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function uQ(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let r=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(r)&&this._shimmedLocalStreams[i.id].push(r):this._shimmedLocalStreams[i.id]=[i,r],r};let i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")});let t=this.getSenders();i.apply(this,arguments);let r=this.getSenders().filter(e=>-1===t.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(r)};let r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],r.apply(this,arguments)};let n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{let i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]}),n.apply(this,arguments)}}function uZ(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return uQ(e);let i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){let e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};let r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[t.id]){let i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}r.apply(this,[t])};let n=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let r=e._reverseStreams[t],n=e._streams[r.id];i=i.replace(RegExp(n.id,"g"),r.id)}),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");let r=[].slice.call(arguments,1);if(1!==r.length||!r[0].getTracks().find(e=>e===t))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(e=>e.track===t))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let n=this._streams[i.id];if(n)n.addTrack(t),dQ.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{let r=new e.MediaStream([t]);this._streams[i.id]=r,this._reverseStreams[r.id]=i,this.addStream(r)}
1return this.getSenders().find(e=>e.track===t)},["createOffer","createAnswer"].forEach(function(t){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){let e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{let i=o(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then(e=>o(this,e))}})[t]});let a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){var e,t;let i;return arguments.length&&arguments[0].type&&(arguments[0]=(e=this,t=arguments[0],i=t.sdp,Object.keys(e._reverseStreams||[]).forEach(t=>{let r=e._reverseStreams[t],n=e._streams[r.id];i=i.replace(RegExp(r.id,"g"),n.id)}),new RTCSessionDescription({type:t.type,sdp:i}))),a.apply(this,arguments)};let s=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){let e=s.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){let t;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(e._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{},Object.keys(this._streams).forEach(i=>{this._streams[i].getTracks().find(t=>e.track===t)&&(t=this._streams[i])}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function u$(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}})[t]})}function u0(e,t){uV(e,"negotiationneeded",e=>{let i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e})}var u1=Object.freeze({__proto__:null,fixNegotiationNeeded:u0,shimAddTrackRemoveTrack:uZ,shimAddTrackRemoveTrackWithNative:uQ,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then(t=>{let r=i.video&&i.video.width,n=i.video&&i.video.height,o=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},r&&(i.video.mandatory.maxWidth=r),n&&(i.video.mandatory.maxHeight=n),e.navigator.mediaDevices.getUserMedia(i)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))},shimGetSendersWithDtmf:uq,shimGetStats:uX,shimGetUserMedia:uK,shimMediaStream:uY,shimOnTrack:uz,shimPeerConnection:u$,shimSenderReceiverGetStats:uJ});function u2(e,t){let i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,r){uG("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,r)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){let e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(e((i=JSON.parse(JSON.stringify(i))).audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},r&&r.prototype.getSettings){let t=r.prototype.getSettings;r.prototype.getSettings=function(){let i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(r&&r.prototype.applyConstraints){let t=r.prototype.applyConstraints;r.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(e(i=JSON.parse(JSON.stringify(i)),"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function u3(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function u5(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}})[t]});let i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotec
vendor: 4,521 bytes, line 1
1andidate:"remote-candidate"},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){let[e,n,o]=arguments;return r.apply(this,[e||null]).then(e=>{if(t.version<53&&!n)try{e.forEach(e=>{e.type=i[e.type]||e.type})}catch(t){if("TypeError"!==t.name)throw t;e.forEach((t,r)=>{e.set(r,Object.assign({},t,{type:i[t.type]||t.type}))})}return e}).then(n,o)}}function u4(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender||e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):dQ.resolve(new Map)}}function u6(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender||e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),uV(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function u8(e){!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){uG("removeStream","removeTrack"),this.getSenders().forEach(t=>{var i;t.track&&o5(i=e.getTracks()).call(i,t.track)&&this.removeTrack(t)})})}function u9(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function u7(e){if("object"!=typeof e||!e.RTCPeerConnection)return;let t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]);let i=(e=[...e]).length>0;i&&e.forEach(e=>{if("rid"in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw RangeError("max_framerate must be >= 0.0")});let r=t.apply(this,arguments);if(i){let{sender:t}=r,i=t.getParameters();"encodings"in i&&(1!==i.encodings.length||0!==Object.keys(i.encodings[0]).length)||(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return r})}function pe(e){if("object"!=typeof e||!e.RTCRtpSender)return;let t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){let e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function pt(e){if("object"!=typeof e||!e.RTCPeerConnection)return;let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?dQ.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function pi(e){if("object"!=typeof e||!e.RTCPeerConnection)return;let t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?dQ.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var pr=Object.freeze({__proto__:null,shimAddTransceiver:u7,shimCreateAnswer:pi,shimCreateOffer:pt,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){let e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,dQ.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:pe,shimGetUserMedia:u2,shimOnTrack:u3,shimPeerConnection:u5,shimRTCDataChannel:u9,shimReceiverGetStats:u6,shimRemoveStream:u8,shimSenderGetStats:u4});function pn(e){if("object"==typeof e&&e.RTCPeerConnection){if("getL
1ocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){var i;this._localStreams||(this._localStreams=[]),o5(i=this._localStreams).call(i,e)||this._localStreams.push(e),e.getAudioTracks().forEach(i=>t.call(this,i,e)),e.getVideoTracks().forEach(i=>t.call(this,i,e))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,r=Array(i>1?i-1:0),n=1;n<i;n++)r[n-1]=arguments[n];return r&&r.forEach(e=>{var t;this._localStreams?o5(t=this._localStreams).call(t,e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);let t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);let i=e.getTracks();this.getSenders().forEach(e=>{o5(i).call(i,e.track)&&this.removeTrack(e)})})}}function po(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach(e=>{var t;if(this._remoteStreams||(this._remoteStreams=[]),o5(t=this._remoteStreams).call(t,e))return;this._remoteStreams.push(e);let i=new Event("addstream");i.stream=e,this.dispatchEvent(i)})})}});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){let e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);let i=new Event("addstream");i.stream=t,e.dispatchEvent(i)})}),t.apply(e,arguments)}}}function pa(e){if("object"!=typeof e||!e.RTCPeerConnection)return;let t=e.RTCPeerConnection.prototype,i=t.createOffer,r=t.createAnswer,n=t.setLocalDescription,o=t.setRemoteDescription,a=t.addIceCandidate;t.createOffer=function(e,t){let r=arguments.length>=2?arguments[2]:arguments[0],n=i.apply(this,[r]);return t?(n.then(e,t),dQ.resolve()):n},t.createAnswer=function(e,t){let i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),dQ.resolve()):n};let s=function(e,t,i){let r=n.apply(this,[e]);return i?(r.then(t,i),dQ.resolve()):r};t.setLocalDescription=s,t.setRemoteDescription=s=function(e,t,i){let r=o.apply(this,[e]);return i?(r.then(t,i),dQ.resolve()):r},t.addIceCandidate=s=function(e,t,i){let r=a.apply(this,[e]);return i?(r.then(t,i),dQ.resolve()):r}}function ps(e){let t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){let e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(pc(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=(function(e,i,r){t.mediaDevices.getUserMedia(e).then(i,r)}).bind(t))}function pc(e){return e&&void 0!==e.video?Object.assign({},e,{video:function e(t){var i;return uW(t)?as(i=Object.keys(t)).call(i,function(i,r){let n=uW(t[r]),o=n?e(t[r]):t[r],a=n&&!Object.keys(o).length;return void 0===o||a?i:Object.assign(i,{[r]:o})},{}):t}(e.video)}):e}function pd(e){if(!e.RTCPeerConnection)return;let t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){let t=[];for(let i=0;i<e.iceServers.length;i++){let r=e.iceServers[i];!r.hasOwnProperty("urls")&&r.hasOwnProperty("url")?(uG("RTCIceServer.url","RTCIceServer.urls"),(r=JSON.parse(JSON.stringify(r))).urls=r.url,delete r.url,t.push(r)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function pl(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function ph(e){let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);let t=this.getTransceivers().find(e=>"audio"===e.receiver.track.kind);!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);let i=this.getTransceivers().find(e=>"video"===e.receiver.track.kind);!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function pu(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var pp=Object.freeze({__proto__:null,shimAudioContext:pu,shimCallbacksAPI:pa,shimConstraints:pc,shimCreateOfferLegacy:ph,shimGetUserMedia:ps,shimLocalStreamsAPI:pn,shimRTCIceServerUrls:pd,shimRemoteStreamsAPI:po,shimTrackEventTransceiver:pl}),p_=" \n\v\f\r \xa0áââââââ
ââââââ¯âã\u2028\u2029\uFEFF",pE=rX("".replace),pm=RegExp("^["+p_+"]+"),pf=RegExp("(^|[^"+p_+"])["+p_+"]+$"),pS=function(e){return function(t){var i=oQ(n_(t));return 1&e&&(i=pE(i,pm,"")),2&e&&(i=pE(i,pf,"$1")),i}},pg={start:pS(1),end:pS(2),trim:pS(3)},pT=sD.PROPER,pR=pg.trim;oI({target:"String",proto:!0,forced:(l="trim",rH(function(){return!!p_[l]()||"â\x85á "!=="â\x85á "[l]()||pT&&p_[l].name!==l}))},{trim:function(){return pR(this)}});var pC=oF("String","trim"),pv=String.prototype,py=rW(function(e){var t=e.trim;return"string"==typeof e||e===pv||rJ(pv,e)&&t===pv.trim?pC:t}),pI={exports:{}};let pA={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};pA.localCName=pA.generateIdentifier(),pA.splitLines=function(e){return e.trim().split("\n").map(e=>e.trim())},pA.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n")},pA.getDescription=function(e){let t=pA.splitSections(e);return t&&t[0]},pA.getMediaSections=function(e){let t=pA.splitSections(e);return t.shift(),t},pA.matchPrefix=function(e,t){return pA.splitLines(e).filter(e=>0===e.indexOf(t))},pA.parseCandidate=function(e){let t,i={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" "))[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},pA.writeCandidate=function(e){let t=[];t.push(e.foundation);let i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);let r=e.type;return t.push("typ"),t.push(r),"host"!==r&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.pu
vendor: 16,278 bytes, line 1
1sh(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},pA.parseIceOptions=function(e){return e.substring(14).split(" ")},pA.parseRtpMap=function(e){let t=e.substring(9).split(" "),i={payloadType:parseInt(t.shift(),10)};return i.name=(t=t[0].split("/"))[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},pA.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);let i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},pA.parseExtmap=function(e){let t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},pA.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},pA.parseFmtp=function(e){let t,i={},r=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<r.length;e++)i[(t=r[e].trim().split("="))[0].trim()]=t[1];return i},pA.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){let r=[];Object.keys(e.parameters).forEach(t=>{void 0!==e.parameters[t]?r.push(t+"="+e.parameters[t]):r.push(t)}),t+="a=fmtp:"+i+" "+r.join(";")+"\r\n"}return t},pA.parseRtcpFb=function(e){let t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},pA.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},pA.parseSsrcMedia=function(e){let t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},r=e.indexOf(":",t);return r>-1?(i.attribute=e.substring(t+1,r),i.value=e.substring(r+1)):i.attribute=e.substring(t+1),i},pA.parseSsrcGroup=function(e){let t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},pA.getMid=function(e){let t=pA.matchPrefix(e,"a=mid:")[0];if(t)return t.substring(6)},pA.parseFingerprint=function(e){let t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},pA.getDtlsParameters=function(e,t){return{role:"auto",fingerprints:pA.matchPrefix(e+t,"a=fingerprint:").map(pA.parseFingerprint)}},pA.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach(e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),i},pA.parseCryptoLine=function(e){let t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},pA.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?pA.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},pA.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;let t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},pA.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},pA.getCryptoParameters=function(e,t){return pA.matchPrefix(e+t,"a=crypto:").map(pA.parseCryptoLine)},pA.getIceParameters=function(e,t){let i=pA.matchPrefix(e+t,"a=ice-ufrag:")[0],r=pA.matchPrefix(e+t,"a=ice-pwd:")[0];return i&&r?{usernameFragment:i.substring(12),password:r.substring(10)}:null},pA.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},pA.parseRtpParameters=function(e){let t={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=pA.splitLines(e)[0].split(" ");t.profile=i[2];for(let r=3;r<i.length;r++){let n=i[r],o=pA.matchPrefix(e,"a=rtpmap:"+n+" ")[0];if(o){let i=pA.parseRtpMap(o),r=pA.matchPrefix(e,"a=fmtp:"+n+" ");switch(i.parameters=r.length?pA.parseFmtp(r[0]):{},i.rtcpFeedback=pA.matchPrefix(e,"a=rtcp-fb:"+n+" ").map(pA.parseRtcpFb),t.codecs.push(i),i.name.toUpperCase()){case"RED":case"ULPFEC":t.fecMechanisms.push(i.name.toUpperCase())}}}pA.matchPrefix(e,"a=extmap:").forEach(e=>{t.headerExtensions.push(pA.parseExtmap(e))});let r=pA.matchPrefix(e,"a=rtcp-fb:* ").map(pA.parseRtcpFb);return t.codecs.forEach(e=>{r.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t)})}),t},pA.writeRtpDescription=function(e,t){let i="";i+="m="+e+" ",i+=t.codecs.length>0?"9":"0",i+=" "+(t.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=t.codecs.map(e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",t.codecs.forEach(e=>{i+=pA.writeRtpMap(e),i+=pA.writeFmtp(e),i+=pA.writeRtcpFb(e)});let r=0;return t.codecs.forEach(e=>{e.maxptime>r&&(r=e.maxptime)}),r>0&&(i+="a=maxptime:"+r+"\r\n"),t.headerExtensions&&t.headerExtensions.forEach(e=>{i+=pA.writeExtmap(e)}),i},pA.parseRtpEncodingParameters=function(e){let t,i=[],r=pA.parseRtpParameters(e),n=-1!==r.fecMechanisms.indexOf("RED"),o=-1!==r.fecMechanisms.indexOf("ULPFEC"),a=pA.matchPrefix(e,"a=ssrc:").map(e=>pA.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute),s=a.length>0&&a[0].ssrc,c=pA.matchPrefix(e,"a=ssrc-group:FID").map(e=>e.substring(17).split(" ").map(e=>parseInt(e,10)));c.length>0&&c[0].length>1&&c[0][0]===s&&(t=c[0][1]),r.codecs.forEach(e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let r={ssrc:s,codecPayloadType:parseInt(e.parameters.apt,10)};s&&t&&(r.rtx={ssrc:t}),i.push(r),n&&((r=JSON.parse(JSON.stringify(r))).fec={ssrc:s,mechanism:o?"red+ulpfec":"red"},i.push(r))}}),0===i.length&&s&&i.push({ssrc:s});let d=pA.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substring(5),10)*.95-16e3:void 0,i.forEach(e=>{e.maxBitrate=d})),i},pA.parseRtcpParameters=function(e){let t={},i=pA.matchPrefix(e,"a=ssrc:").map(e=>pA.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute)[0];i&&(t.cname=i.value,t.ssrc=i.ssrc);let r=pA.matchPrefix(e,"a=rtcp-rsize");return t.reducedSize=r.length>0,t.compound=0===r.length,t.mux=pA.matchPrefix(e,"a=rtcp-mux").length>0,t},pA.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},pA.parseMsid=function(e){let t,i=pA.matchPrefix(e,"a=msid:");if(1===i.length)return{stream:(t=i[0].substring(7).split(" "))[0],track:t[1]};let r=pA.matchPrefix(e,"a=ssrc:").map(e=>pA.parseSsrcMedia(e)).filter(e=>"msid"===e.attribute);return r.length>0?{stream:(t=r[0].value.split(" "))[0],track:t[1]}:void 0},pA.parseSctpDescription=function(e){let t,i=pA.parseMLine(e),r=pA.matchPrefix(e,"a=max-message-size:");r.length>0&&(t=parseInt(r[0].substring(19),10)),isNaN(t)&&(t=65536);let n=pA.matchPrefix(e,"a=sctp-port:");if(n.length>0)return{port:parseInt(n[0].substring(12),10),protocol:i.fmt,maxMessageSize:t};let o=pA.matchPrefix(e,"a=sctpmap:");if(o.length>0){let e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:t}}},pA.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},pA.generateSessionId=function(){return Math.random().toString().substr(2,22)},pA.writeSessionBoilerplate=function(e,t,i){return"v=0\r\no="+(i||"thisisadapterortc")+" "+(e||pA.generateSessionId())+" "+(void 0!==t?t:2)+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},pA.getDirection=function(e,t){let i=pA.splitLines(e);for(let e=0;e<i.length;e++)switch(i[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[e].substring(2)}return t?pA.getDirection(t):"sendrecv"},pA.getKind=function(e){return pA.splitLines(e)[0].split(" ")[0].substring(2)},pA.isRejected=function(e){return"0"===e.split(" ",2)[1]},pA.parseMLine=function(e){let t=pA.splitLines(e)[0].substring(2).split(" ");return{kind:t[0],port:parseInt(t[1],10),protocol:t[2],fmt:t.slice(3).join(" ")}},pA.parseOLine=function(e){let t=pA.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:t[0],sessionId:t[1],sessionVersion:parseInt(t[2],10),netType:t[3],addressType:t[4],address:t[5]}},pA.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;let t=pA.splitLines(e);for(let e=0;e<t.length;e++)if(t[e].length<2||"="!==t[e].charAt(1))return!1;return!0},pI.exports=pA;var pb=pI.exports,pO=rW(pb),pw=(h={__proto__:null,default:pO},[pb].forEach(function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach(function(t){if("default"!==t&&!(t in h)){var i=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(h,t,i.get?i:{enumerable:!0,get:function(){return e[t]}})}})}),Object.freeze(h));function pN(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;let t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){let i=Object.assign(new t(e),pO.parseCandidate(e.candidate));return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,uV(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function pD(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||uV(e,"icecandidate",e=>{if(e.candidate){let t=pO.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol=({0:"tls",1:"tcp",2:"udp"})[t.priority>>24])}return e})}function pP(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});let i=function(e){if(!e||!e.sdp)return!1;let t=pO.splitSections(e.sdp);return t.shift(),t.some(e=>{let t=pO.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")})},r=function(e){let t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return -1;let i=parseInt(t[1],10);return i!=i?-1:i},n=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:0x7ffffff5:t.version<60?57===t.version?65535:65536:0x7ffffff5),i},o=function(e,i){let r=65536;"firefox"===t.browser&&57===t.version&&(r=65535);let n=pO.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?r=parseInt(n[0].substr(19),10):"firefox"===t.browser&&-1!==i&&(r=0x7ffffff5),r},a=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){let{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(i(arguments[0])){let e,t=r(arguments[0]),i=n(t),a=o(arguments[0],t);e=0===i&&0===a?1/0:0===i||0===a?Math.max(i,a):Math.min(i,a);let s={};Object.defineProperty(s,"maxMessageSize",{get:()=>e}),this._sctp=s}return a.apply(this,arguments)}}function pL(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){let i=e.send;e.send=function(){let r=arguments[0],n=r.length||r.size||r.byteLength;if("open"===e.readyState&&t.sctp&&n>t.sctp.maxMessageSize)throw TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}let i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){let e=i.apply(this,arguments);return t(e,this),e},uV(e,"datachannel",e=>(t(e.channel,e.target),e))}function pk(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;let t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return({completed:"connected",checking:"connecting"})[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(e=>{let i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{let t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;let i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function pM(e,t){if(!e.RTCPeerConnection||"chrome"===t.browser&&t.version>=71||"safari"===t.browser&&t.version>=605)return;let i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){let i=t.sdp.split("\n").filter(e=>"a=extmap-allow-mixed"!==py(e).call(e)).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function pU(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;let i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?dQ.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),dQ.resolve())})}function px(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;let i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(!(e={type:e.type,sdp:e.sdp}).type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}return e.sdp||"offer"!==e.type&&"answer"!==e.type?i.apply(this,[e]):("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>i.apply(this,[e]))})}var pV=Object.freeze({__proto__:null,removeExtmapAllowMixed:pM,shimAddIceCandidateNullOrEmpty:pU,shimConnectionState:pk,shimMaxMessageSize:pP,shimParameterlessSetLocalDescription:px,shimRTCIceCandidate:pN,shimRTCIceCandidateRelayProtocol:pD,shimSendThrowTypeError:pL});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},i=function(e){let t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;let{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=ux(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=ux(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);
1else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=ux(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),r={browserDetails:i,commonShim:pV,extractVersion:ux,disableLog:uF,disableWarnings:uB,sdp:pw};switch(i.browser){case"chrome":if(!u1||!u$||!t.shimChrome)return uj("Chrome shim is not included in this adapter release.");if(null===i.version)return uj("Chrome shim can not determine version, not shimming.");uj("adapter.js shimming chrome."),r.browserShim=u1,pU(e,i),px(e),uK(e,i),uY(e),u$(e,i),uz(e),uZ(e,i),uq(e),uX(e),uJ(e),u0(e,i),pN(e),pD(e),pk(e),pP(e,i),pL(e),pM(e,i);break;case"firefox":if(!pr||!u5||!t.shimFirefox)return uj("Firefox shim is not included in this adapter release.");uj("adapter.js shimming firefox."),r.browserShim=pr,pU(e,i),px(e),u2(e,i),u5(e,i),u3(e),u8(e),u4(e),u6(e),u9(e),u7(e),pe(e),pt(e),pi(e),pN(e),pk(e),pP(e,i),pL(e);break;case"safari":if(!pp||!t.shimSafari)return uj("Safari shim is not included in this adapter release.");uj("adapter.js shimming safari."),r.browserShim=pp,pU(e,i),px(e),pd(e),ph(e),pa(e),pn(e),po(e),pl(e),ps(e),pu(e),pN(e),pD(e),pP(e,i),pL(e),pM(e,i);break;default:uj("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var pF=rZ.RegExp,pB=!rH(function(){var e=!0;try{pF(".","d")}catch(t){e=!1}var t={},i="",r=e?"dgimsy":"gimsy",n=function(e,r){Object.defineProperty(t,e,{get:function(){return i+=r,!0}})},o={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};for(var a in e&&(o.hasIndices="d"),o)n(a,o[a]);return Object.getOwnPropertyDescriptor(pF.prototype,"flags").get.call(t)!==r||i!==r}),pj=function(){var e=oE(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},pG=RegExp.prototype,pW=pB?function(e){return e.flags}:function(e){return pB||!rJ(pG,e)||nq(e,"flags")?e.flags:ni(pj,e)},pH=Math.floor,pK=rX("".charAt),pY=rX("".replace),pz=rX("".slice),pq=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,pX=/\$([$&'`]|\d{1,2})/g,pJ=function(e,t,i,r,n,o){var a=i+e.length,s=r.length,c=pX;return void 0!==n&&(n=nY(n),c=pq),pY(o,c,function(o,c){var d;switch(pK(c,0)){case"$":return"$";case"&":return e;case"`":return pz(t,0,i);case"'":return pz(t,a);case"<":d=n[pz(c,1,-1)];break;default:var l=+c;if(0===l)return o;if(l>s){var h=pH(l/10);return 0===h?o:h<=s?void 0===r[h-1]?pK(c,1):r[h-1]+pK(c,1):o}d=r[l-1]}return void 0===d?"":d})},pQ=n2("replace"),pZ=TypeError,p$=rX("".indexOf),p0=rX("".replace),p1=rX("".slice),p2=Math.max;oI({target:"String",proto:!0},{replaceAll:function(e,t){var i,r,n,o,a,s,c,d,l,h=n_(this),u=0,p="";if(nm(e)){if((i=oG(e))&&!~p$(oQ(n_(pW(e))),"g"))throw new pZ("`.replaceAll` does not allow non-global regexes");if(r=nx(e,pQ))return ni(r,e,h,t);if(i)return p0(oQ(h),e,t)}for(n=oQ(h),o=oQ(e),(a=r9(t))||(t=oQ(t)),c=p2(1,s=o.length),d=p$(n,o);-1!==d;)l=a?oQ(t(o,d,n)):pJ(o,n,d,[],void 0,t),p+=p1(n,u,d)+l,u=d+s,d=d+c>n.length?-1:p$(n,o,d+c);return u<n.length&&(p+=p1(n,u)),p}});var p3=oF("String","replaceAll"),p5=String.prototype,p4=rW(function(e){var t=e.replaceAll;return"string"==typeof e||e===p5||rJ(p5,e)&&t===p5.replaceAll?p3:t});oI({global:!0,forced:rZ.globalThis!==rZ},{globalThis:rZ});var p6=rW(rZ),p8={exports:{}};u=p8.exports,function(e,t){var i="function",r="undefined",n="object",o="string",a="major",s="model",c="name",d="type",l="vendor",h="version",p="architecture",_="console",E="mobile",m="tablet",f="smarttv",S="wearable",g="embedded",T="Amazon",R="Apple",C="ASUS",v="BlackBerry",y="Browser",I="Chrome",A="Firefox",b="Google",O="Honor",w="Huawei",N="Microsoft",D="Motorola",P="Nvidia",L="OnePlus",k="Opera",M="OPPO",U="Samsung",x="Sharp",V="Sony",F="Xiaomi",B="Zebra",j="Facebook",G="Chromium OS",W="Mac OS",H=" Browser",K=function(e){for(var t={},i=0;i<e.length;i++)t[e[i].toUpperCase()]=e[i];return t},Y=function(e,t){return typeof e===o&&-1!==z(t).indexOf(z(e))},z=function(e){return e.toLowerCase()},q=function(e,t){if(typeof e===o)return e=e.replace(/^\s\s*/,""),typeof t===r?e:e.substring(0,500)},X=function(e,r){for(var o,a,s,c,d,l,h=0;h<r.length&&!d;){var u=r[h],p=r[h+1];for(o=a=0;
vendor: 4,229 bytes, line 1
1o<u.length&&!d&&u[o];)if(d=u[o++].exec(e))for(s=0;s<p.length;s++)l=d[++a],typeof(c=p[s])===n&&c.length>0?2===c.length?typeof c[1]==i?this[c[0]]=c[1].call(this,l):this[c[0]]=c[1]:3===c.length?typeof c[1]!==i||c[1].exec&&c[1].test?this[c[0]]=l?l.replace(c[1],c[2]):void 0:this[c[0]]=l?c[1].call(this,l,c[2]):void 0:4===c.length&&(this[c[0]]=l?c[3].call(this,l.replace(c[1],c[2])):t):this[c]=l||t;h+=2}},J=function(e,i){for(var r in i)if(typeof i[r]===n&&i[r].length>0){for(var o=0;o<i[r].length;o++)if(Y(i[r][o],e))return"?"===r?t:r}else if(Y(i[r],e))return"?"===r?t:r;return i.hasOwnProperty("*")?i["*"]:e},Q={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},Z={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[h,[c,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[h,[c,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[c,h],[/opios[\/ ]+([\w\.]+)/i],[h,[c,k+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[h,[c,k+" GX"]],[/\bopr\/([\w\.]+)/i],[h,[c,k]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[h,[c,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[h,[c,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[c,h],[/quark(?:pc)?\/([-\w\.]+)/i],[h,[c,"Quark"]],[/\bddg\/([\w\.]+)/i],[h,[c,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[h,[c,"UC"+y]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[h,[c,"WeChat"]],[/konqueror\/([\w\.]+)/i],[h,[c,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[h,[c,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[h,[c,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[h,[c,"Smart Lenovo "+y]],[/(avast|avg)\/([\w\.]+)/i],[[c,/(.+)/,"$1 Secure "+y],h],[/\bfocus\/([\w\.]+)/i],[h,[c,A+" Focus"]],[/\bopt\/([\w\.]+)/i],[h,[c,k+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[h,[c,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[h,[c,"Dolphin"]],[/coast\/([\w\.]+)/i],[h,[c,k+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[h,[c,"MIUI"+H]],[/fxios\/([\w\.-]+)/i],[h,[c,A]],[/\bqihoobrowser\/?([\w\.]*)/i],[h,[c,"360"]],[/\b(qq)\/([\w\.]+)/i],[[c,/(.+)/,"$1Browser"],h],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[c,/(.+)/,"$1"+H],h],[/samsungbrowser\/([\w\.]+)/i],[h,[c,U+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[h,[c,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[c,"Sogou Mobile"],h],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[c,h],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[c],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[h,c],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[c,j],h],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/(daum)apps[\/ ]([\w\.]+)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[c,h],[/\bgsa\/([\w\.]+) .*safari\//i],[h,[c,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[h,[c,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[h,[c,I+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[c,I+" WebView"],h],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[h,[c,"Android "+y]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[c,h],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[h,[c,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[h,c],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[c,[h,J,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}
vendor: 9,151 bytes, line 1
1]],[/(webkit|khtml)\/([\w\.]+)/i],[c,h],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[c,"Netscape"],h],[/(wolvic|librewolf)\/([\w\.]+)/i],[c,h],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[h,[c,A+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(amaya|dillo|doris|icab|ladybird|lynx|mosaic|netsurf|obigo|polaris|w3m|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/\b(links) \(([\w\.]+)/i],[c,[h,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[c,[h,/master.|lts./,""]]],cpu:[[/\b((amd|x|x86[-_]?|wow|win)64)\b/i],[[p,"amd64"]],[/(ia32(?=;))/i,/\b((i[346]|x)86)(pc)?\b/i],[[p,"ia32"]],[/\b(aarch64|arm(v?[89]e?l?|_?64))\b/i],[[p,"arm64"]],[/\b(arm(v[67])?ht?n?[fl]p?)\b/i],[[p,"armhf"]],[/( (ce|mobile); ppc;|\/[\w\.]+arm\b)/i],[[p,"arm"]],[/((ppc|powerpc)(64)?)( mac|;|\))/i],[[p,/ower/,"",z]],[/ sun4\w[;\)]/i],[[p,"sparc"]],[/\b(avr32|ia64(?=;)|68k(?=\))|\barm(?=v([1-7]|[5-7]1)l?|;|eabi)|(irix|mips|sparc)(64)?\b|pa-risc)/i],[[p,z]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[s,[l,U],[d,m]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[s,[l,U],[d,E]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[s,[l,R],[d,E]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[s,[l,R],[d,m]],[/(macintosh);/i],[s,[l,R]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[s,[l,x],[d,E]],[/\b((?:brt|eln|hey2?|gdi|jdn)-a?[lnw]09|(?:ag[rm]3?|jdn2|kob2)-a?[lw]0[09]hn)(?: bui|\)|;)/i],[s,[l,O],[d,m]],[/honor([-\w ]+)[;\)]/i],[s,[l,O],[d,E]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?|605hw|bg2-u03|(?:gem|fdr|m2|ple|t1)-[7a]0[1-4][lu]|t1-a2[13][lw]|mediapad[\w\. ]*(?= bui|\)))\b(?!.+d\/s)/i],[s,[l,w],[d,m]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[s,[l,w],[d,E]],[/oid[^\)]+; (2[\dbc]{4}(182|283|rp\w{2})[cgl]|m2105k81a?c)(?: bui|\))/i,/\b((?:red)?mi[-_ ]?pad[\w- ]*)(?: bui|\))/i],[[s,/_/g," "],[l,F],[d,m]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i,/ ([\w ]+) miui\/v?\d/i],[[s,/_/g," "],[l,F],[d,E]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[s,[l,M],[d,E]],[/\b(opd2(\d{3}a?))(?: bui|\))/i],[s,[l,J,{OnePlus:["304","403","203"],"*":M}],[d,m]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[s,[l,"Vivo"],[d,E]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[s,[l,"Realme"],[d,E]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto(?! 360)[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[s,[l,D],[d,E]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[s,[l,D],[d,m]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[s,[l,"LG"],[d,m]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv|watch)\w+)/i,/\blg-?([\d\w]+) bui/i],[s,[l,"LG"],[d,E]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])( bui|;|\)|\/)/i,/lenovo ?(b[68]0[08]0-?[hf]?|tab(?:[\w- ]+?)|tb[\w-]{6,7})( bui|;|\)|\/)/i],[s,[l,"Lenovo"],[d,m]],[/(nokia) (t[12][01])/i],[l,s,[d,m]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,/nokia[-_ ]?(([-\w\. ]*))/i],[[s,/_/g," "],[d,E],[l,"Nokia"]],[/(pixel (c|tablet))\b/i],[s,[l,b],[d,m]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[s,[l,b],[d,E]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[s,[l,V],[d,E]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[s,"Xperia Tablet"],[l,V],[d,m]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[s,[l,L],[d,E]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[s,[l,T],[d,m]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[s,/(.+)/g,"Fire Phone $1"],[l,T],[d,E]],[/(playbook);[-\w\),; ]+(rim)/i],[s,l,[d,m]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[s,[l,v],[d,E]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[s,[l,C],[d,m]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[s,[l,C],[d,E]],[/(nexus 9)/i],[s,[l,"HTC"],[d,m]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[l,[s,/_/g," "],[d,E]],[/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])\w*(\)| bui)/i],[s,[l,"TCL"],[d,m]],[/(itel) ((\w+))/i],[[l,z],s,[d,J,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[s,[l,"Acer"],[d,m]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[s,[l,"Meizu"],[d,E]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[s,[l,"Ulefone"],[d,E]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[s,[l,"Energizer"],[d,E]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[s,[l,"Cat"],[d,E]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[s,[l,"Smartfren"],[d,E]],[/droid.+; (a(?:015|06[35]|142p?))/i],[s,[l,"Nothing"],[d,E]],[/; (x67 5g|tikeasy \w+|ac[1789]\d\w+)( b|\))/i,/archos ?(5|gamepad2?|([\w ]*[t1789]|hello) ?\d+[\w ]*)( b|\))/i],[s,[l,"Archos"],[d,m]],[/archos ([\w ]+)( b|\))/i,/; (ac[3-6]\d\w{2,8})( b|\))/i],[s,[l,"Archos"],[d,E]],[/(imo) (tab \w+)/i,/(infinix) (x1101b?)/i],[l,s,[d,m]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus(?! zenw)|dell|jolla|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (hmd|imo) ([\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,/(oppo) ?([\w ]+) bui/i],[l,s,[d,E]],[/(kobo)\s(ereader|touch)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[l,s,[d,m]],[/(surface duo)/i],[s,[l,N],[d,m]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[s,[l,"Fairphone"],[d,E]],[/(u304aa)/i],[s,[l,"AT&T"],[d,E]],[/\bsie-(\w*)/i],[s,[l,"Siemens"],[d,E]],[/\b(rct\w+) b/i],[s,[l,"RCA"],[d,m]],[/\b(venue[\d ]{2,7}) b/i],[s,[l,"Dell"],[d,m]],[/\b(q(?:mv|ta)\w+) b/i],[s,[l,"Verizon"],[d,m]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[s,[l,"Barnes & Noble"],[d,m]],[/\b(tm\d{3}\w+) b/i],[s,[l,"NuVision"],[d,m]],[/\b(k88) b/i],[s,[l,"ZTE"],[d,m]],[/\b(nx\d{3}j) b/i],[s,[l,"ZTE"],[d,E]],[/\b(gen\d{3}) b.+49h/i],[s,[l,"Swiss"],[d,E]],[/\b(zur\d{3}) b/i],[s,[l,"Swiss"],[d,m]],[/\b((zeki)?tb.*\b) b/i],[s,[l,"Zeki"],[d,m]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[l,"Dragon Touch"],s,[d,m]],[/\b(ns-?\w{0,9}) b/i],[s,[l,"Insignia"],[d,m]],[/\b((nxa|next)-?\w{0,9}) b/i],[s,[l,"NextBook"],[d,m]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[l,"Voice"],s,[d,E]],[/\b(lvtel\-)?(v1[12]) b/i],[[l,"LvTel"],s,[d,E]],[/\b(ph-1) /i],[s,[l,"Essential"],[d,E]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[s,[l,"Envizen"],[d,m]],[/\b(trio[-\w\. ]+) b/i],[s,[l,"MachSpeed"],[d,m]],[/\btu_(1491) b/i],[s,[l,"Rotor"],[d,m]],[/((?:tegranote|shield t(?!.+d tv))[\w- ]*?)(?: b|\))/i],[s,[l,P],[d,m]],[/(sprint) (\w+)/i],[l,s,[d,E]],[/(kin\.[onetw]{3})/i],[[s,/\./g," "],[l,N],[d,E]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[s,[l,B],[d,m]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[s,[l,B],[d,E]],[/smart-tv.+(samsung)/i],[l,[d,f]],[/hbbtv.+maple;(\d+)/i],[[s,/^/,"SmartTV"],[l,U],[d,f]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[l,"LG"],[d,f]],[/(apple) ?tv/i],[l,[s,R+" TV"],[d,f]],[/crkey/i],[[s,I+"cast"],[l,b],[d,f]],[/droid.+aft(\w+)( bui|\))/i],[s,[l,T],[d,f]],[/(shield \w+ tv)/i],[s,[l,P],[d,f]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[s,[l,x],[d,f]],[/(bravia[\w ]+)( bui|\))/i],[s,[l,V],[d,f]],[/(mi(tv|box)-?\w+) bui/i],[s,[l,F],[d,f]],[/Hbbtv.*(technisat) (.*);/i],[l,s,[d,f]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[l,q],[s,q],[d,f]],[/droid.+; ([\w- ]+) (?:android tv|smart[- ]?tv)/i],[s,[d,f]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[d,f]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[l,s,[d,_]],[/droid.+; (shield)( bui|\))/i],[s,[l,P],[d,_]],[/(playstation \w+)/i],[s,[l,V],[d,_]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[s,[l,N],[d,_]],[/\b(sm-[lr]\d\d[0156][fnuw]?s?|gear live)\b/i],[s,[l,U],[d,S]],[/((pebble))app/i,/(asu
1s|google|lg|oppo) ((pixel |zen)?watch[\w ]*)( bui|\))/i],[l,s,[d,S]],[/(ow(?:19|20)?we?[1-3]{1,3})/i],[s,[l,M],[d,S]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[s,[l,R],[d,S]],[/(opwwe\d{3})/i],[s,[l,L],[d,S]],[/(moto 360)/i],[s,[l,D],[d,S]],[/(smartwatch 3)/i],[s,[l,V],[d,S]],[/(g watch r)/i],[s,[l,"LG"],[d,S]],[/droid.+; (wt63?0{2,3})\)/i],[s,[l,B],[d,S]],[/droid.+; (glass) \d/i],[s,[l,b],[d,S]],[/(pico) (4|neo3(?: link|pro)?)/i],[l,s,[d,S]],[/; (quest( \d| pro)?)/i],[s,[l,j],[d,S]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[l,[d,g]],[/(aeobc)\b/i],[s,[l,T],[d,g]],[/(homepod).+mac os/i],[s,[l,R],[d,g]],[/windows iot/i],[[d,g]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[s,[d,E]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[s,[d,m]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[d,m]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[d,E]],[/droid .+?; ([\w\. -]+)( bui|\))/i],[s,[l,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[h,[c,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[c,h],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[h,[c,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[c,h],[/ladybird\//i],[[c,"LibWeb"]],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[h,c]],os:[[/microsoft (windows) (vista|xp)/i],[c,h],[/(windows (?:phone(?: os)?|mobile|iot))[\/ ]?([\d\.\w ]*)/i],[c,[h,J,Q]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[h,J,Q],[c,"Windows"]],[/[adehimnop]{4,7}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[h,/_/g,"."],[c,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[c,W],[h,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[h,c],[/(ubuntu) ([\w\.]+) like android/i],[[c,/(.+)/,"$1 Touch"],h],[/(android|bada|blackberry|kaios|maemo|meego|openharmony|qnx|rim tablet os|sailfish|series40|symbian|tizen|webos)\w*[-\/; ]?([\d\.]*)/i],[c,h],[/\(bb(10);/i],[h,[c,v]],[/(?:symbian ?os|symbos|s60(?=;)|series ?60)[-\/ ]?([\w\.]*)/i],[h,[c,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[h,[c,A+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[h,[c,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[h,[c,"watchOS"]],[/crkey\/([\d\.]+)/i],[h,[c,I+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[c,G],h],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux)(?: arm\w*| x86\w*| ?)([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[c,h],[/(sunos) ?([\w\.\d]*)/i],[[c,"Solaris"],h],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[c,h]]},$=function(u,_){if(typeof u===n&&(_=u,u=t),!(this instanceof $))return new $(u,_).getResult();var f=typeof e!==r&&e.navigator?e.navigator:t,S=u||(f&&f.userAgent?f.userAgent:""),g=f&&f.userAgentData?f.userAgentData:t,T=_?function(e,t){var i={};for(var r in e)t[r]&&t[r].length%2==0?i[r]=t[r].concat(e[r]):i[r]=e[r];return i}(Z,_):Z,R=f&&f.userAgent==S;return this.getBrowser=function(){var e,r={};return r[c]=t,r[h]=t,X.call(r,S,T.browser),r[a]=typeof(e=r[h])===o?e.replace(/[^\d\.]/g,"").split(".")[0]:t,R&&f&&f.brave&&typeof f.brave.isBrave==i&&(r[c]="Brave"),r},this.getCPU=function(){var e={};return e[p]=t,X.call(e,S,T.cpu),e},this.getDevice=function(){var e={};return e[l]=t,e[s]=t,e[d]=t,X.call(e,S,T.device),R&&!e[d]&&g&&g.mobile&&(e[d]=E),R&&"Macintosh"==e[s]&&f&&typeof f.standalone!==r&&f.maxTouchPoints&&f.maxTouchPoints>2&&(e[s]="iPad",e[d]=m),e},this.getEngine=function(){var e={};return e[c]=t,e[h]=t,X.call(e,S,T.engine),e},this.getOS=function(){var e={};return e[c]=t,e[h]=t,X.call(e,S,T.os),R&&!e[c]&&g&&g.platform&&"Unknown"!=g.platform&&(e[c]=g.platform.replace(/chrome os/i,G).replace(/macos/i,W)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return S},this.setUA=function(e){return S=typeof e===o&&e.length>500?q(e,500):e,this},this.setUA(S),this};$.VERSION="0.7.41",$.BROWSER=K([c,h,a]),$.CPU=K([p]),$.DEVICE=K([s,l,d,_,E,f,m,S,g]),$.ENGINE=$.OS=K([c,h]),p8.exports&&(u=p8.exports=$),u.UAParser=$;var ee=typeof e!==r&&(e.jQuery||e.Zepto);if(ee&&!ee.ua){var et=new $;ee.ua=et.getResult(),ee.ua.get=function(){return et.getUA()},ee.ua.set=function(e){et.setUA(e);var t=et.getResult();for(var i in t)ee.ua[i]=t[i]}}}("object"==typeof window?window:rG);var p9=rW(p8.exports);oI({global:!0,bind:!0,enumerable:!0,forced:rZ.clearImmediate!==cD},{clearImmediate:cD});var p7=rZ.Function,_e=/MSIE .\./.test(nC)||"BUN"===at&&((p=rZ.Bun.version.split(".")).length<3||"0"===p[0]&&(p[1]<3||"3"===p[1]&&"0"===p[2])),_t=rZ.setImmediate?(_=1,_e?function(e,t){var i=c_(arguments.length,1)>_,r=r9(e)?e:p7(e),n=i?cu(arguments,_):[],o=i?function(){r2(r,this,n)}:r;return cN(o)}:cN):cN;oI({global:!0,bind:!0,enumerable:!0,forced:rZ.setImmediate!==_t},{setImmediate:_t});var _i=rW(nf.setImmediate);oI({global:!0,enumerable:!0,dontCallGetSet:!0,forced:rH(function(){return ne&&1!==Object.getOwnPropertyDescriptor(rZ,"queueMicrotask").value.length})},{queueMicrotask:function(e){c_(arguments.length,1),cJ(nU(e))}});var _r=rW(nf.queueMicrotask);function _n(e,t){return function(){return e.apply(t,arguments)}}let{toString:_o}=Object.prototype,{getPrototypeOf:_a}=Object,{iterator:_s,toStringTag:_c}=Symbol,_d=(ts=Object.create(null),e=>{let t=_o.call(e);return ts[t]||(ts[t]=t.slice(8,-1).toLowerCase())}),_l=e=>(e=e.toLowerCase(),t=>_d(t)===e),_h=e=>t=>typeof t===e,{isArray:_u}=Array,_p=_h("undefined");function __(e){return null!==e&&!_p(e)&&null!==e.constructor&&!_p(e.constructor)&&_f(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}let _E=_l("ArrayBuffer"),_m=_h("string"),_f=_h("function"),_S=_h("number"),_g=e=>null!==e&&"object"==typeof e,_T=e=>{if("object"!==_d(e))return!1;let t=_a(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||_c in e||_s in e)},_R=_l("Date"),_C=_l("File"),_v=_l("Blob"),_y=_l("FileList"),_I=_l
1("URLSearchParams"),[_A,_b,_O,_w]=["ReadableStream","Request","Response","Headers"].map(_l);function _N(e,t){let i,r,{allOwnKeys:n=!1}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(null!=e)if("object"!=typeof e&&(e=[e]),_u(e))for(i=0,r=e.length;i<r;i++)t.call(null,e[i],i,e);else{let r;if(__(e))return;let o=n?Object.getOwnPropertyNames(e):Object.keys(e),a=o.length;for(i=0;i<a;i++)r=o[i],t.call(null,e[r],r,e)}}function _D(e,t){if(__(e))return null;t=t.toLowerCase();let i=Object.keys(e),r,n=i.length;for(;n-- >0;)if(t===(r=i[n]).toLowerCase())return r;return null}let _P=void 0!==p6?p6:"undefined"!=typeof self?self:"undefined"!=typeof window?window:i.g,_L=e=>!_p(e)&&e!==_P,_k=(tc="undefined"!=typeof Uint8Array&&_a(Uint8Array),e=>tc&&e instanceof tc),_M=_l("HTMLFormElement"),_U=(e=>{let{hasOwnProperty:t}=e;return(e,i)=>t.call(e,i)})(Object.prototype),_x=_l("RegExp"),_V=(e,t)=>{let i=Object.getOwnPropertyDescriptors(e),r={};_N(i,(i,n)=>{let o;!1!==(o=t(i,n,e))&&(r[n]=o||i)}),Object.defineProperties(e,r)},_F=_l("AsyncFunction"),_B=(td="function"==typeof _i,tl=_f(_P.postMessage),td?_i:tl?(th="axios@".concat(Math.random()),tu=[],_P.addEventListener("message",e=>{let{source:t,data:i}=e;t===_P&&i===th&&tu.length&&tu.shift()()},!1),e=>{tu.push(e),_P.postMessage(th,"*")}):e=>setTimeout(e)),_j=void 0!==_r?_r.bind(_P):void 0!==r&&r.nextTick||_B;var _G={isArray:_u,isArrayBuffer:_E,isBuffer:__,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||_f(e.append)&&("formdata"===(t=_d(e))||"object"===t&&_f(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&_E(e.buffer)},isString:_m,isNumber:_S,isBoolean:e=>!0===e||!1===e,isObject:_g,isPlainObject:_T,isEmptyObject:e=>{if(!_g(e)||__(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(e){return!1}},isReadableStream:_A,isRequest:_b,isResponse:_O,isHeaders:_w,isUndefined:_p,isDate:_R,isFile:_C,isBlob:_v,isRegExp:_x,isFunction:_f,isStream:e=>_g(e)&&_f(e.pipe),isURLSearchParams:_I,isTypedArray:_k,isFileList:_y,forEach:_N,merge:function e(){let{caseless:t,skipUndefined:i}=_L(this)&&this||{},r={},n=(n,o)=>{let a=t&&_D(r,o)||o;_T(r[a])&&_T(n)?r[a]=e(r[a],n):_T(n)?r[a]=e({},n):_u(n)?r[a]=n.slice():i&&_p(n)||(r[a]=n)};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&_N(arguments[e],n);return r},extend:function(e,t,i){let{allOwnKeys:r}=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return _N(t,(t,r)=>{i&&_f(t)?e[r]=_n(t,i):e[r]=t},{allOwnKeys:r}),e},trim:e=>py(e)?py(e).call(e):e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,i,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),i&&Object.assign(e.prototype,i)},toFlatObject:(e,t,i,r)=>{let n,o,a,s={};if(t=t||{},null==e)return t;do{for(o=(n=Object.getOwnPropertyNames(e)).length;o-- >0;)a=n[o],r&&!r(a,e,t)||s[a]||(t[a]=e[a],s[a]=!0);e=!1!==i&&_a(e)}while(e&&(!i||i(e,t))&&e!==Object.prototype);return t},kindOf:_d,kindOfTest:_l,endsWith:(e,t,i)=>{e=String(e),(void 0===i||i>e.length)&&(i=e.length),i-=t.length;let r=e.indexOf(t,i);return -1!==r&&r===i},toArray:e=>{if(!e)return null;if(_u(e))return e;let t=e.length;if(!_S(t))return null;let i=Array(t);for(;t-- >0;)i[t]=e[t];return i},forEachEntry:(e,t)=>{let i,r=(e&&e[_s]).call(e);for(;(i=r.next())&&!i.done;){let r=i.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let i,r=[];for(;null!==(i=e.exec(t));)r.push(i);return r},isHTMLForm:_M,hasOwnProperty:_U,hasOwnProp:_U,reduceDescriptors:_V,freezeMethods:e=>{_V(e,(t,i)=>{if(_f(e)&&-1!==["arguments","caller","callee"].indexOf(i))return!1;_f(e[i])&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+i+"'")}))})},toObjectSet:(e,t)=>{let i={};return(_u(e)?e:String(e).split(t)).forEach(e=>{i[e]=!0}),i},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,i){return t.toUpperCase()+i}),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e*=1)?e:t,findKey:_D,global:_P,isContextDefined:_L,isSpecCompliantForm:function(e){return!!(e&&_f(e.append)&&"FormData"===e[_c]&&e[_s])},toJSONObject:e=>{let t=Array(10),i=(e,r)=>{if(_g(e)){if(t.indexOf(e)>=0)return;if(__(e))return e;if(!("toJSON"in e)){t[r]=e;let n=_u(e)?[]:{};return _N(e,(e,t)=>{let o=i(e,r+1);_p(o)||(n[t]=o)}),t[r]=void 0,n}}return e};return i(e,0)},isAsyncFn:_F,isThenable:e=>e&&(_g(e)||_f(e))&&_f(e.then)&&_f(e.catch),setImmediate:_B,asap:_j,isIterable:e=>null!=e&&_f(e[_s])};function _W(e,t,i,r,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),i&&(this.config=i),r&&(this.request=r),n&&(this.response=n,this.status=n.status?n.status:null)}_G.inherits(_W,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:_G.toJSONObject(this.config),code:this.code,status:this.status}}});let _H=_W.prototype,_K={};function _Y(e){return _G.isPlainObject(e)||_G.isArray(e)}function _z(e){return _G.endsWith(e,"[]")?e.slice(0,-2):e}function _q(e,t,i){return e?e.concat(t).map(function(e,t){return e=_z(e),!i&&t?"["+e+"]":e}).join(i?".":""):t}["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","E
1RR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{_K[e]={value:e}}),Object.defineProperties(_W,_K),Object.defineProperty(_H,"isAxiosError",{value:!0}),_W.from=(e,t,i,r,n,o)=>{let a=Object.create(_H);_G.toFlatObject(e,a,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e);let s=e&&e.message?e.message:"Error",c=null==t&&e?e.code:t;return _W.call(a,s,c,i,r,n),e&&null==a.cause&&Object.defineProperty(a,"cause",{value:e,configurable:!0}),a.name=e&&e.name||"Error",o&&Object.assign(a,o),a};let _X=_G.toFlatObject(_G,{},null,function(e){return/^is[A-Z]/.test(e)});function _J(e,t,i){if(!_G.isObject(e))throw TypeError("target must be an object");t=t||new FormData;let r=(i=_G.toFlatObject(i,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!_G.isUndefined(t[e])})).metaTokens,o=i.visitor||l,a=i.dots,s=i.indexes,c=(i.Blob||"undefined"!=typeof Blob&&Blob)&&_G.isSpecCompliantForm(t);if(!_G.isFunction(o))throw TypeError("visitor must be a function");function d(e){if(null===e)return"";if(_G.isDate(e))return e.toISOString();if(_G.isBoolean(e))return e.toString();if(!c&&_G.isBlob(e))throw new _W("Blob is not supported. Use a Buffer instead.");return _G.isArrayBuffer(e)||_G.isTypedArray(e)?c&&"function"==typeof Blob?new Blob([e]):n.from(e):e}function l(e,i,n){let o=e;if(e&&!n&&"object"==typeof e)if(_G.endsWith(i,"{}"))i=r?i:i.slice(0,-2),e=JSON.stringify(e);else{var c;if(_G.isArray(e)&&(c=e,_G.isArray(c)&&!c.some(_Y))||(_G.isFileList(e)||_G.endsWith(i,"[]"))&&(o=_G.toArray(e)))return i=_z(i),o.forEach(function(e,r){_G.isUndefined(e)||null===e||t.append(!0===s?_q([i],r,a):null===s?i:i+"[]",d(e))}),!1}return!!_Y(e)||(t.append(_q(n,i,a),d(e)),!1)}let h=[],u=Object.assign(_X,{defaultVisitor:l,convertValue:d,isVisitable:_Y});if(!_G.isObject(e))throw TypeError("data must be an object");return function e(i,r){if(!_G.isUndefined(i)){if(-1!==h.indexOf(i))throw Error("Circular reference detected in "+r.join("."));h.push(i),_G.forEach(i,function(i,n){!0===(!(_G.isUndefined(i)||null===i)&&o.call(t,i,_G.isString(n)?py(n).call(n):n,r,u))&&e(i,r?r.concat(n):[n])}),h.pop()}}(e),t}function _Q(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function _Z(e,t){this._pairs=[],e&&_J(e,this,t)}let _$=_Z.prototype;function _0(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function _1(e,t,i){let r;if(!t)return e;let n=i&&i.encode||_0;_G.isFunction(i)&&(i={serialize:i});let o=i&&i.serialize;if(r=o?o(t,i):_G.isURLSearchParams(t)?t.toString():new _Z(t,i).toString(n)){let t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+r}return e}_$.append=function(e,t){this._pairs.push([e,t])},_$.toString=function(e){let t=e?function(t){return e.call(this,t,_Q)}:_Q;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};var _2=class{use(e,t,i){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!i&&i.synchronous,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){_G.forEach(this.handlers,function(t){null!==t&&e(t)})}constructor(){this.handlers=[]}},_3={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},_5={exports:{}},_4=oh.f;oI({target:"Object",stat:!0,forced:Object.defineProperty!==_4,sham:!ne},{defineProperty:_4});var _6=nf.Object,_8=_5.exports=function(e,t,i){return _6.defineProperty(e,t,i)};_6.defineProperty.sham&&(_8.sham=!0);var _9=rW(_5.exports),_7=TypeError,Ee=n2("species"),Et=Array,Ei=function(e){var t;return ac(e)&&(cs(t=e.constructor)&&(t===Et||ac(t.prototype))||nm(t)&&null===(t=t[Ee]))&&(t=void 0),void 0===t?Et:t},Er=function(e,t){return new(Ei(e))(0===t?0:t)},En=n2("species"),Eo=function(e){return nb>=51||!rH(function(){var t=[];return(t.constructor={})[En]=function(){return{foo:1}},1!==t[e](Boolean).foo})},Ea=function(e){if(e>0x1fffffffffffff)throw _7("Maximum allowed index exceeded");return e},Es=n2("isConcatSpreadable"),Ec=nb>=51||!rH(function(){var e=[];return e[Es]=!1,e.concat()[0]!==e}),Ed=function(e){if(!nm(e))return!1;var t=e[Es];return void 0!==t?!!t:ac(e)};oI({target:"Array",proto:!0,arity:1,forced:!Ec||!Eo("concat")},{concat:function(e){var t,i,r,n,o,a=nY(this),s=Er(a,0),c=0;for(t=-1,r=arguments.length;t<r;t++)if(Ed(o=-1===t?a:arguments[t]))for(Ea(c+(n=oM(o))),i=0;i<n;i++,c++)i in o&&hr(s,c,o[i]);else Ea(c+1),hr(s,c++,o);return s.length=c,s}});var El={},Eh=ab.f,Eu="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];El.f=function(e){return Eu&&"Window"===r4(e)?function(e){try{return Eh(e)}catch(e){return cu(Eu)}}(e):Eh(nE(e))};var Ep={};Ep.f=n2;var E_=oh.f,EE=function(e){var t=nf.Symbol||(nf.Symbol={});nq(t,e)||E_(t,e,{value:Ep.f(e)})},Em=function(){var e=ng("Symbol"),t=e&&e.prototype,i=t&&t.valueOf,r=n2("toPrimitive");t&&!t[r]&&sP(t,r,function(e){return ni(i,this)},{arity:1}
1)},Ef=rX([].push),ES=function(e){var t=1===e,i=2===e,r=3===e,n=4===e,o=6===e,a=7===e,s=5===e||o;return function(c,d,l,h){for(var u,p,_=nY(c),E=nh(_),m=oM(E),f=ol(d,l),S=0,g=h||Er,T=t?g(c,m):i||a?g(c,0):void 0;m>S;S++)if((s||S in E)&&(p=f(u=E[S],S,_),e))if(t)T[S]=p;else if(p)switch(e){case 3:return!0;case 5:return u;case 6:return S;case 2:Ef(T,u)}else switch(e){case 4:return!1;case 7:Ef(T,u)}return o?-1:r||n?n:T}},Eg={forEach:ES(0),map:ES(1),filter:ES(2),some:ES(3),every:ES(4),find:ES(5),findIndex:ES(6),filterReject:ES(7)},ET=Eg.forEach,ER=am("hidden"),EC="Symbol",Ev="prototype",Ey=sb(EC),EI=Object[Ev],EA=rZ.Symbol,Eb=EA&&EA[Ev],EO=rZ.RangeError,Ew=rZ.TypeError,EN=rZ.QObject,ED=r7.f,EP=oh.f,EL=El.f,Ek=nr.f,EM=rX([].push),EU=nH("symbols"),Ex=nH("op-symbols"),EV=nH("wks"),EF=!EN||!EN[Ev]||!EN[Ev].findChild,EB=function(e,t,i){var r=ED(EI,t);r&&delete EI[t],EP(e,t,i),r&&e!==EI&&EP(EI,t,r)},Ej=ne&&rH(function(){return 7!==aq(EP({},"a",{get:function(){return EP(this,"a",{value:7}).a}})).a})?EB:EP,EG=function(e,t){var i=EU[e]=aq(Eb);return sA(i,{type:EC,tag:e,description:t}),ne||(i.description=t),i},EW=function(e,t,i){e===EI&&EW(Ex,t,i),oE(e);var r=n8(t);return oE(i),nq(EU,r)?(i.enumerable?(nq(e,ER)&&e[ER][r]&&(e[ER][r]=!1),i=aq(i,{enumerable:nc(0,!1)})):(nq(e,ER)||EP(e,ER,nc(1,aq(null))),e[ER][r]=!0),Ej(e,r,i)):EP(e,r,i)},EH=function(e,t){oE(e);var i=nE(t);return ET(aV(i).concat(Eq(i)),function(t){ne&&!ni(EK,i,t)||EW(e,t,i[t])}),e},EK=function(e){var t=n8(e),i=ni(Ek,this,t);return!(this===EI&&nq(EU,t)&&!nq(Ex,t))&&(!(i||!nq(this,t)||!nq(EU,t)||nq(this,ER)&&this[ER][t])||i)},EY=function(e,t){var i=nE(e),r=n8(t);if(i!==EI||!nq(EU,r)||nq(Ex,r)){var n=ED(i,r);return!n||!nq(EU,r)||nq(i,ER)&&i[ER][r]||(n.enumerable=!0),n}},Ez=function(e){var t=EL(nE(e)),i=[];return ET(t,function(e){nq(EU,e)||nq(aO,e)||EM(i,e)}),i},Eq=function(e){var t=e===EI,i=EL(t?Ex:nE(e)),r=[];return ET(i,function(e){nq(EU,e)&&(!t||nq(EI,e))&&EM(r,EU[e])}),r};nw||(sP(Eb=(EA=function(){if(rJ(Eb,this))throw new Ew("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?oQ(arguments[0]):void 0,t=nZ(e),i=function(e){var r=void 0===this?rZ:this;r===EI&&ni(i,Ex,e),nq(r,ER)&&nq(r[ER],t)&&(r[ER][t]=!1);var n=nc(1,e);try{Ej(r,t,n)}catch(e){if(!(e instanceof EO))throw e;EB(r,t,n)}};return ne&&EF&&Ej(EI,t,{configurable:!0,set:i}),EG(t,e)})[Ev],"toString",function(){return Ey(this).tag}),sP(EA,"withoutSetter",function(e){return EG(nZ(e),e)}),nr.f=EK,oh.f=EW,ax.f=EH,r7.f=EY,ab.f=El.f=Ez,ak.f=Eq,Ep.f=function(e){return EG(n2(e),e)},ne&&s0(Eb,"description",{configurable:!0,get:function(){return Ey(this).description}})),oI({global:!0,constructor:!0,wrap:!0,forced:!nw,sham:!nw},{Symbol:EA}),ET(aV(EV),function(e){EE(e)}),oI({target:EC,stat:!0,forced:!nw},{useSetter:function(){EF=!0},useSimple:function(){EF=!1}}),oI({target:"Object",stat:!0,forced:!nw,sham:!ne},{create:function(e,t){return void 0===t?aq(e):EH(aq(e),t)},defineProperty:EW,defineProperties:EH,getOwnPropertyDescriptor:EY}),oI({target:"Object",stat:!0,forced:!nw},{getOwnPropertyNames:Ez}),Em(),sB(EA,EC),aO[ER]=!0;var EX=nw&&!!Symbol.for&&!!Symbol.keyFor,EJ=nH("string-to-symbol-registry"),EQ=nH("symbol-to-string-registry");oI({target:"Symbol",stat:!0,forced:!EX},{for:function(e){var t=oQ(e);if(nq(EJ,t))return EJ[t];var i=ng("Symbol")(t);return EJ[t]=i,EQ[i]=t,i}});var EZ=nH("symbol-to-string-registry");oI({target:"Symbol",stat:!0,forced:!EX},{keyFor:function(e){if(!nP(e))throw TypeError(nk(e)+" is not a symbol");if(nq(EZ,e))return EZ[e]}});var E$=rX([].push),E0=function(e){if(r9(e))return e;if(ac(e)){for(var t=e.length,i=[],r=0;r<t;r++){var n=e[r];"string"==typeof n?E$(i,n):"number"!=typeof n&&"Number"!==r4(n)&&"String"!==r4(n)||E$(i,oQ(n))}var o=i.length,a=!0;return function(e,t){if(a)return a=!1,t;if(ac(this))return t;for(var r=0;r<o;r++)if(i[r]===e)return t}}},E1=String,E2=ng("JSON","stringify"),E3=rX(/./.exec),E5=rX("".charAt),E4=rX("".charCodeAt),E6=rX("".replace),E8=rX(1.1.toString),E9=/[\uD800-\uDFFF]/g,E7=/^[\uD800-\uDBFF]$/,me=/^[\uDC00-\uDFFF]$/,mt=!nw||rH(function(){var e=ng("Symbol")("stringify detection");return"[null]"!==E2([e])||"{}"!==E2({a:e})||"{}"!==E2(Object(e))}),mi=rH(function(){return'"\udf06\ud834"'!==E2("\udf06\ud834")||'"\udead"'!==E2("\udead")}),mr=function(e,t){var i=cu(arguments),r=E0(t);
1if(r9(r)||void 0!==e&&!nP(e))return i[1]=function(e,t){if(r9(r)&&(t=ni(r,this,E1(e),t)),!nP(t))return t},r2(E2,null,i)},mn=function(e,t,i){var r=E5(i,t-1),n=E5(i,t+1);return E3(E7,e)&&!E3(me,n)||E3(me,e)&&!E3(E7,r)?"\\u"+E8(E4(e,0),16):e};E2&&oI({target:"JSON",stat:!0,arity:3,forced:mt||mi},{stringify:function(e,t,i){var r=cu(arguments),n=r2(mt?mr:E2,null,r);return mi&&"string"==typeof n?E6(n,E9,mn):n}}),oI({target:"Object",stat:!0,forced:!nw||rH(function(){ak.f(1)})},{getOwnPropertySymbols:function(e){var t=ak.f;return t?t(nY(e)):[]}}),EE("asyncDispose"),EE("asyncIterator"),EE("dispose"),EE("hasInstance"),EE("isConcatSpreadable"),EE("iterator"),EE("match"),EE("matchAll"),EE("replace"),EE("search"),EE("species"),EE("split"),EE("toPrimitive"),Em(),EE("toStringTag"),sB(ng("Symbol"),"Symbol"),EE("unscopables"),sB(rZ.JSON,"JSON",!0);var mo=nf.Symbol,ma=oh.f,ms=n2("metadata"),mc=Function.prototype;void 0===mc[ms]&&ma(mc,ms,{value:null}),EE("metadata");var md=ng("Symbol"),ml=md.keyFor,mh=rX(md.prototype.valueOf),mu=md.isRegisteredSymbol||function(e){try{return void 0!==ml(mh(e))}catch(e){return!1}};oI({target:"Symbol",stat:!0},{isRegisteredSymbol:mu});for(var mp=ng("Symbol"),m_=mp.isWellKnownSymbol,mE=ng("Object","getOwnPropertyNames"),mm=rX(mp.prototype.valueOf),mf=nH("wks"),mS=0,mg=mE(mp),mT=mg.length;mS<mT;mS++)try{var mR=mg[mS];nP(mp[mR])&&n2(mR)}catch(e){}var mC=function(e){if(m_&&m_(e))return!0;try{for(var t=mm(e),i=0,r=mE(mf),n=r.length;i<n;i++)if(mf[r[i]]==t)return!0}catch(e){}return!1};oI({target:"Symbol",stat:!0,forced:!0},{isWellKnownSymbol:mC}),EE("customMatcher"),EE("observable"),oI({target:"Symbol",stat:!0,name:"isRegisteredSymbol"},{isRegistered:mu}),oI({target:"Symbol",stat:!0,name:"isWellKnownSymbol",forced:!0},{isWellKnown:mC}),EE("matcher"),EE("metadataKey"),EE("patternMatch"),EE("replaceAll");var mv=rW(mo),my=rW(Ep.f("iterator"));function mI(e){return(mI="function"==typeof mv&&"symbol"==typeof my?function(e){return typeof e}:function(e){return e&&"function"==typeof mv&&e.constructor===mv&&e!==mv.prototype?"symbol":typeof e})(e)}var mA=rW(Ep.f("toPrimitive"));function mb(e,t,i){var r;return(r=function(e,t){if("object"!=mI(e)||!e)return e;var i=e[mA];if(void 0!==i){var r=i.call(e,t||"default");if("object"!=mI(r))return r;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(t,"string"),(t="symbol"==mI(r)?r:r+"")in e)?_9(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}var mO=rW(l9),mw={isBrowser:!0,classes:{URLSearchParams:void 0!==mO?mO:_Z,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};let mN="undefined"!=typeof window&&"undefined"!=typeof document,mD="object"==typeof navigator&&navigator||void 0,mP=mN&&(!mD||0>["ReactNative","NativeScript","NS"].indexOf(mD.product)),mL="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,mk=mN&&window.location.href||"http://localhost";function mM(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function mU(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?mM(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):mM(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}var mx=mU(mU({},Object.freeze({__proto__:null,hasBrowserEnv:mN,hasStandardBrowserEnv:mP,hasStandardBrowserWebWorkerEnv:mL,navigator:mD,origin:mk})),mw);function mV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}var mF=dH.charAt,mB=/./.exec,mj=TypeError,mG=function(e,t){var i=e.exec;if(r9(i)){var r=ni(i,e,t);return null!==r&&oE(r),r}if("RegExp"===r4(e))return ni(mB,e,t);throw new mj("RegExp#exec called on incompatible receiver")},mW=n2("matchAll"),mH="RegExp String",mK=mH+" Iterator",mY=sb(mK),mz=TypeError,mq=r6("".indexOf),mX=r6("".matchAll),mJ=!!mX&&!rH(function(){mX("a",/./)}),mQ=sG(function(e,t,i,r){sA(this,{type:mK,regexp:e,string:t,global:i,unicode:r,done:!1})},mH,function(){var e,t=mY(this);if(t.done)return sQ(void 0,!0);var i=t.regexp,r=t.string,n=mG(i,r);return null===n?(t.done=!0,sQ(void 0,!0)):(t.global?""===oQ(n[0])&&(e=ok(i.lastIndex),i.lastIndex=e+(t.unicode?mF(r,e).length:1)):t.done=!0,sQ(n,!1))}),mZ=function(e){var t,i,r,n=oE(this),o=oQ(e),a=ch(n,RegExp),s=oQ(pW(n));return t=new a(a===RegExp?n.source:n,s),i=!!~mq(s,"g"),r=!!~mq(s,"u"),t.lastIndex=ok(n.lastIndex),new mQ(t,o,i,r)};oI({target:"String",proto:!0,forced:mJ},{matchAll:function(e){var t,i,r=n_(this);if(nm(e)){if(oG(e)&&!~mq(oQ(n_(pW(e))),"g"))throw new mz("`.matchAll` does not allow non-global regexes");if(mJ)return mX(r,e);if(void 0===(i=nx(e,mW))&&"RegExp"===r4(e)&&(i=mZ),i)return ni(i,e,r)}else if(mJ)return mX(r,e);return t=oQ(r),ni(mZ,RegExp(e,"g"),t)}});var m$=oF("String","matchAll"),m0=String.prototype,m1=rW(function(e){var t=e.matchAll;return"string"==typeof e||e===m0||rJ(m0,e)&&t===m0.matchAll?m$:t});function m2(e){if(_G.isFormData(e)&&_G.isFunction(e.entries)){let t={};return _G.forEachEntry(e,(e,i)=>{!function e(t,i,r,n){let o=t[n++];if("__proto__"===o)return!0;let a=Number.isFinite(+o),s=n>=t.length;return(o=!o&&_G.isArray(r)?r.length:o,s)?_G.hasOwnProp(r,o)?r[o]=[r[o],i]:r[o]=i:(r[o]&&_G.isObject(r[o])||(r[o]=[]),e(t,i,r[o],n)&&_G.isArray(r[o])&&(r[o]=function(e){let t,i,r={},n=Object.keys(e),o=n.length;for(t=0;t<o;t++)r[i=n[t]]=e[i];return r}(r[o]))),!a}(m1(_G).call(_G,/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0]),i,t,0)}),t}return null}let m3={transitional:_3,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){let i,r=t.getContentType()||"",n=r.indexOf("application/json")>-1,o=_G.isObject(e);
1if(o&&_G.isHTMLForm(e)&&(e=new FormData(e)),_G.isFormData(e))return n?JSON.stringify(m2(e)):e;if(_G.isArrayBuffer(e)||_G.isBuffer(e)||_G.isStream(e)||_G.isFile(e)||_G.isBlob(e)||_G.isReadableStream(e))return e;if(_G.isArrayBufferView(e))return e.buffer;if(_G.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1){var a,s;return(a=e,s=this.formSerializer,_J(a,new mx.classes.URLSearchParams,function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?mV(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):mV(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}({visitor:function(e,t,i,r){return mx.isNode&&_G.isBuffer(e)?(this.append(t,e.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)}},s))).toString()}if((i=_G.isFileList(e))||r.indexOf("multipart/form-data")>-1){let t=this.env&&this.env.FormData;return _J(i?{"files[]":e}:e,t&&new t,this.formSerializer)}}return o||n?(t.setContentType("application/json",!1),function(e,t,i){if(_G.isString(e))try{return(0,JSON.parse)(e),py(_G).call(_G,e)}catch(e){if("SyntaxError"!==e.name)throw e}return(0,JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){let t=this.transitional||m3.transitional,i=t&&t.forcedJSONParsing,r="json"===this.responseType;if(_G.isResponse(e)||_G.isReadableStream(e))return e;if(e&&_G.isString(e)&&(i&&!this.responseType||r)){let i=!(t&&t.silentJSONParsing)&&r;try{return JSON.parse(e,this.parseReviver)}catch(e){if(i){if("SyntaxError"===e.name)throw _W.from(e,_W.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:mx.classes.FormData,Blob:mx.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};_G.forEach(["delete","get","head","post","put","patch"],e=>{m3.headers[e]={}});let m5=_G.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),m4=Symbol("internals");function m6(e){var t;return e&&py(t=String(e)).call(t).toLowerCase()}function m8(e){return!1===e||null==e?e:_G.isArray(e)?e.map(m8):String(e)}function m9(e,t,i,r,n){return _G.isFunction(r)?r.call(this,t,i):(n&&(t=i),_G.isString(t)?_G.isString(r)?-1!==t.indexOf(r):_G.isRegExp(r)?r.test(t):void 0:void 0)}class m7{set(e,t,i){var r;let n=this;function o(e,t,i){let r=m6(t);if(!r)throw Error("header name must be a non-empty string");let o=_G.findKey(n,r);o&&void 0!==n[o]&&!0!==i&&(void 0!==i||!1===n[o])||(n[o||t]=m8(e))}let a=(e,t)=>_G.forEach(e,(e,i)=>o(e,i,t));if(_G.isPlainObject(e)||e instanceof this.constructor)a(e,t);else if(_G.isString(e)&&(e=py(e).call(e))&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(py(r=e).call(r)))a((e=>{let t,i,r,n={};return e&&e.split("\n").forEach(function(e){var o,a;r=e.indexOf(":"),t=py(o=e.substring(0,r)).call(o).toLowerCase(),i=py(a=e.substring(r+1)).call(a),!t||n[t]&&m5[t]||("set-cookie"===t?n[t]?n[t].push(i):n[t]=[i]:n[t]=n[t]?n[t]+", "+i:i)}),n})(e),t);else if(_G.isObject(e)&&_G.isIterable(e)){let i,r,n={};for(let t of e){if(!_G.isArray(t))throw TypeError("Object iterator must return a key-value pair");n[r=t[0]]=(i=n[r])?_G.isArray(i)?[...i,t[1]]:[i,t[1]]:t[1]}a(n,t)}else null!=e&&o(t,e,i);return this}get(e,t){if(e=m6(e)){let i=_G.findKey(this,e);if(i){let e=this[i];if(!t)return e;if(!0===t){let t,i=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
1for(;t=r.exec(e);)i[t[1]]=t[2];return i}if(_G.isFunction(t))return t.call(this,e,i);if(_G.isRegExp(t))return t.exec(e);throw TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=m6(e)){let i=_G.findKey(this,e);return!(!i||void 0===this[i]||t&&!m9(0,this[i],i,t))}return!1}delete(e,t){let i=this,r=!1;function n(e){if(e=m6(e)){let n=_G.findKey(i,e);n&&(!t||m9(0,i[n],n,t))&&(delete i[n],r=!0)}}return _G.isArray(e)?e.forEach(n):n(e),r}clear(e){let t=Object.keys(this),i=t.length,r=!1;for(;i--;){let n=t[i];e&&!m9(0,this[n],n,e,!0)||(delete this[n],r=!0)}return r}normalize(e){let t=this,i={};return _G.forEach(this,(r,n)=>{var o;let a=_G.findKey(i,n);if(a)return t[a]=m8(r),void delete t[n];let s=e?py(n).call(n).toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,i)=>t.toUpperCase()+i):py(o=String(n)).call(o);s!==n&&delete t[n],t[s]=m8(r),i[s]=!0}),this}concat(){for(var e=arguments.length,t=Array(e),i=0;i<e;i++)t[i]=arguments[i];return this.constructor.concat(this,...t)}toJSON(e){let t=Object.create(null);return _G.forEach(this,(i,r)=>{null!=i&&!1!==i&&(t[r]=e&&_G.isArray(i)?i.join(", "):i)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(e=>{let[t,i]=e;return t+": "+i}).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e){let t=new this(e);for(var i=arguments.length,r=Array(i>1?i-1:0),n=1;n<i;n++)r[n-1]=arguments[n];return r.forEach(e=>t.set(e)),t}static accessor(e){let t=(this[m4]=this[m4]={accessors:{}}).accessors,i=this.prototype;function r(e){let r=m6(e);t[r]||(!function(e,t){let i=_G.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+i,{value:function(e,i,n){return this[r].call(this,t,e,i,n)},configurable:!0})})}(i,e),t[r]=!0)}return _G.isArray(e)?e.forEach(r):r(e),this}constructor(e){e&&this.set(e)}}function fe(e,t){let i=this||m3,r=t||i,n=m7.from(r.headers),o=r.data;return _G.forEach(e,function(e){o=e.call(i,o,n.normalize(),t?t.status:void 0)}),n.normalize(),o}function ft(e){return!(!e||!e.__CANCEL__)}function fi(e,t,i){_W.call(this,null==e?"canceled":e,_W.ERR_CANCELED,t,i),this.name="CanceledError"}function fr(e,t,i){let r=i.config.validateStatus;i.status&&r&&!r(i.status)?t(new _W("Request failed with status code "+i.status,[_W.ERR_BAD_REQUEST,_W.ERR_BAD_RESPONSE][Math.floor(i.status/100)-4],i.config,i.request,i)):e(i)}m7.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),_G.reduceDescriptors(m7.prototype,(e,t)=>{let{value:i}=e,r=t[0].toUpperCase()+t.slice(1);return{get:()=>i,set(e){this[r]=e}}}),_G.freezeMethods(m7),_G.inherits(fi,_W,{__CANCEL__:!0});let fn=function(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:3,r=0,n=function(e,t){let i=Array(e=e||10),r=Array(e),n,o=0,a=0;return t=void 0!==t?t:1e3,function(s){let c=Date.now(),d=r[a];n||(n=c),i[o]=s,r[o]=c;let l=a,h=0;for(;l!==o;)h+=i[l++],l%=e;if((o=(o+1)%e)===a&&(a=(a+1)%e),c-n<t)return;let u=d&&c-d;return u?Math.round(1e3*h/u):void 0}}(50,250);return function(e,t){let i,r,n=0,o=1e3/t,a=function(t){let o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();n=o,i=null,r&&(clearTimeout(r),r=null),e(...t)};return[function(){let e=Date.now(),t=e-n;for(var s=arguments.length,c=Array(s),d=0;d<s;d++)c[d]=arguments[d];t>=o?a(c,e):(i=c,r||(r=setTimeout(()=>{r=null,a(i)},o-t)))},()=>i&&a(i)]}(i=>{let o=i.loaded,a=i.lengthComputable?i.total:void 0,s=o-r,c=n(s);r=o,e({loaded:o,total:a,progress:a?o/a:void 0,bytes:s,rate:c||void 0,estimated:c&&a&&o<=a?(a-o)/c:void 0,event:i,lengthComputable:null!=a,[t?"download":"upload"]:!0})},i)},fo=(e,t)=>{let i=null!=e;return[r=>t[0]({lengthComputable:i,total:e,loaded:r}),t[1]]},fa=e=>function(){for(var t=arguments.length,i=Array(t),r=0;r<t;r++)i[r]=arguments[r];return _G.asap(()=>e(...i))};var fs=mx.hasStandardBrowserEnv?(c=new uk(mx.origin),d=mx.navigator&&/(msie|trident)/i.test(mx.navigator.userAgent),e=>(e=new uk(e,mx.origin),c.protocol===e.protocol&&c.host===e.host&&(d||c.port===e.port))):()=>!0,fc=mx.hasStandardBrowserEnv?{write(e,t,i,r,n,o,a){if("undefined"==typeof document)return;let s=["".concat(e,"=").concat(encodeURIComponent(t))];_G.isNumber(i)&&s.push("expires=".concat(new Date(i).toUTCString())),_G.isString(r)&&s.push("path=".concat(r)),_G.isString(n)&&s.push("domain=".concat(n)),!0===o&&s.push("secure"),_G.isString(a)&&s.push("SameSite=".concat(a)),document.cookie=s.join("; ")},read(e){if("undefined"==typeof document)return null;let t=document.cookie.match(RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read:()=>null,remove(){}};function fd(e,t,i){let r=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(r||0==i)?t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e:t}function fl(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function fh(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
1t%2?fl(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):fl(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let fu=e=>e instanceof m7?fh({},e):e;function fp(e,t){t=t||{};let i={};function r(e,t,i,r){return _G.isPlainObject(e)&&_G.isPlainObject(t)?_G.merge.call({caseless:r},e,t):_G.isPlainObject(t)?_G.merge({},t):_G.isArray(t)?t.slice():t}function n(e,t,i,n){return _G.isUndefined(t)?_G.isUndefined(e)?void 0:r(void 0,e,0,n):r(e,t,0,n)}function o(e,t){if(!_G.isUndefined(t))return r(void 0,t)}function a(e,t){return _G.isUndefined(t)?_G.isUndefined(e)?void 0:r(void 0,e):r(void 0,t)}function s(i,n,o){return o in t?r(i,n):o in e?r(void 0,i):void 0}let c={url:o,method:o,data:o,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:s,headers:(e,t,i)=>n(fu(e),fu(t),0,!0)};return _G.forEach(Object.keys(fh(fh({},e),t)),function(r){let o=c[r]||n,a=o(e[r],t[r],r);_G.isUndefined(a)&&o!==s||(i[r]=a)}),i}var f_=e=>{let t=fp({},e),{data:i,withXSRFToken:r,xsrfHeaderName:n,xsrfCookieName:o,headers:a,auth:s}=t;if(t.headers=a=m7.from(a),t.url=_1(fd(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),s&&a.set("Authorization","Basic "+btoa((s.username||"")+":"+(s.password?unescape(encodeURIComponent(s.password)):""))),_G.isFormData(i)){if(mx.hasStandardBrowserEnv||mx.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(_G.isFunction(i.getHeaders)){let e=i.getHeaders(),t=["content-type","content-length"];Object.entries(e).forEach(e=>{let[i,r]=e;o5(t).call(t,i.toLowerCase())&&a.set(i,r)})}}if(mx.hasStandardBrowserEnv&&(r&&_G.isFunction(r)&&(r=r(t)),r||!1!==r&&fs(t.url))){let e=n&&o&&fc.read(o);e&&a.set(n,e)}return t},fE="undefined"!=typeof XMLHttpRequest&&function(e){return new dQ(function(t,i){let r=f_(e),n=r.data,o=m7.from(r.headers).normalize(),a,s,c,d,l,{responseType:h,onUploadProgress:u,onDownloadProgress:p}=r;function _(){d&&d(),l&&l(),r.cancelToken&&r.cancelToken.unsubscribe(a),r.signal&&r.signal.removeEventListener("abort",a)}let E=new XMLHttpRequest;function m(){if(!E)return;let r=m7.from("getAllResponseHeaders"in E&&E.getAllResponseHeaders());fr(function(e){t(e),_()},function(e){i(e),_()},{data:h&&"text"!==h&&"json"!==h?E.response:E.responseText,status:E.status,statusText:E.statusText,headers:r,config:e,request:E}),E=null}E.open(r.method.toUpperCase(),r.url,!0),E.timeout=r.timeout,"onloadend"in E?E.onloadend=m:E.onreadystatechange=function(){E&&4===E.readyState&&(0!==E.status||E.responseURL&&0===E.responseURL.indexOf("file:"))&&setTimeout(m)},E.onabort=function(){E&&(i(new _W("Request aborted",_W.ECONNABORTED,e,E)),E=null)},E.onerror=function(t){let r=new _W(t&&t.message?t.message:"Network Error",_W.ERR_NETWORK,e,E);r.event=t||null,i(r),E=null},E.ontimeout=function(){let t=r.timeout?"timeout of "+r.timeout+"ms exceeded":"timeout exceeded",n=r.transitional||_3;r.timeoutErrorMessage&&(t=r.timeoutErrorMessage),i(new _W(t,n.clarifyTimeoutError?_W.ETIMEDOUT:_W.ECONNABORTED,e,E)),E=null},void 0===n&&o.setContentType(null),"setRequestHeader"in E&&_G.forEach(o.toJSON(),function(e,t){E.setRequestHeader(t,e)}),_G.isUndefined(r.withCredentials)||(E.withCredentials=!!r.withCredentials),h&&"json"!==h&&(E.responseType=r.responseType),p&&([c,l]=fn(p,!0),E.addEventListener("progress",c)),u&&E.upload&&([s,d]=fn(u),E.upload.addEventListener("progress",s),E.upload.addEventListener("loadend",d)),(r.cancelToken||r.signal)&&(a=t=>{E&&(i(!t||t.type?new fi(null,e,E):t),E.abort(),E=null)},r.cancelToken&&r.cancelToken.subscribe(a),r.signal&&(r.signal.aborted?a():r.signal.addEventListener("abort",a)));let f=function(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(r.url);f&&-1===mx.protocols.indexOf(f)?i(new _W("Unsupported protocol "+f+":",_W.ERR_BAD_REQUEST,e)):E.send(n||null)})},fm=rW(dq),ff=Ep.f("asyncIterator"),fS=rW(ff);function fg(e,t){this.v=e,this.k=t}function fT(e){return function(){return new fR(e.apply(this,arguments))}}function fR(e){var t,i;function r(t,i){try{var o=e[t](i),a=o.value,s=a instanceof fg;fm.resolve(s?a.v:a).then(function(i){if(s){var c="return"===t?"return":"next";if(!a.k||i.done)return r(c,i);i=e[c](i).value}n(o.done?"return":"normal",i)},function(e){r("throw",e)})}catch(e){n("throw",e)}}function n(e,n){switch(e){case"return":t.resolve({value:n,done:!0});break;case"throw":t.reject(n);break;default:t.resolve({value:n,done:!1})}(t=t.next)?r(t.key,t.arg):i=null}this._invoke=function(e,n){return new fm(function(o,a){var s={key:e,arg:n,resolve:o,reject:a,next:null};i?i=i.next=s:(t=i=s,r(e,n))})}
1,"function"!=typeof e.return&&(this.return=void 0)}function fC(e){return new fg(e,0)}function fv(e){var t={},i=!1;function r(t,r){return i=!0,{done:!1,value:new fg(r=new fm(function(i){i(e[t](r))}),1)}}return t[void 0!==mv&&my||"@@iterator"]=function(){return this},t.next=function(e){return i?(i=!1,e):r("next",e)},"function"==typeof e.throw&&(t.throw=function(e){if(i)throw i=!1,e;return r("throw",e)}),"function"==typeof e.return&&(t.return=function(e){return i?(i=!1,e):r("return",e)}),t}fR.prototype["function"==typeof mv&&fS||"@@asyncIterator"]=function(){return this},fR.prototype.next=function(e){return this._invoke("next",e)},fR.prototype.throw=function(e){return this._invoke("throw",e)},fR.prototype.return=function(e){return this._invoke("return",e)};var fy=rW(ff);function fI(e){var t,i,r,n=2;for("undefined"!=typeof Symbol&&(i=fy,r=Symbol.iterator);n--;){if(i&&null!=(t=e[i]))return t.call(e);if(r&&null!=(t=e[r]))return new fA(t.call(e));i="@@asyncIterator",r="@@iterator"}throw TypeError("Object is not async iterable")}function fA(e){function t(e){if(Object(e)!==e)return dQ.reject(TypeError(e+" is not an object."));var t=e.done;return dQ.resolve(e.value).then(function(e){return{value:e,done:t}})}return(fA=function(e){this.s=e,this.n=e.next}).prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var i=this.s.return;return void 0===i?dQ.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?dQ.reject(e):t(i.apply(this.s,arguments))}},new fA(e)}let fb=function*(e,t){let i=e.byteLength;if(!t||i<t)return void(yield e);let r,n=0;for(;n<i;)r=n+t,yield e.slice(n,r),n=r},fO=(E=fT(function*(e,t){var i,r=!1,n=!1;try{for(var o,a=fI(fw(e));r=!(o=yield fC(a.next())).done;r=!1){let e=o.value;yield*fv(fI(fb(e,t)))}}catch(e){n=!0,i=e}finally{try{r&&null!=a.return&&(yield fC(a.return()))}finally{if(n)throw i}}}),function(e,t){return E.apply(this,arguments)}),fw=(m=fT(function*(e){if(e[fy])return void(yield*fv(fI(e)));let t=e.getReader();try{for(;;){let{done:e,value:i}=yield fC(t.read());if(e)break;yield i}}finally{yield fC(t.cancel())}}),function(e){return m.apply(this,arguments)}),fN=(e,t,i,r)=>{let n=fO(e,t),o,a=0,s=e=>{o||(o=!0,r&&r(e))};return new ReadableStream({async pull(e){try{let{done:t,value:r}=await n.next();if(t)return s(),void e.close();let o=r.byteLength;if(i){let e=a+=o;i(e)}e.enqueue(new Uint8Array(r))}catch(e){throw s(e),e}},cancel:e=>(s(e),n.return())},{highWaterMark:2})};function fD(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function fP(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?fD(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):fD(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let{isFunction:fL}=_G,fk=(e=>{let{Request:t,Response:i}=e;return{Request:t,Response:i}})(_G.global),{ReadableStream:fM,TextEncoder:fU}=_G.global,fx=function(e){try{for(var t=arguments.length,i=Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return!!e(...i)}catch(e){return!1}},fV=e=>{var t;let{fetch:i,Request:r,Response:n}=e=_G.merge.call({skipUndefined:!0},fk,e),o=i?fL(i):"function"==typeof fetch,a=fL(r),s=fL(n);if(!o)return!1;let c=o&&fL(fM),d=o&&("function"==typeof fU?(t=new fU,e=>t.encode(e)):async e=>new Uint8Array(await new r(e).arrayBuffer())),l=a&&c&&fx(()=>{let e=!1,t=new r(mx.origin,{body:new fM,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),h=s&&c&&fx(()=>_G.isReadableStream(new n("").body)),u={stream:h&&(e=>e.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(e=>{u[e]||(u[e]=(t,i)=>{let r=t&&t[e];if(r)return r.call(t);throw new _W("Response type '".concat(e,"' is not supported"),_W.ERR_NOT_SUPPORT,i)})});let p=async(e,t)=>{let i=_G.toFiniteNumber(e.getContentLength());return null==i?(async e=>{if(null==e)return 0;if(_G.isBlob(e))return e.size;if(_G.isSpecCompliantForm(e)){let t=new r(mx.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return _G.isArrayBufferView(e)||_G.isArrayBuffer(e)?e.byteLength:(_G.isURLSearchParams(e)&&(e+=""),_G.isString(e)?(await d(e)).byteLength:void 0)})(t):i};return async e=>{let t,{url:o,method:s,data:c,signal:d,cancelToken:_,timeout:E,onDownloadProgress:m,onUploadProgress:f,responseType:S,headers:g,withCredentials:T="same-origin",fetchOptions:R}=f_(e),C=i||fetch;S=S?(S+"").toLowerCase():"text";let v=((e,t)=>{let{length:i}=e=e?e.filter(Boolean):[];if(t||i){let i,r=new AbortController,n=function(e){if(!i){i=!0,a();let t=e instanceof Error?e:this.reason;r.abort(t instanceof _W?t:new fi(t instanceof Error?t.message:t))}},o=t&&setTimeout(()=>{o=null,n(new _W("timeout ".concat(t," of ms exceeded"),_W.ETIMEDOUT))},t),a=()=>
1{e&&(o&&clearTimeout(o),o=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(n):e.removeEventListener("abort",n)}),e=null)};e.forEach(e=>e.addEventListener("abort",n));let{signal:s}=r;return s.unsubscribe=()=>_G.asap(a),s}})([d,_&&_.toAbortSignal()],E),y=null,I=v&&v.unsubscribe&&(()=>{v.unsubscribe()});try{if(f&&l&&"get"!==s&&"head"!==s&&0!==(t=await p(g,c))){let e,i=new r(o,{method:"POST",body:c,duplex:"half"});if(_G.isFormData(c)&&(e=i.headers.get("content-type"))&&g.setContentType(e),i.body){let[e,r]=fo(t,fn(fa(f)));c=fN(i.body,65536,e,r)}}_G.isString(T)||(T=T?"include":"omit");let i=a&&"credentials"in r.prototype,d=fP(fP({},R),{},{signal:v,method:s.toUpperCase(),headers:g.normalize().toJSON(),body:c,duplex:"half",credentials:i?T:void 0});y=a&&new r(o,d);let _=await (a?C(y,R):C(o,d)),E=h&&("stream"===S||"response"===S);if(h&&(m||E&&I)){let e={};["status","statusText","headers"].forEach(t=>{e[t]=_[t]});let t=_G.toFiniteNumber(_.headers.get("content-length")),[i,r]=m&&fo(t,fn(fa(m),!0))||[];_=new n(fN(_.body,65536,i,()=>{r&&r(),I&&I()}),e)}S=S||"text";let A=await u[_G.findKey(u,S)||"text"](_,e);return!E&&I&&I(),await new dQ((t,i)=>{fr(t,i,{data:A,headers:m7.from(_.headers),status:_.status,statusText:_.statusText,config:e,request:y})})}catch(t){if(I&&I(),t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message))throw Object.assign(new _W("Network Error",_W.ERR_NETWORK,e,y),{cause:t.cause||t});throw _W.from(t,t&&t.code,e,y)}}},fF=new Map,fB=e=>{let t=e&&e.env||{},{fetch:i,Request:r,Response:n}=t,o=[r,n,i],a,s,c=o.length,d=fF;for(;c--;)a=o[c],void 0===(s=d.get(a))&&d.set(a,s=c?new Map:fV(t)),d=s;return s};fB();let fj={http:null,xhr:fE,fetch:{get:fB}};_G.forEach(fj,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}});let fG=e=>"- ".concat(e),fW=e=>_G.isFunction(e)||null===e||!1===e;var fH=function(e,t){let i,r,{length:n}=e=_G.isArray(e)?e:[e],o={};for(let a=0;a<n;a++){let n;if(r=i=e[a],!fW(i)&&void 0===(r=fj[(n=String(i)).toLowerCase()]))throw new _W("Unknown adapter '".concat(n,"'"));if(r&&(_G.isFunction(r)||(r=r.get(t))))break;o[n||"#"+a]=r}if(!r){let e=Object.entries(o).map(e=>{let[t,i]=e;return"adapter ".concat(t," ")+(!1===i?"is not supported by the environment":"is not available in the build")});throw new _W("There is no suitable adapter to dispatch the request "+(n?e.length>1?"since :\n"+e.map(fG).join("\n"):" "+fG(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return r};function fK(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new fi(null,e)}function fY(e){return fK(e),e.headers=m7.from(e.headers),e.data=fe.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1),fH(e.adapter||m3.adapter,e)(e).then(function(t){return fK(e),t.data=fe.call(e,e.transformResponse,t),t.headers=m7.from(t.headers),t},function(t){return ft(t)||(fK(e),t&&t.response&&(t.response.data=fe.call(e,e.transformResponse,t.response),t.response.headers=m7.from(t.response.headers))),dQ.reject(t)})}let fz="1.13.2",fq={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{fq[e]=function(i){return typeof i===e||"a"+(t<1?"n ":" ")+e}});let fX={};fq.transitional=function(e,t,i){function r(e,t){return"[Axios v"+fz+"] Transitional option '"+e+"'"+t+(i?". "+i:"")}return(i,n,o)=>{if(!1===e)throw new _W(r(n," has been removed"+(t?" in "+t:"")),_W.ERR_DEPRECATED);return t&&!fX[n]&&(fX[n]=!0,console.warn(r(n," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(i,n,o)}},fq.spelling=function(e){return(t,i)=>(console.warn("".concat(i," is likely a misspelling of ").concat(e)),!0)};var fJ=function(e,t,i){if("object"!=typeof e)throw new _W("options must be an object",_W.ERR_BAD_OPTION_VALUE);let r=Object.keys(e),n=r.length;for(;n-- >0;){let o=r[n],a=t[o];if(a){let t=e[o],i=void 0===t||a(t,o,e);if(!0!==i)throw new _W("option "+o+" must be "+i,_W.ERR_BAD_OPTION_VALUE)}else if(!0!==i)throw new _W("Unknown option "+o,_W.ERR_BAD_OPTION)}};let fQ=class{async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=Error();let i=t.stack?t.stack.replace(/^.+\n/,""):"";try{e.stack?i&&!String(e.stack).endsWith(i.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+i):e.stack=i}catch(e){}}throw e}}_request(e,t){let i;"string"==typeof e?(t=t||{}).url=e:t=e||{};let{transitional:r,paramsSerializer:n,headers:o}=t=fp(this.defaults,t);void 0!==r&&fJ(r,{silentJSONParsing:fq.transitional(fq.boolean),forcedJSONParsing:fq.transitional(fq.boolean),clarifyTimeoutError:fq.transitional(fq.boolean)}
1,!1),null!=n&&(_G.isFunction(n)?t.paramsSerializer={serialize:n}:fJ(n,{encode:fq.function,serialize:fq.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),fJ(t,{baseUrl:fq.spelling("baseURL"),withXsrfToken:fq.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let a=o&&_G.merge(o.common,o[t.method]);o&&_G.forEach(["delete","get","head","post","put","patch","common"],e=>{delete o[e]}),t.headers=m7.concat(a,o);let s=[],c=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(c=c&&e.synchronous,s.unshift(e.fulfilled,e.rejected))});let d=[];this.interceptors.response.forEach(function(e){d.push(e.fulfilled,e.rejected)});let l,h=0;if(!c){let e=[fY.bind(this),void 0];for(e.unshift(...s),e.push(...d),l=e.length,i=dQ.resolve(t);h<l;)i=i.then(e[h++],e[h++]);return i}l=s.length;let u=t;for(;h<l;){let e=s[h++],t=s[h++];try{u=e(u)}catch(e){t.call(this,e);break}}try{i=fY.call(this,u)}catch(e){return dQ.reject(e)}for(h=0,l=d.length;h<l;)i=i.then(d[h++],d[h++]);return i}getUri(e){return _1(fd((e=fp(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}constructor(e){this.defaults=e||{},this.interceptors={request:new _2,response:new _2}}};_G.forEach(["delete","get","head","options"],function(e){fQ.prototype[e]=function(t,i){return this.request(fp(i||{},{method:e,url:t,data:(i||{}).data}))}}),_G.forEach(["post","put","patch"],function(e){function t(t){return function(i,r,n){return this.request(fp(n||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:i,data:r}))}}fQ.prototype[e]=t(),fQ.prototype[e+"Form"]=t(!0)});class fZ{throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){let e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new fZ(function(t){e=t}),cancel:e}}constructor(e){let t;if("function"!=typeof e)throw TypeError("executor must be a function.");this.promise=new dQ(function(e){t=e});let i=this;this.promise.then(e=>{if(!i._listeners)return;let t=i._listeners.length;for(;t-- >0;)i._listeners[t](e);i._listeners=null}),this.promise.then=e=>{let t,r=new dQ(e=>{i.subscribe(e),t=e}).then(e);return r.cancel=function(){i.unsubscribe(t)},r},e(function(e,r,n){i.reason||(i.reason=new fi(e,r,n),t(i.reason))})}}let f$={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,Parti
1alContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(f$).forEach(e=>{let[t,i]=e;f$[i]=t});let f0=function e(t){let i=new fQ(t),r=_n(fQ.prototype.request,i);return _G.extend(r,fQ.prototype,i,{allOwnKeys:!0}),_G.extend(r,i,null,{allOwnKeys:!0}),r.create=function(i){return e(fp(t,i))},r}(m3);f0.Axios=fQ,f0.CanceledError=fi,f0.CancelToken=fZ,f0.isCancel=ft,f0.VERSION=fz,f0.toFormData=_J,f0.AxiosError=_W,f0.Cancel=f0.CanceledError,f0.all=function(e){return dQ.all(e)},f0.spread=function(e){return function(t){return e.apply(null,t)}},f0.isAxiosError=function(e){return _G.isObject(e)&&!0===e.isAxiosError},f0.mergeConfig=fp,f0.AxiosHeaders=m7,f0.formToJSON=e=>m2(_G.isHTMLForm(e)?new FormData(e):e),f0.getAdapter=fH,f0.HttpStatusCode=f$,f0.default=f0;let f1=()=>{};function f2(){let e={promise:void 0,isResolved:!1,isRejected:!1,isFinished:!1,resolve:void 0,reject:void 0,cancel:f1};return e.promise=new dQ((t,i)=>{e.resolve=i=>{e.isFinished||(e.isResolved=!0,e.isFinished=!0,t(i),e.value=i)},e.reject=t=>{e.isFinished||(e.isRejected=!0,e.isFinished=!0,i(t))}}),e}let f3=new Map,f5=new Map,f4=new Map,f6=((f={}).WIN_10="Windows 10",f.WIN_81="Windows 8.1",f.WIN_8="Windows 8",f.WIN_7="Windows 7",f.WIN_VISTA="Windows Vista",f.WIN_SERVER_2003="Windows Server 2003",f.WIN_XP="Windows XP",f.WIN_2000="Windows 2000",f.ANDROID="Android",f.HARMONY_OS="HarmonyOS",f.OPEN_BSD="Open BSD",f.SUN_OS="Sun OS",f.LINUX="Linux",f.IOS="iOS",f.MAC_OS="Mac OS",f.CHROMIUM_OS="Chromium OS",f.QNX="QNX",f.UNIX="UNIX",f.BEOS="BeOS",f.OS_2="OS/2",f.SEARCH_BOT="Search Bot",f),f8=((S={}).CHROME="Chrome",S.SAFARI="Safari",S.EDGE="Edge",S.FIREFOX="Firefox",S.OPERA="OPR",S.QQ="QQBrowser",S.WECHAT="MicroMessenger",S),f9=new p9,f7=f9.getResult(),Se=null;function St(e){if(!Se){var t;e&&f9.setUA(e);let i=function(e){if("Blink"===e.engine.name&&"WeChat"!==e.browser.name)return f8.CHROME;switch(e.browser.name){case"Chrome Headless":case"Chrome":case"Chromium":return f8.CHROME;case"Safari":case"Mobile Safari":return f8.SAFARI;case"Edge":return f8.EDGE;case"Firefox":return f8.FIREFOX;case"QQ":case"QQBrowser":return f8.QQ;case"Opera":return f8.OPERA;case"WeChat":return f8.WECHAT;default:return e.browser.name||""}}(f7=f9.getResult()),r=Si(f7),n="Windows"===(t=f7).os.name?t.os.version?t.os.name+" "+t.os.version:t.os.name:t.os.name||"",o=f7.os.version,a=Si(f7,!1),s=f7.device.type;if(!(i&&r&&n&&o))return{name:i,version:r,os:n,osVersion:o,browserVersion:a,deviceType:s};Se={name:i,version:r,os:n,osVersion:o,browserVersion:a,deviceType:s}}return Se}function Si(e){let t,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return t="Blink"===e.engine.name?e.engine.version||"":e.browser.version||"",i?t.split(".")[0]:t}function Sr(){return St().os}function Sn(){let e=St();return"".concat(e.os," ").concat(e.osVersion)}function So(){let e=St();return!!("WebKit"===f7.engine.name&&e.os===f6.MAC_OS&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0&&e.name!==f8.SAFARI||Sh()&&e.name!==f8.SAFARI)}function Sa(){return St().name===f8.CHROME}function Ss(){return St().name===f8.SAFARI}function Sc(){let e=St();if(e.name!==f8.SAFARI||!e.browserVersion)return!1;let t=e.browserVersion.split(".");return Number(t[0])>15||15===Number(t[0])&&Number(t[1])>=4}function Sd(){return St().name===f8.EDGE}function Sl(){return St().name===f8.FIREFOX}function Sh(){return St().os===f6.IOS}function Su(e){let t=St();return!(t.name!==f8.CHROME||!t.osVersion)&&Number(t.version)>=e}function Sp(e){let t=St();return!(t.name!==f8.CHROME||!t.osVersion)&&Number(t.version)<e}function S_(e,t,i){let r=St();return!(r.name!==e||!r.osVersion)&&(i?Number(r.version)>=t&&Number(r.version)<=i:Number(r.version)===t)}function SE(e){let t=St();return!(t.name!==f8.EDGE||!t.osVersion)&&Number(t.version)>=e}function Sm(e){let t=St();return!(t.name!==f8.FIREFOX||!t.osVersion)&&Number(t.version)>=e}function Sf(e){let t=St();return!(t.name!==f8.SAFARI||!t.osVersion)&&Number(t.version)>=e}function SS(e,t,i){let r=St();
1if(r.os!==f6.IOS||!r.osVersion)return!1;let n=r.osVersion.split(".");return i?t&&Number(n[0])===e&&Number(n[1])>t||Number(n[0])>e:t?Number(n[0])===e&&Number(n[1])>=t||Number(n[0])>e:Number(n[0])>=e}function Sg(e,t,i){let r=St();if(r.os!==f6.IOS||!r.osVersion)return!1;let n=r.osVersion.split(".");return i?t&&Number(n[0])===e&&Number(n[1])<t||Number(n[0])<e:t?Number(n[0])===e&&Number(n[1])<=t||Number(n[0])<e:Number(n[0])<=e}function ST(e,t,i){let r=St();if(r.name!==f8.SAFARI||!r.osVersion||!r.browserVersion)return!1;let n=r.browserVersion.split(".");return i?t&&Number(n[0])===e&&Number(n[1])<t||Number(n[0])<e:t?Number(n[0])===e&&Number(n[1])<=t||Number(n[0])<e:Number(n[0])<=e}function SR(e){let t=St();return!(t.name!==f8.OPERA||!t.osVersion)&&Number(t.version)>=e}function SC(){let e=St();if(e.os!==f6.IOS||!e.osVersion)return!1;let t=e.osVersion.split(".");return 14>Number(t[0])||14===Number(t[0])&&6>=Number(t[1])}function Sv(){let e=St();return e.os===f6.IOS&&!!e.osVersion&&15===Number(e.osVersion.split(".")[0])}function Sy(){let e=St();return e.os===f6.IOS&&!!e.osVersion&&16===Number(e.osVersion.split(".")[0])}function SI(){let e=St();if(e.os!==f6.IOS||!e.osVersion)return!1;let t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=1}function SA(){return Ss()&&navigator.maxTouchPoints>0}function Sb(){return St().name===f8.WECHAT}function SO(){return window.navigator.appVersion&&null!==window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)&&window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)[1]<=35}function Sw(){let e=Sr();return function(){let{deviceType:e}=St();return"mobile"===e||"tablet"===e}()||e===f6.ANDROID||e===f6.IOS||e===f6.HARMONY_OS}function SN(){let e=St();return e.name!==f8.EDGE&&e.name!==f8.SAFARI&&!!navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]./i)}function SD(){return Sr()===f6.ANDROID}function SP(){let e=St();return SD()&&(e.name===f8.CHROME||e.name===f8.WECHAT||/chrome|chromium/i.test(navigator.userAgent))}function SL(e,t,i){var r;return(t="symbol"==typeof(r=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,"string");if("object"!=typeof r)return r;throw TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(t))?r:r+"")in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function Sk(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function SM(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Sk(Object(i),!0).forEach(function(t){SL(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Sk(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let SU=((g={}).UNEXPECTED_ERROR="UNEXPECTED_ERROR",g.UNEXPECTED_RESPONSE="UNEXPECTED_RESPONSE",g.TIMEOUT="TIMEOUT",g.INVALID_PARAMS="INVALID_PARAMS",g.NOT_READABLE="NOT_READABLE",g.NOT_SUPPORTED="NOT_SUPPORTED",g.INVALID_OPERATION="INVALID_OPERATION",g.OPERATION_ABORTED="OPERATION_ABORTED",g.WEB_SECURITY_RESTRICT="WEB_SECURITY_RESTRICT",g.EXCHANGE_SDP_FAILED="EXCHANGE_SDP_FAILED",g.ADD_CANDIDATE_FAILED="ADD_CANDIDATE_FAILED",g.DATACHANNEL_FAILED="DATACHANNEL_FAILED",g.NETWORK_ERROR="NETWORK_ERROR",g.NETWORK_TIMEOUT="NETWORK_TIMEOUT",g.NETWORK_RESPONSE_ERROR="NETWORK_RESPONSE_ERROR",g.API_INVOKE_TIMEOUT="API_INVOKE_TIMEOUT",g.ENUMERATE_DEVICES_FAILED="ENUMERATE_DEVICES_FAILED",g.DEVICE_NOT_FOUND="DEVICE_NOT_FOUND",g.ELECTRON_IS_NULL="ELECTRON_IS_NULL",g.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR="ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR",g.CHROME_PLUGIN_NO_RESPONSE="CHROME_PLUGIN_NO_RESPONSE",g.CHROME_PLUGIN_NOT_INSTALL="CHROME_PLUGIN_NOT_INSTALL",g.MEDIA_OPTION_INVA
vendor: 6,681 bytes, line 1
1LID="MEDIA_OPTION_INVALID",g.PERMISSION_DENIED="PERMISSION_DENIED",g.CONSTRAINT_NOT_SATISFIED="CONSTRAINT_NOT_SATISFIED",g.TRACK_IS_DISABLED="TRACK_IS_DISABLED",g.GET_VIDEO_ELEMENT_VISIBLE_ERROR="GET_VIDEO_ELEMENT_VISIBLE_ERROR",g.SHARE_AUDIO_NOT_ALLOWED="SHARE_AUDIO_NOT_ALLOWED",g.LOW_STREAM_ENCODING_ERROR="LOW_STREAM_ENCODING_ERROR",g.SET_ENCODING_PARAMETER_ERROR="SET_ENCODING_PARAMETER_ERROR",g.TRACK_STATE_UNREACHABLE="TRACK_STATE_UNREACHABLE",g.INVALID_UINT_UID_FROM_STRING_UID="INVALID_UINT_UID_FROM_STRING_UID",g.CAN_NOT_GET_PROXY_SERVER="CAN_NOT_GET_PROXY_SERVER",g.CAN_NOT_GET_GATEWAY_SERVER="CAN_NOT_GET_GATEWAY_SERVER",g.VOID_GATEWAY_ADDRESS="VOID_GATEWAY_ADDRESS",g.UID_CONFLICT="UID_CONFLICT",g.MULTI_UNILBS_RESPONSE_ERROR="MULTI_UNILBS_RESPONSE_ERROR",g.UPDATE_TICKET_FAILED="UPDATE_TICKET_FAILED",g.TOKEN_EXPIRE="TOKEN_EXPIRE",g.INVALID_LOCAL_TRACK="INVALID_LOCAL_TRACK",g.INVALID_TRACK="INVALID_TRACK",g.SENDER_NOT_FOUND="SENDER_NOT_FOUND",g.CREATE_OFFER_FAILED="CREATE_OFFER_FAILED",g.SET_ANSWER_FAILED="SET_ANSWER_FAILED",g.ICE_FAILED="ICE_FAILED",g.PC_CLOSED="PC_CLOSED",g.SENDER_REPLACE_FAILED="SENDER_REPLACE_FAILED",g.GET_LOCAL_CAPABILITIES_FAILED="GET_LOCAL_CAPABILITIES_FAILED",g.GET_LOCAL_CONNECTION_PARAMS_FAILED="GET_LOCAL_CONNECTION_PARAMS_FAILED",g.SUBSCRIBE_FAILED="SUBSCRIBE_FAILED",g.UNSUBSCRIBE_FAILED="UNSUBSCRIBE_FAILED",g.GATEWAY_P2P_LOST="GATEWAY_P2P_LOST",g.NO_ICE_CANDIDATE="NO_ICE_CANDIDATE",g.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS="CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS",g.EXIST_DISABLED_VIDEO_TRACK="EXIST_DISABLED_VIDEO_TRACK",g.INVALID_REMOTE_USER="INVALID_REMOTE_USER",g.REMOTE_USER_IS_NOT_PUBLISHED="REMOTE_USER_IS_NOT_PUBLISHED",g.CUSTOM_REPORT_SEND_FAILED="CUSTOM_REPORT_SEND_FAILED",g.CUSTOM_REPORT_FREQUENCY_TOO_HIGH="CUSTOM_REPORT_FREQUENCY_TOO_HIGH",g.FETCH_AUDIO_FILE_FAILED="FETCH_AUDIO_FILE_FAILED",g.READ_LOCAL_AUDIO_FILE_ERROR="READ_LOCAL_AUDIO_FILE_ERROR",g.DECODE_AUDIO_FILE_FAILED="DECODE_AUDIO_FILE_FAILED",g.WS_ABORT="WS_ABORT",g.WS_DISCONNECT="WS_DISCONNECT",g.WS_ERR="WS_ERR",g.EXTERNAL_SIGNAL_ABORT="EXTERNAL_SIGNAL_ABORT",g.LIVE_STREAMING_TASK_CONFLICT="LIVE_STREAMING_TASK_CONFLICT",g.LIVE_STREAMING_INVALID_ARGUMENT="LIVE_STREAMING_INVALID_ARGUMENT",g.LIVE_STREAMING_INTERNAL_SERVER_ERROR="LIVE_STREAMING_INTERNAL_SERVER_ERROR",g.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED="LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED",g.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED="LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED",g.LIVE_STREAMING_CDN_ERROR="LIVE_STREAMING_CDN_ERROR",g.LIVE_STREAMING_INVALID_RAW_STREAM="LIVE_STREAMING_INVALID_RAW_STREAM",g.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT="LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT",g.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE="LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE",g.LIVE_STREAMING_WARN_FREQUENT_REQUEST="LIVE_STREAMING_WARN_FREQUENT_REQUEST",g.WEBGL_INTERNAL_ERROR="WEBGL_INTERNAL_ERROR",g.BEAUTY_PROCESSOR_INTERNAL_ERROR="BEAUTY_PROCESSOR_INTERNAL_ERROR",g.CROSS_CHANNEL_WAIT_STATUS_ERROR="CROSS_CHANNEL_WAIT_STATUS_ERROR",g.CROSS_CHANNEL_FAILED_JOIN_SRC="CROSS_CHANNEL_FAILED_JOIN_SEC",g.CROSS_CHANNEL_FAILED_JOIN_DEST="CROSS_CHANNEL_FAILED_JOIN_DEST",g.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST="CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST",g.CROSS_CHANNEL_SERVER_ERROR_RESPONSE="CROSS_CHANNEL_SERVER_ERROR_RESPONSE",g.METADATA_OUT_OF_RANGE="METADATA_OUT_OF_RANGE",g.LOCAL_AEC_ERROR="LOCAL_AEC_ERROR",g.INVALID_PLUGIN="INVALID_PLUGIN",g.DISCONNECT_P2P="DISCONNECT_P2P",g.CONVERTING_IMAGEDATA_TO_BLOB_FAILED="CONVERTING_IMAGEDATA_TO_BLOB_FAILED",g.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED="CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED",g.INIT_DATACHANNEL_TIMEOUT="INIT_DATACHANNEL_TIMEOUT",g.CREATE_DATACHANNEL_ERROR="CREATE_DATACHANNEL_ERROR",g.DATACHANNEL_CONNECTION_TIMEOUT="DATACHANNEL_CONNECTION_TIMEOUT",g.PROHIBITED_OPERATION="PROHIBITED_OPERATION",g.IMAGE_MODERATION_UPLOAD_FAILED="IMAGE_MODERATION_UPLOAD_FAILED",g.P2P_MESSAGE_FAILED="P2P_MESSAGE_FAILED",g),Sx=class extends Error{toString(){return this.data?"".concat(this.message,"\ndata: ").concat(JSON.stringify(this.data)):this.message}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error",t=arguments.length>1?arguments[1]:void 0;return"error"===e&&(t||console).error(this.toString()),"warning"===e&&(t||console).warn(this.toString()),this}throw(e){throw this.print("error",e),this}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",i=arguments.length>2?arguments[2]:void 0;super(t),SL(this,"code",void 0),SL(this,"message",void 0),SL(this,"data",void 0),SL(this,"name","AgoraRTCException"),this.code=e,this.message="AgoraRTCError ".concat(this.code,": ").concat(t),this.data=i}};function SV(e,t){if("boolean"!=typeof e)throw new Sx(SU.INVALID_PARAMS,"Invalid ".concat(t,": The value is of the boolean type."))}function SF(e,t,i){if(!o5(i).call(i,e))throw new Sx(SU.INVALID_PARAMS,"".concat(t," can only be set as ").concat(JSON.stringify(i)))}function SB(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e4;if(e<i||e>r||(!(arguments.length>4&&void 0!==arguments[4])||arguments[4])&&("number"!=typeof e||e%1!=0))throw new Sx(SU.INVALID_PARAMS,"invalid ".concat(t,": the value range is [").concat(i,", ").concat(r,"]. integer only"))}function Sj(e,t){if("number"!=typeof e){if(!(e.min||e.max||e.ideal||e.exact))throw new Sx(SU.INVALID_PARAMS,"".concat(t," is not a valid ConstrainLong"));void 0!==e.min&&SB(e.min,"".concat(t,".min"),0,1/0),void 0!==e.max&&SB(e.max,"".concat(t,".max"),1,1/0),void 0!==e.exact&&SB(e.exact,"".concat(t,".exact"),1,1/0),void 0!==e.ideal&&SB(e.ideal,"".concat(t,".ideal"),1,1/0)}else SB(e,t,1,1/0)}function SG(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:255,n=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];if(null==e)throw new Sx(SU.INVALID_PARAMS,"".concat(t||"param"," cannot be empty"));if(!SK(e,i,r,n))throw new Sx(SU.INVALID_PARAMS,"Invalid ".concat(t||"string param",": Length of the string: [").concat(i,",").concat(r,"].").concat(n?" ASCII characters only.":""))}function SW(e,t){if(!Array.isArray(e))throw new Sx(SU.INVALID_PARAMS,"".concat(t," should be an array"))}function SH(e){return null==e}function SK(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:255,r=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return"string"==typeof e&&e.length<=i&&e.length>=t&&(!r||function(e){if("string"!=typeof e)return!1;for(let t=0;t<e.length;t+=1){let i=e.charCodeAt(t);if(i<0||i>
1255)return!1}return!0}(e))}function SY(e,t,i){if("getBigUint64"in DataView.prototype)return e.getBigUint64(t,i);let r=e.getUint32(t,i),n=e.getUint32(t+4,i),o=Number(!!i),a=Number(!i);return BigInt(r*a+n*o)<<BigInt(32)|BigInt(r*o+n*a)}function Sz(e,t,i,r){if("setBigUint64"in DataView.prototype)return e.setBigUint64(t,i,r);let n=Number(i>>BigInt(32)),o=Number(i&BigInt(0xffffffff));r?(e.setUint32(t+4,n,r),e.setUint32(t,o,r)):(e.setUint32(t,n,r),e.setUint32(t+4,o,r))}var Sq=((T=Sq||{}).COVERED="COVERED",T.POSITION="POSITION",T.SIZE="SIZE",T.STYLE="STYLE",T),SX=((R=SX||{}).UNMOUNTED="UNMOUNTED",R.INVALID_HTML_ELEMENT="INVALID_HTML_ELEMENT",R);let SJ=new class{constructor(){SL(this,"_clientSize",null),SL(this,"getClientWidth",()=>document.documentElement?document.documentElement.clientWidth:document.body.clientWidth),SL(this,"getClientHeight",()=>document.documentElement?document.documentElement.clientHeight:document.body.clientHeight),SL(this,"getStyle",e=>window.getComputedStyle(e,null)),SL(this,"checkCssVisibleProperty",e=>{var t;let i=!0,{display:r,visibility:n,opacity:o,filter:a}=this.getStyle(e);return("none"===r||o5(t=["hidden","collapse"]).call(t,n)||.1>Number(o))&&(i=!1),!!i&&(a&&a.split(" ").filter(e=>{var t;let i=e.split("(")[0];return o5(t=["brightness","blur","opacity"]).call(t,i)}).map(e=>{let[t,i]=e.split(/\(|\)/);return[t,Number(i.match(/^[0-9\.]+/))]}).forEach(e=>{let[t,r]=e;switch(t){case"brightness":(r<.1||r>3)&&(i=!1);break;case"blur":r>3&&(i=!1);break;case"opacity":r<.1&&(i=!1)}}),i)}),SL(this,"checkPropertyUpToAllParentNodes",(e,t)=>{let i=!0,r=!0,n=e=>t(e),o=e;for(;o&&r;)n(o)||(i=!1,r=!1),(o=o.parentElement)||(r=!1);return i}),SL(this,"checkActualCssVisibleIncludeInherit",e=>this.checkPropertyUpToAllParentNodes(e,this.checkCssVisibleProperty)),SL(this,"getSizeAboutClient",e=>{let{width:t,height:i,left:r,right:n,top:o,bottom:a}=e.getBoundingClientRect(),s=this.getClientWidth(),c=this.getClientHeight();return{width:t,height:i,left:r,right:n,top:o,bottom:a,clientWidth:s,clientHeight:c,clientMin:Math.min(s,c)}}),SL(this,"checkActualSize",()=>{let{width:e,height:t,clientMin:i}=this._clientSize;return this.checkSizeIsVisible(e,t,i)}),SL(this,"elementFromPoint",(e,t)=>document.elementFromPoint?document.elementFromPoint(e,t):null),SL(this,"checkCoverForAPoint",(e,t,i)=>{let r=this.elementFromPoint(e,t);return null!==r&&r!==i}),SL(this,"getPointPositionList",()=>{let{width:e,height:t,left:i,top:r}=this._clientSize,n=e/6,o=t/6,a=[];for(let e=0;e<5;e++)for(let t=0;t<5;t++){let s=(1e6*i+(0===e?.1:4===e?(n*e*1e6-1e5)/1e6:n*e)*1e6)/1e6,c=(1e6*r+(0===t?.1:4===t?(o*t*1e6-1e5)/1e6:o*t)*1e6)/1e6;a.push({x:s,y:c})}return[...a]}),SL(this,"checkElementCover",e=>this.getPointPositionList().map(t=>this.checkCoverForAPoint(t.x,t.y,e)).filter(e=>!!e).length>6),SL(this,"checkSizeIsVisible",(e,t,i)=>(e>50||i/e<=10)&&(t>50||i/t<=10)),SL(this,"checkSizeOfPartInClient",()=>{let e,t,i,{left:r,right:n,top:o,bottom:a,clientHeight:s,clientWidth:c,clientMin:d}=this._clientSize;if(r<0)e=0;else{if(!(r<c))return!1;e=r}if(n<0)return!1;if(t=n<c?n:c,o<0)i=0;else{if(!(o<s))return!1;i=o}if(a<0)return!1;let l=t-e,h=(a<s?a:s)-i;return this.checkSizeIsVisible(l,h,d)}),SL(this,"returnHiddenResult",e=>(this._clientSize=null,{visible:!1,reason:e})),SL(this,"checkOneElementVisible",e=>{if(e instanceof HTMLElement){if(this.checkElementIsMountedOnDom(e)){if(this.checkActualCssVisibleIncludeInherit(e)){if(this._clientSize=this.getSizeAboutClient(e),this.checkElementCover(e))return this.returnHiddenResult(Sq.COVERED);{let e=this.checkActualSize(),t=this.checkSizeOfPartInClient();return e&&!t?this.returnHiddenResult(Sq.POSITION):e?(this._clientSize=null,{visible:!0}):this.returnHiddenResult(Sq.SIZE)}}return this.returnHiddenResult(Sq.STYLE)}return this.returnHiddenResult(SX.UNMOUNTED)}return this.returnHiddenResult(SX.INVALID_HTML_ELEMENT)}),SL(this,"checkElementIsMountedOnDom",e=>this.checkPropertyUpToAllParentNodes(e,e=>"HTML"!==e.nodeName.toUpperCase()?null!==e.parentElement:!!document.documentElement))}};function SQ(e){return(new TextEncoder).encode(e)}let SZ=function(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},S$=async e=>{var t;let i;return t=await crypto.subtle.digest("SHA-256",SQ(e)),i="",new Uint8Array(t).forEach(e
1=>{i+=e.toString(16).padStart(2,"0")}),i},S0=class{getListeners(e){return this._events[e]?this._events[e].map(e=>e.listener):[]}on(e,t){this._events[e]||(this._events[e]=[]);let i=this._events[e];-1===this._indexOfListener(i,t)&&i.push({listener:t,once:!1})}once(e,t){this._events[e]||(this._events[e]=[]);let i=this._events[e];-1===this._indexOfListener(i,t)&&i.push({listener:t,once:!0})}off(e,t){if(!this._events[e])return;let i=this._events[e],r=this._indexOfListener(i,t);-1!==r&&i.splice(r,1),0===this._events[e].length&&delete this._events[e]}removeAllListeners(e){e?delete this._events[e]:this._events={}}emit(e){this._events[e]||(this._events[e]=[]);let t=this._events[e].map(e=>e);for(var i=arguments.length,r=Array(i>1?i-1:0),n=1;n<i;n++)r[n-1]=arguments[n];for(let i=0;i<t.length;i+=1){let n=t[i];n.once&&this.off(e,n.listener),n.listener.apply(this,r||[])}}safeEmit(e){for(var t=arguments.length,i=Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];[...this._events[e]||[]].forEach(t=>{t.once&&this.off(e,t.listener);try{t.listener.apply(this,i)}catch(t){console.error("safeEmit event:".concat(e," error ").concat(null==t?void 0:t.toString()))}})}_indexOfListener(e,t){let i=e.length;for(;i--;)if(e[i].listener===t)return i;return -1}constructor(){SL(this,"_events",{}),SL(this,"addListener",this.on)}},S1=null;function S2(){if(S1)return S1;if(window.electron)return S1=window.electron;if(!window.require)return null;try{return S1=window.require("electron")}catch(e){return null}}let S3=((C={}).CREATE_CLIENT="createClient",C.CHECK_SYSTEM_REQUIREMENTS="checkSystemRequirements",C.SET_AREA="setArea",C.PRELOAD="PRELOAD",C.CHECK_VIDEO_TRACK_IS_ACTIVE="checkVideoTrackIsActive",C.CHECK_AUDIO_TRACK_IS_ACTIVE="checkAudioTrackIsActive",C.CREATE_MIC_AUDIO_TRACK="createMicrophoneAudioTrack",C.CREATE_CUSTOM_AUDIO_TRACK="createCustomAudioTrack",C.CREATE_BUFFER_AUDIO_TRACK="createBufferSourceAudioTrack",C.CREATE_CAM_VIDEO_TRACK="createCameraVideoTrack",C.CREATE_CUSTOM_VIDEO_TRACK="createCustomVideoTrack",C.CREATE_MIC_AND_CAM_TRACKS="createMicrophoneAndCameraTracks",C.CREATE_SCREEN_VIDEO_TRACK="createScreenVideoTrack",C.SET_ENCRYPTION_CONFIG="Client.setEncryptionConfig",C.START_PROXY_SERVER="Client.startProxyServer",C.STOP_PROXY_SERVER="Client.stopProxyServer",C.SET_PROXY_SERVER="Client.setProxyServer",C.SET_TURN_SERVER="Client.setTurnServer",C.SET_CLIENT_ROLE="Client.setClientRole",C.SET_LOW_STREAM_PARAMETER="Client.setLowStreamParameter",C.ENABLE_DUAL_STREAM="Client.enableDualStream",C.DISABLE_DUAL_STREAM="Client.disableDualStream",C.JOIN="Client.join",C.LEAVE="Client.leave",C.PUBLISH="Client.publish",C.UNPUBLISH="Client.unpublish",C.SUBSCRIBE="Client.subscribe",C.MASS_SUBSCRIBE="Client.massSubscribe",C.MASS_UNSUBSCRIBE="Client.massUnsubscribe",C.UNSUBSCRIBE="Client.unsubscribe",C.RENEW_TOKEN="Client.renewToken",C.SET_REMOTE_VIDEO_STREAM_TYPE="Client.setRemoteVideoStreamType",C.SET_STREAM_FALLBACK_OPTION="Client.setStreamFallbackOption",C.ENABLE_AUDIO_VOLUME_INDICATOR="Client.enableAudioVolumeIndicator",C.SEND_CUSTOM_REPORT_MESSAGE="Client.sendCustomReportMessage",C.INSPECT_VIDEO_CONTENT="Client.inspectVideoContent",C.STOP_INSPECT_VIDEO_CONTENT="Client.stopInspectVideoContent",C.JOIN_FALLBACK_TO_PROXY="Client._joinFallbackToProxy",C.ON_LIVE_STREAM_WARNING="Client.onLiveStreamWarning",C.ON_LIVE_STREAM_ERROR="Client.onLiveStreamingError",C.START_LIVE_STREAMING="Client.startLiveStreaming",C.SET_LIVE_TRANSCODING="Client.setLiveTranscoding",C.STOP_LIVE_STREAMING="Client.stopLiveStreaming",C.START_CHANNEL_MEDIA_RELAY="Client.startChannelMediaRelay",C.UPDATE_CHANNEL_MEDIA_RELAY="Client.updateChannelMediaRelay",C.STOP_CHANNEL_MEDIA_RELAY="Client.stopChannelMediaRelay",C.REQUEST_CONFIG_DISTRIBUTE="_config-distribute-request",C.SET_CONFIG_DISTRIBUTE="_configDistribute",C.LOCAL_TRACK_SET_MUTED="LocalTrack.setMute",C.LOCAL_AUDIO_TRACK_PLAY="LocalAudioTrack.play",C.LOCAL_AUDIO_TRACK_PLAY_IN_ELEMENT="LocalAudioTrack.playInElement",C.LOCAL_AUDIO_TRACK_STOP="LocalAudioTrack.stop",C.LOCAL_AUDIO_TRACK_SET_VOLUME="LocalAudioTrack.setVolume",C.MIC_AUDIO_TRACK_SET_DEVICE="MicrophoneAudioTrack.setDevice",C.BUFFER_AUDIO_TRACK_START="BufferSourceAudioTrack.startProcessAudioBuffer",C.BUFFER_AUDIO_TRACK_STOP="BufferSourceAudioTrack.stopProcessAudioBuffer",C.BUFFER_AUDIO_TRACK_PAUSE="BufferSourceAudioTrack.pauseProcessAudioBuffer",C.BUFFER_AUDIO_TRACK_RESUME="BufferSourceAudioTrack.resumeProcessAudioBuffer",C.BUFFER_AUDIO_TRACK_SEEK="BufferSourceAudioTrack.seekAudioBuffer",C.LOCAL_VIDEO_TRACK_PLAY="LocalVideoTrack.play",C.LOCAL_VIDEO_TRACK_STOP="LocalVideoTrack.stop",C.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE="LocalVideoTrack.getVideoElementVisibleStatus",C.LOCAL_VIDEO_TRACK_BEAUTY="LocalVideoTrack.setBeautyEffect",C.LOCAL_VIDEO_SEND_SEI_DATA="LocalVideoTrack.sendSeiData",C.CAM_VIDEO_TRACK_SET_DEVICE="CameraVideoTrack.setDevice",C.CAM_VIDEO_TRACK_SET_ENCODER_CONFIG="C
1ameraVideoTrack.setEncoderConfiguration",C.REMOTE_VIDEO_TRACK_PLAY="RemoteVideoTrack.play",C.REMOTE_VIDEO_TRACK_STOP="RemoteVideoTrack.stop",C.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE="RemoteVideoTrack.getVideoElementVisibleStatus",C.REMOTE_AUDIO_TRACK_PLAY="RemoteAudioTrack.play",C.REMOTE_AUDIO_TRACK_STOP="RemoteAudioTrack.stop",C.REMOTE_AUDIO_SET_VOLUME="RemoteAudioTrack.setVolume",C.REMOTE_AUDIO_SET_OUTPUT_DEVICE="RemoteAudioTrack.setOutputDevice",C.GET_MEDIA_STREAM_TRACK="Track.getMediaStreamTrack",C.STREAM_TYPE_CHANGE="streamTypeChange",C.CONNECTION_STATE_CHANGE="connectionStateChange",C.LOAD_CONFIG_FROM_LOCALSTORAGE="loadConfigFromLocalStorage",C.IMAGE_MODERATION_UPLOAD="imageModerationUpload",C.REPUB_AFTER_PC_CONNECTED="repubAfterPCConnected",C.PRELOAD_MEDIA_FAILED="preloadMediaFailed",C.MISMATCH_DTLS_PARAMETERS="mismatchDtlsParameters",C.VOS_FALLBACK_CN="vosFallbackCN",C.DATACHANNEL_FAILBACK="datachannelFailback",C),S5=((v={}).TRACER="tracer",v);function S4(e){return SB(e.timeout,"config.timeout",0,1e5),SB(e.timeoutFactor,"config.timeoutFactor",0,100,!1),SB(e.maxRetryCount,"config.maxRetryConfig",0,1/0),SB(e.maxRetryTimeout,"config.maxRetryTimeout",0,1/0),!0}let S6=((y={})[y.AUDIENCE_LEVEL_LOW_LATENCY=1]="AUDIENCE_LEVEL_LOW_LATENCY",y[y.AUDIENCE_LEVEL_ULTRA_LOW_LATENCY=2]="AUDIENCE_LEVEL_ULTRA_LOW_LATENCY",y[y.AUDIENCE_LEVEL_SYNC_LATENCY=3]="AUDIENCE_LEVEL_SYNC_LATENCY",y),S8=((I={}).LEAVE="LEAVE",I.NETWORK_ERROR="NETWORK_ERROR",I.SERVER_ERROR="SERVER_ERROR",I.UID_BANNED="UID_BANNED",I.FALLBACK="FALLBACK",I.IP_BANNED="IP_BANNED",I.CHANNEL_BANNED="CHANNEL_BANNED",I.LICENSE_MISSING="LICENSE_MISSING",I.LICENSE_EXPIRED="LICENSE_EXPIRED",I.LICENSE_MINUTES_EXCEEDED="LICENSE_MINUTES_EXCEEDED",I.LICENSE_PERIOD_INVALID="LICENSE_PERIOD_INVALID",I.LICENSE_MULTIPLE_SDK_SERVICE="LICENSE_MULTIPLE_SDK_SERVICE",I.LICENSE_ILLEGAL="LICENSE_ILLEGAL",I.TOKEN_EXPIRE="TOKEN_EXPIRE",I.FALLBACK_TO_HLS="FALLBACK_TO_HLS",I.UID_CONFLICT="UID_CONFLICT",I);function S9(e){if(!Array.isArray(e)||e.length<1)return!1;try{e.forEach(e=>{if(!e.urls)throw Error()})}catch(e){return!1}return!0}function S7(e){return SG(e.turnServerURL,"turnServerURL"),SG(e.username,"username"),SG(e.password,"password"),e.udpport&&SB(e.udpport,"udpport",1,99999,!0),e.forceturn&&SV(e.forceturn,"forceturn"),e.security&&SV(e.security,"security"),e.tcpport&&SB(e.tcpport,"tcpport",1,99999,!0),!0}let ge=((A={})[A.AUTO_SIMULCAST_STREAM=-1]="AUTO_SIMULCAST_STREAM",A[A.DISABLE_SIMULCAST_STREM=0]="DISABLE_SIMULCAST_STREM",A[A.ENABLE_SIMULCAST_STREAM=1]="ENABLE_SIMULCAST_STREAM",A);function gt(e){return void 0!==e.level&&SF(e.level,"level",[1,2,3]),void 0!==e.delay&&SB(e.delay,"delay",0,3e3,!0),!0}let gi=((b={}).PEERCONNECTION_STATE_CHANGE="peerconnection-state-change",b.AUDIO_METADATA="audio-metadata",b.AUDIO_PTS="audio-pts",b.CONNECTION_STATE_CHANGE="connection-state-change",b.MEDIA_RECONNECT_START="media-reconnect-start",b.MEDIA_RECONNECT_END="media-reconnect-end",b.IS_USING_CLOUD_PROXY="is-using-cloud-proxy",b.USER_JOINED="user-joined",b.USER_LEAVED="user-left",b.USER_PUBLISHED="user-published",b.USER_UNPUBLISHED="user-unpublished",b.USER_INFO_UPDATED="user-info-updated",b.CLIENT_BANNED="client-banned",b.CHANNEL_MEDIA_RELAY_STATE="channel-media-relay-state",b.CHANNEL_MEDIA_RELAY_EVENT="channel-media-relay-event",b.VOLUME_INDICATOR="volume-indicator",b.CRYPT_ERROR="crypt-error",b.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="token-privilege-will-expire",b.ON_TOKEN_PRIVILEGE_DID_EXPIRE="token-privilege-did-expire",b.NETWORK_QUALITY="network-quality",b.STREAM_TYPE_CHANGED="stream-type-changed",b.STREAM_FALLBACK="stream-fallback",b.RECEIVE_METADATA="receive-metadata",b.STREAM_MESSAGE="stream-message",b.LIVE_STREAMING_ERROR="live-streaming-error",b.LIVE_STREAMING_WARNING="live-streaming-warning",b.EXCEPTION="exception",b.ERROR="error",b.P2P_LOST="p2p_lost",b.JOIN_FALLBACK_TO_PROXY="join-fallback-to-proxy",b.CHANNEL_FALLBACK_TO_WEBSOCKET="channel-fallback-to-websocket",b.MEDIA_CONNECTION_TYPE_CHANGE="media-connection-type-change",b.PUBLISHED_USER_LIST="published-user-list",b.CONTENT_INSPECT_CONNECTION_STATE_CHANGE="content-inspect-connection-state-change",b.CONTENT_INSPECT_ERROR="content-inspect-error",b.CONTENT_INSPECT_RESULT="content-inspect-result",b.IMAGE_MODERATION_CONNECTION_STATE_CHANGE="image-moderation-connection-state-change",b.FALLBACK_TO_HLS="fallback-to-hls",b.FIRST_VIDEO_BUFFER_READY="first-video-buffer-ready",b.FIRST_VIDEO_PRE_RENDER="first-video-pre-render",b.AV1_DECODABLE_RESULT="av1-decodable-result",b),gr=((O={}).CONFIG="config",O.VOSERROR="vos_error",O.AP_ERROR="ap_error",O),gn=((w={}
1).NETWORK_ERROR="NETWORK_ERROR",w.SERVER_ERROR="SERVER_ERROR",w.MULTI_IP="MULTI_IP",w.TIMEOUT="TIMEOUT",w.OFFLINE="OFFLINE",w.LEAVE="LEAVE",w.P2P_FAILED="P2P_FAILED",w.FALLBACK="FALLBACK",w.REGIONAL_DISTRIBUTION="REGIONAL_DISTRIBUTION",w),go=((N={}).ONLINE="ONLINE",N.OFFLINE="OFFLINE",N),ga=((D={}).NETWORK_STATE_CHANGE="NETWORK_STATE_CHANGE",D.ONLINE="ONLINE",D.OFFLINE="OFFLINE",D);function gs(e,t){for(var i=arguments.length,r=Array(i>2?i-2:0),n=2;n<i;n++)r[n-2]=arguments[n];return 0===e.getListeners(t).length?dQ.reject(new Sx(SU.UNEXPECTED_ERROR,"can not emit promise")):new dQ((i,n)=>{e.emit(t,...r,i,n)})}function gc(e,t){if(0===e.getListeners(t).length)return dQ.resolve();for(var i=arguments.length,r=Array(i>2?i-2:0),n=2;n<i;n++)r[n-2]=arguments[n];return gs(e,t,...r)}function gd(e,t){if(0===e.getListeners(t).length)return null;for(var i=arguments.length,r=Array(i>2?i-2:0),n=2;n<i;n++)r[n-2]=arguments[n];return gl(e,t,...r)}function gl(e,t){let i=null,r=null;for(var n=arguments.length,o=Array(n>2?n-2:0),a=2;a<n;a++)o[a-2]=arguments[a];if(e.emit(t,...o,e=>{i=e},e=>{r=e}),null!==r)throw r;if(null===i)throw new Sx(SU.UNEXPECTED_ERROR,"handler is not sync");return i}let gh=new class extends S0{set networkState(e){this.emit(ga.NETWORK_STATE_CHANGE,e,this._networkState),e===go.ONLINE?this.emit(ga.ONLINE):e===go.OFFLINE&&(this.onlineWaiter=new dQ(e=>{this.once(ga.ONLINE,()=>{this.onlineWaiter=void 0,e(go.ONLINE)})}),this.emit(ga.OFFLINE)),this._networkState=e}get networkState(){return this._networkState}get isOnline(){return this._networkState===go.ONLINE}constructor(){super(),SL(this,"_moduleName","network-indicator"),SL(this,"_networkState",go.ONLINE),SL(this,"onlineWaiter",void 0),window.addEventListener("online",()=>{this.networkState=go.ONLINE}),window.addEventListener("offline",()=>{this.networkState=go.OFFLINE})}},gu=[];for(let e=0;e<256;++e)gu.push((e+256).toString(16).slice(1));let gp="undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),g_=new Uint8Array(16);function gE(e,t){let i=e.indexOf(t);-1!==i&&e.splice(i,1)}function gm(e){let t=[];return e.forEach(e=>{-1===t.indexOf(e)&&t.push(e)}),t}function gf(e){void 0!==dQ?dQ.resolve().then(e):setTimeout(e,0)}function gS(e){return JSON.parse(JSON.stringify(e))}function gg(e){try{return gS(e)}catch(t){return e}}let gT={};function gR(e,t){gT[t]||(gT[t]=!0,e())}function gC(e){let t=window.atob(e),i=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)i[e]=t.charCodeAt(e);return i}function gv(e){let t="";for(let i=0;i<e.length;i+=1)t+=String.fromCharCode(e[i]);return window.btoa(t)}function gy(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=(new TextEncoder).encode(e);if(i.length>t)i=i.slice(0,t);else if(i.length<t){let e=new Uint8Array(t);e.set(i),i=e}return i}function gI(){for(var e=arguments.length,t=Array(e),i=0;i<e;i++)t[i]=arguments[i];let r=new Uint8Array(new ArrayBuffer(as(t).call(t,(e,t)=>e+t.length,0))),n=0;return t.forEach(e=>{r.set(e,n),n+=e.length}),r}function gA(e){return window.TextEncoder?(new TextEncoder).encode(e).length:e.length}function gb(e){let t=0;return(/DingTalk/i.test(navigator.userAgent)||/AliApp/i.test(navigator.userAgent))&&e.realFormData&&(e=e.realFormData),e.forEach(e=>{t+="string"==typeof e?gA(e):e.size}),t+138}function gO(e){return new dQ(t=>{window.setTimeout(t,e)})}function gw(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:7,t=arguments.length>1?arguments[1]:void 0,i=Math.random().toString(16).substr(2,e).toLowerCase();return i.length===e?"".concat(t).concat(i):"".concat(t).concat(i)+gw(e-i.length,"")}function gN(){let t,i=!1;try{var r,n,o;t=p4(r=gp?gp():function(t,i,r){var n,o,a,s;let c=null!=(n=null!=(o=(t=t||{}).random)?o:null==(a=(s=t).rng)?void 0:a.call(s))?n:function(){if(!e){if("undefined"==typeof crypto||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");e=crypto.getRandomValues.bind(crypto)}return e(g_)}();if(c.length<16)throw Error("Random bytes length must be >= 16");if(c[6]=15&c[6]|64,c[8]=63&c[8]|128,i){if((r=r||0)<0||r+16>i.length)throw RangeError("UUID byte range ".concat(r,":").concat(r+15," is out of buffer bounds"));for(let e=0;e<16;++e)i[r+e]=c[e];return i}return function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return(gu[e[t+0]]+gu[e[t+1]]+gu[e[t+2]]+gu[e[t+3]]+"-"+gu[e[t+4]]+gu[e[t+5]]+"-"+gu[e[t+6]]+gu[e[t+7]]+"-"+gu[e[t+8]]+gu[e[t+9]]+"-"+gu[e[t+10]]+gu[e[t+11]]+gu[e[t+12]]+gu[e[t+13]]+gu[e[t+14]]+gu[e[t+15]]).toLowerCase()}(c)}(n,o,void 0)).call(r,"-","")}catch(e){i=!0}return!i&&t&&32===t.length||(t=gw(32,"")),t.toUpperCase()}let gD=()=>{},gP=new class{throttleByKey(e,t,i,r){for(var n=arguments.length,o=Array(n>4?n-4:0),a=4;a<n;a++)o[a-4]=arguments[a];if(this.fnMap.has(t)){let n=this.fnMap.get(t);if(n.threshold!==i){n.fn(...n.args),clearTimeout(n.timer);let a=window.setTimeout(()=>{let e=this.fnMap.get(t);e&&e.fn(...e.args),this.fnMap.delete(t)},i);this.fnMap.set(t,{fn:e,threshold:i,timer:a,args:o,skipFn:r})}else n.skipFn&&n.skipFn(...n.args),this.fnMap.set(t,SM(SM({},n),{},{fn:e,args:o,skipFn:r}))}else{let n=window.setTimeout(()=>{let e=this.fnMap.get(t);e&&e.fn(...e.args),this.fnMap.delete(t)},i);this.fnMap.set(t,{fn:e,threshold:i,timer:n,args:o,skipFn:r})}}constructor(){SL(this,"fnMap",new Map)}},gL=gP.throttleByKey.bind(gP);function gk(e){return"object"==typeof e&&null!==e&&!(e instanceof RegExp)}function gM(e,t){let i=[0];if(t&&(i=Array(t).fill(0)),0===e)return i;let r=0;for(;e>0&&(i[r]=255&e,e>>=8,r++,!t||r!==t););return i}function gU(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function gx(e,t){try{return"object"==typeof e&&"object"==typeof t&&JSON.stringify(e)===JSON.stringify(t)}catch(e){return!1}}function gV(e){return as(e).call(e,(e,t)=>e+t,0)}function gF(e){let t="0123456789abcdef";function i(e){let i,r="";for(i=0;i<=3;i++)r+=t.charAt(e>>8*i+4&15)+t.charAt(e>>8*i&15);return r}function r(e,t){let i=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(i>>16)<<16|65535&i}function n(e,t,i,n,o,a){var s;return r((s=r(r(t,e),r(n,a)))<<o|s>>>32-o,i)}function o(e,t,i,r,o,a,s){return n(t&i|~t&r,e,t,o,a,s)}function a(e,t,i,r,o,a,s){return n(t&r|i&~r,e,t,o,a,s)}function s(e,t,i,r,o,a,s){return n(t^i^r,e,t,o,a,s)}function c(e,t,i,r,o,a,s){return n(i^(t|~r),e,t,o,a,s)}let d=function(e){let t,i=1+(e.length+8>>6),r=Array(16*i);for(t=0;t<16*i;t++)r[t]=0;for(t=0;t<e.length;t++)r[t>>2]|=e.charCodeAt(t)<<t%4*8;return r[t>>2]|=128<<t%4*8,r[16*i-2]=8*e.length,r}(e),l,h,u,p,_,E=0x67452301,m=-0x10325477,f=-0x67452302,S=0x10325476;for(l=0;l<d.length;l+=16)h=E,u=m,p=f,_=S,E=o(E,m,f,S,d[l+0],7,-0x28955b88),S=o(S,E,m,f,d[l+1],12,-0x173848aa),f=o(f,S,E,m,d[l+2],17,0x242070db),m=o(m,f,S,E,d[l+3],22,-0x3e423112),E=o(E,m,f,S,d[l+4],7,-0xa83f051),S=o(S,E,m,f,d[l+5],12,0x4787c62a),f=o(f,S,E,m,d[l+6],17,-0x57cfb9ed),m=o(m,f,S,E,d[l+7],22,-0x2b96aff),E=o(E,m,f,S,d[l+8],7,0x698098d8),S=o(S,E,m,f,d[l+9],12,-0x74bb0851),f=o(f,S,E,m,d[l+10],17,-42063),m=o(m,f,S,E,d[l+11],22,-0x76a32842),E=o(E,m,f,S,d[l+12],7,0x6b901122),S=o(S,E,m,f,d[l+13],12,-0x2678e6d),f=o(f,S,E,m,d[l+14],17,-0x5986bc72),m=o(m,f,S,E,d[l+15],22,0x49b40821),E=a(E,m,f,S,d[l+1],5,-0x9e1da9e),S=a(S,E,m,f,d[l+6],9,-0x3fbf4cc0),f=a(f,S,E,m,d[l+11],14,0x265e5a51),m=a(m,f,S,E,d[l+0],20,-0x16493856),E=a(E,m,f,S,d[l+5],5,-0x29d0efa3),S=a(S,E,m,f,d[l+10],9,0
1x2441453),f=a(f,S,E,m,d[l+15],14,-0x275e197f),m=a(m,f,S,E,d[l+4],20,-0x182c0438),E=a(E,m,f,S,d[l+9],5,0x21e1cde6),S=a(S,E,m,f,d[l+14],9,-0x3cc8f82a),f=a(f,S,E,m,d[l+3],14,-0xb2af279),m=a(m,f,S,E,d[l+8],20,0x455a14ed),E=a(E,m,f,S,d[l+13],5,-0x561c16fb),S=a(S,E,m,f,d[l+2],9,-0x3105c08),f=a(f,S,E,m,d[l+7],14,0x676f02d9),m=a(m,f,S,E,d[l+12],20,-0x72d5b376),E=s(E,m,f,S,d[l+5],4,-378558),S=s(S,E,m,f,d[l+8],11,-0x788e097f),f=s(f,S,E,m,d[l+11],16,0x6d9d6122),m=s(m,f,S,E,d[l+14],23,-0x21ac7f4),E=s(E,m,f,S,d[l+1],4,-0x5b4115bc),S=s(S,E,m,f,d[l+4],11,0x4bdecfa9),f=s(f,S,E,m,d[l+7],16,-0x944b4a0),m=s(m,f,S,E,d[l+10],23,-0x41404390),E=s(E,m,f,S,d[l+13],4,0x289b7ec6),S=s(S,E,m,f,d[l+0],11,-0x155ed806),f=s(f,S,E,m,d[l+3],16,-0x2b10cf7b),m=s(m,f,S,E,d[l+6],23,0x4881d05),E=s(E,m,f,S,d[l+9],4,-0x262b2fc7),S=s(S,E,m,f,d[l+12],11,-0x1924661b),f=s(f,S,E,m,d[l+15],16,0x1fa27cf8),m=s(m,f,S,E,d[l+2],23,-0x3b53a99b),E=c(E,m,f,S,d[l+0],6,-0xbd6ddbc),S=c(S,E,m,f,d[l+7],10,0x432aff97),f=c(f,S,E,m,d[l+14],15,-0x546bdc59),m=c(m,f,S,E,d[l+5],21,-0x36c5fc7),E=c(E,m,f,S,d[l+12],6,0x655b59c3),S=c(S,E,m,f,d[l+3],10,-0x70f3336e),f=c(f,S,E,m,d[l+10],15,-1051523),m=c(m,f,S,E,d[l+1],21,-0x7a7ba22f),E=c(E,m,f,S,d[l+8],6,0x6fa87e4f),S=c(S,E,m,f,d[l+15],10,-0x1d31920),f=c(f,S,E,m,d[l+6],15,-0x5cfebcec),m=c(m,f,S,E,d[l+13],21,0x4e0811a1),E=c(E,m,f,S,d[l+4],6,-0x8ac817e),S=c(S,E,m,f,d[l+11],10,-0x42c50dcb),f=c(f,S,E,m,d[l+2],15,0x2ad7d2bb),m=c(m,f,S,E,d[l+9],21,-0x14792c6f),E=r(E,h),m=r(m,u),f=r(f,p),S=r(S,_);return i(E)+i(m)+i(f)+i(S)}let gB=1,gj=console,gG=class{static setLogger(e){gj=e}logger(e,t){let i=(this.id?"[".concat(this.id,"]"):"")+"[lock-".concat(this.name,"-").concat(this.lockId,"]"),r="created"===e?"is ".concat(e,"."):"is ".concat(e,", current queue ").concat(this.locks,". ").concat(null!=t?t:"");gj.debug("".concat(i," ").concat(r))}setId(e){this.id=e}get isLocked(){return this.locks>0}lock(e){let t;this.locks+=1,this.logger("locked",e);let i=new dQ(i=>{t=()=>{this.locks-=1,this.logger("unlocked",e),i()}}),r=this.lockingPromise.then(()=>t);return this.lockingPromise=this.lockingPromise.then(()=>i),r}constructor(e,t){SL(this,"id",void 0),SL(this,"lockingPromise",dQ.resolve()),SL(this,"locks",0),SL(this,"name",""),SL(this,"lockId",void 0),this.lockId=gB++,e&&(this.name=e),t&&(this.id=t),this.logger("created")}};function gW(e,t){return function(i,r,n){let o=n.value;if("function"!=typeof o)throw Error("Cannot use mutex on object property.");return n.value=async function(){let i=this[t];if(!i)throw Error("mutex property key ".concat(t," doesn't exist on ").concat(e));let n=await i.lock("From ".concat(e,".").concat(r));try{for(var a=arguments.length,s=Array(a),c=0;c<a;c++)s[c]=arguments[c];return await o.apply(this,s)}finally{n()}},n}}let gH={timeout:500,timeoutFactor:1.5,maxRetryCount:1/0,maxRetryTimeout:1e4};function gK(e,t){let i=Math.floor(t.timeout*Math.pow(t.timeoutFactor,e));return Math.min(t.maxRetryTimeout,i)}function gY(e,t,i,r){let n=Object.assign({},gH,r),o=n.timeout,a=async()=>{var e;await (e=o,new dQ(t=>{window.setTimeout(t,e)})),o*=n.timeoutFactor,o=Math.min(n.maxRetryTimeout,o)},s=!1,c=new dQ(async(r,o)=>{t=t||(()=>!1),i=i||(()=>!0);for(let c=0;c<n.maxRetryCount;c+=1){if(s)return o(new Sx(SU.OPERATION_ABORTED));try{let i=await e();if(!t(i,c)||c+1===n.maxRetryCount)return r(i);await a()}catch(e){if(!i(e,c)||c+1===n.maxRetryCount)return o(e);await a()}}});return c.cancel=()=>s=!0,c}let gz,gq=class{add(e){this.input.push(e),this.input.length>this.size&&this.input.splice(0,1)}mean(){var e;return 0===this.input.length?0:as(e=this.input).call(e,(e,t)=>e+t)/this.input.length}constructor(e){SL(this,"input",[]),SL(this,"size",void 0),this.size=e}},gX=0,gJ=0;function gQ(e,t,i,r){return new dQ((n,o)=>{t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),gX+=gA(t.data)):i&&(t.data.size?gX+=t.data.size:t.data instanceof FormData?gX+=gb(t.data):gX+=gA(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,f0.request(t).then(e=>{"string"==typeof e.data?gJ+=gA(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?gJ+=e.data.byteLength:gJ+=gA(JSON.stringify(e.data)),r&&n({data:e.data,headers:e.headers}),n(e.data)}).catch(e=>{f0.isCancel(e)?o(new Sx(SU.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?o(new Sx(SU.NETWORK_TIMEOUT,e.message)):e.response?o(new Sx(SU.NETWORK_RESPONSE_E
1RROR,e.response.status)):o(new Sx(SU.NETWORK_ERROR,e.message))})})}async function gZ(e,t){let i=new Blob([t.data],{type:"buffer"});return await gQ(e,SM(SM({},t),{},{data:i,headers:{"Content-Type":"application/octet-stream"}}),!0)}function g$(e){if(Array.isArray(e))return e.map(e=>e);if(!g0(e))return e;let t={};for(let i in e){let r=e[i];g0(r)||Array.isArray(r)?t[i]=g$(r):t[i]=r}return t}function g0(e){return!("object"!=typeof e||Array.isArray(e)||!e)}let g1=class{add(e){this.input.push(e),this.input.length>this.size&&this.input.splice(0,1)}diffMean(){return 0===this.input.length?0:(this.input[this.input.length-1]-this.input[0])/this.input.length}constructor(e){SL(this,"input",[]),SL(this,"size",void 0),this.size=e}},g2={address:"unknown",candidateType:"unknown",id:"unknown",port:0,priority:0,protocol:"unknown",type:"unknown"},g3={timestamp:0,bitrate:{actualEncoded:0,transmit:0},sendPacketLossRate:0,recvPacketLossRate:0,videoRecv:[],videoSend:[],audioRecv:[],audioSend:[],transport:{bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0},selectedCandidatePair:{id:"unknown",localCandidate:g2,remoteCandidate:g2},updateInterval:0},g5={firsCount:0,nacksCount:0,plisCount:0,framesDecodeCount:0,framesDecodeInterval:0,framesDecodeFreezeTime:0,decodeFrameRate:0,bytes:0,packetsLost:0,packetLostRate:0,packets:0,ssrc:0,qpSumPerFrame:0,framesDroppedCount:0,outputFrameRate:0,packetsDiscarded:0,framesAssembledFromMultiplePackets:0,totalProcessingDelay:0,avgDecodeMs:0,avgFramesAssembledFromMultiplePacketsMs:0,avgProcessingDelayMs:0,avgInterFrameDelayMs:0,totalAssemblyTime:0},g4={firsCount:0,nacksCount:0,plisCount:0,frameCount:0,bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0,qpSumPerFrame:0},g6={bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0},g8={jitterBufferMs:0,jitterMs:0,bytes:0,packetsLost:0,packetLostRate:0,packetsDiscarded:0,packets:0,ssrc:0,receivedFrames:0,droppedFrames:0,concealedSamples:0,totalSamplesReceived:0,silentConcealedSamples:0,concealmentEvents:0,freezeMs80:0,freezeMs200:0,freezeSamples80:0,freezeSamples200:0},g9=class{getStats(){return this.stats}getSelectedCandidatePair(){return new dQ(e=>{e({local:SM({},g2),remote:SM({},g2)})})}setVideoIsReady(e){this.videoIsReady=e}setVideoIsReady2(e,t){this.videoIsReady2[e]=t}getVideoIsReady(e){return this.videoIsReady2[e]||!1}setIsFirstAudioDecoded(e){}destroy(){window.clearInterval(this.intervalTimer),this.pc=void 0}calcLossRate(e){this.lossRateWindowStats.push(e),this.lossRateWindowStats.length>this.options.lossRateInterval&&this.lossRateWindowStats.splice(0,1);let t=this.lossRateWindowStats.length,i=0,r=0,n=0,o=0;for(let a of["videoSend","audioSend","videoRecv","audioRecv"])e[a].forEach((e,s)=>{if(!this.lossRateWindowStats[t-1][a][s]||!this.lossRateWindowStats[0][a][s])return;let c=this.lossRateWindowStats[t-1][a][s].packets-this.lossRateWindowStats[0][a][s].packets,d=this.lossRateWindowStats[t-1][a][s].packetsLost-this.lossRateWindowStats[0][a][s].packetsLost;"videoSend"===a||"audioSend"===a?(i+=c,n+=d):(r+=c,o+=d),Number.isNaN(c)||Number.isNaN(c)?e.packetLostRate=0:e.packetLostRate=c<=0||d<=0?0:d/(c+d)});e.sendPacketLossRate=i<=0||n<=0?0:n/(i+n),e.recvPacketLossRate=r<=0||o<=0?0:o/(r+o)}constructor(e,t){SL(this,"onFirstVideoReceived",void 0),SL(this,"onFirstVideoDecoded",void 0),SL(this,"onFirstAudioReceived",void 0),SL(this,"onFirstVideoDecodedTimeout",void 0),SL(this,"onFirstAudioDecoded",void 0),SL(this,"onSelectedLocalCandidateChanged",void 0),SL(this,"onSelectedRemoteCandidateChanged",void 0),SL(this,"videoIsReady",!1),SL(this,"videoIsReady2",{}),SL(this,"pc",void 0),SL(this,"options",void 0),SL(this,"intervalTimer",void 0),SL(this,"stats",g$(g3)),SL(this,"isFirstVideoReceived",{}),SL(this,"isFirstVideoDecoded",{}),SL(this,"isFirstAudioReceived",{}),SL(this,"isFirstAudioDecoded",{}),SL(this,"isFirstVideoDecodedTimeout",{}),SL(this,"lossRateWindowStats",[]),this.pc=e,this.options=t,this.intervalTimer=window.setInterval(async()=>{this.updateStats()},this.options.updateInterval)}},g7=class extends g9{async updateStats(){let e=await this._getStats(),t=this.statsResponsesToObjects(e);this._stats=g$(g3);let i=t.filter(e=>"ssrc"===e.type);this.processSSRCStats(i);let r=t.find(e=>"VideoBwe"===e.type);r&&this.processBandwidthStats(r),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats}processBandwidthStats(e){this._stats.bitrate={actualEncoded:Number(e.googActualEncBitrate),targetEncoded:Number(e.googTargetEncBitrate),retransmit:Number(e.googRetransmitBitrate),transmit:Number(e.googTransmitBitrate)},this._stats.sendBandwidth=Number(e.googAvailableSendBandwidth)}
vendor: 4,588 bytes, line 1
1processSSRCStats(e){e.forEach(e=>{var t;let i=o5(t=e.id).call(t,"send");switch("".concat(e.mediaType,"_").concat(i?"send":"recv")){case"video_send":{let t=g$(g4);t.codec=e.googCodecName,t.adaptionChangeReason="none",e.googCpuLimitedResolution&&(t.adaptionChangeReason="cpu"),e.googBandwidthLimitedResolution&&(t.adaptionChangeReason="bandwidth"),t.avgEncodeMs=Number(e.googAvgEncodeMs),t.inputFrame={width:Number(e.googFrameWidthInput)||Number(e.googFrameWidthSent),height:Number(e.googFrameHeightInput)||Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},t.sentFrame={width:Number(e.googFrameWidthSent),height:Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},t.firsCount=Number(e.googFirReceived),t.nacksCount=Number(e.googNacksReceived),t.plisCount=Number(e.googPlisReceived),t.frameCount=Number(e.framesEncoded),t.bytes=Number(e.bytesSent),t.packets=Number(e.packetsSent),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.rttMs=Number(e.googRtt||0),this._stats.videoSend.push(t),this._stats.rtt=t.rttMs;break}case"video_recv":{let t=g$(g5),i=this.lastDecodeVideoReceiverStats.get(Number(e.ssrc));if(t.codec=e.googCodecName,t.targetDelayMs=Number(e.googTargetDelayMs),t.renderDelayMs=Number(e.googRenderDelayMs),t.currentDelayMs=Number(e.googCurrentDelayMs),t.minPlayoutDelayMs=Number(e.googMinPlayoutDelayMs),t.decodeMs=Number(e.googDecodeMs),t.maxDecodeMs=Number(e.googMaxDecodeMs),t.receivedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateReceived)},t.decodedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateDecoded)},t.decodeFrameRate=Number(e.googFrameRateDecoded),t.outputFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateOutput)},t.jitterBufferMs=Number(e.googJitterBufferMs),t.firsCount=Number(e.googFirsSent),t.nacksCount=Number(e.googNacksSent),t.plisCount=Number(e.googPlisSent),t.framesDecodeCount=Number(e.framesDecoded),t.bytes=Number(e.bytesReceived),t.packets=Number(e.packetsReceived),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.packets>0&&!this.isFirstVideoReceived[t.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(t.ssrc),this.isFirstVideoReceived[t.ssrc]=!0),t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]&&(this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,t.decodedFrame.width,t.decodedFrame.height),this.isFirstVideoDecoded[t.ssrc]=!0),i){let r=i.stats,n=Date.now()-i.lts;t.framesDecodeFreezeTime=r.framesDecodeFreezeTime,t.framesDecodeInterval=r.framesDecodeInterval,t.framesDecodeCount>r.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(i.lts=Date.now(),t.framesDecodeInterval=n,t.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc,10))?t.framesDecodeFreezeTime+=t.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):t.framesDecodeCount<i.stats.framesDecodeCount&&(t.framesDecodeInterval=0)}this.lastDecodeVideoReceiverStats.set(t.ssrc,{stats:SM({},t),lts:Date.now()}),this._stats.videoRecv.push(t);break}case"audio_recv":{let t=g$(g8);t.codec=e.googCodecName,t.outputLevel=Math.abs(Number(e.audioOutputLevel))/32767,t.decodingCNG=Number(e.googDecodingCNG),t.decodingCTN=Number(e.googDecodingCTN),t.decodingCTSG=Number(e.googDecodingCTSG),t.decodingNormal=Number(e.googDecodingNormal),t.decodingPLC=Number(e.googDecodingPLC),t.decodingPLCCNG=Number(e.googDecodingPLCCNG),t.expandRate=Number(e.googExpandRate),t.accelerateRate=Number(e.googAccelerateRate),t.preemptiveExpandRate=Number(e.googPreemptiveExpandRate),t.secondaryDecodedRate=Number(e.googSecondaryDecodedRate),t.speechExpandRate=Number(e.googSpeechExpandRate),t.preferredJitterBufferMs=Number(e.googPreferredJitterBufferMs),t.jitterBufferMs=Number(e.googJitterBufferMs),t.jitterMs=Number(e.googJitterReceived),t.bytes=Number(e.bytesReceived),t.packets=Number(e.packetsReceived),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.receivedFrames=Number(e.googDecodingCTN)||Number(e.packetsReceived),t.droppedFrames=Number(e.googDecodingPLC)+Number(e.googDecodingPLCCNG)||Number(e.packetsLost),t.receivedFrames>0&&!this.isFirstAudioReceived[t.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(t.ssrc),this.isFirstAudioReceived[t.ssrc]=!0),t.decodingNormal>0&&!this.isFirstAudioDecoded[t.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(t.ssrc),this.isFirstAudioDecoded[t.ssrc]=!0),this._stats.audioRecv.pu
1sh(t);break}case"audio_send":{let t=g$(g6);t.codec=e.googCodecName,t.inputLevel=Math.abs(Number(e.audioInputLevel))/32767,t.aecReturnLoss=Number(e.googEchoCancellationReturnLoss||0),t.aecReturnLossEnhancement=Number(e.googEchoCancellationReturnLossEnhancement||0),t.residualEchoLikelihood=Number(e.googResidualEchoLikelihood||0),t.residualEchoLikelihoodRecentMax=Number(e.googResidualEchoLikelihoodRecentMax||0),t.bytes=Number(e.bytesSent),t.packets=Number(e.packetsSent),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.rttMs=Number(e.googRtt||0),this._stats.rtt=t.rttMs,this._stats.audioSend.push(t)}}})}_getStats(){return new dQ((e,t)=>{this.pc.getStats(e,t)})}statsResponsesToObjects(e){let t=[];return e.result().forEach(e=>{let i={id:e.id,timestamp:e.timestamp.valueOf().toString(),type:e.type};e.names().forEach(t=>{i[t]=e.stat(t)}),t.push(i)}),t}constructor(){super(...arguments),SL(this,"_stats",g3),SL(this,"lastDecodeVideoReceiverStats",new Map)}},Te=((P={}).BANDWIDTH="bandwidth",P.CPU="cpu",P.NONE="none",P.OTHER="other",P),Tt=((L={}).L1T1="L1T1",L.L1T2="L1T2",L.L1T3="L1T3",L.L1T3_KEY="L1T3_KEY",L.L2T1_KEY="L2T1_KEY",L.L2T2_KEY="L2T2_KEY",L.L2T3_KEY="L2T3_KEY",L.L3T1_KEY="L3T1_KEY",L.L3T2_KEY="L3T2_KEY",L.L3T3_KEY="L3T3_KEY",L),Ti=((k={})[k.new=0]="new",k[k.connecting=1]="connecting",k[k.connected=2]="connected",k[k.disconnected=3]="disconnected",k[k.failed=4]="failed",k[k.closed=5]="closed",k),Tr=((M={}).CERTIFICATE="certificate",M.CODEC="codec",M.CANDIDATE_PAIR="candidate-pair",M.LOCAL_CANDIDATE="local-candidate",M.REMOTE_CANDIDATE="remote-candidate",M.INBOUND="inbound-rtp",M.TRACK="track",M.OUTBOUND="outbound-rtp",M.PC="peer-connection",M.REMOTE_INBOUND="remote-inbound-rtp",M.REMOTE_OUTBOUND="remote-outbound-rtp",M.TRANSPORT="transport",M.CSRC="csrc",M.DATA_CHANNEL="data-channel",M.STREAM="stream",M.SENDER="sender",M.RECEIVER="receiver",M);var Tn=((U=Tn||{})[U.kNone=1]="kNone",U[U.kMillisecondsFromSeconds=1e3]="kMillisecondsFromSeconds",U[U.kBytesToBits=8]="kBytesToBits",U);function To(e,t,i,r){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:Tn.kNone;if(!t)return;let o=Number(t[i]);if("number"!=typeof o)return;let a=Number(t[r]);if("number"!=typeof a)return;if(!e)return a?o/a*n:void 0;let s=Number(e[i]);if("number"!=typeof s)return;let c=Number(e[r]);if("number"!=typeof c)return;let d=a-c;return d?(o-s)/d*n:void 0}let Ta=class extends g9{async updateStats(){this.report=await this.pc.getStats(),this._stats=g$(g3),this.report.forEach(e=>{switch(e.type){case Tr.OUTBOUND:case Tr.INBOUND:{let t=e.mediaType||e.kind,i=!t&&"frameWidth"in e,r=!t&&!("frameWidth"in e);e.type===Tr.OUTBOUND?"audio"===t||r?this.processAudioOutboundStats(e):("video"===t||i)&&this.processVideoOutboundStats(e):e.type===Tr.INBOUND&&("audio"===t||r?this.processAudioInboundStats(e):("video"===t||i)&&this.processVideoInboundStats(e));break}case Tr.TRANSPORT:{this.processTransportStats(e);let t=this.report.get(e.selectedCandidatePairId);t&&this.processCandidatePairStats(t);break}case Tr.CANDIDATE_PAIR:e.selected&&this.processCandidatePairStats(e)}}),this.updateSendBitrate(),this._stats.updateInterval=Date.now()-this.stats.timestamp,this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats}async getSelectedCandidatePair(){let e=await this.pc.getStats(),t={local:SM({},g2),remote:SM({},g2)};return e.forEach(i=>{let r;if(i.type===Tr.TRANSPORT&&(r=e.get(i.selectedCandidatePairId)),i.type===Tr.CANDIDATE_PAIR&&i.selected&&(r=i),r){let i=(e,t)=>{e.type=t.type,e.id=t.id,t.address&&(e.address=t.address),t.candidateType&&(e.candidateType=t.candidateType),t.port&&(e.port=t.port),t.priority&&(e.priority=t.priority),t.protocol&&(e.protocol=t.protocol),t.relayProtocol&&(e.relayProtocol=t.relayProtocol)};if(r.localCandidateId){let n=e.get(r.localCandidateId);n&&i(t.local,n)}if(r.remoteCandidateId){let n=e.get(r.remoteCandidateId);n&&i(t.remote,n)}}}),t}processCandidatePairStats(e){if(this._stats.sendBandwidth=e.availableOutgoingBitrate||0,e.currentRoundTripTime&&(this._stats.rtt=1e3*e.currentRoundTripTime),this._stats.videoSend.forEac
1h(t=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime)}),this._stats.audioSend.forEach(t=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime)}),this._stats.selectedCandidatePair.id=e.id,e.localCandidateId){let t=this.report.get(e.localCandidateId);t&&this.processCandidateStats(t)}if(e.remoteCandidateId){let t=this.report.get(e.remoteCandidateId);t&&this.processCandidateStats(t)}}processCandidateStats(e){let t;e.type===Tr.LOCAL_CANDIDATE&&(t=this._stats.selectedCandidatePair.localCandidate),e.type===Tr.REMOTE_CANDIDATE&&(t=this._stats.selectedCandidatePair.remoteCandidate),t&&(t.type=e.type,t.id=e.id,e.address&&(t.address=e.address),e.candidateType&&(t.candidateType=e.candidateType),e.port&&(t.port=e.port),e.priority&&(t.priority=e.priority),e.protocol&&(t.protocol=e.protocol),e.relayProtocol&&(t.relayProtocol=e.relayProtocol),e.type===Tr.LOCAL_CANDIDATE&&this.stats.selectedCandidatePair.localCandidate.id!==t.id&&this.onSelectedLocalCandidateChanged&&this.onSelectedLocalCandidateChanged(SM({},t),SM({},this.stats.selectedCandidatePair.localCandidate)),e.type===Tr.REMOTE_CANDIDATE&&this.stats.selectedCandidatePair.remoteCandidate.id!==t.id&&this.onSelectedRemoteCandidateChanged&&this.onSelectedRemoteCandidateChanged(SM({},t),SM({},this.stats.selectedCandidatePair.remoteCandidate)))}processAudioInboundStats(e){let t=this._stats.audioRecv.find(t=>t.ssrc===e.ssrc);t||(t=g$(g8),this._stats.audioRecv.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsReceived,t.packetsLost=e.packetsLost,t.packetsDiscarded=e.packetsDiscarded,t.bytes=e.bytesReceived,t.jitterMs=1e3*e.jitter,t.retransmittedBytesReceived=e.retransmittedBytesReceived,t.retransmittedPacketsReceived=e.retransmittedPacketsReceived,t.totalProcessingDelay=e.totalProcessingDelay,t.jitterBufferEmittedCount=e.jitterBufferEmittedCount,t.estimatedPlayoutTimestamp=e.estimatedPlayoutTimestamp;let i=this.lastDecodeAudioReceiverStats.get(t.ssrc);t.avgProcessingDelayMs=To(i,t,"totalProcessingDelay","jitterBufferEmittedCount",Tn.kMillisecondsFromSeconds),this.processAudioTrackReceiverStats(e,e.trackId,t),this.calculateAudioFreeze(t,i,e),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),t.receivedFrames||(t.receivedFrames=e.packetsReceived),t.droppedFrames||(t.droppedFrames=e.packetsLost),t.receivedFrames>0&&!this.isFirstAudioReceived[t.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(t.ssrc),this.isFirstAudioReceived[t.ssrc]=!0),t.outputLevel&&t.outputLevel>0&&!this.isFirstAudioDecoded[t.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(t.ssrc),this.isFirstAudioDecoded[t.ssrc]=!0),"number"==typeof e.concealedSamples&&(t.concealedSamples=e.concealedSamples),this.lastDecodeAudioReceiverStats.set(t.ssrc,SM({},t))}calculateAudioFreeze(e,t,i){let r=this.lastAudioConcealment.get(e.ssrc);if(null!=t&&null!=r){let n=r.lts,o=i.timestamp,a=o-n;if(a<=0)return;let s=e.concealedSamples-t.concealedSamples-0,c=r.nonSilent+s,d=e.totalSamplesReceived-t.totalSamplesReceived;if(d<=0)return;let l=a/d,h=0;e.freezeSamples80=t.freezeSamples80,e.freezeMs80=t.freezeMs80,c>80*d/a&&(r.plc80>0?(e.freezeSamples80+=s,e.freezeMs80+=Math.round(s*l)):(e.freezeSamples80+=c,e.freezeMs80+=Math.round(c*l)),h=r.plc80+1);let u=0;e.freezeSamples200=t.freezeSamples200,e.freezeMs200=t.freezeMs200,c>200*d/a&&(r.plc200>0?(e.freezeSamples200+=s,e.freezeMs200+=Math.round(s*l)):(e.freezeSamples200+=c,e.freezeMs200+=Math.round(c*l)),u=r.plc200+1),this.lastAudioConcealment.set(e.ssrc,{nonSilent:s,lts:o,plc80:h,plc200:u})}else e.freezeSamples80=0,e.freezeSamples200=0,e.freezeMs80=0,e.freezeMs200=0,this.lastAudioConcealment.set(e.ssrc,{nonSilent:0,lts:i.timestamp,plc80:0,plc200:0})}processVideoInboundStats(e){let t=this._stats.videoRecv.find(t=>t.ssrc===e.ssrc);t||(t=g$(g5),this._stats.videoRecv.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsReceived,t.packetsLost=e.packetsLost,t.bytes=e.bytesReceived,t.firsCount=e.firCount,t.nacksCount=e.nackCount,t.plisCount=e.pliCount,t.framesDecodeCount=e.framesDecoded,t.framesDroppedCount=e.framesDropped,t.totalInterFrameDelay=e.totalInterFrameDelay,t.totalSquaredInterFrameDelay=e.totalSquaredInterFrameDelay,t.totalFreezesDuration=e.totalFreezesDuration,t.totalProcessingDelay=e.totalProcessingDelay,t.packetsDiscarded=e.packetsDiscarded,t.framesAssembledFromMultiplePackets=e.framesAssembledFromMultiplePackets,t.totalAssemblyTime=e.totalAssemblyTime,t.keyFramesDecoded=e.keyFramesDecoded,t.retransmittedBytesReceived=e.retransmittedBytesReceived,t.retransmittedPacketsReceived=e.retransmittedPacketsReceived,t.estimatedPlayoutTimestamp=e.estimatedPlayoutTimestamp;let i=this.lastDecodeVideoReceiverStats.get(t.ssrc),r=this.lastVideoFramesDecode.get(t.
1ssrc),n=this.lastVideoFramesOutput.get(t.ssrc),o=Date.now();if(t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]){let e=t.decodedFrame?t.decodedFrame.width:0,i=t.decodedFrame?t.decodedFrame.height:0;this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,e,i),this.isFirstVideoDecoded[t.ssrc]=!0}if(i){let r=i.stats,n=o-i.lts;t.framesDecodeFreezeTime=r.framesDecodeFreezeTime,t.framesDecodeInterval=r.framesDecodeInterval,this.isFirstVideoDecoded[t.ssrc]||!(n>this.options.firstVideoDecodedTimeout)||this.isFirstVideoDecodedTimeout[t.ssrc]||(this.onFirstVideoDecodedTimeout&&this.onFirstVideoDecodedTimeout(t.ssrc),this.isFirstVideoDecodedTimeout[t.ssrc]=!0),t.framesDecodeCount>r.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(i.lts=Date.now(),t.framesDecodeInterval=n,t.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc))?t.framesDecodeFreezeTime+=t.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):t.framesDecodeCount<r.framesDecodeCount&&(t.framesDecodeInterval=0),e.framesDecoded&&e.qpSum&&(i.stats.framesDecodeCount>e.framesDecoded?t.qpSumPerFrame=e.qpSum/e.framesDecoded:t.qpSumPerFrame=(e.qpSum-i.qpSum)/(e.framesDecoded-i.stats.framesDecodeCount))}e.totalDecodeTime&&(t.decodeMs=1e3*e.totalDecodeTime,t.avgDecodeMs=To(null==i?void 0:i.stats,t,"decodeMs","framesDecodeCount")),t.avgProcessingDelayMs=To(null==i?void 0:i.stats,t,"totalProcessingDelay","framesDecodeCount",Tn.kMillisecondsFromSeconds),t.avgFramesAssembledFromMultiplePacketsMs=To(null==i?void 0:i.stats,t,"totalAssemblyTime","framesAssembledFromMultiplePackets",Tn.kMillisecondsFromSeconds),t.avgInterFrameDelayMs=To(null==i?void 0:i.stats,t,"totalInterFrameDelay","framesDecodeCount",Tn.kMillisecondsFromSeconds),r&&o-r.lts>=800?(t.decodeFrameRate=Math.round((t.framesDecodeCount-r.count)/((o-r.lts)/1e3)),this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:o,rate:t.decodeFrameRate})):r?t.decodeFrameRate=r.rate:this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:o,rate:0}),t.framesDroppedCount&&e.framesReceived&&(n&&o-n.lts>=800?(t.outputFrameRate=Math.round((e.framesReceived-t.framesDroppedCount-n.count)/((o-n.lts)/1e3)),this.lastVideoFramesOutput.set(t.ssrc,{count:e.framesReceived-t.framesDroppedCount,lts:o,rate:Math.max(t.outputFrameRate,0)})):n?t.outputFrameRate=n.rate:this.lastVideoFramesOutput.set(t.ssrc,{count:e.framesReceived-t.framesDroppedCount,lts:o,rate:0})),this.processVideoTrackReceiverStats(e,e.trackId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),e.framerateMean&&(t.framesRateFirefox=e.framerateMean),t.packets>0&&!this.isFirstVideoReceived[t.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(t.ssrc),this.isFirstVideoReceived[t.ssrc]=!0),this.lastDecodeVideoReceiverStats.set(t.ssrc,{stats:SM({},t),lts:i?i.lts:Date.now(),qpSum:e.qpSum})}processVideoOutboundStats(e){let t=this._stats.videoSend.find(t=>t.ssrc===e.ssrc);t||(t=g$(g4),this._stats.videoSend.push(t));let i=this.mediaBytesSent.get(e.ssrc);if(i)i.add(e.bytesSent);else{let t=new g1(10);t.add(e.bytesSent),this.mediaBytesSent.set(e.ssrc,t)}if(void 0!==e.retransmittedBytesSent){let t=this.mediaBytesRetransmit.get(e.ssrc);if(t)t.add(e.retransmittedBytesSent);else{let t=new g1(10);t.add(e.retransmittedBytesSent),this.mediaBytesRetransmit.set(e.ssrc,t)}}if(e.totalEncodedBytesTarget){let t=this.mediaBytesTargetEncode.get(e.ssrc);if(t)t.add(e.totalEncodedBytesTarget);else{let t=new g1(10);t.add(e.totalEncodedBytesTarget),this.mediaBytesTargetEncode.set(e.ssrc,t)}}if(t.ssrc=e.ssrc,t.bytes=e.bytesSent,t.packets=e.packetsSent,t.firsCount=e.firCount,t.nacksCount=e.nackCount,t.plisCount=e.pliCount,t.frameCount=e.framesEncoded,t.adaptionChangeReason=e.qualityLimitationReason,t.scalabilityMode=e.scalabilityMode,t.retransmittedBytesSent=e.retransmittedBytesSent,t.retransmittedPacketsSent=e.retransmittedPacketsSent,t.hugeFramesSent=e.hugeFramesSent,t.keyFramesEncoded=e.keyFramesEncoded,t.targetBitrate=e.targetBitrate,e.totalEncodeTime&&e.framesEncoded){let i=this.lastEncoderMs.get(e.ssrc);if(!i||i.lastFrameCount>e.framesEncoded)t.avgEncodeMs=1e3*e.totalEncodeTime/e.framesEncoded;else{let r=e.framesEncoded-i.lastFrameCount,n=e.totalEncodeTime-i.lastEncoderTime;t.avgEncodeMs=1e3*n/r}}if(e.framesEncoded&&e.qpSum){let i=this.lastEncoderMs.get(e.ssrc);!i||i.lastFrameCount>e.framesEncoded?t.qpSumPerFrame=e.qpSum/e.framesEncoded:t.qpSumPerFrame=(e.qpSum-i.lastQpSum)/(e.framesEncoded-i.lastFrameCount)}
1if(this.lastEncoderMs.set(e.ssrc,{lastFrameCount:e.framesEncoded,lastEncoderTime:e.totalEncodeTime,lastQpSum:e.qpSum,lts:Date.now()}),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),e.mediaSourceId&&this.processVideoMediaSource(e.mediaSourceId,t),this.processVideoTrackSenderStats(e,e.trackId,t),e.remoteId)this.processRemoteInboundStats(e.remoteId,t);else{let i=this.findRemoteStatsId(e.ssrc,Tr.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t)}}processAudioOutboundStats(e){let t=this._stats.audioSend.find(t=>t.ssrc===e.ssrc);if(t||(t=g$(g6),this._stats.audioSend.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsSent,t.bytes=e.bytesSent,t.retransmittedBytesSent=e.retransmittedBytesSent,t.retransmittedPacketsSent=e.retransmittedPacketsSent,e.mediaSourceId&&this.processAudioMediaSource(e.mediaSourceId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),this.processAudioTrackSenderStats(e,e.trackId,t),e.remoteId)this.processRemoteInboundStats(e.remoteId,t);else{let i=this.findRemoteStatsId(e.ssrc,Tr.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t)}}processTransportStats(e){this._stats.transport.bytesReceived=e.bytesReceived||this._stats.transport.bytesReceived,this._stats.transport.bytesSent=e.bytesSent||this._stats.transport.bytesSent,this._stats.transport.packetsReceived=e.packetsReceived||this._stats.transport.packetsReceived,this._stats.transport.packetsSent=e.packetsSent||this._stats.transport.packetsSent}findRemoteStatsId(e,t){var i;let r=Array.from(d1(i=this.report).call(i)).find(i=>i.type===t&&i.ssrc===e);return r?r.id:null}processVideoMediaSource(e,t){let i=this.report.get(e);i&&i.width&&i.height&&i.framesPerSecond&&(t.inputFrame={width:i.width,height:i.height,frameRate:i.framesPerSecond})}processAudioMediaSource(e,t){let i=this.report.get(e);i&&(t.inputLevel=i.audioLevel)}processVideoTrackSenderStats(e,t,i){var r,n,o,a;let s=t?this.report.get(t):void 0,c=null!=(r=null==s?void 0:s.framesSent)?r:e.framesSent;if("number"!=typeof c)return;let d=null!=(n=null==s?void 0:s.frameWidth)?n:e.frameWidth,l=null!=(o=null==s?void 0:s.frameHeight)?o:e.frameHeight,h=null!=(a=null==s?void 0:s.framesPerSecond)?a:e.framesPerSecond;if("number"==typeof d&&"number"==typeof l||(d=0,l=0),null==h){let e=Date.now(),t=this.lastVideoFramesSent.get(i.ssrc);t&&e-t.lts>=800?(h=Math.round((c-t.count)/((e-t.lts)/1e3)),this.lastVideoFramesSent.set(i.ssrc,{count:c,lts:e,rate:h})):t?h=t.rate:this.lastVideoFramesSent.set(i.ssrc,{count:c,lts:e,rate:0})}i.sentFrame={width:d,height:l,frameRate:Math.max(0,h)}}processVideoTrackReceiverStats(e,t,i){var r,n,o,a,s;let c=t?this.report.get(t):void 0,d=null!=(r=null==c?void 0:c.framesReceived)?r:e.framesReceived,l=null!=(n=null==c?void 0:c.frameWidth)?n:e.frameWidth,h=null!=(o=null==c?void 0:c.frameHeight)?o:e.frameHeight,u=null!=(a=null==c?void 0:c.jitterBufferDelay)?a:e.jitterBufferDelay,p=null!=(s=null==c?void 0:c.jitterBufferEmittedCount)?s:e.jitterBufferEmittedCount;if("number"==typeof d){let e=this.lastVideoFramesRecv.get(i.ssrc),t=Date.now();i.framesReceivedCount=d;let r=0;e&&t-e.lts>=800?(r=Math.round((d-e.count)/((t-e.lts)/1e3)),this.lastVideoFramesRecv.set(i.ssrc,{count:d,lts:t,rate:r})):e?r=e.rate:this.lastVideoFramesRecv.set(i.ssrc,{count:d,lts:t,rate:0}),i.receivedFrame={width:l||0,height:h||0,frameRate:r||0},i.decodedFrame={width:l||0,height:h||0,frameRate:i.decodeFrameRate||0},i.outputFrame={width:l||0,height:h||0,frameRate:i.outputFrameRate||i.decodeFrameRate||0}}if(u&&p){let e=this.lastVideoJBDelay.get(i.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0},t=e.jitterBufferMs,r=p-e.jitterBufferEmittedCount;r>0&&(t=1e3*(u-e.jitterBufferDelay)/r),i.jitterBufferMs=t,i.currentDelayMs=Math.round(t),this.lastVideoJBDelay.set(i.ssrc,{jitterBufferDelay:u,jitterBufferEmittedCount:p,jitterBufferMs:i.currentDelayMs})}}processAudioTrackSenderStats(e,t,i){var r,n,o,a;let s=t?this.report.get(t):void 0,c=null!=(r=null!=(n=null==s?void 0:s.echoReturnLoss)?n:e.echoReturnLoss)?r:0,d=null!=(o=null!=(a=null==s?void 0:s.echoReturnLossEnhancement)?a:e.echoReturnLossEnhancement)?o:0;
1i.aecReturnLoss=c,i.aecReturnLossEnhancement=d}processAudioTrackReceiverStats(e,t,i){var r,n,o,a,s,c,d,l,h;let u=t?this.report.get(t):void 0,p=null!=(r=null==u?void 0:u.removedSamplesForAcceleration)?r:e.removedSamplesForAcceleration,_=null!=(n=null==u?void 0:u.totalSamplesReceived)?n:e.totalSamplesReceived,E=null!=(o=null==u?void 0:u.jitterBufferDelay)?o:e.jitterBufferDelay,m=null!=(a=null==u?void 0:u.jitterBufferEmittedCount)?a:e.jitterBufferEmittedCount,f=null!=(s=null==u?void 0:u.audioLevel)?s:null==e?void 0:e.audioLevel,S=null!=(c=null==u?void 0:u.totalSamplesDuration)?c:null==e?void 0:e.totalSamplesDuration,g=null!=(d=null==u?void 0:u.concealedSamples)?d:e.concealedSamples,T=null!=(l=null==u?void 0:u.silentConcealedSamples)?l:e.silentConcealedSamples,R=null!=(h=null==u?void 0:u.concealmentEvents)?h:e.concealmentEvents;if("number"==typeof _&&(i.totalSamplesReceived=_),"number"==typeof T&&(i.silentConcealedSamples=T),"number"==typeof R&&(i.concealmentEvents=R),"number"==typeof g&&(i.concealedSamples=g),p&&_&&(i.accelerateRate=p/_),E&&m){let e=this.lastAudioJBDelay.get(i.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0},t=e.jitterBufferMs,r=m-e.jitterBufferEmittedCount;r>0&&(t=1e3*(E-e.jitterBufferDelay)/r),i.jitterBufferMs=Math.round(t),this.lastAudioJBDelay.set(i.ssrc,{jitterBufferDelay:E,jitterBufferEmittedCount:m,jitterBufferMs:i.jitterBufferMs})}i.outputLevel=f;let C=1920;S&&_&&(C=_/S/50,i.receivedFrames=Math.round(_/C)),g&&(i.droppedFrames=Math.round(g/C))}processRemoteInboundStats(e,t){let i=this.report.get(e);i&&(t.packetsLost=i.packetsLost,i.roundTripTime&&(t.rttMs=1e3*i.roundTripTime),i.jitter&&(t.jitterMs=1e3*i.jitter),i.timestamp&&(t.timestamp=i.timestamp))}getCodecFromCodecStats(e){let t=this.report.get(e);if(!t)return"";let i=t.mimeType.match(/\/(.*)$/);return i&&i[1]?i[1]:""}updateSendBitrate(){let e=0,t=null,i=null;this.mediaBytesSent.forEach(t=>{e+=t.diffMean()}),this.mediaBytesRetransmit.forEach(e=>{t=null===t?e.diffMean():t+e.diffMean()}),this.mediaBytesTargetEncode.forEach(e=>{i=null===i?e.diffMean():i+e.diffMean()});let r=null!==t?e-t:e;this._stats.bitrate={actualEncoded:8*r/(this.options.updateInterval/1e3),transmit:8*e/(this.options.updateInterval/1e3)},null!==t&&(this._stats.bitrate.retransmit=8*t/(this.options.updateInterval/1e3)),null!==i&&(this._stats.bitrate.targetEncoded=8*i/(this.options.updateInterval/1e3))}constructor(){super(...arguments),SL(this,"_stats",g3),SL(this,"report",void 0),SL(this,"lastDecodeVideoReceiverStats",new Map),SL(this,"lastVideoFramesRecv",new Map),SL(this,"lastVideoFramesSent",new Map),SL(this,"lastVideoFramesDecode",new Map),SL(this,"lastVideoFramesOutput",new Map),SL(this,"lastVideoJBDelay",new Map),SL(this,"lastAudioJBDelay",new Map),SL(this,"mediaBytesSent",new Map),SL(this,"mediaBytesRetransmit",new Map),SL(this,"mediaBytesTargetEncode",new Map),SL(this,"lastDecodeAudioReceiverStats",new Map),SL(this,"lastAudioConcealment",new Map),SL(this,"lastEncoderMs",new Map)}},Ts=class extends g9{updateStats(){return dQ.resolve()}};function Tc(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:250,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:8,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:500,n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1e4,o=function(){let e=navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]*/i);return e&&e[0]?Number(e[0].split("/")[1]):null}();return o?o<76?new g7(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:r,firstVideoDecodedTimeout:n}):new Ta(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:r,firstVideoDecodedTimeout:n}):!function(e){if(!window.RTCStatsReport)return!1;let t=e.getStats();return!!(t instanceof dQ||t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then)}(e)?new Ts(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:r,firstVideoDecodedTimeout:n}):new Ta(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:r,firstVideoDecodedTimeout:n})}let Td="websdk_ng_install_id";function Tl(){try{if(TR("INSTALL_ID"))return TR("INSTALL_ID");let e=window.localStorage.getItem(Td);return e||(e=gN(),window.localStorage.setItem(Td,e)),TT("INSTALL_ID",e),e}catch(e){return}}let Th=function(e){if(e.match(/[0-9]+\.[0-9]+\.[0-9]+$/))return e;let t=e.match(/([0-9]+\.[0-9]+\.[0-9]+)\-([0-9]+)/);if(t&&t[1]&&t[2]){let e=t[1],i=t[2];return"".concat(e,".").concat(i)}return"4.0.0.999"}("4.24.2"),Tu=function(){try{return!0===JSON.parse("true")}catch(e){return!0}}(),Tp=((x={}).Default="default",x.Auto="auto",x.Relay="relay",x.SdRtn="sd-rtn",x),T_=function(){let e=["t","s","t"];e.splice(1,0,"e");let t=e.join(""),i=[];for(let e=0;e<6;e++)i.push("1");let r=i.join(""),n={};return n["us".concat("erna","me")]=t,n["pa".concat("sswo","rd")]=r,Object.assign(n,{turnServerURL:"",tcpport:3433,udpport:3478,forceturn:!1})}();window.DEFAULT_TURN_CONFIG=T_;
vendor: 5,684 bytes, line 1
1let TE={ENABLE_PUBLISHED_USER_LIST:!0,MAX_SUBSCRIPTION:50,SUBSCRIBE_AUDIO_FILTER_TOPN:void 0,ENABLE_PUBLISH_AUDIO_FILTER:void 0,ENABLE_USER_LICENSE_CHECK:!0,DISABLE_FEC:void 0,ENABLE_NTP_REPORT:!1,ENABLE_INSTANT_VIDEO:!1,ENABLE_USER_AUTO_REBALANCE_CHECK:!0,ENABLE_LOSSBASED_BWE:!0,ENABLE_AUT_CC:!0,FORCE_ENABLE_AUT_CC:!1,ENABLE_CC_FALLBACK:void 0,SUBSCRIBE_TWCC:!0,PUBLISH_TWCC:!1,ENABLE_SVC_DEFAULT_CODECS:["H264","VP8","VP9","AV1"],SVC:[],ENABLE_FULL_LINK_AV_SYNC:!1,SVC_MODE:null,PRE_SUB_NUM:1,ENABLE_AUT_FEEDBACK:!0,SVC_EXTENDED:["VP9"]},Tm={MIN_FRAME_RATE:1,MAX_FRAME_RATE:30,MAX_THRESHOLD_FRAMERATE:30,BITRATE_MIN_THRESHOLD:100,BITRATE_MAX_THRESHOLD:100,MAX_SCALE:5,BWE_SCALE_UP_THRESHOLD:.6,BWE_SCALE_DOWN_THRESHOLD:.6,PERF_SCALE_UP_THRESHOLD:.7,PERF_SCALE_DOWN_THRESHOLD:.6,MOTION_RESOLUTION_FACTOR:.8,MOTION_BITRATE_FACTOR:.6,DETAIL_FRAMERATE_FACTOR:.8,DETAIL_BITRATE_FACTOR:.6,BALANCE_RESOLUTION_FACTOR:.9,BALANCE_FRAMERATE_FACTOR:.9,BALANCE_BITRATE_FACTOR:.6,OVERUSE_TIMES_THRESHOLD:10,UNDERUSE_TIMES_THRESHOLD:40},Tf="v4.24.2-0-g002485b1-dirty(12/12/2025, 5:26:54 PM)",TS={ENABLE_EVENT_REPORT:!0,UPLOAD_LOG:!1,ENABLE_AG_ADAPTATION:!0,FORCE_AG_HIGH_FRAMERATE:!1,FORCE_SUPPORT_AG_ADAPTATION:!1,ENCODER_CONFIG_LIMIT:{},CAMERA_CAPTURE_CONFIG:void 0,ENABLE_PRELOAD:!0,NEW_ICE_RESTART:!0,ICE_RESTART_INTERVAL:1e4,RESTART_SEQUENCE:["udp_tcp_relay","relay"],FIRST_TCP_CANDIDATE:!1,FIRST_TCP_CANDIDATE_INTERVAL:1e3,TURN_DOMAIN:"edge.agora.io",TURN_DOMAINS:["edge.agora.io"],USE_TURN_IP:!0,NEW_TURN_MODE:4,NEW_FORCE_TURN:!1,USE_NEW_RENDER_FREEZE_TIME:!1,FLS_FALLBACK_TIMEOUT:3e4,RTE_DETAIL_REPORT_INTERVAL:6e4,ENCODE_EXCEPTION_TIMES:5,ENABLE_ENCODE_EXCEPTION:!0,ENCODE_EXCEPTION_VALIDATE_CODEC:["h264"],VIDEO_ENCODER_CONFIG_LIST:[{width:240,height:180},{width:320,height:240},{width:400,height:300},{width:480,height:360},{width:560,height:420},{width:640,height:480}],DELETE_NEQ_AFTER_USER_LEAVE:!0,UPDATE_RTP_CAP_IN_HOST:!1,IOS_BG_TAG:!0,IOS_AUTO_RESTART_BG_TAG:!0,IGNORE_UID_CHECK:!1,ENABLE_UP_SPS_PPS:!1,ENABLE_DOWN_SPS_PPS:!1,NO_EDGES_RETRY:!0,BUFFER_READY_FRAMES:3,FLS_SYNC_AV_PLAY_LIMIT:0,FLS_BUFFER_WAIT_TIME:1500,VOS_CONFIGURE:void 0,ENABLE_QUALITY_FALLBACK:!1,QUALITY_FALLBACK_REHEARSAL:!0,ENABLE_FLS_AV1_FIRST:!1,ENABLE_AP_MULTI_IP:!0,FLS_ENABLE_AV1_DETECT:!0,FLS_ENABLE_AV1_DECODE_DETECT:!0},Tg=SM(SM(SM(SM({},TS),{},{PROCESS_ID:"",ENCRYPT_AES:!0,AREAS:["CHINA","GLOBAL"],WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io","webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io","webrtc2-4.ap.sd-rtn.com"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-web-2.ap.sd-rtn.com","cds-ap-web-3.agora.io","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-web-2.ap.sd-rtn.com","sua-ap-web-3.agora.io","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-ap-web-1.agora.io","uap-web-2.ap.sd-rtn.com","uap-ap-web-3.agora.io","uap-web-4.ap.sd-rtn.com"],LOG_UPLOAD_SERVER:"logservice.agora.io",EVENT_REPORT_DOMAIN:"statscollector-1.agora.io",EVENT_REPORT_BACKUP_DOMAIN:"web-2.statscollector.sd-rtn.com",GATEWAY_ADDRESS:[],GATEWAY_WSS_ADDRESS:"",LIVE_STREAMING_ADDRESS:"",HTTP_CONNECT_TIMEOUT:5e3,SIGNAL_REQUEST_TIMEOUT:1e4,REPORT_STATS:!0,NOT_REPORT_EVENT:[],PING_PONG_TIME_OUT:10,WEBSOCKET_TIMEOUT_MIN:1e4,EVENT_REPORT_SEND_INTERVAL:3e3,CONFIG_DISTRIBUTE_INTERVAL:3e5,ENABLE_CONFIG_DISTRIBUTE:!0,CANDIDATE_TIMEOUT:5e3,SHOW_REPORT_INVOKER_LOG:!1,SHOW_REPORT_USER_INVOKER_LOG:!0,JOIN_EXTEND:"",PUB_EXTEND:"",SUB_EXTEND:"",FORCE_TURN:!1,TURN_ENABLE_TCP:!0,TURN_ENABLE_UDP:!0,MAX_UPLOAD_CACHE:50,UPLOAD_CACHE_INTERVAL:2e3,AJAX_REQUEST_CONCURRENT:3,REPORT_APP_SCENARIO:void 0,GATEWAY_DOMAINS:["edge.agora.io","edge.sd-rtn.com"],CONNECT_GATEWAY_WITHOUT_DOMAIN:!1,WORKER_DOMAIN:"edge.agora.io",EVENT_REPORT_RETRY:!0,CHROME_FORCE_PLAN_B:!1,AUDIO_SOURCE_VOLUME_UPDATE_INTERVAL:400,AUDIO_SOURCE_AVG_VOLUME_DURATION:3e3,AUDIO_VOLUME_INDICATION_INTERVAL:2e3,VOLUME_VOICE_WEIGHT:10,GET_VOLUME_OF_MUTED_AUDIO_TRACK:!1,STATS_UPDATE_INTERVAL:250,NORMAL_EVENT_QUEUE_CAPACITY:100,CUSTOM_REPORT:!0,CUSTOM_REPORT_LIMIT:20,PROXY_SERVER_TYPE2:"webnginx-proxy.agora.io",PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.sd-rtn.com","webrtc-cloud-proxy.agora.io"],CUSTOM_PUB_ANSWER_MODIFIER:null,CUSTOM_SUB_ANSWER_MODIFIER:null,CUSTOM_PUB_OFFER_MODIFIER:null,CUSTOM_SUB_OFFER_MODIFIER:null,DSCP_TYPE:"high",REMOVE_NEW_CODECS:!0,FRAGEMENT_LENGTH:3,WEBSOCKET_COMPRESS:!1,SIMULCAST:!1,CHECK_VIDEO_VISIBLE_INTERVAL:3e4,CHECK_LOCAL_STATS_INTERVAL:250,PROFILE_SWITCH_INTERVAL:2e3,UNSUPPORTED_VIDEO_CODEC:[],ENUMERATE_DEVICES_INTERVAL:!1,ENUMERATE_DEVICES_INTERVAL_TIME:1e4,USE_NEW_TOKEN:!1,CLOSE_AFB_FOR_LOCAL_AP:!0,JOIN_MAX_CONCURRENCY:6,JOIN_WITH_FALLBACK_SIGNAL_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE:!1,JOIN_GATEWAY_TRY_443PORT_DURATION:2e3,JOIN_GATEWAY_USE_443PORT_ONLY:!1,JOIN_GATEWAY_USE_DUAL_DOMAIN:!0,JOIN_GATEWAY_FALLBACK_PORT:443,USE_TURN_SERVER_OF_GATEWAY:!1,H264_PROFILE_LEVEL_ID:"",USE_NEW_LOG:!1,LOG_VERSION:3,MEDIA_DEVICE_CONSTRAINTS:null,ENCRYPT_PROXY_USERNAME_AND_PSW:!0,SDP_LOGGING:!1,CSP_DETECTED_HOSTNAME_LIST:["agora.io","sd-rtn.com"],REMOTE_AUDIO_TRACK_USES_WEB_AUDIO:!1,LOCAL_AUDIO_TRACK_USES_WEB_AUDIO:!1,BITRATE_ADAPTER_TYPE:"STANDARD_BITRATE",AI_DENOISER_PARAMETERS:{excludedLinks:[]},ADJUST_3A_FROM_PLUGINS:!0,RAISE_H264_BASELINE_PRIORITY:!0,FILTER_SEND_H264_BASELINE:!1,FIRST_H264_PROFILE_LEVEL_ID:"42001f",FIRST_PACKETIZATION_MODE:"",X_GOOGLE_START_BITRATE:void 0,NEW_REPORT_SERVER:!1,NEW_REPORT_SERVER_DOMAINS:["data-reporting.agora.io","data-reporting.agora.io"],VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT:3e5,VIDEO_INSPECT_INTERVAL_MINIMUM:1e3,VIDEO_INSPECT_QUALITY_RATIO:.9,V
1IDEO_INSPECT_WORKER_MANAGER_HOST:"edge.agora.io",VIDEO_INSPECT_WORKER_MANAGER_PORT:"",VIDEO_INSPECT_WORKER_MANAGER_WSS:"",VIDEO_INSPECT_WORKER_PORT:"",SHOW_VIDEO_INSPECT_WORKER_MESSAGE:!1,STATS_COLLECTOR_PORT:443,FORCE_TURN_TCP:!1,WEBAUDIO_INIT_OPTIONS:void 0,FILTER_VIDEO_FEC:!0,FILTER_AUDIO_FEC:!1,CHROME_DUAL_STREAM_USE_ENCODING:!0,DISABLE_DUAL_STREAM_USE_ENCODING:!1,EXTENSION_USAGE_UPLOAD_INTERVAL:1e4,ICE_RESTART:!0,FINGERPRINT:null,ENABLE_VIDEO_FRAME_CALLBACK:!0,VIDEO_FREEZE_DURATION:500,SPATIALIZER_PARAMETERS:{},UPLOAD_LOG_INTERVAL:3e3,UPLOAD_LOG_REQUEST_RETRY_INTERVAL:2e3,UPLOAD_LOG_REQUEST_MAX_RETRY_INTERVAL:2e4,UPLOAD_LOG_TRY_INTERVAL_WHILE_OFF:5e3,UPLOAD_LOG_RETRY_INTERVAL_V1:1e4,UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1:200,UPLOAD_LOG_LENGTH_EACH_TIME:10,APP_TYPE:0,DISABLE_WEBAUDIO:!1,CHANNEL_MEDIA_RELAY_SERVERS:void 0,KEEP_LAST_FRAME:!0,FORWARD_P2P_CREATION:!0,SYNC_GROUP:!0,BLOCK_LOCAL_CLIENT:!1,ENABLE_AUDIO_TOPN:!1,ENABLE_AUDIO_METADATA:!1,ENABLE_AUDIO_PTS:!1,TOPN_SMOOTH_LEVEL:void 0,TOPN_NEW_SPEAKER_DELAY:void 0,TOPN_SWITCH_HOLD_MS:void 0,TOPN_AUDIO_GAIN:void 0,TOPN_SILENCE_THRESHOLD:250,AP_AREA:!0,ENABLE_ENCODED_TRANSFORM:!1,ENABLE_VIDEO_SEI:!1,IMAGE_MODERATION_WORKER_HOST:"edge.agora.io",IMAGE_MODERATION_WORKER_WSS:"",IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT:3e5,IMAGE_MODERATION_INTERVAL_MINIMUM:1e3,SHOW_IMAGE_MODERATION_WORKER_MESSAGE:!1,IMAGE_MODERATION_QUALITY_RATIO:.9,IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL:5e3,SHOW_GLOBAL_CLIENT_LIST:!1,DATASTREAM_MAX_RETRANSMITS:10,TCP_CANDIDATE_ONLY:!1,EXTERNAL_SIGNAL_REQUEST_TIMEOUT:3e3,SHOW_P2P_LOG:!1,MAX_P2P_TIMEOUT:3e4,P2P_TOKEN_INTERVAL:1e3,SHOW_DATASTREAM2_LOG:!1,RESTRICTION_SET_PLAYBACK_DEVICE:!0,USE_PURE_ENCRYPTION_MASTER_KEY:!1,ENABLE_AUDIO_RED:!1,OPUS_PTIME:void 0,AUDIO_DUPLICATE_NUM:void 0,ENABLE_ABSSENDTIME_AS_SENTTS:!0,ACCOUNT_REGISTER_RETRY_TIMEOUT:1,ACCOUNT_REGISTER_RETRY_RATIO:2,ACCOUNT_REGISTER_RETRY_TIMEOUT_MAX:6e4,ACCOUNT_REGISTER_RETRY_COUNT_MAX:1e5,AUDIO_CONTEXT:null,WEBCS_BACKUP_CONNECT_TIMEOUT:6e3,PLAYER_STATE_DEFER:2e3,SIGNAL_REQUEST_WATCH_INTERVAL:1e3,FILEPATH_LENMAX:255,DUALSTREAM_OPERATION_CHECK:!0,MEDIA_ELEMENT_EXISTS_DEPTH:3,SHIM_CANDIDATE:!1,LEAVE_MSG_TIMEOUT:2e3,STATS_FILTER:{transportId:!0,googTrackId:!0},FILTER_VIDEO_CODEC:[],SIGNAL_CHANNEL:0,TRANSMITTER_INITIAL_RTT:30,TRANSMITTER_INITIAL_RTO:30,TRANSMITTER_MAX_BATCH_ACK_COUNT:2,TRANSMITTER_MAX_RTO:500,DATACHANNEL_COMPRESS:!1,DC_JOIN_WITH_FAILBACK:4e3,DC_CONNECTION_TIMEOUT:2e3,DC_PINGPONG_INTERVAL:2e3,DC_DEBUG_LOG:!1,UNSUPPORTED_VIDEO_UPLINK_CODEC:[],UNSUPPORTED_VIDEO_DOWNLINK_CODEC:[],USE_NEW_NETWORK_CONFIG:!1,AUTO_RESET_AUDIO_ROUTE:!1,PLUGIN_INFO:[],OVERUSE_DETECTOR_PARAMS:Tm,CUSTOM_ADAPTATION_DEFAULT_MODE:"",HIDE_NO_POSTER:!1,AP_CACHE_NUM:10,AP_UPDATE_INTERVAL:12e4,AP_CACHE_LIFETIME:12e4,MAX_PRELOAD_ASYNC_LENGTH:3,DISABLE_SCREEN_SHARE_REMB:!1},TE),{},{USE_CANDIDATE_FROM_AP_DETAIL:!1,AP_REQUEST_DETAIL:void 0,ENABLE_ROLE_SELECT_EDGE:!1,CLIENT_ROLE_OPTIONS:void 0,REMOTE_VIDEO_STREAM_TYPE:void 0,COMPATIBLE_SDP_EXTENSION:["gdpr_forbidden"],LIMIT_BITRATE:void 0,EXPERIMENTS:{},USE_PUB_RTX:!0,USE_SUB_RTX:!0,ENABLE_DATASTREAM_2:!1,USE_XR:!0,ENABLE_PREALLOC_PC:!1,ENABLE_PRE_SUB:!1,ENABLE_SVC:!1,ENABLE_FORCE_HLS:!1,MAX_WEBAUDIO_VOLUME:300,ENABLE_VOS_FALLBACK:!1,ENABLE_FALLBACK_TO_HLS:!1,ENABLE_PRE_RENDER:!1,FORCE_DISABLE_AUTO_SUB:!1,ENABLE_PRE_SUB_WITH_PRE_PC:!0,PRE_USE_LOCAL_CODECS:!0},{INSTALL_ID:""}),{},{K_MIN_RENDER_DELAY:66,USE_STANDARD_BITRATE_DEFAULT:!1,VIDEO_NEW_BITRATE_RATIO:void 0,VIDEO_STANDARD_BITRATE_VERSION:2,BASELINE_MORE_H264_BITRATE_RATIO:1.1,IGNORE_RTC_DEVICE_CHECK:!1,FLS_AUTOPLAY_EMITS:!1,ENABLE_DUAL_STREAM_FLAG:!1,FORBID_MODIFY_LOCAL_OFFER_SDP:!1,RESERVE_MID_1_MLINE:!1});function TT(e,t,i){var r,n,o;o5(r=Object.keys(Tg)).call(r,e)&&(!i&&o5(n=Object.keys(Tv)).call(n,e)||(Tg[e]=t,"ENABLE_VIDEO_SEI"!==e&&"ENABLE_AUDIO_TOPN"!==e&&"ENABLE_AUDIO_METADATA"!==e&&"ENABLE_AUDIO_PTS"!==e||!0!==t||(Tg.ENABLE_ENCODED_TRANSFORM=!0),"USE_NEW_NETWORK_CONFIG"===e&&t&&(Tg.USE_NEW_NETWORK_CONFIG=o=!!t,o&&(Tg.WEBCS_DOMAIN=["webrtc2-2.ap.sd-rtn.com"],Tg.WEBCS_DOMAIN_BACKUP_LIST=["webrtc2-4.ap.sd-rtn.com"],Tg.CDS_AP=["cds-web-2.ap.sd-rtn.com","cds-web-4.ap.sd-rtn.com"],Tg.ACCOUNT_REGISTER=["sua-web-2.ap.sd-rtn.com","sua-web-4.ap.sd-rtn.com"],Tg.EVENT_REPORT_DOMAIN="web-2.statscollector.sd-rtn.com",Tg.EVENT_REPORT_BACKUP_DOMAIN="statscollector-1.agora.io",Tg.GATEWAY_DOMAINS=["edge.sd-rtn.com"])),"ENABLE_PRE_SUB"===e&&t&&(Tg.ENABLE_INSTANT_VIDEO=!0,Tg.ENABLE_PREALLOC_PC=!0),"ENABLE_SVC"===e&&t&&(Tg.ENABLE_AUT_CC=!0),"NEW_FORCE_TURN"===e&&t&&(Tg.NEW_TURN_MODE||(Tg.NEW_TURN_MODE=4))))}function TR(e){if("TURN_DOMAINS"===e){let e=Tg.TURN_DOMAINS;return o5(e).call(e,TR("TURN_DOMAIN"))?e:[TR("TURN_DOMAIN")].concat(e)}return Tg[e]}Tu||(Tg.WEBCS_DOMAIN=["ap-web-1-oversea.agora.io","ap-web-1-north-america.agora.io"],Tg.WEBCS_DOMAIN_BACKUP_LIST=["ap-web-2-oversea.agora.io","ap-web-2-north-america.agora.io"],Tg.PROXY_CS=["proxy-ap-web-oversea.agora.io","proxy-ap-web-america.agora.io"],Tg.CDS_AP=["cds-ap-web-oversea.agora.io","cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],Tg.ACCOUNT_REGISTER=["sua-ap-web-oversea.agora.io","sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],Tg.UAP_AP=["uap-ap-web-oversea.agora.io","uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],Tg.LOG_UPLOAD_SERVER="logservice-oversea.agora.io",Tg.EVENT_REPORT_DOMAIN="statscollector-1-oversea.agora.io",Tg.EVENT_REPORT_BACKUP_DOMAIN="statscollector-2-oversea.agora.io",Tg.PROXY_SERVER_TYPE3="webrtc-cloud-proxy.agora.io",Tg.AREAS=["NORTH_AMERICA","OVERSEA"]);let TC=((V={})[V.REALTIME=1]="REALTIME",V),Tv={};var Ty=((F=Ty||{}
1).SET_SESSION_ID="SET_SESSION_ID",F.SET_RTE_URL="SET_RTE_URL",F.SET_RTE_SID="SET_RTE_SID",F.SET_P2P_ID="SET_P2P_id",F.SET_DC_ID="SET_DC_id",F.SET_UID="SET_UID",F.SET_INT_UID="SET_INT_UID",F.SET_PUB_ID="SET_PUB_ID",F.SET_CLOUD_PROXY_SERVER_MODE="SET_CLOUD_PROXY_SERVER_MODE",F.KEY_METRIC_CLIENT_CREATED="KEY_METRIC_CLIENT_CREATED",F.KEY_METRIC_JOIN_START="KEY_METRIC_JOIN_START",F.KEY_METRIC_PRELOAD_START="KEY_METRIC_PRELOAD_START",F.KEY_METRIC_PRELOAD_END="KEY_METRIC_PRELOAD_END",F.KEY_METRIC_JOIN_END="KEY_METRIC_JOIN_END",F.KEY_METRIC_REQUEST_AP_START="KEY_METRIC_REQUEST_AP_START",F.KEY_METRIC_REQUEST_AP_END="KEY_METRIC_REQUEST_AP_END",F.KEY_METRIC_REQUEST_SUA_END="KEY_METRIC_REQUEST_SUA_END",F.KEY_METRIC_BEFORE_CONNECT="KEY_METRIC_BEFORE_CONNECT",F.KEY_METRIC_PEER_RECEIVER="KEY_METRIC_PEER_RECEIVER",F.KEY_METRIC_SIGNAL_CONNECTED="KEY_METRIC_SIGNAL_CONNECTED",F.KEY_METRIC_JOIN_REQ="KEY_METRIC_JOIN_REQ",F.KEY_METRIC_JOIN_REP="KEY_METRIC_JOIN_REP",F.KEY_METRIC_JOIN_GATEWAY_START="KEY_METRIC_JOIN_GATEWAY_START",F.KEY_METRIC_JOIN_GATEWAY_END="KEY_METRIC_JOIN_GATEWAY_END",F.KEY_METRIC_PEER_CONNECTION_START="KEY_METRIC_PEER_CONNECTION_START",F.KEY_METRIC_PEER_CONNECTION_END="KEY_METRIC_PEER_CONNECTION_END",F.KEY_METRIC_FIRST_VIDEO_FRAME_DECODED="KEY_METRIC_FIRST_VIDEO_FRAME_DECODED",F.KEY_METRIC_DESCRIPTION_START="KEY_METRIC_DESCRIPTION_START",F.KEY_METRIC_ICE_CONNECTION_END="KEY_METRIC_ICE_CONNECTION_END",F.KEY_METRIC_SIGNAL_CHANNEL_OPEN="KEY_METRIC_SIGNAL_CHANNEL_OPEN",F.KEY_METRIC_PUBLISH="KEY_METRIC_PUBLISH",F.KEY_METRIC_SUBSCRIBE="KEY_METRIC_SUBSCRIBE",F.RECORD_JOIN_CHANNEL_SERVICE="RECORD_JOIN_CHANNEL_SERVICE",F.RESET_JOIN_CHANNEL_SERVICE_RECORDS="RESET_JOIN_CHANNEL_SERVICE_RECORDS",F.RESET_KEY_METRICS="RESET_KEY_METRICS",F.RESET_FIRST_VIDEO_FRAME_DECODED="RESET_FIRST_VIDEO_FRAME_DECODED",F.SET_USE_P2P="SET_USE_P2P",F.SET_TRANSPORT_TYPE="SET_TRANSPORT_TYPE",F);let TI=((B={}).h264="h264",B.h265="h265",B.vp8="vp8",B.vp9="vp9",B.av1="av1",B);(j={}).opus="opus",j.pcma="pcma",j.pcmu="pcmu",j.g722="g722";let TA=0;var Tb=(()=>{var e={8:(e,t,i)=>{var r;let n;i.r(t),i.d(t,{Parser:()=>R,Printer:()=>A,parse:()=>N,print:()=>D});let o="".concat("\r").concat("\n");function a(e){return e>="0"&&e<="9"}function s(e){return e>="!"&&e<="~"}function c(e){return s(e)||e>="\x80"&&e<="\xff"}function d(e){return"!"===e||e>="#"&&e<="'"||e>="*"&&e<="+"||e>="-"&&e<="."||e>="0"&&e<="9"||e>="A"&&e<="Z"||e>="^"&&e<="~"}function l(e){return e>="1"&&e<="9"}function h(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function u(e){return"d"===e||"h"===e||"m"===e||"s"===e}function p(e){return e>"\x01"&&e<" "||e>"\v"&&e<"\f"||e>"\x0e"&&e<"\xff"}function _(e){return h(e)||a(e)||"+"===e||"/"===e}function E(e){return a(e)||h(e)||"+"===e||"/"===e||"-"===e||"_"===e}function m(e){return h(e)||a(e)||"+"===e||"/"===e}function f(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function S(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?f(Object(i),!0).forEach(function(t){g(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):f(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}function g(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}(r=n||(n={})).VERSION="v",r.ORIGIN="o",r.SESSION_NAME="s",r.INFORMATION="i",r.URI="u",r.EMAIL="e",r.PHONE="p",r.CONNECTION="c",r.BANDWIDTH="b",r.TIME="t",r.REPEAT="r",r.ZONE_ADJUSTMENTS="z",r.KEY="k",r.ATTRIBUTE="a",r.MEDIA="m";class T{consumeText(e,t){let i=t;for(;i<e.length;){let t=e[i];if("\0"===t||"\r"===t||"\n"===t)break;i+=1}if(i-t==0)throw Error("Invalid text, at ".concat(e));return i}consumeUnicastAddress(e,t,i){return this.consumeTill(e,t," ")}consumeOneOrMore(e,t,i){let r=t;for(;i(e[r]);)r++;if(r-t==0)throw Error("Invalid rule at ".concat(t,"."));return r}consumeSpace(e,t){if(" "===e[t])return t+1;throw Error("Invalid space at ".concat(t,"."))}consumeIP4Address(e,t){let i=t;for(let t=0;t<4;t++)if(i=this.consumeDecimalUChar(e,i),3!==t){if("."!==e[i])throw Error("Invalid IP4 address.");i++}return i}consumeDecimalUChar(e,t){let i=t;for(let t=0;t<3&&a(e[i]);t++,i++);if(i-t==0)throw Error("Invalid decimal uchar.");let r=parseInt(e.slice(t,i));if(r>=0&&r<=255)return i;throw Error("Invalid decimal uchar")}consumeIP6Address(e,t){let i=this.consumeHexpart(e,t);return":"===e[i]?(i+=1,i=this.consumeIP4Address(e,i)):i}consumeHexpart(e,t){let i=t;if(":"===e[i]&&":"===e[i+1]){i+=2;try{i=this.consumeHexseq(e,i)}catch(e){}return i}if(i=this.consumeHexseq(e,i),":"===e[i]&&":"===e[i+1]){i+=2;try{i=this.consumeHexseq(e,i)}catch(e){}}return i}consumeHexseq(e,t){let i=t;for(;i=this.consumeHex4(e,i),":"===e[i]&&":"!==e[i+1];)i+=1;return i}consumeHex4(e,t){var i;let r=0;for(;r<4;r++)if(!((i=e[t+r])>="0"&&i<="9"||i>="a"&&i<="f"||i>="A"&&i<="F")){if(0===r)throw Error("Invalid hex 4");break}return t+r}consumeFQDN(e,t){let i=t;for(;a(e[i])||h(e[i])||"-"===e[i]||"."===e[i];)i+=1;if(i-t<4)throw Error("Invalid FQDN");return i}consumeExtnAddr(e,t){return this.consumeOneOrMore(e,t,c)}consumeMulticastAddress(e,t,i){switch(i){case"IP4":case"ip4":return this.consumeIP4MulticastAddress(e,t);case"IP6":case"ip6":return this.consumeIP6MulticastAddress(e,t);default:try{return this.consumeFQDN(e,t)}catch(i){return this.consumeExtnAddr(e,t)}}}consumeIP6MulticastAddress(e,t){let i=this.consumeHexpart(e,t);return"/"===e[i]?this.consumeInteger(e,i+1):i}consumeIP4MulticastAddress(e,t){let i=t+3,r=parseInt(e.slice(t,i));if(r<224||r>239)throw Error("Invalid IP4 multicast address, IPv4 multicast addresses may be in the range 224.0.0.0 to 239.255.255.255.");for(let t=0;t<3;t++){if("."!==e[i])throw Error("Invalid IP4 multicast address.");i+=1,i=this.consumeDecimalUChar(e,i)}return"/"===e[i]&&(i+=1),i=this.consumeTTL(e,i),"/"===e[i]&&(i=this.consumeInteger(e,i
1)),i}consumeInteger(e,t){if(!l(e[t]))throw Error("Invalid integer.");for(t+=1;a(e[t]);)t+=1;return t}consumeTTL(e,t){if("0"===e[t])return t+1;if(!l(e[t]))throw Error("Invalid TTL.");t+=1;for(let i=0;i<2&&a(e[t]);i++)t+=1;return t}consumeToken(e,t){return this.consumeOneOrMore(e,t,d)}consumeTime(e,t){let i=t;if("0"===e[i])return i+1;for(l(e[i])&&(i+=1);a(e[i]);)i++;if(i-t<10)throw Error("Invalid time");return i}consumeAddress(e,t){return this.consumeTill(e,t," ")}consumeTypedTime(e,t){let i=t;return i=this.consumeOneOrMore(e,i,a),u(e[i])?i+1:i}consumeRepeatInterval(e,t){if(!l(e[t]))throw Error("Invalid repeat interval");for(t+=1;a(e[t]);)t+=1;return u(e[t])&&(t+=1),t}consumePort(e,t){return this.consumeOneOrMore(e,t,a)}consume(e,t,i){for(let r=0;r<i.length;r++){if(t+r>=e.length)throw Error("consume exceeding value length");if(e[t+r]!==i[r])throw Error("consume ".concat(i," failed at ").concat(r))}return t+i.length}consumeTill(e,t,i){let r=t;for(;r<e.length&&("string"!=typeof i||e[r]!==i)&&("function"!=typeof i||!i(e[r]));)r++;return r}}class R extends T{parse(e){let t=this.probeEOL(e);this.records=e.split(t).filter(e=>!!py(e).call(e)).map(this.parseLine),this.currentLine=0;let i=this.parseVersion(),r=this.parseOrigin(),n=this.parseSessionName(),o=this.parseInformation(),a=this.parseUri(),s=this.parseEmail(),c=this.parsePhone(),d=this.parseConnection(),l=this.parseBandWidth(),h=this.parseTimeFields(),u=this.parseKey(),p=this.parseSessionAttribute(),_=this.parseMediaDescription();if(this.currentLine!==this.records.length)throw Error("parsing failed, non exhaustive sdp lines.");return{version:i,origin:r,sessionName:n,information:o,uri:a,emails:s,phones:c,connection:d,bandwidths:l,timeFields:h,key:u,attributes:p,mediaDescriptions:_}}getCurrentRecord(){let e=this.records[this.currentLine];if(!e)throw Error("Record doesn't exit.");return e}probeEOL(e){for(let t=0;t<e.length;t++)if("\n"===e[t])return"\r"===e[t-1]?o:"\n";throw Error("Invalid newline character.")}parseLine(e,t){if(e.length<2)throw Error("Invalid sdp line, sdp line should be of form <type>=<value>.");let i=e[0];if("="!==e[1])throw Error('Invalid sdp line, <type> should be a single character followed by an "=" sign.');return{type:i,value:e.slice(2),line:t,cur:0}}parseSessionAttribute(){let e=new v;for(;this.currentLine<this.records.length;){let t=this.getCurrentRecord();if(t.type!==n.ATTRIBUTE)break;let i={attField:this.extractOneOrMore(t,e=>d(e)&&":"!==e),_cur:0};":"===t.value[t.cur]&&(t.cur+=1,i.attValue=this.extractOneOrMore(t,p)),e.parse(i),this.currentLine++}return e.digest()}parseMediaAttributes(e){let t=new y(e);for(;this.currentLine<this.records.length;){let e=this.getCurrentRecord();if(e.type!==n.ATTRIBUTE)break;let i={attField:this.extractOneOrMore(e,e=>d(e)&&":"!==e),_cur:0};":"===e.value[e.cur]&&(e.cur+=1,i.attValue=this.extractOneOrMore(e,p)),t.parse(i),this.currentLine++}return t.digest()}parseKey(){let e=this.getCurrentRecord();if(e.type===n.KEY){if("prompt"===e.value||"clear:"===e.value||"base64:"===e.value||"uri:"===e.value)return e.value;throw this.currentLine++,Error("Invalid key.")}}parseZone(){let e=this.getCurrentRecord();if(e.type===n.ZONE_ADJUSTMENTS){let t=[];for(;;)try{let i=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);let r=!1;"-"===e.value[e.cur]&&(r=!0,e.cur+=1);let n=this.extract(e,this.consumeTypedTime);t.push({time:i,typedTime:n,back:r})}catch(e){break}if(0===t.length)throw Error("Invalid zone adjustments");return this.currentLine++,t}return[]}parseRepeat(){let e=[];for(;;){let t=this.getCurrentRecord();if(t.type!==n.REPEAT)break;{let i=this.extract(t,this.consumeRepeatInterval),r=this.parseTypedTime(t);e.push({repeatInterval:i,typedTimes:r}),this.currentLine++}}return e}parseTypedTime(e){let t=[];for(;;)try{this.consumeSpaceForRecord(e),t.push(this.extract(e,this.consumeTypedTime))}catch(e){break}if(0===t.length)throw Error("Invalid typed time.");return t}parseTime(){let e=this.getCurrentRecord(),t=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);let i=this.extract(e,this.consumeTime);return this.currentLine++,{startTime:t,stopTime:i}}parseBandWidth(){let e=[];for(;this.currentLine<this.records.length;){let t=this.getCurrentRecord();if(t.type!==n.BANDWIDTH)break;{let i=this.extractOneOrMore(t,d);if(":"!==t.value[t.cur])throw Error("Invalid bandwidth field.");t.cur++;let r=this.extractOneOrMore(t,a);e.push({bwtype:i,bandwidth:r}),this.currentLine++}}return e}parseVersion(){let e=this.getCurrentRecord();if(e.type!==n.VERSION)throw Error("first sdp record must be version");let t=e.value.slice(0,this.consumeOneOrMore(e.value,0,a));if(t.length!==e.value.length)throw Error('invalid proto version, "v='.concat(e.value,'"'));return this.currentLine++,t}parseOrigin(){let e=this.getCurrentRecord();if(e.type!==n.ORIGIN)throw Error("second line of sdp must be origin");let t=this.extractOneOrMore(e,c);this.consumeSpaceForRecord(e);let i=this.extractOneOrMore(e,a);this.consumeSpaceForRecord(e);let r=this.extractOneOrMore(e,a);this.consumeSpaceForRecord(e);let o=this.extractOneOrMore(e,d);this.consumeSpaceForRecord(e);let s=this.extractOneOrMore(e,d);this.consumeSpaceForRecord(e);let l=this.extract(e,this.consumeUnicastAddress);return this.currentLine++,{username:t,sessId:i,sessVersion:r,nettype:o,addrtype:s,unicastAddress:l}}parseSessionName(){let e=this.getCurrentRecord();if(e.type===n.SESSION_NAME){let t=this.extract(e,this.consumeText);return this.currentLine++,t}}parseInformation(){let e=this.getCurrentRecord();if(e.type!==n.INFORMATION)return;let t=this.extract(e,this.consumeText);return this.currentLine++,t}parseUri(){let e=this.getCurrentRecord();if(e.type===n.URI)return this.currentLine++,e.value}parseEmail(){let e=[];for(;;){let t=this.getCurrentRecord();if(t.type!==n.EMAIL)break;e.push(t.value),this.currentLine++}return e}parsePhone(){let e=[];for(;;){let t=this.getCurrentRecord();if(t.type!==n.PHONE)break;e.push(t.value),this.currentLine++}return e}parseConnection(){let e=this.getCurrentRecord();if(e.type===n.CONNECTION){let t=this.extractOneOrMore(e,d);this.consumeSpaceForRecord(e);let i=this.extractOneOrMore(e,d);this.consumeSpaceForRecord(e);let r=this.extract(e,this.consumeAddress);return this.currentLine++,{nettype:t,addrtype:i,address:r}}}parseMedia(){let e=this.getCurrentRecord(),t=this.extract(e,this.consumeToken);this.consumeSpaceForRecord(e);let i=this.extract(e,this.consumePort);"/"===e.value[e.cur]&&(e.cur+=1,i+=this.extract(e,this.consumeInteger)),this.consumeSpaceForRecord(e);let r=[];for(r.push(this.extract(e,this.consumeToken));"/"===e.value[e.cur];)e.cur+=1,r.push(this.extract(e,this.consumeToken));if(0===r.length)throw Error("Invalid proto");let n=this.parseFmt(e);return this.currentLine++,{mediaType:t,port:i,protos:r,fmts:n}}parseTimeFields(){let e=[];for(;this.getCurrentRecord().type===n.TIME;){let t=this.parseTime(),i=this.parseRepeat(),r=this.parseZone();e.push({time:t,repeats:i,zones:r})}return e}parseMediaDescription(){let e=[];for(;this.currentLine<this.records.length&&this.getCurrentRecord().type===n.MEDIA;){let t=this.parseMedia(),i=this.parseInformation(),r=this.parseConnections(),n=this.parseBandWidth(),o=this.parseKey(),a=this.parseMediaAttributes(t);e.push({media:t,information:i,connections:r,bandwidths:n,key:o,attributes:a})}return e}parseConnections(){let e=[];for(;this.currentLine<this.records.length&&this.getCurrentRecord().type===n.CONNECTION;)e.push(this.parseConnection());return e}parseFmt(e){let t=[];for(;;)try{this.consumeSpaceForRecord(e),t.push(this.extract(e,this.consumeToken))}catch(e){break}if(0===t.length)throw Error("Invalid fmts");return t}extract(e,t){for(var i=arguments.length,r=Array(i>2?i-2:0),n=2;n<i;n++)r[n-2]=arguments[n];let o=t.call(this,e.value,e.cur,...r),a=e.value.slice(e.cur,o);return e.cur=o,a}extractOneOrMore(e,t){let i=this.consumeOneOrMore(e.value,e.cur,t),r=e.value.slice(e.cur,i);return e.cur=i,r}consumeSpaceForRecord(e){if(" "!==e.value[e.cur])throw Error("Invalid space at ".concat(e.cur,"."));e.cur+=1}constructor(){super(),g(this,"records",[]),g(this,"currentLine",0)}}class C extends T{extractOneOrMore(e,t,i){let r=this.consumeOneOrMore(e.attValue,e._cur,t),n=e.attValue.slice(e._cur,r),[o,a]=i||[];if("number"==typeof o&&n.length<o)throw Error("error in length, should be more or equal than ".concat(o," characters."));if("number"==typeof a&&n.length>a)throw Error("error in length, should be less or equal than ".concat(a," characters."));return e._cur=r,n}consumeAttributeSpace(e){if(" "!==e.attValue[e._cur])throw Error("Invalid space at ".concat(e._cur,"."));e._cur+=1}extract(e,t){if(!e.attValue)throw Error("Nothing to extract from attValue.");for(var i=arguments.length,r=Array(i>2?i-2:0),n=2;n<i;n++)r[n-2]=arguments[n];let o=t.call(this,e.attValue,e._cur,...r),a=e.attValue.slice(e._cur,o);return e._cur=o,a}atEnd(e){if(!e.attValue)throw Error();return e._cur>=e.attValue.length}peekChar(e){if(!e.attValue)throw Error();return e.attValue[e._cur]}peek(e,t){if(!e.attValue)throw Error();for(let i=0;i<t.length;i++)if(t[i]!==e.attValue[e._cur+i])return!1;return!0}parseIceUfrag(e){if(this.attributes.iceUfrag)throw Error("Invalid ice-ufrag, should be only a single line if 'a=ice-ufrag'");this.attributes.iceUfrag=this.extractOneOrMore(e,_,[4,256])}parseIcePwd(e){if(this.attributes.icePwd)throw Error("Invalid ice-pwd, should be only a single line if 'a=ice-pwd'");this.attributes.icePwd=this.extractOneOrMore(e,_,[22,256])}parseIceOptions(e){if(this.attributes.iceOptions)throw Error("Invalid ice-options, should be only one 'ice-options' line");let t=[];for(;!this.atEnd(e);){t.push(this.extractOneOrMore(e,_));try{this.consumeAttributeSpace(e)}catch(t){if(this.atEnd(e))break;throw t}}this.attributes.iceOptions=t}parseFingerprint(e){let t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);let i=this.extract(e,this.consumeTill);this.attributes.fingerprints.push({hashFunction:t,fingerprint:i})}parseExtmap(e){let t,i=this.extractOneOrMore(e,a);"/"===this.peekChar(e)&&(this.extract(e,this.consume,"/"),t=this.extract(e,this.consumeToken)),this.consumeAttributeSpace(e);let r=this.extract(e,this.consumeTill," "),n=S(S({entry:parseInt(i,10)},t&&{direction:t}),{},{extensionName:r});" "===this.peekChar(e)&&(this.consumeAttributeSpace(e),n.extensionAttributes=this.extract(e,this.consumeTill)),this.attributes.extmaps.push(n)}parseSetup(e){if(this.attributes.setup)throw Error("must only be one single 'a=setup' line.");let t=this.extract(e,this.consumeTill);if("active"!==t&&"passive"!==t&&"actpass"!==t&&"holdconn"!==t)throw Error("role must be one of 'active', 'passive', 'actpass', 'holdconn'.");this.attributes.setup=t}constructor(){super(...arguments),g(this,"attributes",void 0),g(this,"digested",!1)}}class v extends C{parse(e){if(this.digested)throw Error("already digested");try{switch(e.attField){case"group":this.parseGroup(e);break;case"ice-lite":this.parseIceLite();break;case"ice-ufrag":this.parseIceUfrag(e);break;case"ice-pwd":this.parseIcePwd(e);break;case"ice-options":this.parseIceOptions(e);break;case"fingerprint":this.parseFingerprint(e);break;case"setup":this.parseSetup(e);break;case"tls-id":this.parseTlsId(e);break;case"identity":this.parseIdentity(e);break;case"extmap":this.parseExtmap(e);break;case"msid-semantic":this.parseMsidSemantic(e);break;default:e.ignored=!0,this.attributes.unrecognized.push(e)}}catch(t){throw console.error("parsing session attribute ".concat(e.attField,' error, "a=').concat(e.attField,":").concat(e.attValue,'"')),t}if(!e.ignored&&e.attValue&&!this.atEnd(e))throw Error("attribute parsing error")}
1digest(){return this.digested=!0,this.attributes}parseGroup(e){let t=this.extract(e,this.consumeToken),i=[];for(;!this.atEnd(e)&&" "===this.peekChar(e);)this.consumeAttributeSpace(e),i.push(this.extract(e,this.consumeToken));this.attributes.groups.push({semantic:t,identificationTag:i})}parseIceLite(){if(this.attributes.iceLite)throw Error("Invalid ice-lite, should be only a single line of 'a=ice-lite'");this.attributes.iceLite=!0}parseTlsId(e){if(this.attributes.tlsId)throw Error("must be only one tld-id line");this.attributes.tlsId=this.extractOneOrMore(e,E)}parseIdentity(e){let t=this.extractOneOrMore(e,m),i=[];for(;!this.atEnd(e)&&" "===this.peekChar(e);){this.consumeAttributeSpace(e);let t=this.extract(e,this.consumeToken);this.extract(e,this.consume,"=");let r=this.extractOneOrMore(e,e=>" "!==e&&p(e));i.push({name:t,value:r})}this.attributes.identities.push({assertionValue:t,extensions:i})}parseMsidSemantic(e){" "===this.peekChar(e)&&this.consumeAttributeSpace(e);let t={semantic:this.extract(e,this.consumeToken),identifierList:[]};for(;;){try{this.consumeAttributeSpace(e)}catch(e){break}if("*"===this.peekChar(e)){this.extract(e,this.consume,"*"),t.applyForAll=!0;break}{let i=this.extract(e,this.consumeTill," ");t.identifierList.push(i)}}this.attributes.msidSemantic=t}constructor(){super(...arguments),g(this,"attributes",{unrecognized:[],groups:[],extmaps:[],fingerprints:[],identities:[]})}}class y extends C{parse(e){if(this.digested)throw Error("already digested");try{switch(e.attField){case"extmap":this.parseExtmap(e);break;case"setup":this.parseSetup(e);break;case"ice-ufrag":this.parseIceUfrag(e);break;case"ice-pwd":this.parseIcePwd(e);break;case"ice-options":this.parseIceOptions(e);break;case"candidate":this.parseCandidate(e);break;case"remote-candidate":this.parseRemoteCandidate(e);break;case"end-of-candidates":this.parseEndOfCandidates();break;case"fingerprint":this.parseFingerprint(e);break;case"rtpmap":this.parseRtpmap(e);break;case"ptime":this.parsePtime(e);break;case"maxptime":this.parseMaxPtime(e);break;case"sendrecv":case"recvonly":case"sendonly":case"inactive":this.parseDirection(e);break;case"ssrc":this.parseSSRC(e);break;case"fmtp":this.parseFmtp(e);break;case"rtcp-fb":this.parseRtcpFb(e);break;case"rtcp-mux":this.parseRTCPMux();break;case"rtcp-mux-only":this.parseRTCPMuxOnly();break;case"rtcp-rsize":this.parseRTCPRsize();break;case"rtcp":this.parseRTCP(e);break;case"mid":this.parseMid(e);break;case"msid":this.parseMsid(e);break;case"imageattr":this.parseImageAttr(e);break;case"rid":this.parseRid(e);break;case"simulcast":this.parseSimulcast(e);break;case"sctp-port":this.parseSctpPort(e);break;case"max-message-size":this.parseMaxMessageSize(e);break;case"ssrc-group":this.parseSSRCGroup(e);break;default:e.ignored=!0,this.attributes.unrecognized.push(e)}}catch(t){throw console.error("parsing media attribute ".concat(e.attField,' error, "a=').concat(e.attField,":").concat(e.attValue,'"')),t}if(!e.ignored&&e.attValue&&!this.atEnd(e))throw Error("attribute parsing error")}parseCandidate(e){let t=this.extractOneOrMore(e,_,[1,32]);this.consumeAttributeSpace(e);let i=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);let r=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);let n=this.extractOneOrMore(e,a,[1,10]);this.consumeAttributeSpace(e);let o=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);let c=this.extract(e,this.consumePort);this.consumeAttributeSpace(e),this.extract(e,this.consume,"typ"),this.consumeAttributeSpace(e);let d={foundation:t,componentId:i,transport:r,priority:n,connectionAddress:o,port:c,type:this.extract(e,this.consumeToken),extension:{}};for(this.peek(e," raddr")&&(this.extract(e,this.consume," raddr"),this.consumeAttributeSpace(e),d.relAddr=this.extract(e,this.consumeAddress)),this.peek(e," rport")&&(this.extract(e,this.consume," rport"),this.consumeAttributeSpace(e),d.relPort=this.extract(e,this.consumePort));" "===this.peekChar(e);){this.consumeAttributeSpace(e);let t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e),d.extension[t]=this.extractOneOrMore(e,s)}this.attributes.candidates.push(d)}parseRemoteCandidate(e){let t=[];for(;;){let i=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);let r=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);let n=this.extract(e,this.consumePort);t.push({componentId:i,connectionAddress:r,port:n});try{this.consumeAttributeSpace(e)}catch(e){break}}this.attributes.remoteCandidatesList.push(t)}parseEndOfCandidates(){if(this.attributes.endOfCandidates)throw Error("must be only one line of end-of-candidates");this.attributes.endOfCandidates=!0}parseRtpmap(e){let t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);let i=this.extract(e,this.consumeTill,"/");this.extract(e,this.consume,"/");let r={encodingName:i,clockRate:this.extractOneOrMore(e,a)};this.atEnd(e)||"/"!==this.peekChar(e)||(this.extract(e,this.consume,"/"),r.encodingParameters=parseInt(this.extract(e,this.consumeTill),10));let n=this.attributes.payloads.find(e=>e.payloadType===parseInt(t,10));n?n.rtpMap=r:this.attributes.payloads.push({payloadType:parseInt(t,10),rtpMap:r,rtcpFeedbacks:[]})}parsePtime(e){if(this.attributes.ptime)throw Error("must be only one line of ptime");this.attributes.ptime=this.extract(e,this.consumeTill)}parseMaxPtime(e){if(this.attributes.maxPtime)throw Error("must be only one line of ptime");this.attributes.maxPtime=this.extract(e,this.consumeTill)}parseDirection(e){if(this.attributes.direction)throw Error("must be only one line of direction info");this.attributes.direction=e.attField}parseSSRC(e){let t,i=this.extractOneOrMore(e,a);this.consumeAttributeSpace(e);let r=this.extract(e,this.consumeTill,":");":"===this.peekChar(e)&&(this.extract(e,this.consume,":"),t=this.extract(e,this.consumeTill));let n=this.attributes.ssrcs.find(e=>e.ssrcId===parseInt(i,10));n?n.attributes[r]=t:this.attributes.ssrcs.push({ssrcId:parseInt(i,10),attributes:{[r]:t}})}parseFmtp(e){let t=this.extract(e,this.consumeTill," ");this.consumeAttributeSpace(e);let i=this.extract(e,this.consumeTill),r={};i.split(";
1").forEach(e=>{let[t,i]=e.split("=");t=py(t).call(t);let n="string"==typeof i?py(i).call(i):null;"string"==typeof t&&t.length>0&&(r[t]=n)});let n=this.attributes.payloads.find(e=>e.payloadType===parseInt(t,10));n?n.fmtp={parameters:r}:this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[],fmtp:{parameters:r}})}parseFmtParameters(e){let t={},i=this.extract(e,this.consumeTill,"=");e._cur++;let r=this.extract(e,this.consumeTill,";");for(t[i]=r;";"===e.attValue[e._cur];){let i=this.extract(e,this.consumeTill,"=");e._cur++;let r=this.extract(e,this.consumeTill,";");t[i]=r}return t}parseRtcpFb(e){let t,i="";i="*"===this.peekChar(e)?this.extract(e,this.consume,"*"):this.extract(e,this.consumeTill," "),this.consumeAttributeSpace(e);let r=this.extract(e,this.consumeTill," ");if("trr-int"===r)t={type:r,interval:this.extract(e,this.consumeTill)};else{let i={type:r};" "===this.peekChar(e)&&(this.consumeAttributeSpace(e),i.parameter=this.extract(e,this.consumeToken)," "===this.peekChar(e)&&(i.additional=this.extract(e,this.consumeTill))),t=i}if("*"===i)this.attributes.rtcpFeedbackWildcards.push(t);else{let e=this.attributes.payloads.find(e=>e.payloadType===parseInt(i,10));e?e.rtcpFeedbacks.push(t):this.attributes.payloads.push({payloadType:parseInt(i,10),rtcpFeedbacks:[t]})}}parseRTCPMux(){if(this.attributes.rtcpMux)throw Error("must be single line of rtcp-mux");this.attributes.rtcpMux=!0}parseRTCPMuxOnly(){if(this.attributes.rtcpMuxOnly)throw Error("must be single line of rtcp-only");this.attributes.rtcpMuxOnly=!0}parseRTCPRsize(){if(this.attributes.rtcpRsize)throw Error("must be single line of rtcp-rsize");this.attributes.rtcpRsize=!0}parseRTCP(e){if(this.attributes.rtcp)throw Error("must be single line of rtcp");let t={port:this.extract(e,this.consumePort)};" "===this.peekChar(e)&&(this.consumeAttributeSpace(e),t.netType=this.extractOneOrMore(e,d),this.consumeAttributeSpace(e),t.addressType=this.extractOneOrMore(e,d),this.consumeAttributeSpace(e),t.address=this.extract(e,this.consumeAddress)),this.attributes.rtcp=t}parseMsid(e){let t={id:this.extractOneOrMore(e,d,[1,64])};" "===this.peekChar(e)&&(this.consumeAttributeSpace(e),t.appdata=this.extractOneOrMore(e,d,[1,64])),this.attributes.msids.push(t)}parseImageAttr(e){this.attributes.imageattr.push(e.attValue)}parseRid(e){let t=this.extractOneOrMore(e,e=>h(e)||a(e)||"_"===e||"-"===e);this.consumeAttributeSpace(e);let i={id:t,direction:this.extract(e,this.consumeToken),params:[]};if(" "===this.peekChar(e)){if(this.consumeAttributeSpace(e),this.peek(e,"pt=")){this.extract(e,this.consume,"pt=");let t=[];for(;;){let i=this.extract(e,this.consumeToken);t.push(i);try{this.extract(e,this.consume,",")}catch(e){break}}i.payloads=t," "===this.peekChar(e)&&this.extract(e,this.consume," ")}for(;;){let t=this.extract(e,this.consumeToken);if("depend"===t){let r={type:t,rids:this.extract(e,this.consume,"=").split(",")};i.params.push(r)}else{let r={type:t};"="===this.peekChar(e)&&(this.extract(e,this.consume,"="),r.val=this.extract(e,this.consumeTill,";")),i.params.push(r)}try{this.extract(e,this.consume,";")}catch(e){break}}}this.attributes.rids.push(i)}parseSimulcast(e){if(this.attributes.simulcast)throw Error("must be single line of simulcast");this.attributes.simulcast=e.attValue,this.extract(e,this.consumeTill)}parseSctpPort(e){this.attributes.sctpPort=this.extractOneOrMore(e,a,[1,5])}parseMaxMessageSize(e){this.attributes.maxMessageSize=this.extractOneOrMore(e,a,[1,void 0])}digest(){return this.digested=!0,this.attributes}parseMid(e){this.attributes.mid=this.extract(e,this.consumeToken)}parseSSRCGroup(e){let t=this.extract(e,this.consumeToken),i=[];for(;;)try{this.consumeAttributeSpace(e);let t=this.extract(e,this.consumeInteger);i.push(parseInt(t,10))}catch(e){break}this.attributes.ssrcGroups.push({semantic:t,ssrcIds:i})}constructor(e){super(),g(this,"attributes",void 0),-1!==e.protos.indexOf("RTP")||e.protos.indexOf("rtp"),this.attributes={unrecognized:[],candidates:[],extmaps:[],fingerprints:[],imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[]}}}function I(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class A{print(e,t){let i="";return t&&(this.eol=t),i+=this.printVersion(e.version),i+=this.printOrigin(e.origin),i+=this.printSessionName(e.sessionName),i+=this.printInformation(e.information),i+=this.printUri(e.uri),i+=this.printEmail(e.emails),i+=this.printPhone(e.phones),i+=this.printConnection(e.connection),i+=this.printBandwidth(e.bandwidths),i+=this.printTimeFields(e.timeFields),i+=this.printKey(e.ke
1y),i+=this.printSessionAttributes(e.attributes),i+=this.printMediaDescription(e.mediaDescriptions)}printVersion(e){return"v=".concat(e).concat(this.eol)}printOrigin(e){return"o=".concat(e.username," ").concat(e.sessId," ").concat(e.sessVersion," ").concat(e.nettype," ").concat(e.addrtype," ").concat(e.unicastAddress).concat(this.eol)}printSessionName(e){return e?"s=".concat(e).concat(this.eol):""}printInformation(e){return e?"i=".concat(e).concat(this.eol):""}printUri(e){return e?"u=".concat(e).concat(this.eol):""}printEmail(e){let t="";for(let i of e)t+="e=".concat(i).concat(this.eol);return t}printPhone(e){let t="";for(let i of e)t+="e=".concat(i).concat(this.eol);return t}printConnection(e){return e?"c=".concat(e.nettype," ").concat(e.addrtype," ").concat(e.address).concat(this.eol):""}printBandwidth(e){let t="";for(let i of e)t+="b=".concat(i.bwtype,":").concat(i.bandwidth).concat(this.eol);return t}printTimeFields(e){let t="";for(let i of e){for(let e of(t+="t=".concat(i.time.startTime," ").concat(i.time.startTime).concat(this.eol),i.repeats))t+="r=".concat(e.repeatInterval," ").concat(e.typedTimes.join(" ")).concat(this.eol);i.zoneAdjustments&&(t+="z=",t+="z=".concat(i.zoneAdjustments.map(e=>"".concat(e.time," ").concat(e.back?"-":""," ").concat(e.typedTime)).join(" ")).concat(this.eol),t+=this.eol)}return t}printKey(e){return e?"k=".concat(e).concat(this.eol):""}printAttributes(e){let t="";for(let i of e)t+="a=".concat(i.attField).concat(i.attValue?":".concat(i.attValue):"").concat(this.eol);return t}printMediaDescription(e){let t="";for(let i of e)t+=this.printMedia(i.media),t+=this.printInformation(i.information),t+=this.printConnections(i.connections),t+=this.printBandwidth(i.bandwidths),t+=this.printKey(i.key),t+=this.printMediaAttributes(i);return t}printConnections(e){let t="";for(let i of e)t+=this.printConnection(i);return t}printMedia(e){return"m=".concat(e.mediaType," ").concat(e.port," ").concat(e.protos.join("/")," ").concat(e.fmts.join(" ")).concat(this.eol)}printSessionAttributes(e){return new O(this.eol).print(e)}printMediaAttributes(e){return new w(this.eol).print(e)}constructor(){I(this,"eol",o)}}class b{printIceUfrag(e){return void 0===e?"":"a=ice-ufrag:".concat(e).concat(this.eol)}printIcePwd(e){return void 0===e?"":"a=ice-pwd:".concat(e).concat(this.eol)}printIceOptions(e){return void 0===e?"":"a=ice-options:".concat(e.join(" ")).concat(this.eol)}printFingerprints(e){return e.length>0?e.map(e=>"a=fingerprint:".concat(e.hashFunction).concat(" ").concat(e.fingerprint)).join(this.eol)+this.eol:""}printExtmap(e){return e.map(e=>"a=extmap:".concat(e.entry).concat(e.direction?"/".concat(e.direction):"").concat(" ").concat(e.extensionName).concat(e.extensionAttributes?"".concat(" ").concat(e.extensionAttributes):"").concat(this.eol)).join("")}printSetup(e){return void 0===e?"":"a=setup:".concat(e).concat(this.eol)}printUnrecognized(e){return e.map(e=>"a=".concat(e.attField).concat(e.attValue?":".concat(e.attValue):"").concat(this.eol)).join("")}constructor(e){I(this,"eol",void 0),this.eol=e}}class O extends b{print(e){let t="";return t+=this.printGroups(e.groups),t+=this.printMsidSemantic(e.msidSemantic),t+=this.printIceLite(e.iceLite),t+=this.printIceUfrag(e.iceUfrag),t+=this.printIcePwd(e.icePwd),t+=this.printIceOptions(e.iceOptions),t+=this.printFingerprints(e.fingerprints),t+=this.printSetup(e.setup),t+=this.printTlsId(e.tlsId),t+=this.printIdentity(e.identities),t+=this.printExtmap(e.extmaps),t+=this.printUnrecognized(e.unrecognized)}printGroups(e){let t="";return e.length>0&&(t+=e.map(e=>"a=group:".concat(e.semantic).concat(e.identificationTag.map(e=>"".concat(" ").concat(e)).join("")).concat(this.eol)).join("")),t}printIceLite(e){return void 0===e?"":"a=ice-lite"+this.eol}printTlsId(e){return e?"a=tls-id:".concat(e).concat(this.eol):""}printIdentity(e){return 0===e.length?"":e.map(e=>"a=identity:".concat(e.assertionValue).concat(e.extensions.map(e=>"".concat(" ").concat(e.name).concat(e.value?"=".concat(e.value):"")))).join(this.eol)+this.eol}printMsidSemantic(e){if(!e)return"";let t="a=msid-semantic:".concat(e.semantic);return e.applyForAll?t+="".concat(" ","*"):e.identifierList.length>0&&(t+=e.identifierList.map(e=>"".concat(" ").concat(e))),t+this.eol}}class w extends b{print(e){let t=e.attributes,i="";
1return i+=this.printRTCP(t.rtcp),i+=this.printIceUfrag(t.iceUfrag),i+=this.printIcePwd(t.icePwd),i+=this.printIceOptions(t.iceOptions),i+=this.printCandidates(t.candidates),i+=this.printRemoteCandidatesList(t.remoteCandidatesList),i+=this.printEndOfCandidates(t.endOfCandidates),i+=this.printFingerprints(t.fingerprints),i+=this.printSetup(t.setup),i+=this.printMid(t.mid),i+=this.printExtmap(t.extmaps),i+=this.printRTPRelated(t),i+=this.printPtime(t.ptime),i+=this.printMaxPtime(t.maxPtime),i+=this.printDirection(t.direction),i+=this.printSSRCGroups(t.ssrcGroups),i+=this.printSSRC(t.ssrcs),i+=this.printRTCPMux(t.rtcpMux),i+=this.printRTCPMuxOnly(t.rtcpMuxOnly),i+=this.printRTCPRsize(t.rtcpRsize),i+=this.printMSId(t.msids),i+=this.printImageattr(t.imageattr),i+=this.printRid(t.rids),i+=this.printSimulcast(t.simulcast),i+=this.printSCTPPort(t.sctpPort),i+=this.printMaxMessageSize(t.maxMessageSize),i+=this.printUnrecognized(t.unrecognized)}printCandidates(e){return e.map(e=>"a=candidate:".concat(e.foundation).concat(" ").concat(e.componentId).concat(" ").concat(e.transport).concat(" ").concat(e.priority).concat(" ").concat(e.connectionAddress).concat(" ").concat(e.port).concat(" ","typ").concat(" ").concat(e.type).concat(e.relAddr?"".concat(" ","raddr").concat(" ").concat(e.relAddr):"").concat(e.relPort?"".concat(" ","rport").concat(" ").concat(e.relPort):"").concat(Object.keys(e.extension).map(t=>"".concat(" ").concat(t).concat(" ").concat(e.extension[t])).join("")).concat(this.eol)).join("")}printRemoteCandidatesList(e){return e.map(e=>"a=remote-candidates:".concat(e.join(" ")).concat(this.eol)).join("")}printEndOfCandidates(e){return void 0===e?"":"a=end-of-candidates"+this.eol}printRTPRelated(e){if(!e.payloads)return"";let t=e.payloads,i="";for(let r of(i+=e.rtcpFeedbackWildcards.map(e=>this.printRTCPFeedback("*",e)).join(""),t))i+=this.printRtpMap(r.payloadType,r.rtpMap),i+=this.printFmtp(r.payloadType,r.fmtp),i+=r.rtcpFeedbacks.map(e=>this.printRTCPFeedback(r.payloadType,e)).join("");return i}printFmtp(e,t){if(!t)return"";let i=Object.keys(t.parameters);return 1===i.length&&null===t.parameters[i[0]]?"a=fmtp:".concat(e).concat(" ").concat(i[0]).concat(this.eol):"a=fmtp:".concat(e).concat(" ").concat(Object.keys(t.parameters).map(e=>"".concat(e,"=").concat(t.parameters[e])).join(";")).concat(this.eol)}printRtpMap(e,t){return t?"a=rtpmap:".concat(e).concat(" ").concat(t.encodingName,"/").concat(t.clockRate).concat(t.encodingParameters?"/".concat(t.encodingParameters):"").concat(this.eol):""}printRTCPFeedback(e,t){let i="a=rtcp-fb:".concat(e).concat(" ");return"trr-int"===t.type?i+="ttr-int".concat(" ").concat(t.interval):(i+="".concat(t.type),t.parameter&&(i+="".concat(" ").concat(t.parameter),t.additional&&(i+="".concat(" ").concat(t.additional)))),i+this.eol}printPtime(e){return void 0===e?"":"a=ptime:".concat(e).concat(this.eol)}printMaxPtime(e){return void 0===e?"":"a=maxptime:".concat(e).concat(this.eol)}printDirection(e){return void 0===e?"":"a=".concat(e).concat(this.eol)}printSSRC(e){return e.map(e=>Object.keys(e.attributes).map(t=>"a=ssrc:".concat(e.ssrcId.toString(10)).concat(" ").concat(t).concat(e.attributes[t]?":".concat(e.attributes[t]):"").concat(this.eol)).join("")).join("")}printRTCPMux(e){return void 0===e?"":"a=rtcp-mux".concat(this.eol)}printRTCPMuxOnly(e){return void 0===e?"":"a=rtcp-mux-only".concat(this.eol)}printRTCPRsize(e){return void 0===e?"":"a=rtcp-rsize".concat(this.eol)}printRTCP(e){if(void 0===e)return"";let t="a=rtcp:".concat(e.port);return e.netType&&(t+="".concat(" ").concat(e.netType)),e.addressType&&(t+="".concat(" ").concat(e.addressType)),e.address&&(t+="".concat(" ").concat(e.address)),t+this.eol}printMSId(e){return e.map(e=>"a=msid:".concat(e.id).concat(e.appdata?"".concat(" ").concat(e.appdata):"").concat(this.eol)).join("")}printImageattr(e){return e.map(e=>"a=imageattr:".concat(e).concat(this.eol)).join("")}printRid(e){return e.map(e=>{let t="a=rid:".concat(e.id).concat(" ").concat(e.direction);return e.payloads&&(t+="".concat(" ","pt=").concat(e.payloads.join(","))),e.params.length>0&&(t+="".concat(" ").concat(e.params.map(e=>
1"depend"===e.type?"depend=".concat(e.rids.join(",")):"".concat(e.type,"=").concat(e.val)).join(";"))),t+this.eol}).join("")}printSimulcast(e){return void 0===e?"":"a=simulcast:".concat(e).concat(this.eol)}printSCTPPort(e){return void 0===e?"":"a=sctp-port:".concat(e).concat(this.eol)}printMaxMessageSize(e){return void 0===e?"":"a=max-message-size:".concat(e).concat(this.eol)}printMid(e){return void 0===e?"":"a=mid:".concat(e).concat(this.eol)}printSSRCGroups(e){return e.map(e=>"a=ssrc-group:".concat(e.semantic).concat(e.ssrcIds.map(e=>"".concat(" ").concat(e.toString(10))).join("")).concat(this.eol)).join("")}}function N(e){return(new R).parse(e)}function D(e,t){return(new A).print(e,t)}}},t={};function i(r){if(t[r])return t[r].exports;var n=t[r]={exports:{}};return e[r](n,n.exports,i),n.exports}return i.d=(e,t)=>{for(var r in t)i.o(t,r)&&!i.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i(8)})();function TO(e){return Tb.parse(e)}function Tw(e,t){return Tb.print(e,t)}var TN=oF("Array","keys"),TD=Array.prototype,TP={DOMTokenList:!0,NodeList:!0},TL=rW(function(e){var t=e.keys;return e===TD||rJ(TD,e)&&t===TD.keys||nq(TP,oX(e))?TN:t});function Tk(e,t,i){var r;return(t="symbol"==typeof(r=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,"string");if("object"!=typeof r)return r;throw TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(t))?r:r+"")in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function TM(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function TU(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?TM(Object(i),!0).forEach(function(t){Tk(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):TM(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}function Tx(e,t){return(Tx=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e})(e,t)}function TV(){TV=function(e,t){return new i(e,void 0,t)};var e=RegExp.prototype,t=new WeakMap;function i(e,r,n){var o=RegExp(e,r);return t.set(o,n||t.get(e)),Tx(o,i.prototype)}function r(e,i){var r,n=t.get(i);return as(r=Object.keys(n)).call(r,function(t,i){var r=n[i];if("number"==typeof r)t[i]=e[r];else{for(var o=0;void 0===e[r[o]]&&o+1<r.length;)o++;t[i]=e[r[o]]}return t},Object.create(null))}return function(e,t){if("function"!=typeof t&&null!==t)throw TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Tx(e,t)}(i,RegExp),i.prototype.exec=function(t){var i=e.exec.call(this,t);if(i){i.groups=r(i,this);var n=i.indices;n&&(n.groups=r(n,this))}return i},i.prototype[Symbol.replace]=function(i,n){if("string"==typeof n){var o=t.get(this);return e[Symbol.replace].call(this,i,n.replace(/\$<([^>]+)(>|$)/g,function(e,t,i){if(""===i)return e;var r=o[t];return Array.isArray(r)?"$"+r.join("$"):"number"==typeof r?"$"+r:""}))}if("function"==typeof n){var a=this;return e[Symbol.replace].call(this,i,function(){var e=arguments;return"object"!=typeof e[e.length-1]&&(e=[].slice.call(e)).push(r(e,a)),n.apply(this,e)})}return e[Symbol.replace].call(this,i,n)},TV.apply(this,arguments)}let TF=new class extends S0{reportLogUploadError(e){let{errorRange:t}=e;t[t.length-1]&&t[t.length-1]>this.currentUploadLogID&&(this.currentUploadLogID=t[t.length-1],this.emit("REPORT_LOG_UPLOAD",e))}constructor(){super(...arguments),Tk(this,"currentUploadLogID",0)}};class TB{debug(){for(var e=arguments.length,t=Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.debug(...this.prefixLists,...t)}info(){for(var e=arguments.length,t=Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.info(...this.prefixLists,...t)}warning(){for(var e=arguments.length,t=Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.warning(...this.prefixLists,...t)}error(){for(var e=arguments.length,t=Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.error(...this.prefixLists,...t)}prefix(e){return this.prefixLists.push(e),this}popPrefix(){return this.prefixLists.pop(),this}constructor(e){Tk(this,"logger",void 0),Tk(this,"prefixLists",[]),this.logger=e}}function Tj(){let e=new Date;
1return e.toTimeString().split(" ")[0]+":"+e.getMilliseconds()}function TG(){let e=new Date,t=/((\d+:){2}\d+)/.exec((new Date).toUTCString());return t?(null==t?void 0:t[0])+":"+e.getUTCMilliseconds():e.toTimeString().split(" ")[0]+":"+e.getMilliseconds()}let TW={DEBUG:0,INFO:1,WARNING:2,ERROR:3,NONE:4},TH=Date.now(),TK=e=>{for(let t in TW)if(Object.prototype.hasOwnProperty.call(TW,t)&&TW[t]===e)return t;return"DEFAULT"},TY=new class{debug(){for(var e=arguments.length,t=Array(e),i=0;i<e;i++)t[i]=arguments[i];let r=[TW.DEBUG].concat(t);this.log.apply(this,r)}info(){for(var e=arguments.length,t=Array(e),i=0;i<e;i++)t[i]=arguments[i];let r=[TW.INFO].concat(t);this.log.apply(this,r)}warning(){for(var e=arguments.length,t=Array(e),i=0;i<e;i++)t[i]=arguments[i];let r=[TW.WARNING].concat(t);this.log.apply(this,r)}warn(){this.warning(...arguments)}error(){for(var e=arguments.length,t=Array(e),i=0;i<e;i++)t[i]=arguments[i];let r=[TW.ERROR].concat(t);this.log.apply(this,r)}upload(){for(var e=arguments.length,t=Array(e),i=0;i<e;i++)t[i]=arguments[i];let r=[TW.DEBUG].concat(t);this.uploadLog.apply(this,r)}setLogLevel(e){e=Math.min(Math.max(0,e),4),this.logLevel=e}enableLogUpload(){TT("UPLOAD_LOG",!0)}disableLogUpload(){TT("UPLOAD_LOG",!1),this.uploadLogUploadingList=[],this.uploadLogWaitingList=[]}setProxyServer(e){this.proxyServerURL=e}prefix(e){return new TB(this).prefix(e)}log(){for(var e=arguments.length,t=Array(e),i=0;i<e;i++)t[i]=arguments[i];if(Date.now()-TH<100)return void setTimeout(()=>{this.log(...t)},Date.now()-TH);let r=Math.max(0,Math.min(4,t[0]));if(t[0]=Tj()+" Agora-SDK [".concat(TK(r),"]:"),this.appendLogToWaitingList(r,...t),r<this.logLevel)return;let n=Tj()+" %cAgora-SDK [".concat(TK(r),"]:"),o=[];if(!TR("USE_NEW_LOG"))switch(r){case TW.DEBUG:o=[n,"color: #64B5F6;"].concat(t.slice(1)),console.log.apply(console,o);break;case TW.INFO:o=[n,"color: #1E88E5; font-weight: bold;"].concat(t.slice(1)),console.log.apply(console,o);break;case TW.WARNING:o=[n,"color: #FB8C00; font-weight: bold;"].concat(t.slice(1)),console.warn.apply(console,o);break;case TW.ERROR:o=[n,"color: #B00020; font-weight: bold;"].concat(t.slice(1)),console.error.apply(console,o)}}uploadLog(){for(var e=arguments.length,t=Array(e),i=0;i<e;i++)t[i]=arguments[i];if(Date.now()-TH<100)return void setTimeout(()=>{this.uploadLog(...t)},Date.now()-TH);let r=Math.max(0,Math.min(4,t[0]));t[0]=Tj()+" Agora-SDK [".concat(TK(r),"]:"),this.appendLogToWaitingList(r,...t)}appendLogToWaitingList(e){if(!TR("UPLOAD_LOG"))return;for(var t=arguments.length,i=Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];Array.isArray(i[0])?i[0][0]=TG()+" Agora-SDK [".concat(TK(e),"]:"):i[0]=TG()+" Agora-SDK [".concat(TK(e),"]:");let n="";i.forEach(e=>{"object"==typeof e&&(e=JSON.stringify(e)),n+="".concat(e," ")}),this.uploadLogWaitingList.push({payload_str:n,log_level:e,log_item_id:this.currentLogID++}),"uploading"===this.uploadState&&0===this.uploadLogUploadingList.length&&this.uploadLogInterval()}startUpload(){this.uploadState="uploading",0===this.uploadLogUploadingList.length&&this.uploadLogInterval()}async uploadLogs(){let e=this.uploadLogUploadingList,t={sdk_version:Th,process_id:TR("PROCESS_ID"),payload:JSON.stringify(e)};return gY(async()=>{let e=await f0.post(this.url||(this.proxyServerURL?"https://".concat(this.proxyServerURL,"/ls/?h=").concat(TR("LOG_UPLOAD_SERVER"),"&p=443&d=upload/v1"):"https://".concat(TR("LOG_UPLOAD_SERVER"),"/upload/v1")),t,{responseType:"text"});if("OK"!==e.data){let t=Error("unexpected upload log response");throw t.response=e,t}},()=>(this.uploadLogUploadingList=[],!1),t=>{let i={status:-1,message:t.message,errorRange:e.map(e=>e.log_item_id)};return t.response?(i.status=t.response.status,i.data=t.response.data,i.headers=t.response.headers):t.request&&(i.status=t.request.status),TF.reportLogUploadError(i),!0},{timeout:TR("UPLOAD_LOG_REQUEST_RETRY_INTERVAL"),maxRetryTimeout:TR("UPLOAD_LOG_REQUEST_MAX_RETRY_INTERVAL")})}uploadLogInterval(){0===this.uploadLogUploadingList.length&&0===this.uploadLogWaitingList.length||(0===this.uploadLogUploadingList.length&&(this.uploadLogUploadingList=this.uploadLogWaitingList.splice(0,TR("UPLOAD_LOG_LENGTH_EACH_TIME"))),this.uploadLogs().then(()=>{this.uploadErrorCount=0,this.uploadLogWaitingList.length>0&&window.setTimeout(()=>this.uploadLogInterval(),TR("UPLOAD_LOG_INTERVAL"))}).catch(e=>{this.uploadErrorCount+=1,this.uploadErrorCount<2?window.setTimeout(()=>this.uploadLogInterval(),TR("UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1")):window.setTimeout(()=>this.uploadLogInterval(),TR("UPLOAD_LOG_RETRY_INTERVAL_V1"))}))}constructor(){Tk(this,"proxyServerURL",void 0),Tk(this,"logLevel",TW.DEBUG),Tk(this,"uploadState","collecting"),Tk(this,"uploadLogWaitingList",[]),Tk(this,"uploadLogUploadingList",[]),Tk(this,"uploadErrorCount",0),Tk(this,"currentLogID",0),Tk(this,"url",void 0),Tk(this,"extLog",(e,t)=>{this.appendLogToWaitingList(e,...t)})}};function Tz(e){return SG(e.reportId,"params.reportId",0,100,!1),SG(e.category,"params.category",0,100,!1),SG(e.event,"params.event",0,100,!1),SG(e.label,"params.label",0,100,!1),SB(e.value,"params.value",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,!1),!0}(tp={}).FREE="free",tp.UPLOADING="uploading",(G={})[G.MISC=0]="MISC",G[G.INTERNAL_EVENT=1]="INTERNAL_EVENT",G[G.PUBLIC_EVENT=2]="PUBLIC_EVENT",G[G.WEB_EVENT=3]="WEB_EVENT",G[G.INTERNAL_API=4]="INTERNAL_API",G[G.WEB_API=5]="WEB_API",G[G.PUBLIC_API=6]="P
1UBLIC_API";let Tq={sid:"",lts:0,success:null,cname:null,uid:null,peer:null,cid:null,elapse:null,extend:null,vid:0},TX=((W={}).PUBLISH="publish",W.SUBSCRIBE="subscribe",W.WS_COMPRESSOR_INIT="ws_compressor_init",W.SESSION_INIT="session_init",W.JOIN_CHOOSE_SERVER="join_choose_server",W.RTE_DETAIL="rte_detail_stats",W.REQ_USER_ACCOUNT="req_user_account",W.JOIN_GATEWAY="join_gateway",W.REJOIN_GATEWAY="rejoin_gateway",W.STREAM_SWITCH="stream_switch",W.REQUEST_PROXY_WORKER_MANAGER="request_proxy_worker_manager",W.REQUEST_PROXY_APPCENTER="request_proxy_appcenter",W.FIRST_VIDEO_RECEIVED="first_video_received",W.FIRST_AUDIO_RECEIVED="first_audio_received",W.FIRST_VIDEO_DECODE="first_video_decode",W.FIRST_AUDIO_DECODE="first_audio_decode",W.XLA_PEER_FIRST_VIDEO_FRAME="xla_peer_first_video_frame",W.ON_ADD_AUDIO_STREAM="on_add_audio_stream",W.ON_ADD_VIDEO_STREAM="on_add_video_stream",W.ON_UPDATE_STREAM="on_update_stream",W.ON_REMOVE_STREAM="on_remove_stream",W.USER_ANALYTICS="req_user_analytics",W.PC_STATS="pc_stats",W.UPDATE_REMOTE_RTPCAPABILITIES="update_remote_rtpCapabilities",W.AB_TEST="ab_test",W),TJ=((H={}).SESSION="io.agora.pb.Wrtc.Session",H.JOIN_CHOOSE_SERVER="io.agora.pb.Wrtc.JoinChooseServer",H.RTE_DETAIL="io.agora.pb.Wrtc.RteDetailStats",H.REQ_USER_ACCOUNT="io.agora.pb.Wrtc.ReqUserAccount",H.JOIN_GATEWAY="io.agora.pb.Wrtc.JoinGateway",H.RE_JOIN_GATEWAY="io.agora.pb.Wrtc.ReJoinGateway",H.PUBLISH="io.agora.pb.Wrtc.Publish",H.SUBSCRIBE="io.agora.pb.Wrtc.Subscribe",H.WS_COMPRESSOR_INIT="io.agora.pb.Wrtc.WsCompressorInit",H.STREAM_SWITCH="io.agora.pb.Wrtc.StreamSwitch",H.AUDIO_SENDING_STOPPED="io.agora.pb.Wrtc.AudioSendingStopped",H.VIDEO_SENDING_STOPPED="io.agora.pb.Wrtc.VideoSendingStopped",H.REQUEST_PROXY_APPCENTER="io.agora.pb.Wrtc.RequestProxyAppCenter",H.REQUEST_PROXY_WORKER_MANAGER="io.agora.pb.Wrtc.RequestProxyWorkerManager",H.API_INVOKE="io.agora.pb.Wrtc.ApiInvoke",H.FIRST_VIDEO_RECEIVED="io.agora.pb.Wrtc.FirstVideoReceived",H.FIRST_AUDIO_RECEIVED="io.agora.pb.Wrtc.FirstAudioReceived",H.FIRST_VIDEO_DECODE="io.agora.pb.Wrtc.FirstVideoDecode",H.FIRST_AUDIO_DECODE="io.agora.pb.Wrtc.FirstAudioDecode",H.XLA_PEER_FIRST_VIDEO_FRAME="io.agora.pb.Wrtc.XLAPeerFirstVideoFrame",H.ON_ADD_AUDIO_STREAM="io.agora.pb.Wrtc.OnAddAudioStream",H.ON_ADD_VIDEO_STREAM="io.agora.pb.Wrtc.OnAddVideoStream",H.ON_UPDATE_STREAM="io.agora.pb.Wrtc.OnUpdateStream",H.ON_REMOVE_STREAM="io.agora.pb.Wrtc.OnRemoveStream",H.JOIN_CHANNEL_TIMEOUT="io.agora.pb.Wrtc.JoinChannelTimeout",H.PEER_PUBLISH_STATUS="io.agora.pb.Wrtc.PeerPublishStatus",H.WORKER_EVENT="io.agora.pb.Wrtc.WorkerEvent",H.AP_WORKER_EVENT="io.agora.pb.Wrtc.APWorkerEvent",H.JOIN_WEB_PROXY_AP="io.agora.pb.Wrtc.JoinWebProxyAP",H.WEBSOCKET_QUIT="io.agora.pb.Wrtc.WebSocketQuit",H.USER_ANALYTICS="io.agora.pb.Wrtc.UserAnalytics",H.AUTOPLAY_FAILED="io.agora.pb.Wrtc.AutoplayFailed",H.PC_STATS="io.agora.pb.Wrtc.PCStats",H.UPDATE_REMOTE_RTPCAPABILITIES="io.agora.pb.Wrtc.UpdateRemoteRTPCapabilities",H.AB_TEST="io.agora.pb.Wrtc.ABTest",H);(K={})[K.WORKER_EVENT=156]="WORKER_EVENT",K[K.AP_WORKER_EVENT=160]="AP_WORKER_EVENT";let TQ=((Y={})[Y.SESSION=26]="SESSION",Y[Y.JOIN_CHOOSE_SERVER=27]="JOIN_CHOOSE_SERVER",Y[Y.REQ_USER_ACCOUNT=196]="REQ_USER_ACCOUNT",Y[Y.JOIN_GATEWAY=28]="JOIN_GATEWAY",Y[Y.PUBLISH=30]="PUBLISH",Y[Y.SUBSCRIBE=29]="SUBSCRIBE",Y[Y.WS_COMPRESSOR_INIT=9430]="WS_COMPRESSOR_INIT",Y[Y.STREAM_SWITCH=32]="STREAM_SWITCH",Y[Y.AUDIO_SENDING_STOPPED=33]="AUDIO_SENDING_STOPPED",Y[Y.VIDEO_SENDING_STOPPED=34]="VIDEO_SENDING_STOPPED",Y[Y.REQUEST_PROXY_APPCENTER=35]="REQUEST_PROXY_APPCENTER",Y[Y.REQUEST_PROXY_WORKER_MANAGER=36]="REQUEST_PROXY_WORKER_MANAGER",Y[Y.API_INVOKE=41]="API_INVOKE",Y[Y.FIRST_VIDEO_RECEIVED=348]="FIRST_VIDEO_RECEIVED",Y[Y.FIRST_AUDIO_RECEIVED=349]="FIRST_AUDIO_RECEIVED",Y[Y.FIRST_VIDEO_DECODE=350]="FIRST_VIDEO_DECODE",Y[Y.FIRST_AUDIO_DECODE=351]="FIRST_AUDIO_DECODE",Y[Y.ON_ADD_AUDIO_STREAM=352]="ON_ADD_AUDIO_STREAM",Y[Y.ON_ADD_VIDEO_STREAM=353]="ON_ADD_VIDEO_STREAM",Y[Y.ON_UPDATE_STREAM=356]="ON_UPDATE_STREAM",Y[Y.ON_REMOVE_STREAM=355]="ON_REMOVE_STREAM",Y[Y.JOIN_CHANNEL_TIMEOUT=407]="JOIN_CHANNEL_TIMEOUT",Y[Y.PEER_PUBLISH_STATUS=408]="PEER_PUBLISH_STATUS",Y[Y.WORKER_EVENT=156]="WORKER_EVENT",Y[Y.AP_WORKER_EVENT=160]="AP_WORKER_EVENT",Y[Y.JOIN_WEB_PROXY_AP=700]="JOIN_WEB_PROXY_AP",Y[Y.WEBSOCKET_QUIT=671]="WEBSOCKET_QUIT",Y[Y.USER_ANALYTICS=1e4]="USER_ANALYTICS",Y[Y.AUTOPLAY_FAILED=9178]="AUTOPLAY_FAILED",Y);function TZ(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(t,i,r){let n=r.value;if("function"==typeof n){let o=e.className||t.__className__||("AgoraRTCClient"===t.constructor.name?"Client":t.constructor.name);r.value=function(){for(var t,r=arguments.length,a=Array(r),s=0;s<r;s++)a[s]=arguments[s];let c=a;if(e.argsMap)try{c=e.argsMap(this,...a)}catch(e){TY.warning(e),c=[]}try{JSON.stringify(c)}catch(e){TY.warning("arguments for method ".concat(o,".").concat(String(i)," not serializable for apiInvoke.")),c=[]}let d=(e.report||T$).reportApiInvoke(this._sessionId||null,{id:this._clientId||(null==(t=this.store)?void 0:t.clientId)||this._ID,name:"".concat(o,".").concat(String(i)),options:c,tag:S5.TRACER,reportResult:e.reportResult},e.throttleTime);try{let t=n.apply(this,a);return t instanceof dQ?t.then(t=>(d.onSuccess(e.reportResult&&t),t)).catch(e=>{throw d.onError(e),e}):(d.onSuccess(e.reportResult&&t),t)}catch(e){throw d.onError(e),e}}}return r}}let T$=new class{getBaseInfoBySessionId(e){return this.baseInfoMap.get(e)}setAppId(e){this._appId=e,this._aid=parseInt(e.replace(/[a-fA-F0-9]{8}/g,e=>{let[t,i]=e;return t+i}),16)||0}reportApiInvoke(e,t,i){t.timeout=t.timeout||6e4,t.reportResult=void 0===t.reportResult||t.reportResult;let r=Date.now();this.apiInvokeCount+=1;let n=this.apiInvokeCount,o=!!TR("SHOW_REPORT_INVOKER_LOG"),a=!!TR("SHOW_REPORT_USER_INVOKER_LOG"),s=o||a&&t.id;s&&(this.apiInvokeLoggedCount+=1);let c=this.apiInvokeLoggedCount;function d(e,i){if(s){let r="[apiInvoke-".concat(c,"]");if(t.id&&(r+="[".concat(t.id,"]")),t.name&&(r+="[".concat(t.name,"]"),t.name===S3.JOIN))return TY.info("".concat(r," ").concat(e));TY.info("".concat(r," ").concat(e),"start"===e?t.options:i||"")}}let l=()=>({tag:t.tag,invokeId:n,sid:e,name:t.name,apiInvokeTime:r,options:t.options,states:t.states||null});d("start");let h=!1;gO(t.timeout).then(()=>{h||(this.sendApiInvoke(TU(TU({},l()),{},{error:SU.API_INVOKE_TIMEOUT,success:!1})),d("timeout"))});let u=new Sx(SU.UNEXPECTED_ERROR,"".concat(t.name,": this api invoke is end"));return{onSuccess:e=>{let r=()=>{if(h)throw u;return h=!0,this.sendApiInvoke(TU(TU({},l()),{},{success:!0},t.reportResult&&{result:e})),d("onSuccess"),e};return i?gL(r,t.name+"Success",i,()=>h=!0):r()},onError:e=>{let r=()=>{if(h)throw e;h=!0,this.sendApiInvoke(TU(TU({},l()),{},{success:!1,error:e})),d("onFailure",e.toString())};return i?gL(r,t.name+"Error",i,()=>h=!0):r()}}}_send(e,t,i){this.send({type:e,data:t},i)}_sendApiInvoke(e){return this.sendApiInvoke(e)}sessionInit(e,t){var i;if(this.baseInfoMap.has(e))return;let r=Date.now(),n=this.createBaseInfo(e,r);n.cname=t.cname,n.rteUrl=t.rteUrl;let o=Object.assign({},{willUploadConsoleLog:TR("UPLOAD_LOG"),maxTouchPoints:navigator.maxTouchPoints,areaVersion:Tu?"global":"oversea",areas:TR("AREAS")&&TR("AREAS").join(",")},t.extend),{stringUid:a,channelProfile:s,channelMode:c,isABTestSuccess:d,lsid:l,clientRole:h}=t,u=Date.now(),p=TU(TU({},n),{},{eventType:TX.SESSION_INIT,appid:t.appid,browser:navigator.userAgent,buildFormat:t.buildFormat,build:Tf,lts:u,elapse:u-r,extend:JSON.stringify(o),mode:t.mode,process:TR("PROCESS_ID"),appType:TR("APP_TYPE"),success:!0,version:Th,stringUid:a,channelProfile:s,channelMode:c,isABTestSuccess:d,lsid:l,clientType:o5(i=window.navigator.userAgent).call(i,"AgoraWebView")?42:20,clientRole:h,serviceId:TR("PROCESS_ID"),extensionID:TR("PLUGIN_INFO").join(",")||"",rteUrl:t.rteUrl,rteSid:t.rteSid});this.send({type:TJ.SESSION,data:p},!0)}reportRteDetail(e){let t=this.baseInfoMap.get(e);if(!t)return;let i=t.info,r=Date.now(),n=TU(TU({},i),{},{eventType:TX.RTE_DETAIL,lts:r,success:!0,elapse:r-t.startTime,vid:void 0===i.vid?0:Number(i.vid),ua:navigator.userAgent});this.send({type:TJ.RTE_DETAIL,data:n},!0)}joinChooseServer(e,t){let i=this.baseInfoMap.get(e);if(!i)return;let r=i.info;t.vid&&(r.vid=t.vid);let n=Date.now(),o=TU(TU({},r),{},{role:t.role,eventType:TX.JOIN_CHOOSE_SERVER,lts:n,eventElapse:t.elapse||n-t.lts,chooseServerAddr:t.csAddr,errorCode:t.ec,elapse:n-i.startTime,success:t.succ,chooseServerAddrList:JSON.stringify(t.serverList),uid:t.uid?parseInt(t.uid):null,cid:t.cid?parseInt(t.cid):null,chooseServerIp:t.csIp||"",opid:t.opid,unilbsServerIds:t.unilbsServerIds,extend:t.extend||void 0,isHttp3:t.isHttp3,corssRegionTagReq:t.corssRegionTagReq||void 0,corssRegionTagRes:t.corssRegionTagRes||void 0,ua:navigator.userAgent,resourceTimingInfo:t.resourceTimingInfo||void 0});this.send({type:TJ.JOIN_CHOOSE_SERVER,data:o},!0)}reqUserAccount(e,t){let i=this.baseInfoMap.get(e);if(!i)return;let r=i.info,n=Date.now(),o=TU(TU({},r),{},{eventType:TX.REQ_USER_ACCOUNT,lts:n,success:t.success,serverAddress:t.serverAddr,stringUid:t.stringUid,uid:t.uid,errorCode:t.errorCode,elapse:t.elapse||n-i.startTime,eventElapse:n-t.lts,extend:JSON.stringify(t.extend)});this.send({type:TJ.REQ_USER_ACCOUNT,data:o},!0)}joinGateway(e,t){let i=this.baseInfoMap.get(e);if(!i)return;let r=i.info;t.vid&&(r.vid=t.vid),r.uid=t.uid,r.cid=t.cid;let n=Date.now(),{firstSuccess:o,addr:a,isProxy:s}=t,c=n-i.startTime,d=TU(TU({},r),{},{eventType:TX.JOIN_GATEWAY,lts:n,gatewayAddr:t.addr,success:t.succ,errorCode:t.ec,errorMsg:t.errorMsg||"",elapse:c,eventElapse:n-t.lts,firstSuccess:o,signalChannel:t.signalChannel,preload:+!!t.preload,installId:Tl(),isABTestSuccess:+!!t.isABTestSuccess,gatewayIp:null,gatewayPort:null,isProxy:+!!s}),l=+!!d.success;if(t.succ&&(i.lastJoinSuccessTime=n),a)if("1"===d.signalChannel){let e=TV(/(\d+\.\d+\.\d+\.\d+):(\d+)/,{ip:1,port:2}),t=a.match(e);d.gatewayIp=t&&t.groups?t.groups.ip:"",d.gatewayPort=t&&t.groups?t.groups.port:""}else if(s){let e=a.match(/h=(\d{1,3}-){3}\d{1,3}/g),t=a.match(/p=[0-9]{1,6}/g);d.gatewayIp=e&&e.length?e[0].split("=")[1].replace(/-/g,"."):"",d.gatewayPort=t&&t.length?t[0].split("=")[1]:""}else{let e=a.match(/wss:\/\/(\d{1,3}-){3}\d{1,3}/g),t=a.match(/(:|p=)[0-9]{1,6}/g);d.gatewayIp=e&&e.length?e[0].split("//")[1].replace(/-/g,"."):"",d.gatewayPort=t&&t.length?t[0].split(/:|p=/g)[1]:""}if(o)this.send({type:TJ.JOIN_GATEWAY,data:d},!0);else{let e={isSuccess:l,port:d.gatewayPort};delete d.success,delete d.eventType,delete d.firstSuccess,delete d.gatewayPort,d.vid=Number(d.vid);let t=Object.assign({},d,e,{eventType:TX.REJOIN_GATEWAY});this.send({type:TJ.RE_JOIN_GATEWAY,data:t},!0)}}joinChannelTimeout(e,t){let i=this.baseInfoMap.get(e);if(!i)return;let r=Date.now(),n=TU(TU({},i.info),{},{lts:r,timeout:t,elapse:r-i.startTime});this.send({type:TJ.JOIN_CHANNEL_TIMEOUT,data:n},!0)}publish(e,t){let i=this.baseInfoMap.get(e);if(!i)return;let r=i.info,n=Date.now(),o=TU(TU({},r),{},{eventType:TX.PUBLISH,lts:n,eventElapse:t.eventElapse,elapse:n-i.startTime,success:t.succ,errorCode:t.ec,videoName:t.videoName,audioName:t.audioName,screenName:t.screenName,screenshare:t.screenshare,audio:t.audio,video:t.video,p2pid:t.p2pid,publishRequestid:t.publishRequestid});this.send({type:TJ.PUBLISH,data:o},!0)}subscribe(e,t,i){let r=this.baseInfoMap.get(e);if(!r)return;let n=r.info,o=Date.now(),a=TU(TU({},n),{},{eventType:TX.SUBSCRIBE,lts:o,eventElapse:t.eventElapse,elapse:o-r.startTime,success:t.succ,errorCode:t.ec,video:t.video,audio:t.audio,subscribeRequestid:t.subscribeRequestid,p2pid:t.p2pid,preSsrc:+!!t.preSsrc},i&&{extend:JSON.stringify({isMassSubscribe:!0})});"string"==typeof t.peerid?a.peerSuid=t.peerid:a.peer=t.peerid,this.send({type:TJ.SUBSCRIBE,data:a},!0)}wsCompressorInit(e){var t;let i=[...TL(t=this.baseInfoMap).call(t)],r=i.length?i[0]:"UnableToGetSid",n=this.baseInfoMap.get(r);if(!n)return;let o=n.info,a=Date.now(),s=TU(TU({},o),{},{eventType:TX.WS_COMPRESSOR_INIT,lts:a,eventElapse:e.eventElapse,elapse:a-n.startTime,status:e.status?1:2});this.send({type:TJ.WS_COMPRESSOR_INIT,data:s},!0)}firstXLAPeerFirstVideoFrame(e,t){let i=this.baseInfoMap.get(e);if(!i)return;let r=i.info,n=Date.now(),o=t.peerPubStatusMs-(i.lastJoinSuccessTime||n),a=TU(TU({},r),{},{elapse:n-i.startTime,eventType:TX.XLA_PEER_FIRST_VIDEO_FRAME,lts:n,peer:t.peer,width:t.width,height:t.height,ssrc:t.ssrc,p2pid:t.p2pid,peerPublishDuration:t.peerPublishDuration,joinChannelSuccessElapse:o,peerPubStatusMs:t.peerPubStatusMs-t.joinChannelStart,availablePublish:+(t.peerPublishDuration>o),preloadStart:Math.max(t.preloadStart-t.joinChannelStart,0),preloadEnd:Math.max(t.preloadEnd-t.joinChannelStart,0),encrypt:Math.max(t.a
1pStart-t.joinChannelStart,0),ap:Math.max(t.apEnd-t.joinChannelStart,0),sua:Math.max(t.suaEnd-t.joinChannelStart,0),beforeConnect:Math.max(t.beforeConnect-t.joinChannelStart,0),peerRecevier:Math.max(t.peerReceiver-t.joinChannelStart,0),ice:Math.max(t.ice-t.joinChannelStart,0),pc:Math.max(t.pc-t.joinChannelStart,0),signalConnected:Math.max(t.signalConnected-t.joinChannelStart,0),joinReq:Math.max(t.joinReq-t.joinChannelStart,0),joinRes:Math.max(t.joinRes-t.joinChannelStart,0),userJoinNotify:Math.max(t.userJoinNotify-t.joinChannelStart,0),videoSsrcNotify:Math.max(t.videoAddNotify-t.joinChannelStart,0),subscribeDelayMs:Math.max(t.subscribeStart-t.videoAddNotify,0),subscribeStart:Math.max(t.subscribeStart-t.joinChannelStart,0),subscribeEnd:Math.max(t.subscribeEnd-t.joinChannelStart,0),firstReceived:Math.max(t.firstReceived-t.joinChannelStart,0),firstDecoded:Math.max(t.firstDecoded-t.joinChannelStart,0),firstPreRender:Math.max(t.firstPreRender-t.joinChannelStart,0),firstRender:Math.max(t.firstRender-t.joinChannelStart,0),playDelayMs:Math.max(t.playStart-t.subscribeEnd,0),playStart:Math.max(t.playStart-t.joinChannelStart,0),playEnd:Math.max(t.playEnd-t.joinChannelStart,0),isPreSub:+!!t.isPreSub,isPrePc:+!!t.isPrePc,isPreInstantVideo:+!!t.isPreInstantVideo,firstReceivedEncodedFrame:t.firstReceivedEncodedFrame?Math.max(t.firstReceivedEncodedFrame-t.joinChannelStart,0):void 0,frameType:t.frameType||"",rtpTimestamp:t.rtpTimestamp||0,framePayloadType:t.framePayloadType||0,frameDataLength:t.frameDataLength||0,mimeType:t.mimeType||""});this.send({type:TJ.XLA_PEER_FIRST_VIDEO_FRAME,data:a},!0)}firstRemoteVideoDecode(e,t,i,r){let n=this.baseInfoMap.get(e);if(!n)return;let o=n.info,a=Date.now(),s=TU(TU(TU({},o),r),{},{elapse:a-n.startTime,eventType:t,lts:a,firstDecodeFrame:Math.max((r.firstFrame||a)-n.startTime,0),apEnd:Math.max(r.apEnd-n.startTime,0),apStart:Math.max(r.apStart-n.startTime,0),joinGwEnd:Math.max(r.joinGwEnd-n.startTime,0),joinGwStart:Math.max(r.joinGwStart-n.startTime,0),pcEnd:Math.max(r.pcEnd-n.startTime,0),pcStart:Math.max(r.pcStart-n.startTime,0),subscriberEnd:Math.max(r.subscriberEnd-n.startTime,0),subscriberStart:Math.max(r.subscriberStart-n.startTime,0),videoAddNotify:Math.max(r.videoAddNotify-n.startTime,0)});this.send({type:i,data:s},!0)}firstRemoteFrame(e,t,i,r){let n=this.baseInfoMap.get(e);if(!n)return;let o=n.info,a=Date.now(),s=TU(TU(TU({},o),r),{},{elapse:a-n.startTime,eventType:t,lts:a});this.send({type:i,data:s},!0)}abTest(e,t){let i=this.baseInfoMap.get(e);if(!i)return;let r=i.info,n=Date.now(),o=TU(TU(TU({},r),t),{},{vid:void 0===r.vid?0:Number(r.vid),elapse:n-i.startTime,eventType:TX.AB_TEST,lts:n});this.send({type:TJ.AB_TEST,data:o},!0)}pcStats(e,t){let i=this.baseInfoMap.get(e);if(!i)return;let r=i.info,n=Date.now(),o=TU(TU(TU({},r),t),{},{vid:void 0===r.vid?0:Number(r.vid),elapse:n-i.startTime,eventType:TX.PC_STATS,lts:n,preallocation:+!!t.preallocation});this.send({type:TJ.PC_STATS,data:o},!0)}updateRemoteRTPCapabilities(e,t){if(e){let i=this.baseInfoMap.get(e);if(!i)return;let r=i.info,n=Date.now(),o=TU(TU(TU({},r),t),{},{vid:void 0===r.vid?0:Number(r.vid),eventType:TX.UPDATE_REMOTE_RTPCAPABILITIES,lts:n});this.send({type:TJ.UPDATE_REMOTE_RTPCAPABILITIES,data:o},!0)}}onGatewayStream(e,t,i,r){let n=this.baseInfoMap.get(e);if(!n)return;let o=n.info,a=Date.now(),s=TU(TU(TU({},o),r),{},{eventType:t,lts:a});this.send({type:i,data:s},!0)}streamSwitch(e,t){let i=this.baseInfoMap.get(e);if(!i)return;let r=i.info,n=Date.now(),o=TU(TU({},r),{},{eventType:TX.STREAM_SWITCH,lts:n,isDual:t.isdual,elapse:n-i.startTime,success:t.succ});this.send({type:TJ.STREAM_SWITCH,data:o},!0)}requestProxyAppCenter(e,t){let i=this.baseInfoMap.get(e);if(!i)return;let r=i.info,n=Date.now(),o=TU(TU({},r),{},{eventType:TX.REQUEST_PROXY_APPCENTER,lts:n,eventElapse:n-t.lts,elapse:n-i.startTime,APAddr:t.APAddr,workerManagerList:t.workerManagerList,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:TJ.REQUEST_PROXY_APPCENTER,data:o},!0)}requestProxyWorkerManager(e,t){let i=this.baseInfoMap.get(e);if(!i)return;let r=i.info,n=Date.now(),o=TU(TU({},r),{},{eventType:TX.REQUEST_PROXY_WORKER_MANAGER,lts:n,eventElapse:n-t.lts,elapse:n-i.startTime,workerManagerAddr:t.workerManagerAddr,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:TJ.REQUEST_PROXY_WORKER_MANAGER,data:o},!0)}setProxyServer(e){this.proxyServer=e,e?TY.debug("reportProxyServerurl: ".concat(e)):TY.debug("disable reportProxyServerurl: ".concat(e))}peerPublishStatus(e,t){let i=this.baseInfoMap.get(e);if(!i)return;let r=i.info,n=Date.now(),o=TU(TU({},r),{},{subscribeElapse:t.subscribeElapse,peer:t.peer,peerPublishDuration:Math.max(t.audioPublishDuration,t.videoPublishDuration),audiotag:t.audioPublishDuration>0?1:-1,videotag:t.videoPublishDuration>0?1:-1,lts:n,elapse:n-i.startTime,joinChannelSuccessElapse:n-(i.lastJoinSuccessTime||n),peerPublishDurationVideo:t.videoPublishDuration,peerPublishDurationAudio:t.audioPublishDuration});this.send({type:TJ.PEER_PUBLISH_STATUS,data:o},!0)}workerEvent(e,t){let i=this.baseInfoMap.get(e);if(!i)return;let r=i.info,n=Date.now();(function(e,t,i){let r=e[t];if(!r||"string"!=typeof r)return[e];e[t]="";let n=gA(JSON.stringify(e)),o=0,a=[],s=0;for(let i=0;i<r.length;i++)(s+=127>=r.charCodeAt(i)?1:3)<=1300-n||(a[a.length]=SM(SM({},e),{},{[t]:r.substring(o,i)}),o=i,s=127>=r.charCodeAt(i)?1:3);return o!==r.length-1&&(a[a.length]=SM(SM({},e),{},{[t]:r.substring(o)})),a})(TU(TU(TU({},r),t),{},{elapse:n-i.startTime,lts:n,productType:"WebRTC"}
1),"payload",0).forEach(e=>this.send({type:TJ.WORKER_EVENT,data:e},!0))}apworkerEvent(e,t){let i=this.baseInfoMap.get(e);if(!i)return;let r=i.info,n=Date.now(),o=TU(TU(TU({},r),t),{},{elapse:n-i.startTime,lts:n});this.send({type:TJ.AP_WORKER_EVENT,data:o},!0)}joinWebProxyAP(e,t){let i=this.baseInfoMap.get(e);if(!i)return;let r=i.info,n=Date.now(),o=TU(TU(TU({},r),t),{},{elapse:n-i.startTime,lts:n,extend:t.extend||void 0});this.send({type:TJ.JOIN_WEB_PROXY_AP,data:o},!0)}WebSocketQuit(e,t){let i=this.baseInfoMap.get(e);if(!i)return;let r=i.info,n=Date.now(),o=TU(TU(TU({},r),t),{},{elapse:n-i.startTime,lts:n});this.send({type:TJ.WEBSOCKET_QUIT,data:o},!0)}async sendCustomReportMessage(e,t){if(this.customReportCount+=t.length,this.customReportCount>TR("CUSTOM_REPORT_LIMIT"))throw new Sx(SU.CUSTOM_REPORT_FREQUENCY_TOO_HIGH);this.customReportCounterTimer||(this.customReportCounterTimer=window.setInterval(()=>{this.customReportCount=0},5e3));let i=Date.now(),r=t.map(t=>({type:TJ.USER_ANALYTICS,data:TU(TU({sid:e},t),{},{lts:i})}));try{TR("NEW_REPORT_SERVER")?await this.postDataToStatsCollector2(r):await this.postDataToStatsCollector(r)}catch(e){throw TY.error("send custom report message failed",e.toString()),new Sx(SU.CUSTOM_REPORT_SEND_FAILED,e.message)}}sendApiInvoke(e){let t,i=TR("NOT_REPORT_EVENT");if(e.tag&&o5(i)&&o5(i).call(i,e.tag))return!1;if(null===e.sid)return this.apiInvokeUploadPendingItems.push(e),!1;let r=this.baseInfoMap.get(e.sid);if(!r)return this.apiInvokeUploadPendingItems.push(e),!1;let{cname:n,uid:o,cid:a}=r.info;if(e.lts=e.lts||Date.now(),e.error)if(e.error instanceof Sx){let{code:i,message:r}=e.error;t=i||r||e.error.toString()}else t=e.error.toString();let s={invokeId:e.invokeId,sid:e.sid,cname:n,cid:a,uid:o,lts:e.lts,success:e.success,elapse:e.lts-r.startTime,execElapse:e.lts-e.apiInvokeTime,apiName:e.name,options:e.options?JSON.stringify(e.options):void 0,execStates:e.states?JSON.stringify(e.states):void 0,execResult:e.result?JSON.stringify(e.result):void 0,errorCode:e.error?t:void 0,errorMsg:e.error?JSON.stringify(e.error):void 0};return this.send({type:TJ.API_INVOKE,data:s},!1),!0}addSid(e){this.sids.add(e)}removeSid(e){this.sids.delete(e)}appendSessionId(){let e=this.apiInvokeUploadPendingItems;if(0===e.length)return;let t=Array.from(this.sids).find(e=>null!==e);t&&e.forEach(e=>{e&&(e.sid=t,this.sendApiInvoke(Object.assign({},e)))}),e.length=0}send(e,t){if(t)return this.keyEventUploadPendingItems.push(e),void this.sendItems(this.keyEventUploadPendingItems,!0);this.normalEventUploadPendingItems.push(e),this.normalEventUploadPendingItems.length>TR("NORMAL_EVENT_QUEUE_CAPACITY")&&this.normalEventUploadPendingItems.splice(0,1),this.normalEventUploadPendingItems.length>=10&&this.sendItems(this.normalEventUploadPendingItems,!1)}doSend(){this.keyEventUploadPendingItems.length>0&&this.sendItems(this.keyEventUploadPendingItems,!0),this.normalEventUploadPendingItems.length>0&&Date.now()-this.lastSendNormalEventTime>=5e3&&this.sendItems(this.normalEventUploadPendingItems,!1)}sendItems(e,t){let i=[],r=[];for(;e.length;){let t=e.shift();i.length<20?i.push(t):r.push(t)}for(let t of(e.push(...r),[...i])){var n;-1!==this.ltsList.indexOf(t.data.lts)?(t.data.lts=this.ltsList[this.ltsList.length-1]+1,this.ltsList.push(t.data.lts)):(this.ltsList.push(t.data.lts),ll(n=this.ltsList).call(n,(e,t)=>e-t))}
1return t||(this.lastSendNormalEventTime=Date.now()),TR("ENABLE_EVENT_REPORT")&&i.length&&(TR("NEW_REPORT_SERVER")?this.postDataToStatsCollector2(i):this.postDataToStatsCollector(i)).catch(e=>{TR("EVENT_REPORT_RETRY")&&(t?this.keyEventUploadPendingItems=this.keyEventUploadPendingItems.concat(i):(this.normalEventUploadPendingItems=this.normalEventUploadPendingItems.concat(i),this.normalEventUploadPendingItems.length>TR("NORMAL_EVENT_QUEUE_CAPACITY")&&(this.normalEventUploadPendingItems.splice(0,this.normalEventUploadPendingItems.length-TR("NORMAL_EVENT_QUEUE_CAPACITY")),TY.warning("report: drop normal events"))))}),e}async postDataToStatsCollector2(e){gh.networkState===go.OFFLINE&&await dQ.race([gh.onlineWaiter,gO(2*gH.maxRetryTimeout)]);let t=e=>{let t=new Uint8Array;return e.forEach(e=>{let i,r=SQ(JSON.stringify(e.data)),n=new ArrayBuffer(5),o=(i=0,Object.entries(TJ).forEach(t=>{let[r,n]=t;n===e.type&&(i=TQ[r])}),i),a=new DataView(n);a.setUint16(0,r.byteLength,!0),a.setUint8(2,255&o),a.setUint8(3,o>>>8&255),a.setUint8(4,o>>>16&255),t=SZ(t,new Uint8Array(n)),t=SZ(t,r)}),t},i="event",r=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(TR("NEW_REPORT_SERVER_DOMAINS")[0],"&p=443&d=").concat(i):"https://".concat(TR("NEW_REPORT_SERVER_DOMAINS")[0],"/").concat(i);for(let n=0;n<2;n+=1){1===n&&(r=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(TR("NEW_REPORT_SERVER_DOMAINS")[1],"&p=443&d=").concat(i):"https://".concat(TR("NEW_REPORT_SERVER_DOMAINS")[1],"/").concat(i));try{await gQ(r,{timeout:1e4,data:t(e),headers:TU(TU({biz:"webrtc",sendts:Math.round(Date.now()/1e3),debug:"false"},this._appId&&{appid:this._appId}),{},{"Content-Type":"application/octet-stream"})},!0)}catch(e){if(1===n)throw e;continue}return}}async postDataToStatsCollector(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=(e=>{let t=e&&e.data.sid&&this.baseInfoMap.get(e.data.sid);return t&&t.info.vid&&+t.info.vid||0})(e[0]),r=i?void 0:this._aid,n={msgType:"EventMessages",sentTs:Math.round(Date.now()/1e3),payloads:e.map(e=>JSON.stringify(e)),vid:i,aid:r};gh.networkState===go.OFFLINE&&await dQ.race([gh.onlineWaiter,gO(2*gH.maxRetryTimeout)]);let o=t?"/events/proto-raws":"/events/messages",a=this.url||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(TR("EVENT_REPORT_DOMAIN"),"&p=").concat(TR("STATS_COLLECTOR_PORT"),"&d=").concat(o):"https://".concat(TR("EVENT_REPORT_DOMAIN"),":").concat(TR("STATS_COLLECTOR_PORT")).concat(o));for(let e=0;e<2;e+=1){1===e&&(a=this.backupUrl||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(TR("EVENT_REPORT_BACKUP_DOMAIN"),"&p=").concat(TR("STATS_COLLECTOR_PORT"),"&d=").concat(o):"https://".concat(TR("EVENT_REPORT_BACKUP_DOMAIN"),":").concat(TR("STATS_COLLECTOR_PORT")).concat(o)));try{t?await gZ(a,{timeout:1e4,data:n}):await gQ(a,{timeout:1e4,data:n})}catch(t){if(1===e)throw t;continue}return}}createBaseInfo(e,t){let i=Object.assign({},Tq);return i.sid=e,this.baseInfoMap.set(e,{info:i,startTime:t}),i}reportResourceTiming(e,t){let i=performance.getEntriesByName(e),r=i[i.length-1];r&&this.reportApiInvoke(t,{name:"Client.resourceTiming",options:r,tag:S5.TRACER}).onSuccess()}constructor(){Tk(this,"baseInfoMap",new Map),Tk(this,"proxyServer",void 0),Tk(this,"eventUploadTimer",void 0),Tk(this,"setSessionIdTimer",void 0),Tk(this,"url",void 0),Tk(this,"sids",new Set),Tk(this,"backupUrl",void 0),Tk(this,"_appId",void 0),Tk(this,"_aid",0),Tk(this,"keyEventUploadPendingItems",[]),Tk(this,"normalEventUploadPendingItems",[]),Tk(this,"apiInvokeUploadPendingItems",[]),Tk(this,"apiInvokeCount",0),Tk(this,"apiInvokeLoggedCount",0),Tk(this,"ltsList",[]),Tk(this,"lastSendNormalEventTime",Date.now()),Tk(this,"customReportCounterTimer",void 0),Tk(this,"customReportCount",0),Tk(this,"extApiInvoke",async e=>{for(let t of e){let e=TU(TU({},t),{},{sid:null,invokeId:++this.apiInvokeCount,tag:S5.TRACER});this.sendApiInvoke(e)}}),this.eventUploadTimer=window.setInterval(this.doSend.bind(this),TR("EVENT_REPORT_SEND_INTERVAL")),this.setSessionIdTimer=window.setInterval(this.appendSessionId.bind(this),TR("EVENT_REPORT_SEND_INTERVAL"))}};TF.on("REPORT_LOG_UPLOAD",e=>{e.networkState=gh.networkState,T$.reportApiInvoke(null,{name:"logUploadError",options:e,tag:S5.TRACER}).onSuccess("logUploadError")});let T0=class extends Sx{print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error";return super.print(e,TY)}throw(){super.throw(TY)}constructor(e){super(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",arguments.length>2?arguments[2]:void 0),Tk(this,"name","AgoraRTCException")}},T1={getDisplayMedia:!1,getStreamFromExtension:!1,supportUnifiedPlan:!1,supportMinBitrate:!1,supportSetRtpSenderParameters:!1,supportDualStream:!0,webAudioMediaStreamDest:!1,supportReplaceTrack:!1,supportWebGL:!1,webAudioWithAEC:!1,supportRequestFrame:!1,supportShareAudio:!1,supportDualStreamEncoding:!1,supportDataChannel:!1,supportPCSetConfiguration:!1,supportWebRTCEncodedTransform:!1,supportWebRTCInsertableStream:!1,supportRequestVideoFrameCallback:!1,supportWebCrypto:!1,supportSuppressLocalAudioPlayback:!1,supportRestrictOwnAudio:!1};function T2(){return"setSinkId"in HTMLAudioElement.prototype&&(!TR("RESTRICTION_SET_PLAYBACK_DEVICE")||(Sa()||Sd())&&!Sw())}function T3(){return!T1.supportUnifiedPlan||TR("CHROME_FORCE_PLAN_B")&&SN()}function T5(e){return!(Sl()||Sp(87)||T3()||!TR("ENABLE_PRE_SUB")&&(null==e||!e.autoSubscribe||TR("FORCE_DISABLE_AUTO_SUB")))}function T4(e){return TR("ENABLE_INSTANT_VIDEO")?TR("ENABLE_INSTANT_VIDEO"):!(null==e||!e.autoSubscribe||TR("FORCE_DISABLE_AUTO_SUB"))}
1function T6(){return navigator.mediaDevices&&"getSupportedConstraints"in navigator.mediaDevices}function T8(){if(T6()){let e=navigator.mediaDevices.getSupportedConstraints();return!(!("suppressLocalAudioPlayback"in e)||!e.suppressLocalAudioPlayback)}return Su(141)||SE(141)||SR(141)}function T9(){if(T6()){let e=navigator.mediaDevices.getSupportedConstraints();return!(!("restrictOwnAudio"in e)||!e.restrictOwnAudio)}return Su(141)||SE(141)||SR(125)}let T7=((z={}).IOS_15_16_INTERRUPTION_START="ios15_16-interruption-start",z.IOS_15_16_INTERRUPTION_END="ios15_16-interruption-end",z.IOS_INTERRUPTION_START="ios-interruption-start",z.IOS_INTERRUPTION_END="ios-interruption-end",z.STATE_CHANGE="state-change",z);function Re(e,t,i){return{sampleRate:e,stereo:t,bitrate:i}}function Rt(e,t,i,r,n){return{width:e,height:t,frameRate:i,bitrateMin:r,bitrateMax:n}}function Ri(e,t,i,r,n){return{width:{max:e},height:{max:t},frameRate:i,bitrateMin:r,bitrateMax:n}}function Rr(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}let Rn={"90p":Rt(160,90),"90p_1":Rt(160,90),"120p":Rt(160,120,15,30,65),"120p_1":Rt(160,120,15,30,65),"120p_3":Rt(120,120,15,30,50),"120p_4":Rt(212,120),"180p":Rt(320,180,15,30,140),"180p_1":Rt(320,180,15,30,140),"180p_3":Rt(180,180,15,30,100),"180p_4":
1Rt(240,180,15,30,120),"240p":Rt(320,240,15,40,200),"240p_1":Rt(320,240,15,40,200),"240p_3":Rt(240,240,15,40,140),"240p_4":Rt(424,240,15,40,220),"360p":Rt(640,360,15,80,400),"360p_1":Rt(640,360,15,80,400),"360p_3":Rt(360,360,15,80,260),"360p_4":Rt(640,360,30,80,600),"360p_6":Rt(360,360,30,80,400),"360p_7":Rt(480,360,15,80,320),"360p_8":Rt(480,360,30,80,490),"360p_9":Rt(640,360,15,80,800),"360p_10":Rt(640,360,24,80,800),"360p_11":Rt(640,360,24,80,1e3),"480p":Rt(640,480,15,100,500),"480p_1":Rt(640,480,15,100,500),"480p_2":Rt(640,480,30,100,1e3),"480p_3":Rt(480,480,15,100,400),"480p_4":Rt(640,480,30,100,750),"480p_6":Rt(480,480,30,100,600),"480p_8":Rt(848,480,15,100,610),"480p_9":Rt(848,480,30,100,930),"480p_10":Rt(640,480,10,100,400),"720p":Rt(1280,720,15,120,1130),"720p_auto":Rt(1280,720,30,900,3e3),"720p_1":Rt(1280,720,15,120,1130),"720p_2":Rt(1280,720,30,120,2e3),"720p_3":Rt(1280,720,30,120,1710),"720p_5":Rt(960,720,15,120,910),"720p_6":Rt(960,720,30,120,1380),"1080p":Rt(1920,1080,15,120,2080),"1080p_1":Rt(1920,1080,15,120,2080),"1080p_2":Rt(1920,1080,30,120,3e3),"1080p_3":Rt(1920,1080,30,120,3150),"1080p_5":Rt(1920,1080,60,120,4780),"1440p":Rt(2560,1440,30,120,4850),"1440p_1":Rt(2560,1440,30,120,4850),"1440p_2":Rt(2560,1440,60,120,7350),"4k":Rt(3840,2160,30,120,8910),"4k_1":Rt(3840,2160,30,120,8910),"4k_3":Rt(3840,2160,60,120,13500)},Ro={"480p":Ri(640,480,5),"480p_1":Ri(640,480,5),"480p_2":Ri(640,480,30),"480p_3":Ri(640,480,15),"720p":Ri(1280,720,5),"720p_auto":Rt(1280,720,30,900,3e3),"720p_1":Ri(1280,720,5),"720p_2":Ri(1280,720,30),"720p_3":Ri(1280,720,15),"1080p":Ri(1920,1080,5),"1080p_1":Ri(1920,1080,5),"1080p_2":Ri(1920,1080,30),"1080p_3":Ri(1920,1080,15)},Ra={"1SL1TL":Rr(1,1),"3SL3TL":Rr(3,3),"2SL3TL":Rr(2,3)};function Rs(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},Rn[e]):e}function Rc(e){return"string"==typeof e?Object.assign({},Ro[e]):e}function Rd(e){return"string"==typeof e?Object.assign({},Ra[e]):e}let Rl={speech_low_quality:Re(16e3,!1),speech_standard:Re(32e3,!1,18),music_standard:Re(48e3,!1),standard_stereo:Re(48e3,!0,56),high_quality:Re(48e3,!1,128),high_quality_stereo:Re(48e3,!0,192)};function Rh(e){return"string"==typeof e?Object.assign({},Rl[e]):e}let Ru=[];function Rp(e){return SF(e,"mediaSource",["screen","window","application"]),!0}let R_=((q={}).NEED_RENEGOTIATE="@need_renegotiate",q.NEED_REPLACE_TRACK="@need_replace_track",q.NEED_REPLACE_MIXING_TRACK="@need_replace_mixing_track",q.NEED_CLOSE="@need_close",q.NEED_ENABLE_TRACK="@need_enable_track",q.NEED_DISABLE_TRACK="@need_disable_track",q.NEED_SESSION_ID="@need_sid",q.SET_OPTIMIZATION_MODE="@set_optimization_mode",q.GET_STATS="@get_stats",q.GET_RTC_STATS="@get_rtc_stats",q.GET_LOW_VIDEO_TRACK="@get_low_video_track",q.NEED_RESET_REMOTE_SDP="@need_reset_remote_sdp",q.NEED_UPDATE_VIDEO_ENCODER="@need_update_video_encoder",q.NEED_UPDATE_VIDEO_SEND_PARAMETERS="@need_update_video_send_parameters",q.NEED_MUTE_TRACK="@need_mute_track",q.NEED_UNMUTE_TRACK="@need_unmute_track",q),RE=((X={}).SCREEN_TRACK="screen_track",X.CUSTOM_TRACK="custome_track",X.LOW_STREAM="low_stream",X.SCREEN_LOW_TRACK="screen_low_track",X),Rm=((J={})[J.HIGH_STREAM=0]="HIGH_STREAM",J[J.LOW_STREAM=1]="LOW_STREAM",J),Rf=((Q={})[Q.HIGH_STREAM=0]="HIGH_STREAM",Q[Q.LOW_STREAM=1]="LOW_STREAM",Q[Q.HIGH_STREAM_LAYER1=4]="HIGH_STREAM_LAYER1",Q[Q.HIGH_STREAM_LAYER2=5]="HIGH_STREAM_LAYER2",Q[Q.HIGH_STREAM_LAYER3=6]="HIGH_STREAM_LAYER3",Q[Q.HIGH_STREAM_LAYER4=7]="HIGH_STREAM_LAYER4",Q[Q.HIGH_STREAM_LAYER5=8]="HIGH_STREAM_LAYER5",Q[Q.HIGH_STREAM_LAYER6=9]="HIGH_STREAM_LAYER6",Q),RS=((Z={})[Z.DISABLE=0]="DISABLE",Z[Z.LOW_STREAM=1]="LOW_STREAM",Z[Z.AUDIO_ONLY=2]="AUDIO_ONLY",Z[Z.HIGH_STREAM_LAYER1=3]="HIGH_STREAM_LAYER1",Z[Z.HIGH_STREAM_LAYER2=4]="HIGH_STREAM_LAYER2",Z[Z.HIGH_STREAM_LAYER3=5]="HIGH_STREAM_LAYER3",Z[Z.HIGH_STREAM_LAYER4=6]="HIGH_STREAM_LAYER4",Z[Z.HIGH_STREAM_LAYER5=7]="HIGH_STREAM_LAYER5",Z[Z.HIGH_STREAM_LAYER6=8]="HIGH_STREAM_LAYER6",Z),Rg=(($={}).TRANSCEIVER_UPDATED="transceiver-updated",$.SEI_TO_SEND="sei-to-send",$.SEI_RECEIVED="sei-received",$.TRACK_UPDATED="track-updated",$),RT=((ee={}).SOURCE_STATE_CHANGE="source-state-change",ee.TRACK_ENDED="track-ended",ee.BEAUTY_EFFECT_OVERLOAD="beauty-effect-overload",ee.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",ee.CLOSED="closed",ee),RR=((et={}).FIRST_FRAME_DECODED="first-frame-decoded",et.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",et.VIDEO_STATE_CHANGED="video-state-changed",et.PLAY_START="play-start",et.PLAY_END="play-end",et.FIRST_FRAME_RENDER="first-frame-render",et),RC=((ei={}).AUDIO="audio",ei.VIDEO="video",ei.DATA="data",ei),Rv=((er={}).AUDIO_SOURCE_STATE_CHANGE="audio_source_state_change",er.RECEIVE_TRACK_BUFFER="receive_track_buffer",er.ON_AUDIO_BUFFER="on_audio_buffer",er.UPDATE_SOURCE="update_source",er),Ry={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},RI={sendBytes:0,sendBitrate:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,sendResolutionHeight:0,send
1ResolutionWidth:0,captureResolutionHeight:0,captureResolutionWidth:0,targetSendBitrate:0,totalDuration:0,totalFreezeTime:0,currentPacketLossRate:0},RA={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveLevel:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,receivePacketsDiscarded:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1},Rb={uplinkNetworkQuality:0,downlinkNetworkQuality:0},RO={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,receiveResolutionHeight:0,receiveResolutionWidth:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1},Rw=((en={}).ON_TRACK="on_track",en.ON_NODE="on_node",en),RN=((eo={}).REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",eo.REQUEST_CONSTRAINTS="request_constraints",eo),RD=((ea={}).IDLE="IDLE",ea.INITING="INITING",ea.INITEND="INITEND",ea),RP=((es={}).STATE_CHANGE="state_change",es.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",es.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",es.CAMERA_DEVICE_CHANGED="cameraDeviceChanged",es),RL=((ec={}).NONE="none",ec.INIT="init",ec.CANPLAY="canplay",ec.PLAYING="playing",ec.PAUSED="paused",ec.SUSPEND="suspend",ec.STALLED="stalled",ec.WAITING="waiting",ec.ERROR="error",ec.DESTROYED="destroyed",ec.ABORT="abort",ec.ENDED="ended",ec.EMPTIED="emptied",ec.LOADEDDATA="loadeddata",ec),Rk=((ed={})[ed.VideoStateStopped=0]="VideoStateStopped",ed[ed.VideoStateStarting=1]="VideoStateStarting",ed[ed.VideoStateDecoding=2]="VideoStateDecoding",ed[ed.VideoStateFrozen=3]="VideoStateFrozen",ed),RM={uninit:100,none:110,init:120,loadeddata:130,canplay:200,playing:210,paused:220,suspend:300,stalled:310,waiting:320,error:330,destroyed:340,abort:350,ended:360,emptied:370},RU=((el={}).OPEN="open",el.MESSAGE="message",el.CLOSE="close",el.CLOSING="closing",el.ERROR="error",el);function Rx(e,t,i,r,n){var o,a,s={};return Object.keys(r).forEach(function(e){s[e]=r[e]}),s.enumerable=!!s.enumerable,s.configurable=!!s.configurable,("value"in s||s.initializer)&&(s.writable=!0),s=as(o=a_(a=i.slice()).call(a)).call(o,function(i,r){return r(e,t,i)||i},s),n&&void 0!==s.initializer&&(s.value=s.initializer?s.initializer.call(n):void 0,s.initializer=void 0),void 0===s.initializer?(Object.defineProperty(e,t,s),null):s}function RV(e,t,i){var r;return(t="symbol"==typeof(r=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,"string");if("object"!=typeof r)return r;throw TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(t))?r:r+"")in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function RF(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function RB(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?RF(Object(i),!0).forEach(function(t){RV(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):RF(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}class Rj extends S0{set _mediaStreamTrack(e){e!==this.mediaStreamTrack&&(this.safeEmit(Rg.TRACK_UPDATED,e),this.mediaStreamTrack=e)}get _mediaStreamTrack(){return this.mediaStreamTrack}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){return e||gR(()=>{var e;T$.reportApiInvoke(null,{name:S3.GET_MEDIA_STREAM_TRACK,options:[],tag:S5.TRACER}).onSuccess((null==(e=this._mediaStreamTrack)?void 0:e.label)||"")},this.mediaStreamTrack.id||this.getTrackId()),this._mediaStreamTrack}getRTCRtpTransceiver(e){return e===Rm.LOW_STREAM?this._lowRtpTransceiver:this._rtpTransceiver}getMediaStreamTrackSettings(){return this.getMediaStreamTrack(!0).getSettings()}close(){this._isClosed=!0,this._lowRtpTransceiver=void 0,this._rtpTransceiver=void 0,function(e){let t=Ru.indexOf(e);-1!==t&&Ru.splice(t,1)}
1(this),this.emit(RT.CLOSED),this.removeAllListeners(Rg.SEI_RECEIVED)}_updateRtpTransceiver(e,t){if(t===Rm.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e}else{if(this._rtpTransceiver===e)return;this._rtpTransceiver=e}this.emit(Rg.TRANSCEIVER_UPDATED,e,t)}constructor(e,t){super(),RV(this,"trackMediaType",void 0),RV(this,"_ID",void 0),RV(this,"_rtpTransceiver",void 0),RV(this,"_lowRtpTransceiver",void 0),RV(this,"_hints",[]),RV(this,"_isClosed",!1),RV(this,"_originMediaStreamTrack",void 0),RV(this,"mediaStreamTrack",void 0),RV(this,"_external",{}),this._ID=t||gw(8,"track-"),this._originMediaStreamTrack=e,this.mediaStreamTrack=e,function(e){o5(Ru).call(Ru,e)||Ru.push(e)}(this)}}class RG extends Rj{get isExternalTrack(){return this._isExternalTrack}get muted(){return this._muted}get enabled(){return this._enabled}get processorContext(){return this._processorContext}getTrackLabel(){var e,t;return null!=(e=null==(t=this._originMediaStreamTrack)?void 0:t.label)?e:""}close(){this._isClosed||(this.stop(),this._originMediaStreamTrack.stop(),this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack.stop(),this._mediaStreamTrack=null),this._originMediaStreamTrack=null,this._enabledMutex=null,TY.debug("[".concat(this.getTrackId(),"] close")),this.emit(R_.NEED_CLOSE),super.close())}async _updateOriginMediaStreamTrack(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this._isExternalTrack=i,e!==this._originMediaStreamTrack&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await gc(this,R_.NEED_REPLACE_TRACK,this),this.processor&&this._processorContext&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this._processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){TY.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(RT.TRACK_ENDED)}stateCheck(e,t){if(TY.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(t,"]")),SV(t,e),this._enabled&&this._muted&&"enabled"===e&&!1===t)throw new Sx(SU.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print("error",TY);if(!this._enabled&&!this._muted&&"muted"===e&&!0===t)throw new Sx(SU.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print("error",TY)}getProcessorStats(){return this._processorContext&&this._processorContext.gatherStats()||[]}getProcessorUsage(){return this._processorContext?this._processorContext.gatherUsage():dQ.resolve([])}constructor(e,t){super(e,t),RV(this,"_enabled",!0),RV(this,"_muted",!1),RV(this,"_isExternalTrack",!1),RV(this,"_isClosed",!1),RV(this,"_enabledMutex",void 0),RV(this,"processor",void 0),RV(this,"_processorContext",void 0),RV(this,"_handleTrackEnded",()=>{this.onTrackEnded()}),this._enabledMutex=new gG("".concat(this.getTrackId())),e.addEventListener("ended",this._handleTrackEnded)}}let RW=window.AudioContext||window.webkitAudioContext,RH,RK=null,RY=new class extends S0{get duringInterruption(){return"running"===this.prevState&&"interrupted"===this.curState}bindInterruptDetectorTrack(e){TY.debug("webaudio bindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack||(this.interruptDetectorTrack=e,this.interruptDetectorTrack._mediaStreamTrack.onmute=this.onLocalAudioTrackMute,this.interruptDetectorTrack._mediaStreamTrack.onunmute=this.onLocalAudioTrackUnmute)}unbindInterruptDetectorTrack(e){TY.debug("webaudio unbindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack&&this.interruptDetectorTrack===e&&(this.interruptDetectorTrack._mediaStreamTrack&&(this.interruptDetectorTrack._mediaStreamTrack.onmute=null,this.interruptDetectorTrack._mediaStreamTrack.onunmute=null),this.interruptDetectorTrack=void 0)}constructor(){super(...arguments),RV(this,"prevState",void 0),RV(this,"cur
1State",void 0),RV(this,"currentTime",void 0),RV(this,"currentTimeStuckAt",void 0),RV(this,"interruptDetectorTrack",void 0),RV(this,"onLocalAudioTrackMute",()=>{TY.info("ios15-interruption-start"),this.emit(T7.IOS_15_16_INTERRUPTION_START)}),RV(this,"onLocalAudioTrackUnmute",async()=>{TY.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?TY.info("ios15-interruption-end-canceled"):(RK&&await RK.suspend(),this.emit(T7.IOS_15_16_INTERRUPTION_END))})}};function Rz(){if(!RK&&(function(){if(!RW)return TY.error("your browser is not support web audio");TY.info("create audio context");let e=RB({},TR("WEBAUDIO_INIT_OPTIONS"));TY.debug("audio context init option:",JSON.stringify(e)),RY.curState=(RK=new RW(e)).state,RK.onstatechange=()=>{RY.prevState=RY.curState,RY.curState=RK?RK.state:void 0;let{prevState:e,curState:t}=RY,i="running"===t,r="interrupted"===t,n="running"===e,o="suspended"===e,a="interrupted"===e,s=St().osVersion;(Sh()||SA())&&n&&r&&(TY.info("ios".concat(s,"-interruption-start")),RY.emit(T7.IOS_INTERRUPTION_START)),(Sh()||SA())&&(o||a)&&i&&(TY.info("ios".concat(s,"-interruption-end")),RY.emit(T7.IOS_INTERRUPTION_END)),e!==t&&RY.emit(T7.STATE_CHANGE,t,e)},setInterval(()=>{var e;let t=null==(e=RK)?void 0:e.currentTime;RY.currentTime!==t?(RY.currentTimeStuckAt&&(TY.debug("AudioContext current time resume at ".concat(t)),RY.currentTimeStuckAt=void 0),RY.currentTime=t):(t!==RY.currentTimeStuckAt&&(T$.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:t},tag:S5.TRACER}).onSuccess(),TY.warning("AudioContext current time stuck at ".concat(t))),RY.currentTimeStuckAt=t)},5e3),(async function(e){let t=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","touchend","keydown","keyup"],i,r,n=!1,o=!1,a=!1;function s(t){"running"===e.state?c(!1):Sh()||SA()?"suspended"===e.state&&(c(!0),t&&e.resume().then(d,d)):"closed"!==e.state&&(c(!0),t&&e.resume().then(d,d))}function c(e){if(n!==e){n=e;for(let i=0;i<t.length;i+=1){let r=t[i];e?window.addEventListener(r,l,{capture:!0,passive:!0}):window.removeEventListener(r,l,{capture:!0,passive:!0})}}}function d(){s(!1)}function l(){s(!0)}function h(){let e;try{(e=i.play())?e.then(_,_):(i.addEventListener("playing",_),i.addEventListener("abort",_),i.addEventListener("error",_))}catch(e){_()}}function u(e){a||(i.paused?e?(p(!1),a=!0,h()):p(!0):p(!1))}function p(e){if(o!==e){o=e;for(let i=0;i<t.length;i++){let r=t[i];e?window.addEventListener(r,E,{capture:!0,passive:!0}):window.removeEventListener(r,E,{capture:!0,passive:!0})}}}function _(){i.removeEventListener("playing",_),i.removeEventListener("abort",_),i.removeEventListener("error",_),a=!1,u(!1)}function E(){u(!0)}if(Sh()&&TR("IOS_BG_TAG")){let t=e.createMediaStreamDestination(),n=document.createElement("div");n.innerHTML="<audio x-webkit-airplay='deny'></audio>",(i=n.children.item(0)).controls=!1,i.disableRemotePlayback=!0,i.preload="auto",i.srcObject=t.stream,r=()=>{if(TR("IOS_AUTO_RESTART_BG_TAG")&&i&&i.srcObject&&!a&&(!i.paused||!0!==o)){i.paused||i.pause();try{a=!0,h()}catch(e){a=!1}return!0}},u(!0)}return RY.on(T7.STATE_CHANGE,function(){s(!0)}),s(!1),r})(RK).then(e=>{RH=e})}(),!RK))throw new Sx(SU.NOT_SUPPORTED,"can not create audio context");return RK}function Rq(e){if(function(){if(null!==RX)return RX;let e=Rz(),t=e.createBufferSource(),i=e.createGain(),r=e.createGain();t.connect(i),t.connect(r),t.disconnect(i);let n=!1;try{t.disconnect(i)}catch(e){n=!0}return t.disconnect(),RX=n,n}())return;let t=e.connect,i=e.disconnect;e.connect=(i,r,n)=>{var o;return e._inputNodes||(e._inputNodes=[]),o5(o=e._inputNodes).call(o,i)||(i instanceof AudioNode?(e._inputNodes.push(i),t.call(e,i,r,n)):t.call(e,i,r)),e},e.disconnect=(r,n,o)=>{for(let n of(i.call(e),r?gE(e._inputNodes,r):e._inputNodes=[],e._inputNodes))t.call(e,n)}}let RX=null;function RJ(e,t){let i=!1,r=1/t;if(TR("DISABLE_WEBAUDIO")){let t=window.setInterval(()=>{i?window.clearInterval(t):e(performance.now()/1e3)},1e3*r)}else{let t=Rz(),n=t.createGain();n.gain.value=0,n.connect(t.destination);let o=()=>{if(i)return void(n=null);let a=t.createOscillator();a.onended=o,a.connect(n),a.start(0),a.stop(t.currentTime+r),e(t.currentTime)};o()}return()=>{i=!0}}class RQ{updateSource(e){if(e!==this.sourceNode){if(this.sourceNode)try{this.sourceNode.disconnect(this.analyserNode)}catch(e){}this.sourceNode=e,null==e||e.connect(this.analyserNode)}}getVolumeLevel(){if(!this.sourceNode||(!this.context||Sh()||SA()||"running"!==this.context.state&&this.context.resume(),!this.analyserNode))return 0;let e=new Float32Array(this.analyserNode.fftSize);
1if(this.analyserNode.getFloatTimeDomainData)this.analyserNode.getFloatTimeDomainData(e);else{let t=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(t);for(let i=0;i<e.length;++i)e[i]=t[i]/128-1}return Math.max(10*Math.log10(as(e).call(e,(e,t)=>e+t*t,0)/e.length)+100,0)/100}getAnalyserNode(){return this.analyserNode}rebuildAnalyser(){try{var e,t;null==(e=this.sourceNode)||e.disconnect(this.analyserNode),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4,null==(t=this.sourceNode)||t.connect(this.analyserNode)}catch(e){TY.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}constructor(){RV(this,"context",void 0),RV(this,"analyserNode",void 0),RV(this,"sourceNode",void 0),this.context=Rz(),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4}}class RZ extends S0{get processSourceNode(){return this.sourceNode}set processedNode(e){var t,i;if(!this.isDestroyed&&this._processedNode!==e){try{null==(i=this.sourceNode)||i.disconnect(this.outputNode)}catch(e){}null==(t=this._processedNode)||t.disconnect(),this._processedNode=e,this.connect()}}get processedNode(){return this._processedNode}startGetAudioBuffer(e){this.audioBufferNode||(this.audioBufferNode=this.context.createScriptProcessor(e),this.outputNode.connect(this.audioBufferNode),this.audioBufferNode.connect(this.context.destination),this.audioBufferNode.onaudioprocess=e=>{this.emit(Rv.ON_AUDIO_BUFFER,function(e){for(let t=0;t<e.outputBuffer.numberOfChannels;t+=1){let i=e.outputBuffer.getChannelData(t);for(let e=0;e<i.length;e+=1)i[e]=0}return e.inputBuffer}(e))})}stopGetAudioBuffer(){this.audioBufferNode&&(this.audioBufferNode.onaudioprocess=null,this.outputNode.disconnect(this.audioBufferNode),this.audioBufferNode=void 0)}createOutputTrack(){if(!T1.webAudioMediaStreamDest)throw new Sx(SU.NOT_SUPPORTED,"your browser is not support audio processor");return this.destNode&&this.outputTrack||(this.destNode=this.context.createMediaStreamDestination(),this.outputNode.connect(this.destNode),this.outputTrack=this.destNode.stream.getAudioTracks()[0]),this.outputTrack}play(e){"running"!==this.context.state&&gf(()=>{RY.emit("autoplay-failed")}),this.isPlayed=!0,this.playNode=e||this.context.destination,this.outputNode.connect(this.playNode)}stop(){if(this.isPlayed)try{this.outputNode.disconnect(this.playNode)}catch(e){}this.isPlayed=!1}getAccurateVolumeLevel(){return this.volumeLevelAnalyser.getVolumeLevel()}async checkHasAudioInput(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if(t>5)return this.isNoAudioInput=!0,this.onNoAudioInput&&this.onNoAudioInput(),!1;Sh()||SA()?"suspended"===this.context.state&&this.context.resume():"running"!==this.context.state&&this.context.resume();let i=this.volumeLevelAnalyser.getAnalyserNode();i.getFloatTimeDomainData?(e=new Float32Array(i.fftSize),i.getFloatTimeDomainData(e)):(e=new Uint8Array(i.fftSize),i.getByteTimeDomainData(e));let r=!1;for(let t=0;t<e.length;t++)0!==e[t]&&(r=!0);return r?(this.isNoAudioInput=!1,!0):(await gO(200),await this.checkHasAudioInput(t?t+1:1)&&r)}getAudioVolume(){return this.outputNode.gain.value}setVolume(e){this.outputNode.gain.setValueAtTime(e,this.context.currentTime)}destroy(){this.disconnect(),this.stop(),this.isDestroyed=!0,this.onNoAudioInput=void 0}disconnect(){var e,t;null==(e=this.processedNode)||e.disconnect(),null==(t=this.sourceNode)||t.disconnect(),this.outputNode&&this.outputNode.disconnect()}connect(){var e;this.processedNode?null==(e=this.processedNode)||e.connect(this.outputNode):this.sourceNode&&this.sourceNode.connect(this.outputNode),this.volumeLevelAnalyser.updateSource(this.outputNode)}constructor(){super(),RV(this,"outputNode",void 0),RV(this,"outputTrack",void 0),RV(this,"isPlayed",!1),RV(this,"sourceNode",void 0),RV(this,"context",void 0),RV(this,"audioBufferNode",void 0),RV(this,"destNode",void 0),RV(this,"audioOutputLevel",0),RV(this,"volumeLevelAnalyser",void 0),RV(this,"_processedNode",void 0),RV(this,"playNode",void 0),RV(this,"isDestroyed",!1),RV(this,"onNoAudioInput",void 0),RV(this,"isNoAudioInput",!1),RV(this,"_noAudioInputCount",0),this.context=Rz(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),Rq(this.outputNode),this.volumeLevelAnalyser=new RQ}}class R$ extends RZ{get isFreeze(){return!1}updateTrack(e){this.sourceNode.disconnect(),this.track=e,this.isCurrentTrackCloned=!1;let t=new MediaStream([e]);this.sourceNode=this.context.createMediaStreamSource(t),Rq(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit
1(Rv.UPDATE_SOURCE),this.audioElement.srcObject=t}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),RY.off("state-change",this.rebuildWebAudio),null==(e=this.originVolumeLevelAnalyser)||e.destroy(),this.clonedTrack=void 0,super.destroy()}createMediaStreamSourceNode(e){return this.context.createMediaStreamSource(new MediaStream([e]))}updateOriginTrack(e){let t=e.clone();t.enabled=!0,this.clonedTrack&&(this.clonedTrack.stop(),this.clonedTrack=t),TY.debug("create an unmuted track ".concat(t.id," from the original track ").concat(e.id," to get the volume"));let i=this.context.createMediaStreamSource(new MediaStream([t]));Rq(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}constructor(e,t,i){var r;if(super(),RV(this,"sourceNode",void 0),RV(this,"track",void 0),RV(this,"clonedTrack",void 0),RV(this,"audioElement",void 0),RV(this,"isCurrentTrackCloned",!1),RV(this,"isRemoteTrack",!1),RV(this,"originVolumeLevelAnalyser",void 0),RV(this,"rebuildWebAudio",async()=>{if(TY.debug("ready to rebuild web audio, state:",this.context.state),this.isNoAudioInput&&await this.checkHasAudioInput(),!this.isNoAudioInput||this.isDestroyed)return document.body.removeEventListener("click",this.rebuildWebAudio,!0),void TY.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then(()=>TY.info("resume success")),TY.debug("rebuild web audio because of ios 12 bugs"),this.disconnect();let e=this.track;this.track=this.track.clone(),this.isCurrentTrackCloned?e.stop():this.isCurrentTrackCloned=!0;let t=new MediaStream([this.track]);this.sourceNode=this.context.createMediaStreamSource(t),Rq(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();let i=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(i,this.context.currentTime),Rq(this.outputNode),this.emit(Rv.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()}),"audio"!==e.kind)throw new Sx(SU.UNEXPECTED_ERROR);this.track=e;let n=new MediaStream([this.track]);if(this.isRemoteTrack=!!t,this.sourceNode=this.context.createMediaStreamSource(n),Rq(this.sourceNode),i){let e=i.clone();e.enabled=!0,this.clonedTrack=e,TY.debug("create an unmuted track ".concat(e.id," from the original track ").concat(i.id," to get the volume"));let t=this.context.createMediaStreamSource(new MediaStream([e]));Rq(t),this.originVolumeLevelAnalyser=new RQ,this.originVolumeLevelAnalyser.updateSource(t)}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=n;let o=St();t&&o.os===f6.IOS&&15>Number(null==(r=o.osVersion)?void 0:r.split(".")[0])&&(RY.on(T7.STATE_CHANGE,()=>{"suspended"===this.context.state?document.body.addEventListener("click",this.rebuildWebAudio,!0):"running"===this.context.state&&this.rebuildWebAudio()}),this.checkHasAudioInput().then(e=>{e||document.body.addEventListener("click",this.rebuildWebAudio,!0)}))}}async function R0(e,t,i){let r=(e,t)=>e?"number"!=typeof e?e.max||e.exact||e.ideal||e.min||t:e:t,n={audio:!!i&&{mandatory:{chromeMediaSource:"desktop"}},video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e,maxHeight:r(t.height,1080),maxWidth:r(t.width,1920)}}};return t.frameRate&&"number"!=typeof t.frameRate?(n.video.mandatory.maxFrameRate=t.frameRate.max,n.video.mandatory.minFrameRate=t.frameRate.min):"number"==typeof t.frameRate&&(n.video.mandatory.maxFrameRate=t.frameRate),await navigator.mediaDevices.getUserMedia(n)}async function R1(e,t){let i=await R2(e.mediaSource),{sourceId:r,audio:n}=await function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new dQ((i,r)=>{let n=document.createElement("div");n.innerText="share screen",n.setAttribute("style","text-align: center; height: 25px; line-height: 25px; border-radius: 4px 4px 0 0; background: #D4D2D4; border-bottom: solid 1px #B9B8B9;");let o=document.createElement("div");o.setAttribute("style","width: 100%; height: 500px; padding: 15px 25px ; box-sizing: border-box;");let a=document.createElement("div");a.innerText="Agora Web Screensharing wants to share the contents of your screen with webdemo.agorabeckon.com. Choose what you'd like to share.",a.setAttribute("style","height: 12%;");let s=document.createElement("div");s.setAttribute("style","width: 100%; height: 80%; background: #FFF; border: solid 1px #CBCBCB; display: flex; flex-wrap: wrap; justify-content: space-around;
1 overflow-y: scroll; padding: 0 15px; box-sizing: border-box;");let c=document.createElement("div");c.setAttribute("style","display: flex; justify-content: space-between; padding: 16px 0;");let d=document.createElement("button");d.innerHTML="cancel",d.setAttribute("style","width: 85px;"),d.onclick=()=>{document.body.removeChild(u);let e=Error("NotAllowedError");e.name="NotAllowedError",r(e)};let l=t,h=document.createElement("div");if(t){let e=document.createElement("input");e.setAttribute("type","checkbox");let t=document.createElement("span");e.setAttribute("style","margin-right: 6px;"),t.innerText="Share audio",e.checked=l,e.onchange=()=>{l=e.checked},h.appendChild(e),h.appendChild(t)}c.appendChild(h),c.appendChild(d),o.appendChild(a),o.appendChild(s),o.appendChild(c);let u=document.createElement("div");u.setAttribute("style","position: fixed; z-index: 99999999; top: 50%; left: 50%; width: 620px; height: 525px; background: #ECECEC; border-radius: 4px; -webkit-transform: translate(-50%,-50%); transform: translate(-50%,-50%);"),u.appendChild(n),u.appendChild(o),document.body.appendChild(u),e.map(e=>{if(e.id){let t=document.createElement("div");t.setAttribute("style","width: 30%; height: 160px; padding: 20px 0; text-align: center;box-sizing: content-box;");let r=e.thumbnail;try{let{width:e}=r.getSize();e>1920&&(r=r.resize({width:1920}))}catch(e){throw e&&e.message.startsWith("Illegal invocation")&&console.error("Operate thumbnail error, please try to set contextIsolation: false. (https://github.com/electron/electron/issues/34953)"),e}t.innerHTML='<div style="height: 120px; display: table-cell; vertical-align: middle;"><img style="width: 100%; background: #333333; box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.2);" src='+r.toDataURL()+' /></div><span style=" height: 40px; line-height: 40px; display: inline-block; width: 70%; word-break: keep-all; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">'+e.name.replace(/[\u00A0-\u9999<>\&]/g,function(e){return"&#"+e.charCodeAt(0)+";"})+"</span>",t.onclick=()=>{document.body.removeChild(u),i({sourceId:e.id,audio:l})},s.appendChild(t)}})})}(i,t);return await R0(r,e,n)}
1async function R2(e){let t=["window","screen"];"application"!==e&&"window"!==e||(t=["window"]),"screen"===e&&(t=["screen"]);let i=S2();if(!i)throw console.error("failed to fetch electron, please mount it to window"),new Sx(SU.ELECTRON_IS_NULL);let r=null;try{var n;r=(null==(n=i.desktopCapturer)?void 0:n.getSources({types:t}))||i.ipcRenderer.invoke("DESKTOP_CAPTURER_GET_SOURCES",{types:t})}catch(e){r=null}r&&r.then||(r=new dQ((e,r)=>{i.desktopCapturer.getSources({types:t},(t,i)=>{t?r(t):e(i)})}));try{return await r}catch(e){throw new Sx(SU.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}let R3=new gG("safari"),R5=!1,R4=!1;async function R6(e,t){let i=0,r=null;for(;i<2;)try{r=await R8(e,t,i>0);break}catch(r){if(r instanceof Sx)throw TY.error("[".concat(t,"] ").concat(r.toString())),r;let e=R9(r.name||r.code||r,r.message);if(e.code===SU.MEDIA_OPTION_INVALID){TY.debug("[".concat(t,"] detect media option invalid, retry")),i+=1,await gO(500);continue}throw TY.error("[".concat(t,"] ").concat(e.toString())),e}if(!r)throw new Sx(SU.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return r}async function R8(e,t,i){var r,n;if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Sx(SU.NOT_SUPPORTED,"can not find getUserMedia");i&&(e.video&&(delete e.video.width,delete e.video.height),e.screen&&(delete e.screen.width,delete e.screen.height));let o=new MediaStream;if(e.audioSource&&o.addTrack(e.audioSource),e.videoSource&&o.addTrack(e.videoSource),!e.audio&&!e.video&&!e.screen)return TY.debug("Using Video Source/ Audio Source"),o;if(e.screen)if(S2())e.screen.sourceId?R7(o,await R0(e.screen.sourceId,e.screen,!!e.screenAudio)):R7(o,await R1(e.screen,!!e.screenAudio));else if(Sa()&&e.screen.extensionId&&e.screen.mandatory){if(!T1.getStreamFromExtension)throw new Sx(SU.NOT_SUPPORTED,"This browser does not support screen sharing");TY.debug("[".concat(t,'] Screen access on chrome stable, looking for extension"'));let i=await (n=e.screen.extensionId,new dQ((e,i)=>{try{chrome.runtime.sendMessage(n,{getStream:!0},r=>{if(!r||!r.streamId)return TY.error("[".concat(t,"] No response from Chrome Plugin. Plugin not installed properly"),r),void i(new Sx(SU.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));e(r.streamId)})}catch(e){TY.error("[".concat(t,"] AgoraRTC screensharing plugin is not accessible(").concat(n,")"),e.toString()),i(new Sx(SU.CHROME_PLUGIN_NOT_INSTALL))}}));e.screen.mandatory.chromeMediaSourceId=i,R7(o,await navigator.mediaDevices.getUserMedia({video:{mandatory:e.screen.mandatory}}))}else if(T1.getDisplayMedia){e.screen.mediaSource&&Rp(e.screen.mediaSource);let i={width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate,displaySurface:null!=(r=e.screen.displaySurface)?r:"screen"===e.screen.mediaSource?"monitor":e.screen.mediaSource},{selfBrowserSurface:n,surfaceSwitching:a,systemAudio:s,preferCurrentTab:c,windowAudio:d,monitorTypeSurfaces:l}=e.screen,h={selfBrowserSurface:n,surfaceSwitching:a,systemAudio:s,preferCurrentTab:c,windowAudio:d,monitorTypeSurfaces:l};n||delete h.selfBrowserSurface,a||delete h.surfaceSwitching,s||delete h.systemAudio,c||delete h.preferCurrentTab,d||delete h.windowAudio,l||delete h.monitorTypeSurfaces,TY.debug("[".concat(t,"] getDisplayMedia:"),JSON.stringify({video:i,audio:e.screenAudio,controls:h})),R7(o,await navigator.mediaDevices.getDisplayMedia(RB({video:i,audio:e.screenAudio},h)))}else{if(!Sl())throw TY.error("[".concat(t,"] This browser does not support screenSharing")),new Sx(SU.NOT_SUPPORTED,"This browser does not support screen sharing");{e.screen.mediaSource&&Rp(e.screen.mediaSource);let i={video:{mediaSource:e.screen.mediaSource,width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate}};TY.debug("[".concat(t,"] getUserMedia: ").concat(JSON.stringify(i))),R7(o,await navigator.mediaDevices.getUserMedia(i))}}if(!e.video&&!e.audio)return o;let a={video:e.video,audio:e.audio},s=TR("MEDIA_DEVICE_CONSTRAINTS");if(s)try{"string"==typeof s&&(s=JSON.parse(s)),a=function e(t,i){if(!gk(t)||!gk(i)||Array.isArray(t)&&!Array.isArray(i)||!Array.isArray(t)&&Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t)){let r=[...t];for(let n=0;n<i.length;n++)r[n]=e(t[n],i[n]);return r}{let r=SM({},t);for(let n in i)Object.prototype.hasOwnProperty.call(i,n)&&(Object.prototype.hasOwnProperty.call(t,n)?r[n]=e(t[n],i[n]):r[n]=i[n]);return r}}(a,s)}catch(e){}TY.debug("[".concat(t,"] GetUserMedia"),JSON.stringify(a)),St();let c,d=null;(Ss()||Sh()||So())&&(d=await R3.lock());try{c=await navigator.mediaDevices.getUserMedia(a)}catch(e){throw d&&d(),e}return a.audio&&(R5=!0),a.video&&(R4=!0),R7(o,c),d&&d(),o}function R9(e,t){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new Sx(SU.MEDIA_OPTION_INVA
1LID,"".concat(e,": ").concat(t));case"NotFoundError":case"DevicesNotFoundError":return new Sx(SU.DEVICE_NOT_FOUND,"".concat(e,": ").concat(t));case"NotSupportedError":return new Sx(SU.NOT_SUPPORTED,"".concat(e,": ").concat(t));case"NotReadableError":return new Sx(SU.NOT_READABLE,"".concat(e,": ").concat(t));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new Sx(SU.PERMISSION_DENIED,"".concat(e,": ").concat(t));case"ConstraintNotSatisfiedError":return new Sx(SU.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(t));default:return TY.error("getUserMedia unexpected error",e),new Sx(SU.UNEXPECTED_ERROR,"".concat(e,": ").concat(t))}}function R7(e,t){let i=e.getVideoTracks()[0],r=e.getAudioTracks()[0],n=t.getVideoTracks()[0],o=t.getAudioTracks()[0];o&&(r&&e.removeTrack(r),e.addTrack(o)),n&&(i&&e.removeTrack(i),e.addTrack(n))}let Ce=new class extends S0{get state(){return this._state}set state(e){e!==this._state&&(this.emit(RP.STATE_CHANGE,e),this._state=e)}async enumerateDevices(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)throw new Sx(SU.NOT_SUPPORTED,"enumerateDevices() not supported.");let r=await navigator.mediaDevices.enumerateDevices(),n=this.checkMediaDeviceInfoIsOk(r),o=!this.isAccessMicrophonePermission&&e,a=!this.isAccessCameraPermission&&t;n.audio&&(o=!1),n.video&&(a=!1);let s=null,c=null,d=null;if(!i&&(o||a)){if(R3.isLocked&&(TY.debug("[device manager] wait GUM lock"),(await R3.lock())(),TY.debug("[device manager] GUM unlock")),R5&&(o=!1,this.isAccessMicrophonePermission=!0),R4&&(a=!1,this.isAccessCameraPermission=!0),TY.debug("[device manager] check media device permissions",e,t,o,a),o&&a){try{d=await navigator.mediaDevices.getUserMedia({audio:!0,video:!0})}catch(t){let e=R9(t.name||t.code||t,t.message);if(e.code===SU.PERMISSION_DENIED)throw e;TY.warning("getUserMedia failed in getDevices",e)}this.isAccessCameraPermission=!0,this.isAccessMicrophonePermission=!0}else if(o){try{s=await navigator.mediaDevices.getUserMedia({audio:e})}catch(t){let e=R9(t.name||t.code||t,t.message);if(e.code===SU.PERMISSION_DENIED)throw e;TY.warning("getUserMedia failed in getDevices",e)}this.isAccessMicrophonePermission=!0}else if(a){try{c=await navigator.mediaDevices.getUserMedia({video:t})}catch(t){let e=R9(t.name||t.code||t,t.message);if(e.code===SU.PERMISSION_DENIED)throw e;TY.warning("getUserMedia failed in getDevices",e)}this.isAccessCameraPermission=!0}TY.debug("[device manager] mic permission",e,"cam permission",t)}try{let e=await navigator.mediaDevices.enumerateDevices();return s&&s.getTracks().forEach(e=>e.stop()),c&&c.getTracks().forEach(e=>e.stop()),d&&d.getTracks().forEach(e=>e.stop()),s=null,c=null,d=null,e}catch(e){return s&&s.getTracks().forEach(e=>e.stop()),c&&c.getTracks().forEach(e=>e.stop()),d&&d.getTracks().forEach(e=>e.stop()),s=null,c=null,d=null,new Sx(SU.ENUMERATE_DEVICES_FAILED,e.toString()).throw()}}async getRecordingDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter(e=>"audioinput"===e.kind)}async getCamerasDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!1,!0,e)).filter(e=>"videoinput"===e.kind)}async getSpeakers(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter(e=>"audiooutput"===e.kind)}searchDeviceIdByName(e){let t=null;return this.deviceInfoMap.forEach(i=>{i.device.label===e&&(t=i.device.deviceId)}),t}async getDeviceById(e){let t=(await this.enumerateDevices(!0,!0,!0)).find(t=>t.deviceId===e);if(!t)throw new Sx(SU.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return t}async init(){this.state=RD.INITING;try{await this.updateDevicesInfo(),this.state=RD.INITEND}catch(e){if(this.state=RD.IDLE,!("boolean"==typeof isSecureContext?isSecureContext:"https:"===location.protocol||"file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname||"::1"===location.hostname))throw new Sx(SU.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.");throw TY.warning("Device Detection functionality cannot start properly.",e.toString()),e}}async updateDevicesInfo(){let e=await this.enumerateDevices(!0,!0,!0),t=Date.now(),i=[];if(e[0]&&e[0].label&&!1===this.checkdeviceMatched){this.checkdeviceMatched=!0;let t=e.find(e=>"audioinput"===e.kind&&"default"===e.deviceId),i=e.find(e=>"audiooutput"===e.kind&&"default"===e.deviceId);t&&i?i.groupId===t.groupId?TY.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is the same group")):TY.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is not the same group")):TY.debug("[device-check] default input or output not found")}let r=this.checkMediaDeviceInfoIsOk(e);
1if(e.forEach(e=>{if(!e.deviceId)return;let r=this.deviceInfoMap.get("".concat(e.kind,"_").concat(e.deviceId));if("ACTIVE"!==(r?r.state:"INACTIVE")){let r={initAt:t,updateAt:t,device:e,state:"ACTIVE"};this.deviceInfoMap.set("".concat(e.kind,"_").concat(e.deviceId),r),i.push(r)}r&&(r.updateAt=t)}),this.deviceInfoMap.forEach((e,r)=>{"ACTIVE"===e.state&&e.updateAt!==t&&(e.state="INACTIVE",i.push(e))}),this.state!==RD.INITEND)return r.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),void(r.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0));i.forEach(e=>{switch(e.device.kind){case"audioinput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(RP.RECORDING_DEVICE_CHANGED,e);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(RP.CAMERA_DEVICE_CHANGED,e);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(RP.PLAYOUT_DEVICE_CHANGED,e)}}),r.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),r.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0)}checkMediaDeviceInfoIsOk(e){let t=e.filter(e=>"audioinput"===e.kind),i=e.filter(e=>"videoinput"===e.kind),r={audio:!1,video:!1};for(let e of t)if(e.label&&e.deviceId){r.audio=!0;break}for(let e of i)if(e.label&&e.deviceId){r.video=!0;break}return r}constructor(){super(),RV(this,"_state",RD.IDLE),RV(this,"isAccessMicrophonePermission",!1),RV(this,"isAccessCameraPermission",!1),RV(this,"lastAccessMicrophonePermission",!1),RV(this,"lastAccessCameraPermission",!1),RV(this,"checkdeviceMatched",!1),RV(this,"deviceInfoMap",new Map),this.init().then(()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval(()=>{(TR("ENUMERATE_DEVICES_INTERVAL")||(SD()||Sr()===f6.HARMONY_OS)&&SN())&&this.updateDevicesInfo()},TR("ENUMERATE_DEVICES_INTERVAL_TIME"))}).catch(e=>TY.error(e.toString()))}},Ct=!1,Ci=new class extends S0{constructor(){super(...arguments),RV(this,"onAutoplayFailed",void 0),RV(this,"onAudioAutoplayFailed",void 0)}};function Cr(){if(Ct)return TR("FLS_AUTOPLAY_EMITS")?(Ci.onAutoplayFailed&&Ci.onAutoplayFailed(),Ci.emit("autoplay-failed")):void 0;{let e=t=>{t.preventDefault(),Ct=!1,SP()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};Ct=!0,SP()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),TY.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),Ci.onAutoplayFailed?Ci.onAutoplayFailed():Ci.onAudioAutoplayFailed?TY.warning("AgoraRTC.onAudioAutoplayFailed has been deprecated in favor of AgoraRTC.onAutoplayFailed.\n\n Please refer to the Agora document to migrate the newer API, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."):TY.warning("We have detected a media autoplay failed event, and found out that you haven't implemented AgoraRTC.onAutoplayFailed callback yet.\n\n It will cause audio/video element not playing automatically on some browsers without user interaction, possibly hurting user experiences.\n\n Please refer to the Agora document to properly handle autoplay failed event, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."),Ci.emit("autoplay-failed")}}function Cn(e,t,i,r){if(!e)return;let n=T$.getBaseInfoBySessionId(e);if(!n)return;let o=n.info,a=Date.now(),s=RB(RB({},o),{},{vid:void 0===o.vid?0:Number(o.vid),lts:a,elapse:a-n.startTime,cbRegistered:Ci.onAutoplayFailed||Ci.onAudioAutoplayFailed?1:-1,errorMsg:i,mediaType:t,trackId:r,extend:void 0});T$.send({type:TJ.AUTOPLAY_FAILED,data:s},!0)}let Co=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],Ca=new class{async setSinkID(e,t){let i=this.elementMap.get(e);if(this.sinkIdMap.set(e,t),i)try{await i.setSinkId(t)}catch(e){throw new Sx(SU.PERMISSION_DENIED,"can not set sink id: "+e.toString())}}play(e,t,i,r){if(this.elementMap.has(t))return;let n=document.createElement("audio");
1n.autoplay=!0,n.srcObject=new MediaStream([e]),this.bindAudioElementEvents(t,n),this.elementMap.set(t,n),this.elementStateMap.set(t,RL.INIT),this.setVolume(t,i);let o=this.sinkIdMap.get(t);if(o)try{n.setSinkId(o).catch(e=>{TY.warning("[".concat(t,"] set sink id failed"),e.toString())})}catch(e){TY.warning("[".concat(t,"] set sink id failed"),e.toString())}let a=n.play();a&&a.then&&a.catch(e=>{r&&Cn(r,"audio",e.message,t),TY.warning("audio element play warning",e.toString()),this.elementMap.has(t)&&"NotAllowedError"===e.name&&(TY.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(n),gf(()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),Cr()}))})}updateTrack(e,t){let i=this.elementMap.get(e);i&&(i.srcObject=new MediaStream([t]))}isPlaying(e){return this.elementMap.has(e)&&"playing"===this.elementStateMap.get(e)}setVolume(e,t){let i=this.elementMap.get(e);i&&(i.volume=(t=Math.max(0,Math.min(100,t)))/100)}getVolume(e){let t=this.elementMap.get(e);return t?t.volume:0}stop(e){let t=this.elementMap.get(e);if(this.sinkIdMap.delete(e),!t)return;let i=this.elementsNeedToResume.indexOf(t);this.elementsNeedToResume.splice(i,1),t.srcObject=null,t.remove(),this.elementMap.delete(e),this.elementStateMap.delete(e)}bindAudioElementEvents(e,t){Co.forEach(i=>{t.addEventListener(i,i=>{let r=this.elementStateMap.get(e),n="pause"===i.type?"paused":i.type;if(TY.debug("[".concat(e,"] audio-element-status change ").concat(r," => ").concat(n)),"error"===i.type){let i=null==t?void 0:t.error;i&&TY.error("[".concat(e,"] media error, code: ").concat(i.code,", message: ").concat(i.message))}this.elementStateMap.set(e,n)})})}getPlayerState(e){return this.elementStateMap.get(e)||"uninit"}autoResumeAudioElement(){let e=()=>{this.elementsNeedToResume.forEach(e=>{e.play().then(e=>{TY.debug("Auto resume audio element success")}).catch(e=>{TY.warning("Auto resume audio element failed!",e)})}),this.elementsNeedToResume=[]};new dQ(e=>{document.body?e():window.addEventListener("load",()=>e())}).then(()=>{SP()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0))})}constructor(){RV(this,"onAutoplayFailed",void 0),RV(this,"elementMap",new Map),RV(this,"elementStateMap",new Map),RV(this,"elementsNeedToResume",[]),RV(this,"sinkIdMap",new Map),RV(this,"autoResumeAfterInterruption",e=>dQ.all(Array.from(this.elementMap.entries()).map(async t=>{let[i,r]=t,n=this.elementStateMap.get(i),o=r.srcObject.getAudioTracks()[0],a=o&&o.readyState;if(TY.debug("resume after interrupted, ele: ".concat(n," audio: ").concat(a," ").concat(e)),"live"===a){if(e)return r.pause(),r.play();if("running"===RY.curState)return Sv()?(r.pause(),r.play()):n&&"paused"===n?r.play():void 0}}))),RV(this,"autoResumeAfterInterruptionOnIOS15_16",()=>{Array.from(this.elementMap.entries()).forEach(e=>{let[t,i]=e,r=i.srcObject.getAudioTracks()[0];r&&"live"===r.readyState&&(TY.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),i.pause(),i.play())})}),this.autoResumeAudioElement(),RY.on(T7.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),RY.on(T7.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),RY.on(T7.STATE_CHANGE,()=>{Sh()&&"suspended"===RY.prevState&&"running"===RY.curState&&this.autoResumeAfterInterruption()})}};function Cs(){return function(e,t,i){let r=i.value;return"function"==typeof r&&(i.value=function(){this._isClosed&&new Sx(SU.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning",TY);for(var e=arguments.length,t=Array(e),i=0;i<e;i++)t[i]=arguments[i];let n=r.apply(this,t);return n instanceof dQ?new dQ((e,t)=>{n.then(e).catch(t)}):n}),i}}class Cc extends S0{get kind(){return"video"}get enabled(){return!0}pipe(){throw new Sx(SU.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor")}unpipe(){throw new Sx(SU.NOT_SUPPORTED,"VideoProcessor cannot unpipe to any other Processor")}enable(){}disable(){}updateInput(e){if(e.context!==this.videoContext)throw Error("ProcessorContext passed to VideoTrack.processorDestination doesn't match it's belonging VideoTrack's context.\nProbably you are making pipeline like this:\nvideoTrack1.pipe(processor).pipe(videoTrack2.processorDestination).");e.track&&e.track!==this.inputTrack&&(this.videoContext.chained=!0,this.inputTrack=e.track,this.emit
1(Rw.ON_TRACK,e.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(Rw.ON_TRACK,void 0)}constructor(e){super(),RV(this,"name","VideoProcessorDestination"),RV(this,"ID","0"),RV(this,"_source",void 0),RV(this,"videoContext",void 0),RV(this,"inputTrack",void 0),this.videoContext=e}}class Cd extends S0{set chained(e){this._chained=e}get chained(){return this._chained}async getConstraints(){return await gs(this,RN.REQUEST_CONSTRAINTS)}async requestApplyConstraints(e,t){var i;return TY.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),gc(this,RN.REQUEST_UPDATE_CONSTRAINTS,Array.from(d1(i=this.constraintsMap).call(i)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return TY.info("processor ".concat(e.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(e),gc(this,RN.REQUEST_UPDATE_CONSTRAINTS,Array.from(d1(t=this.constraintsMap).call(t)))}registerStats(e,t,i){this.statsRegistry.find(i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t)||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){let i=this.statsRegistry.findIndex(i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t);-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){let e=[];for(let{processorID:t,processorName:i,type:r,cb:n}of this.statsRegistry)try{let o=n();e.push({processorID:t,processorName:i,type:r,stats:o})}catch(e){TY.error(new Sx(SU.UNEXPECTED_ERROR,e.message))}return e}registerUsage(e,t){this.usageRegistry.find(t=>t.processorID===e.ID&&t.processorName===e.name)||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){let t=this.usageRegistry.findIndex(t=>t.processorID===e.ID&&t.processorName===e.name);-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){let e=[];
1if(!this.chained)return[];for(let{cb:t}of this.usageRegistry)try{let i=t();i instanceof dQ&&(i=await i),e.push(RB(RB({},i),{},{direction:this.direction}))}catch(e){TY.error("gather extension usage error",e)}return e}getDirection(){return this.direction}constructor(e,t){super(),RV(this,"constraintsMap",new Map),RV(this,"statsRegistry",[]),RV(this,"usageRegistry",[]),RV(this,"trackId",void 0),RV(this,"direction",void 0),RV(this,"_chained",!1),this.trackId=e,this.direction=t}}class Cl extends S0{get kind(){return"audio"}get enabled(){return!0}pipe(){throw new Sx(SU.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new Sx(SU.NOT_SUPPORTED,"AudioProcessor cannot unpipe to any other Processor")}enable(){}disable(){}reset(){this.inputTrack=void 0,this.inputNode=void 0,this.audioProcessorContext.chained=!1,this.emit(Rw.ON_TRACK,void 0),this.emit(Rw.ON_NODE,void 0)}updateInput(e){if(e.context!==this.audioProcessorContext)throw Error("ProcessorContext passed to AudioTrack.processorDestination doesn't match it's belonging AudioTrack's context.\n Probably you are making pipeline like this: audioTrack1.pipe(processor).pipe(audioTrack2.processorDestination).");e.track&&this.inputTrack!==e.track&&(this.audioProcessorContext.chained=!0,this.inputTrack=e.track,this.emit(Rw.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(Rw.ON_NODE,this.inputNode))}constructor(e){super(),RV(this,"name","AudioProcessorDestination"),RV(this,"ID","0"),RV(this,"inputTrack",void 0),RV(this,"inputNode",void 0),RV(this,"audioProcessorContext",void 0),RV(this,"_source",void 0),this.audioProcessorContext=e}}class Ch extends S0{set chained(e){this._chained=e}get chained(){return this._chained}async getConstraints(){return gs(this,RN.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(e,t){var i;return TY.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),gc(this,RN.REQUEST_UPDATE_CONSTRAINTS,Array.from(d1(i=this.constraintsMap).call(i)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),gc(this,RN.REQUEST_UPDATE_CONSTRAINTS,Array.from(d1(t=this.constraintsMap).call(t)))}registerStats(e,t,i){this.statsRegistry.find(i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t)||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:i})}unregisterStats(e,t){let i=this.statsRegistry.findIndex(i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t);-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){let e=[];for(let{processorID:t,processorName:i,type:r,cb:n}of this.statsRegistry)try{let o=n();e.push({processorID:t,processorName:i,type:r,stats:o})}catch(e){TY.error(new Sx(SU.UNEXPECTED_ERROR,e.message))}return e}registerUsage(e,t){this.usageRegistry.find(t=>t.processorID===e.ID&&t.processorName===e.name)||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){let t=this.usageRegistry.findIndex(t=>t.processorID===e.ID&&t.processorName===e.name);-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){let e=[];
1if(!this.chained)return[];for(let{cb:t}of this.usageRegistry)try{let i=t();i instanceof dQ&&(i=await i),e.push(RB(RB({},i),{},{direction:this.direction}))}catch(e){TY.error("gather extension usage error",e)}return e}getDirection(){return this.direction}constructor(e,t,i){super(),RV(this,"constraintsMap",new Map),RV(this,"statsRegistry",[]),RV(this,"audioContext",void 0),RV(this,"trackId",void 0),RV(this,"direction",void 0),RV(this,"usageRegistry",[]),RV(this,"_chained",!1),this.audioContext=e,this.trackId=t,this.direction=i}}class Cu extends S0{get isPlayed(){return!0}get isFreeze(){return!1}setVolume(){}createOutputTrack(){throw new Sx(SU.NOT_SUPPORTED,"can not create output MediaStreamTrack when WebAudio disabled")}getOriginVolumeLevel(){return 0}getAccurateVolumeLevel(){return 0}stopGetAudioBuffer(){}startGetAudioBuffer(){}play(){}stop(){}destroy(){}updateTrack(){}updateOriginTrack(){}createMediaStreamSourceNode(){}constructor(){super(),RV(this,"context",void 0),RV(this,"processSourceNode",void 0),RV(this,"outputTrack",void 0),RV(this,"processedNode",void 0),RV(this,"clonedTrack",void 0),RV(this,"outputNode",void 0),this.outputNode=new Cp}}class Cp{disconnect(){}connect(){}}function C_(e){return new dQ((t,i)=>{let r=!1,n=document.createElement("video");n.setAttribute("autoplay",""),n.setAttribute("muted",""),n.muted=!0,n.autoplay=!0,n.setAttribute("playsinline",""),n.setAttribute("style","position: fixed; top: 0; left: 0; width: 1px; height: 1px"),document.body.appendChild(n);let o=Sh()?"canplay":"playing";n.addEventListener(o,()=>{let e=n.videoWidth,i=n.videoHeight;!e&&Sl()||(r=!0,n.srcObject=null,n.remove(),t([e,i]))}),n.srcObject=new MediaStream([e]),n.play().catch(gD),setTimeout(()=>{r||(n.srcObject=null,n.remove(),t([n.videoWidth,n.videoHeight]))},4e3)})}function CE(e){let t={};e.facingMode&&(t.facingMode=e.facingMode),e.cameraId&&(t.deviceId={exact:e.cameraId});let i=Rs(e.encoderConfig);return null!=i.width&&(t.width=i.width),null!=i.height&&(t.height=i.height),!SO()&&i.frameRate&&(t.frameRate=i.frameRate),Sd()&&"object"==typeof t.frameRate&&(t.frameRate.max=60),Sl()&&(t.frameRate={ideal:30,max:30}),t}function Cm(e){let t={};return SO()||(void 0!==e.AGC&&(t.autoGainControl=e.AGC),void 0!==e.AEC&&(t.echoCancellation=e.AEC),void 0!==e.ANS&&(t.noiseSuppression=e.ANS,Sa()&&e.ANS&&(t.googHighpassFilter=e.ANS))),t}function Cf(e){let t=Cm(e);if(e.encoderConfig){let i=Rh(e.encoderConfig);t.channelCount=i.stereo?2:1,t.sampleRate=i.sampleRate,t.sampleSize=i.sampleSize}return e.microphoneId&&(t.deviceId={exact:e.microphoneId}),SD()&&(t.sampleRate=void 0),t}let CS=e=>{let t=e._encoderConfig;if(!t)return;let{frameRate:i,width:r,height:n}=e.getMediaStreamTrackSettings(),{frameRate:o=i,width:a=r,height:s=n}=t;if(!o||!a||!s)return;a=gU(a);let{max:c,min:d}=function(e,t,i){let r=200*Math.pow(i/15,.6)*Math.pow(e*t/640/360,.75);return{min:Math.floor(r),max:Math.floor(4*r)}}(a,s=gU(s),o=gU(o)),{bitrateMax:l,bitrateMin:h}=t||{};l||TY.debug("calculate bitrate: [w: ".concat(a,", h: ").concat(s,", fps: ").concat(o,"] => [brMax: ").concat(l,", brMin: ").concat(h,"]"));let{maxFramerate:u}=TR("ENCODER_CONFIG_LIMIT");return u&&"number"==typeof u&&(o=Math.min(o,u)),{frameRate:o,bitrateMax:l||c,bitrateMin:h||d,scaleResolutionDownBy:1,scale:0}},Cg=async(e,t,i)=>await (async(e,t,i)=>{let r=(function(e){let t=[];for(let i=0;i<e.length;i+=2)t.push(parseInt(e.slice(i,i+2),16));return Uint8Array.from(t)})(gF(""+t+i)).slice(0,16),n=r.slice(0,12),o=await window.crypto.subtle.importKey("raw",r,"AES-GCM",!0,["encrypt"]);return new Uint8Array(await window.crypto.subtle.encrypt({name:"AES-GCM",iv:n},o,e))})(e.buffer,t,i),CT=e=>{let t=document.createElement("canvas");return t.width=2,t.height=2,new dQ((i,r)=>{t.toBlob(async e=>{(t.remove(),e)?i({buffer:await CR(e),width:t.width,height:t.height}):r(new Sx(SU.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))},e,1)})},CR=async e=>new Uint8Array(await e.arrayBuffer()),CC=(t_=TZ({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),tE=TZ({argsMap:(e,t)=>[e.getTrackId(),t]}),tm=Cs(),tf=gW("LocalAudioTrack","_enabledMutex"),tS=TZ({argsMap:(e,t)=>[e.getTrackId(),t]}),tg=Cs(),tT=gW("LocalAudioTrack","_enabledMutex"),tR=TZ({argsMap:(e,t)=>[e.getTrackId(),t]}),tC=Cs(),tv=Cs(),ty=Cs(),tI=TZ({argsMap:e=>[e.getTrackId()]}),tA=Cs(),tb=TZ({argsMap:e=>[e.getTrackId()]}),tO=Cs(),tw=TZ({argsMap:e=>[e.getTrackId()]}),tN=TZ({argsMap:(e,t)=>[e.getTrackId(),t.name]}),tD=TZ({argsMap:e=>[e.getTrackId()]}),Rx((tP=class extends RG{get _source(){return this.initWebAudio()}set _source(e){this._trackSource=e}get processorContext(){return this._processorContext||(this._processorContext=this.initProcessor().processorContext),this._processorContext}get processorDestination(){return this._processorDestination||(this._processorDestination=this.initProcessor().processorDestination),this._processorDestination}get isPlaying(){return this._useAudioElement?Ca.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"LocalAudioTrack"}setVolume(e){SB(e,"volume",0,1e3),this._volume=e,this._source.setVolume(e/100),this._useAudioElement&&Ca.setVolume(this.getTrackId(),e);try{if(this._bypassWebAudio)return void TY.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));let e=this._source.createOutputTrack();this._mediaStreamTrack!==e&&(this._mediaStreamTrack=e,gc(this,R_.NEED_REPLACE_TRACK,this).then(()=>{TY.debug("[".concat(this.getTrackId(),"] replace web audio track success"))}).catch(e=>{TY.warning("[".concat(this.getTrackId(),"] replace web audio track failed"),e)}))}catch(e){}}getVolumeLevel(){return this._muted&&this.enabled&&this._getOriginVolumeLevel?this._source.getOriginVolumeLevel():this._source.getAccurateVolumeLevel()}async setPlaybackDevice(e){if(!this._useAudioElement||!T2())throw new Sx(SU.NOT_SUPPORTED,"your browser does not support setting the audio output device");await Ca.setSinkID(this.getTrackId(),e)}async setEnabled(e,t,i){return this._setEnabled(e,t,i)}async _setEnabled(e,t,i){if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(TY.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){this._originMediaStreamTrack.enabled=!0;try{i||(this._enabled=!0),await gc(this,R_.NEED_ENABLE_TRACK,this),TY.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(e," success"))}catch(e){throw i||(this._enabled=!1),TY.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}}else{this._originMediaStreamTrack.enabled=!1,i||(this._enabled=!1);try{await gc(this,R_.NEED_DISABLE_TRACK,this)}catch(e){throw i||(this._enabled=!0),TY.error("[".concat(this.getTrackId(),"] setEnabled to fal
1se error"),e.toString()),e}}}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,TY.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await gc(this,R_.NEED_MUTE_TRACK,this):await gc(this,R_.NEED_UNMUTE_TRACK,this))}getStats(){return gR(()=>{TY.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")},"localAudioTrackGetStatsWarning"),gd(this,R_.GET_STATS)||RB({},Ry)}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(Rv.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(Rv.ON_AUDIO_BUFFER),this._source.on(Rv.ON_AUDIO_BUFFER,t=>e(t))}play(){TY.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(TY.debug("[".concat(this.getTrackId(),"] start audio playback in element")),Ca.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){TY.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?Ca.stop(this.getTrackId()):this._source.stop()}close(){super.close(),this._processorDestination&&this.unbindProcessorDestinationEvents(this._processorDestination),this._processorContext&&this.unbindProcessorContextEvents(this._processorContext),this.unpipe(),this._processorDestination&&this._processorDestination._source&&this._processorDestination._source.unpipe(),this._source.destroy()}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];TY.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&Ca.updateTrack(this.getTrackId(),this._mediaStreamTrack)}async _updateOriginMediaStreamTrack(e,t){this._originMediaStreamTrack!==e&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this.processor&&this._processorContext&&this.processor.updateInput({track:e,context:this._processorContext}),this._mediaStreamTrack!==this._source.outputTrack?(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await gc(this,R_.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(e))}renewMediaStreamTrack(e){return dQ.resolve(void 0)}pipe(e){if(this._bypassWebAudio)throw new Sx(SU.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===e)return e;if(e._source)throw new Sx(SU.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(!this.processor)return;let t=this.processor;null==(e=this._source.processSourceNode)||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(e){e.on(Rw.ON_TRACK,async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e),await gc(this,R_.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await gc(this,R_.NEED_REPLACE_TRACK,this))}),e.on(Rw.ON_NODE,e=>{this._source.processedNode=e})}unbindProcessorDestinationEvents(e){e.removeAllListeners(Rw.ON_TRACK),e.removeAllListeners(Rw.ON_NODE)}bindProcessorContextEvents(e){e.on(RN.REQUEST_CONSTRAINTS,async e=>{e(this._originMediaStreamTrack.getSettings())})}unbindProcessorContextEvents(e){e.removeAllListeners(RN.REQUEST_CONSTRAINTS)}initWebAudio(){return this._trackSource instanceof Cu&&(this._trackSource=new R$(this._mediaStreamTrack,!1,this._getOriginVolumeLevel?this._mediaStreamTrack:void 0)),this._trackSource}initProcessor(){let e=new Ch(this._source.context,this.getTrackId(),"local"),t=new Cl(e);return this._processorContext=e,this._processorDestination=t,this.bindProcessorContextEvents(e),this.bindProcessorDestinationEvents(t),this._source.on(Rv.UPDATE_SOURCE,()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:e})}),this._useAudioElement&&(this._useAudioElement=!1,this.isPlaying&&(Ca.stop(this.getTrackId()),this._source.play()),gc(this,R_.NEED_REPLACE_MIXING_TRACK,this).then(()=>{TY.debug("[".concat(this.getTrackId(),"] replace from origin track to web audio track success"))}).catch(e=>{TY.warning("[".concat(this.getTrackId(),"] replace from origin track to web audio track failed"),e)})),{processorContext:e,processorDestination:t}}constructor(e,t,i,r){super(e,i),RV(this,"trackMediaType",RC.AUDIO),RV(this,"_encoderConfig",void 0),RV(this,"_trackSource",void 0),RV(this,"metadata",[]),RV(this,"_enabled",!0),RV(this,"_volume",100),RV(this,"_useAudioElement",!0),RV(this,"_bypassWebAudio",!1),RV(this,"processor",void 0),RV(this,"_processorContext",void 0),RV(this,"_processorDestination",void 0),RV(this,"_getOriginVolumeLevel",void 0),this._encoderConfig=t,this._getOriginVolumeLevel=!!r,this._trackSource=new Cu,TR("DISABLE_WEBAUDIO")&&(this._bypassWebAudio=!0),TR("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1),Ss()&&!RK?setTimeout(()=>this.initWebAudio()):this.initWebAudio()}}).prototype,"setVolume",[t_],Object.getOwnPropertyDescriptor(tP.prototype,"setVolume"),tP.prototype),Rx(tP.prototype,"setPlaybackDevice",[tE,tm],Object.getOwnPropertyDescriptor(tP.prototype,"setPlaybackDevice"),tP.prototype),Rx(tP.prototype,"setEnabled",[tf,tS,tg],Object.getOwnPropertyDescriptor(tP.prototype,"setEnabled"),tP.prototype),Rx(tP.prototype,"setMuted",[tT,tR,tC],Ob
vendor: 1,058 bytes, line 1
1ject.getOwnPropertyDescriptor(tP.prototype,"setMuted"),tP.prototype),Rx(tP.prototype,"getStats",[tv],Object.getOwnPropertyDescriptor(tP.prototype,"getStats"),tP.prototype),Rx(tP.prototype,"setAudioFrameCallback",[ty],Object.getOwnPropertyDescriptor(tP.prototype,"setAudioFrameCallback"),tP.prototype),Rx(tP.prototype,"play",[tI,tA],Object.getOwnPropertyDescriptor(tP.prototype,"play"),tP.prototype),Rx(tP.prototype,"stop",[tb,tO],Object.getOwnPropertyDescriptor(tP.prototype,"stop"),tP.prototype),Rx(tP.prototype,"close",[tw],Object.getOwnPropertyDescriptor(tP.prototype,"close"),tP.prototype),Rx(tP.prototype,"pipe",[tN],Object.getOwnPropertyDescriptor(tP.prototype,"pipe"),tP.prototype),Rx(tP.prototype,"unpipe",[tD],Object.getOwnPropertyDescriptor(tP.prototype,"unpipe"),tP.prototype),tP),Cv=(tL=TZ({argsMap:(e,t)=>[e.getTrackId(),t]}),tk=Cs(),tM=gW("MicrophoneAudioTrack","_enabledMutex"),tU=TZ({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),tx=Cs(),tV=TZ({argsMap:e=>[e.getTrackId()]}),Rx((tF=class extends CC{get __className__(){return"MicrophoneAudioTrack"}
1async setDevice(e){if(TY.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{let t=await Ce.getDeviceById(e),i={};i.audio=RB({},this._constraints),i.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let r=null;try{r=await R6(i,this.getTrackId())}catch(e){throw TY.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),r=await R6({audio:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(r.getAudioTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(r.getAudioTracks()[0],!1),this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw TY.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{let t=await Ce.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw TY.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}TY.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"))}async setEnabled(e,t,i){if(t)return TY.debug("[".concat(this.getTrackId(),"] setEnabled false (do not close microphone)")),await super._setEnabled(e);if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(TY.info("[".concat(this.getTrackId(),"] start setEnabled"),e),TR("AUTO_RESET_AUDIO_ROUTE")&&(Sh()||SA())){let t=navigator.audioSession;t&&(e||(t.type="playback"),t.type="auto")}if(!e){var r;this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop(),null==(r=this._source.clonedTrack)||r.stop(),i||(this._enabled=!1);try{await gc(this,R_.NEED_DISABLE_TRACK,this)}catch(e){throw TY.error("[".concat(this.getTrackId(),"] setEnabled false failed"),e.toString()),e}return}let n=RB({},this._constraints),o=Ce.searchDeviceIdByName(this._deviceName);o&&!n.deviceId&&(n.deviceId=o);try{i||(this._enabled=!0);let e=await R6({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1),await gc(this,R_.NEED_ENABLE_TRACK,this)}catch(e){throw i||(this._enabled=!1),TY.error("[".concat(this.getTrackId(),"] setEnabled true failed"),e.toString()),e}TY.info("[".concat(this.getTrackId(),"] setEnabled success"))}close(){super.close(),(Sv()||Sy())&&RY.unbindInterruptDetectorTrack(this),Ru.some(e=>"__className__"in e&&"MicrophoneAudioTrack"===e.__className__)||RH&&RH()&&(T$.reportApiInvoke(null,{name:"BG_AUDIO_TAG_RESTART",options:{},tag:S5.TRACER}).onSuccess(),TY.debug("restart background audio tag success"))}onTrackEnded(){if((Sh()||SA())&&this._enabled&&!this._isClosed&&RY.duringInterruption){let e=async()=>{RY.off(T7.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(TY.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};RY.on(T7.IOS_INTERRUPTION_END,e)}else TY.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(RT.TRACK_ENDED)}async renewMediaStreamTrack(e){let t=e||this._constraints,i=Ce.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId=i),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();let e=await R6({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0)}}bindProcessorContextEvents(e){super.bindProcessorContextEvents(e),e.on(RN.REQUEST_UPDATE_CONSTRAINTS,async(e,t,i)=>{try{let i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t()}catch(e){i(e)}})}unbindProcessorContextEvents(e){super.unbindProcessorContextEvents(e),e.removeAllListeners(RN.REQUEST_UPDATE_CONSTRAINTS)}constructor(e,t,i,r){super(e,t.encoderConfig?Rh(t.encoderConfig):{},r,TR("GET_VOLUME_OF_MUTED_AUDIO_TRACK")),RV(this,"_config",void 0),RV(this,"_deviceName","default"),RV(this,"_constraints",void 0),RV(this,"_originalConstraints",void 0),RV(this,"_enabled",!0),this._config=t,this._constraints=i,this._originalConstraints=i,this._deviceName=e.label,"boolean"==typeof t.bypassWebAudio&&(this._bypassWebAudio=t.bypassWebAudio),(Sv()||Sy())&&RY.bindInterruptDetectorTrack(this)}}
vendor: 7,685 bytes, line 1
1).prototype,"setDevice",[tL,tk],Object.getOwnPropertyDescriptor(tF.prototype,"setDevice"),tF.prototype),Rx(tF.prototype,"setEnabled",[tM,tU,tx],Object.getOwnPropertyDescriptor(tF.prototype,"setEnabled"),tF.prototype),Rx(tF.prototype,"close",[tV],Object.getOwnPropertyDescriptor(tF.prototype,"close"),tF.prototype),tF),Cy=(tB=TZ({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),tj=Cs(),tG=TZ({argsMap:e=>[e.getTrackId()]}),tW=Cs(),tH=TZ({argsMap:e=>[e.getTrackId()]}),tK=Cs(),tY=TZ({argsMap:e=>[e.getTrackId()]}),tz=Cs(),tq=TZ({argsMap:e=>[e.getTrackId()]}),tX=Cs(),tJ=TZ({argsMap:e=>[e.getTrackId()]}),tQ=TZ({argsMap:e=>[e.getTrackId()]}),tZ=Cs(),Rx((t$=class extends CC{get __className__(){return"BufferSourceAudioTrack"}get currentState(){return this._bufferSource.currentState}get duration(){return this._bufferSource.duration}get playbackSpeed(){return this._bufferSource.playbackSpeed}getCurrentTime(){return this._bufferSource.currentTime}startProcessAudioBuffer(e){e&&this._bufferSource.updateOptions(e),this._bufferSource.startProcessAudioBuffer()}pauseProcessAudioBuffer(){this._bufferSource.pauseProcessAudioBuffer()}seekAudioBuffer(e){this._bufferSource.seekAudioBuffer(e)}resumeProcessAudioBuffer(){this._bufferSource.resumeProcessAudioBuffer()}stopProcessAudioBuffer(){this._bufferSource.stopProcessAudioBuffer()}close(){this.source=null,this._bufferSource.destroy(),super.close()}setAudioBufferPlaybackSpeed(e){SB(e,"speed",0),this._bufferSource.setAudioBufferPlaybackSpeed(e)}constructor(e,t,i,r){super(t.createOutputTrack(),i,r),RV(this,"source",void 0),RV(this,"_bufferSource",void 0),this._useAudioElement=!1,this.source=e,this._bufferSource=t,this._bufferSource.on(Rv.AUDIO_SOURCE_STATE_CHANGE,e=>{this.safeEmit(RT.SOURCE_STATE_CHANGE,e)});try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}}}).prototype,"startProcessAudioBuffer",[tB,tj],Object.getOwnPropertyDescriptor(t$.prototype,"startProcessAudioBuffer"),t$.prototype),Rx(t$.prototype,"pauseProcessAudioBuffer",[tG,tW],Object.getOwnPropertyDescriptor(t$.prototype,"pauseProcessAudioBuffer"),t$.prototype),Rx(t$.prototype,"seekAudioBuffer",[tH,tK],Object.getOwnPropertyDescriptor(t$.prototype,"seekAudioBuffer"),t$.prototype),Rx(t$.prototype,"resumeProcessAudioBuffer",[tY,tz],Object.getOwnPropertyDescriptor(t$.prototype,"resumeProcessAudioBuffer"),t$.prototype),Rx(t$.prototype,"stopProcessAudioBuffer",[tq,tX],Object.getOwnPropertyDescriptor(t$.prototype,"stopProcessAudioBuffer"),t$.prototype),Rx(t$.prototype,"close",[tJ],Object.getOwnPropertyDescriptor(t$.prototype,"close"),t$.prototype),Rx(t$.prototype,"setAudioBufferPlaybackSpeed",[tQ,tZ],Object.getOwnPropertyDescriptor(t$.prototype,"setAudioBufferPlaybackSpeed"),t$.prototype),t$);class CI extends CC{get __className__(){return"MixingAudioTrack"}get isActive(){for(let e of this.trackList)if(e._enabled&&!e._isClosed&&!e.muted)return!0;return!1}hasAudioTrack(e){return -1!==this.trackList.indexOf(e)}addAudioTrack(e){-1===this.trackList.indexOf(e)?(TY.debug("add ".concat(e.getTrackId()," to mixing track")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):TY.debug("track ".concat(e.getTrackId()," is already added"))}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){TY.debug("remove ".concat(e.getTrackId()," from mixing track"));try{e._source.outputNode.disconnect(this.destNode)}catch(e){}gE(this.trackList,e),this.updateEncoderConfig()}}updateEncoderConfig(){let e={};this.trackList.forEach(t=>{t._encoderConfig&&((t._encoderConfig.bitrate||0)>(e.bitrate||0)&&(e.bitrate=t._encoderConfig.bitrate),(t._encoderConfig.sampleRate||0)>(e.sampleRate||0)&&(e.sampleRate=t._encoderConfig.sampleRate),(t._encoderConfig.sampleSize||0)>(e.sampleSize||0)&&(e.sampleSize=t._encoderConfig.sampleSize),t._encoderConfig.stereo&&(e.stereo=!0))}),this._encoderConfig=e}_updateRtpTransceiver(e){this._rtpTransceiver!==e&&(this._rtpTransceiver=e,this.trackList.forEach(t=>{t instanceof CI?t.emit(Rg.TRANSCEIVER_UPDATED,e):t._updateRtpTransceiver(e)}))}constructor(){let e=Rz().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,gw(8,"track-mix-")),RV(this,"trackList",void 0),RV(this,"destNode",void 0),this._useAudioElement=!1;try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}this.destNode=e,this.trackList=[]}}class CA extends RZ{set currentState(e){e!==this._currentState&&(this._currentState=e,this.safeEmit(Rv.AUDIO_SOURCE_STATE_CHANGE,this._currentState))}get currentState(){return this._currentState}createWebAudioDiagram(){return this.context.createGain()}get duration(){return this.audioBuffer?this.audioBuffer.duration:0}get playbackSpeed(){return this.currentPlaybackSpeed}get currentTime(){return this.audioBuffer?"stopped"===this.currentState?0:"paused"===this.currentState?this.pausePlayTime:((this.context.currentTime-this.startPlayTime)*(this.playbackSpeed/100)+this.startPlayOffset)%this.audioBuffer.duration:0}updateOptions(e){"stopped"===this.currentState?(this.options=e,this.startPlayOffset=this.options.startPlayTime||0):TY.warning("can not set audio source options")}startProcessAudioBuffer(){this.sourceNode&&this.stopProcessAudioBuffer(),this.sourceNode=this.createSourceNode(),this.startSourceNode(),this.currentState="playing"}pauseProcessAudioBuffer(){this.sourceNode&&"playing"===this.currentState&&(this.pausePlayTime=this.currentTime,this.sourceNode.onended=null,this.sourceNode.stop(),this.sourceNode.buffer=null,this.sourceNode=this.createSourceNode(),this.currentState="paused")}seekAudioBuffer(e){this.sourceNode&&(this.sourceNode.onended=null,"playing"===this.currentState&&this.sourceNode.stop(),this.sourceNode=this.createSourceNode(),"playing"===this.currentState?(this.startPlayOffset=e,this.startSourceNode()):"paused"===this.currentState&&(this.pausePlayTime=e))}resumeProcessAudioBuffer(){"paused"===this.currentState&&this.sourceNode&&(this.startPlayOffset=this.pausePlayTime,this.pausePlayTime=0,this.startSourceNode(),this.currentState="playing")}stopProcessAudioBuffer(){if(this.sourceNode){this.sourceNode.onended=null;try{this.sourceNode.stop()}catch(e){}this.reset()}}destroy(){this.audioBuffer=null,super.destroy()}setAudioBufferPlaybackSpeed(e){this.sourceNode&&("playing"===this.currentState&&(this.startPlayOffset=this.currentTime,this.startPlayTime=this.context.currentTime),this.sourceNode.playbackRate.value=e/100),this.currentPlaybackSpeed=e}startSourceNode(){this.sourceNode&&this.sourceNode.buffer&&(this.sourceNode.start(0,this.startPlayOffset),this.startPlayTime=this.context.currentTime,this.sourceNode.onended=this.handleSourceNodeEnded.bind(this))}createSourceNode(){let e=this.context.createBufferSource();return e.buffer=this.audioBuffer,e.loop=!!this.options.loop,e.connect(this.outputNode),e.playbackRate.value=this.currentPlaybackSpeed/100,e}handleSourceNodeEnded(){if(this.currentLoopCount+=1,this.options.cycle&&this.options.cycle>this.currentLoopCount)return this.startPlayOffset=0,this.sourceNode=void 0,void this.startProcessAudioBuffer();this.reset()}reset(){this.startPlayOffset=this.options.startPlayTime||0,this.currentState="stopped",this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=void 0),this.currentLoopCount=0}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),RV(this,"audioBuffer",void 0),RV(this,"sourceNode",void 0),RV(this,"startPlayTime",0),RV(this,"startPlayOffset",0),RV(this,"pausePlayTime",0),RV(this,"options",void 0),RV(this,"currentLoopCount",0),RV(this,"currentPlaybackSpeed",100),RV(this,"_currentState","stopped"),this.audioBuffer=e,this.options=t,this.startPlayOffset=this.options.startPlayTime||0}}
1let Cb=new Map;function CO(e,t){if(0===e.length||0===t.length)return 1/0;let i=gV(e);return Math.floor(gV(t)/i)}class Cw{get rendFrameRate(){return Math.floor(1e3/Math.max(1,CO(this._render_interframe_delays_sizes,this._render_interframe_delays)))}get videoElementStatus(){return this._isInPage?this._videoElementStatus:RL.DESTROYED}set videoElementStatus(e){e!==this._videoElementStatus&&(TY.debug("[".concat(this.trackId,"] video-element-status change ").concat(this._videoElementStatus," => ").concat(e)),this._videoElementStatus=e)}get videoState(){return this._videoState}set videoState(e){var t;e!==this._videoState&&(this._videoState=e,null==(t=this.onVideoStateChanged)||t.call(this,this.videoState))}getVideoElement(){return this.videoElement}getContainerElement(){var e;return null!=(e=this.videoElement.parentElement)?e:void 0}updateConfig(e){this.config=e,this.trackId=e.trackId,e.element!==this.videoElement&&(this.destroy(),this.videoElement=e.element),this.videoTrack&&this.initVideoElement()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.initVideoElement())}play(e){let t=this.videoElement.play();t&&t.catch&&t.catch(t=>{e&&Cn(e,"video",t.message,this.trackId),"NotAllowedError"===t.name?(TY.warning("detected video element autoplay failed",t),this.autoplayFailed=!0,this.handleAutoPlayFailed()):TY.warning("[".concat(this.trackId,"] play warning: "),t)});let i=St();if(("Safari"===i.name&&15===Number(i.version)||Sv())&&t&&t.then){let e=()=>{this.config.mirror&&!this.config.noStyle&&(this.videoElement.style.transform="rotateY(180deg)")};t.then(e).catch(e)}}getCurrentFrame(){let e=document.createElement("canvas");e.width=this.videoElement.videoWidth,e.height=this.videoElement.videoHeight;let t=e.getContext("2d");if(!t)return TY.error("create canvas context failed!"),new ImageData(2,2);t.drawImage(this.videoElement,0,0,e.width,e.height);let i=t.getImageData(0,0,e.width,e.height);return e.remove(),i}async getCurrentFrameToUint8Array(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,i=document.createElement("canvas");i.width=this.videoElement.videoWidth,i.height=this.videoElement.videoHeight;let r=i.getContext("2d");return r?(r.drawImage(this.videoElement,0,0,i.width,i.height),new dQ((r,n)=>{i.toBlob(async e=>{(i.remove(),e)?r({buffer:await CR(e),width:i.width,height:i.height}):n(new Sx(SU.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))},e,t<0?.1:t>1?1:t)})):await CT(e)}destroy(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.isDestroyed=!0,RY.off(T7.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),RY.off(T7.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),e?this.videoElement.pause():this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[],this.videoState=Rk.VideoStateStopped}initVideoElement(){if(this.videoElementStatus=RL.INIT,!this.videoElementCheckInterval&&(CN.forEach(e=>{this.videoElement.addEventListener(e,this.handleVideoEvents)}),this.videoElementCheckInterval=window.setInterval(()=>{var e;this._isInPage=(e=this.videoElement)!==document.body&&document.body.contains(e)},1e3),TR("ENABLE_VIDEO_FRAME_CALLBACK"))){var e,t;let i,r=()=>{"visible"===document.visibilityState&&(document.removeEventListener("visibilitychange",r),this.videoElementFreezeTimeout=window.setTimeout(n,TR("VIDEO_FREEZE_DURATION")))},n=()=>{this.videoElementFreezeTimeout=void 0,this.videoState===Rk.VideoStateDecoding&&("visible"===document.visibilityState?this.videoState=Rk.VideoStateFrozen:document.addEventListener("visibilitychange",r))},o=(e,t)=>{var r,a;if(this.videoElementStatus===RL.PLAYING){if(i){let e=t.presentationTime-i.presentationTime,r=t.presentedFrames-i.presentedFrames;this._render_interframe_delays_sizes.push(r),this._render_interframe_delays.push(e);let o=gV(this._render_interframe_delays_sizes),a=o-this._render_interframe_delays_sizes[0];if(o>30&&a>5&&(this._render_interframe_delays_sizes.shift(),this._render_interframe_delays.shift()),this.videoState===Rk.VideoStateStarting&&(this.videoState=Rk.VideoStateDecoding),this.videoState===Rk.VideoStateDecoding&&this.onVideoStateChanged&&(this.videoElementFreezeTimeout&&window.clearTimeout(this.videoElementFreezeTimeout),this.videoElementFreezeTimeout=window.setTimeout(n,TR("VIDEO_FREEZE_DURATION"))),e<TR("VIDEO_FREEZE_DURATION")&&this.videoState===Rk.VideoStateFrozen&&(this.videoState=Rk.VideoStateDecoding),e>TR("VIDEO_FREEZE_DURATION")&&CF.lastVisibleTime>=CF.lastHiddenTime&&i.timestamp>CF.lastVisibleTime&&i.timestamp>CF.lastHiddenTime){let t=Math.min(66,CO(this._render_interframe_delays_sizes,this._render_interframe_delays)),i=Math.max(0,e-(r-1)*t);this.renderFreezeAccTime2+=i>t?i:0,this.renderFreezeAccTime+=e}}i=RB(RB({},t),{},{timestamp:e})}else this.isSkipCalcRenderFreezeTime()&&(i=RB(RB({},t),{},{timestamp:e}));TR("ENABLE_VIDEO_FRAME_CALLBACK")&&(this.cancelRVFId=null==(r=(a=this.videoElement).requestVideoFrameCallback)?void 0:r.call(a,o))};this.cancelRVFId=null==(e=(t=this.videoElement).requestVideoFrameCallback)?void 0:e.call(t,o)}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),SD()&&!TR("HIDE_NO_POSTER")&&(this.videoElement.poster="noposter");let i=St();this.config.noStyle||("Safari"===i.name&&15===Number(i.version)||Sv()||!this.config.mirror||(this.videoElement.style.transform="rotateY(180deg)"),this.config.fit?this.videoElement.style.objectFit=this.config.fit:this.videoElement.style.objectFit="cover"),this.videoElement.setAttribute("muted",""),this.videoElement.muted=!0,this.videoElement.srcObject&&this.videoElement.srcObject instanceof MediaStream?this.videoElement.srcObject.getVideoTracks()[0]!==this.videoTrack&&(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,Sl()&&this.videoElement.load()):(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,Sl()&&this.videoElement.load());let r=this.videoElement.play();void 0!==r&&r.catch(e=>{TY.debug("[".concat(this.trackId,"] playback interrupted"),e.toString())})}resetVideoElement(){var e,t;
1CN.forEach(e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents)}),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.cancelRVFId&&this.videoElement&&(null==(e=(t=this.videoElement).cancelVideoFrameCallback)||e.call(t,this.cancelRVFId),this.cancelRVFId=void 0),this.videoElementStatus=RL.NONE}isSkipCalcRenderFreezeTime(){return this.videoElementStatus===RL.DESTROYED||this.internal}handleAutoPlayFailed(){let e=t=>{t.preventDefault(),this.videoElement.play().then(()=>{TY.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))}).catch(e=>{TY.error(e)}),this.autoplayFailed=!1,SP()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};SP()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),Cr()}constructor(e){RV(this,"trackId",void 0),RV(this,"config",void 0),RV(this,"onFirstVideoFrameDecoded",void 0),RV(this,"onFirstVideoFrameRender",void 0),RV(this,"onVideoBufferReady",void 0),RV(this,"onVideoStateChanged",void 0),RV(this,"freezeTimeCounterList",[]),RV(this,"renderFreezeAccTime",0),RV(this,"renderFreezeAccTime2",0),RV(this,"isKeepLastFrame",!1),RV(this,"isDestroyed",!1),RV(this,"timeUpdatedCount",0),RV(this,"freezeTime",0),RV(this,"playbackTime",0),RV(this,"lastTimeUpdatedTime",0),RV(this,"autoplayFailed",!1),RV(this,"videoTrack",void 0),RV(this,"videoElement",void 0),RV(this,"cacheVideoElement",void 0),RV(this,"cancelRVFId",void 0),RV(this,"internal",!1),RV(this,"_render_interframe_delays",[]),RV(this,"_render_interframe_delays_sizes",[]),RV(this,"_videoState",Rk.VideoStateStopped),RV(this,"videoElementCheckInterval",void 0),RV(this,"videoElementFreezeTimeout",void 0),RV(this,"_videoElementStatus",RL.NONE),RV(this,"_isInPage",!0),RV(this,"isGettingVideoDimensions",!1),RV(this,"startGetVideoDimensions",()=>{let e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return TY.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(e,500)};this.isGettingVideoDimensions||e()}),RV(this,"autoResumeAfterInterruption",()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&"running"===RY.curState&&(TY.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(Sn())),SI()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack])):this.videoElement.pause(),this.videoElement.play())}),RV(this,"handleVideoEvents",e=>{switch(e.type){case"play":case"playing":"play"===e.type&&TY.debug("[".concat(this.trackId,"] video element status: play")),this.startGetVideoDimensions(),this.videoElementStatus=RL.PLAYING;break;case"loadeddata":if(this.videoState=Rk.VideoStateStarting,this.onFirstVideoFrameRender&&this.onFirstVideoFrameRender(),this.onFirstVideoFrameDecoded&&this.onFirstVideoFrameDecoded(),this.cacheVideoElement){try{this.cacheVideoElement.srcObject=null,this.cacheVideoElement.remove()}catch(e){}this.cacheVideoElement=void 0}break;case"canplay":this.videoElementStatus=RL.CANPLAY;break;case"stalled":this.videoElementStatus=RL.STALLED;break;case"suspend":this.videoElementStatus=RL.SUSPEND;break;case"pause":this.videoElementStatus=RL.PAUSED,Sh()||SA()||Ss()&&this.autoplayFailed||!this.videoTrack||"live"!==this.videoTrack.readyState||(TY.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=RL.WAITING;break;case"abort":this.videoElementStatus=RL.ABORT;break;case"ended":this.videoElementStatus=RL.ENDED;break;case"emptied":this.videoElementStatus=RL.EMPTIED;break;case"error":{let e=this.videoElement.error;e&&(this.videoElementStatus=RL.ERROR,TY.error("[".concat(this.trackId,"] media error: ").concat(e.message," (").concat(e.code,")")));break}case"timeupdate":{let e=performance.now();if(this.timeUpdatedCount+=1,this.onVideoBufferReady&&this.timeUpdatedCount>TR("BUFFER_READY_FRAMES")&&this.onVideoBufferReady(),this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);let t=e-this.lastTimeUpdatedTime,i=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,CF.lastVisibleTime<CF.lastHiddenTime||i<C
1F.lastHiddenTime||i<CF.lastVisibleTime||this.isSkipCalcRenderFreezeTime())return;for(t>TR("VIDEO_FREEZE_DURATION")&&(this.freezeTime+=t),this.playbackTime+=t;this.playbackTime>=6e3;){this.playbackTime-=6e3;let e=Math.min(6e3,this.freezeTime);this.freezeTimeCounterList.push(e),this.freezeTime=Math.max(0,this.freezeTime-6e3)}}}}),RV(this,"autoResumeAfterInterruptionOnIOS15_16",()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&(TY.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(Sn())),SI()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack])):this.videoElement.pause(),this.videoElement.play())}),this.trackId=e.trackId,this.config=e,e.element instanceof HTMLVideoElement?this.videoElement=e.element:this.videoElement=document.createElement("video"),RY.on(T7.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),RY.on(T7.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16)}}let CN=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];class CD extends Cw{updateConfig(e){var t;this.config=e,this.trackId=e.trackId;let i=e.element;!this.internal||this.slot?(i!==this.slot&&(this.destroy(),this.slot=i),this.createElements()):(this.slot=i,i&&this.container?(this.internal=!1,this.container.id="agora-video-player-".concat(this.trackId),this.videoElement.id="video_".concat(this.trackId),this.config.fit?this.videoElement.style.objectFit=this.config.fit:this.videoElement.style.objectFit="cover",null==(t=this.slot)||t.appendChild(this.container)):this.createElements())}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.createElements())}play(e){var t;null!=(t=this.container)&&t.contains(this.videoElement)&&super.play(e)}getCurrentFrame(){var e;return null!=(e=this.container)&&e.contains(this.videoElement)?super.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameToUint8Array(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return null!=(t=this.container)&&t.contains(this.videoElement)?await super.getCurrentFrameToUint8Array(e,i):await CT(e)}destroy(){if(super.destroy(),this.videoElement.remove(),this.videoElement=document.createElement("video"),this.container){try{var e;this.container.remove(),null==(e=this.slot)||e.removeChild(this.container)}catch(e){}this.container=void 0}}createElements(){var e;this.container||(this.container=document.createElement("div")),this.container.id="agora-video-player-".concat(this.trackId),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.overflow="hidden",this.videoTrack?(this.container.style.backgroundColor="black",TR("KEEP_LAST_FRAME")&&this.isKeepLastFrame&&this.videoElement.paused&&this.resetVideoElement(),this.mountedVideoElement()):this.unmountedVideoElement(),null==(e=this.slot)||e.appendChild(this.container)}mountedVideoElement(){var e;!this.container||null!=(e=this.container)&&e.contains(this.videoElement)||this.container.appendChild(this.videoElement),super.initVideoElement(),this.videoElement.id="video_".concat(this.trackId),this.videoElement.className="agora_video_player",this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.left="0",this.videoElement.style.top="0"}unmountedVideoElement(){var e;if(null!=(e=this.container)&&e.contains(this.videoElement)){super.resetVideoElement();try{this.container&&this.container.removeChild(this.videoElement)}catch(e){}this.videoElement=document.createElement("video")}}resetVideoElement(){var e;null!=(e=this.container)&&e.contains(this.videoElement)&&(super.resetVideoElement(),this.cacheVideoElement=this.videoElement,this.videoElement=document.createElement("video"))}getContainerElement(){return this.container}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];super(e),RV(this,"container",void 0),RV(this,"slot",void 0),this.slot=e.element,this.internal=t,this.updateConfig(e)}}let CP=(t0=TZ({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),t1=Cs(),t2=TZ({argsMap:e=>[e.getTrackId()]}),t3=gW("LocalVideoTrack","_enabledMutex"),t5=TZ({argsMap:(e,t)=>[e.getTrackId(),t]}),t4=Cs(),t6=gW("LocalVideoTrack","_enabledMutex"),t8=TZ({argsMap:(e,t)=>[e.getTrackId(),t]}),t9=Cs(),t7=TZ({argsMap:(e,t)=>[e.getTrackId(),t,e._saveEncodeBitrateRatio]}),ie=Cs(),it=TZ({argsMap:(e,t)=>[e.getTrackId(),t]}),ii=Cs(),ir=Cs(),io=TZ({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),ia=Cs(),is=Cs(),ic=Cs(),id=TZ({argsMap:e=>[e.getTrackId()]}),il=Cs(),ih=Cs(),iu=Cs(),ip=Cs(),i_=Cs(),iE=TZ({argsMap:(e,t)=>[e.getTrackId(),t.name]}),im=TZ({argsMap:e=>[e.getTrackId()]}),iS=TZ({argsMap:e=>[e.getTrackId()]}),ig=TZ({argsMap:(e,t,i)=>[e.getTrackId(),t.label,i]}),Rx((iT=class e extends RG{get videoHeight(){if(Ss()){let{height:e}=this._mediaStreamTrack.getSettings();return this._videoHeight=e,this._videoHeight}return this._videoHeight}get videoWidth(){if(Ss()){let{width:e}=this._mediaStreamTrack.getSettings();return this._videoWidth=e,this._videoWidth}return this._videoWidth}get isPlaying(){return!(!this._player||this._player.videoElementStatus!==RL.PLAYING)}get processorDestination(){return this._processorDestination}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}get __className__(){return"LocalVideoTrack"}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e){let t=document.getElementById(e);t?e=t:(TY.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}TY.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));let i=RB(RB(RB({},this._getDefaultPlayerConfig()),t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new Cw(i):this._player=new CD(i),this._player.updateVideoTrack(this._mediaStreamTrack)),this._player.play(),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval(()=>{try{let e=this.getVideoElementVisibleStatus();this.safeEmit(RT.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}},TR("CHECK_VIDEO_VISIBLE_INTERVAL"))}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,TY.debug("[".concat(this.getTrackId(),"] stop video playback")))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(TY.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){this._originMediaStreamTrack.enabled=!1;try{await gc(this,R_.NEED_DISABLE_TRACK,this)}catch(e){throw TY.error("[".concat(this.getTrackId(),"] setEnabled to fal
1se error"),e.toString()),e}return t||(this._enabled=!1),void TY.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}this._originMediaStreamTrack.enabled=!0;try{await gc(this,R_.NEED_ENABLE_TRACK,this)}catch(e){throw TY.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}TY.info("[".concat(this.getTrackId(),"] setEnabled to true success")),t||(this._enabled=!0)}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,TY.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await gc(this,R_.NEED_MUTE_TRACK,this):await gc(this,R_.NEED_UNMUTE_TRACK,this))}async setSaveEncodeBitrateRatio(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this._saveEncodeBitrateRatio;if(1!==this._saveEncodeBitrateRatio&&this._encoderConfig&&this._encoderConfig.bitrateMax&&this._encoderConfig.bitrateMin){this._encoderConfig.bitrateMin=Math.floor(this._encoderConfig.bitrateMin*e),this._encoderConfig.bitrateMax=Math.floor(this._encoderConfig.bitrateMax*e),TY.debug("[".concat(this.getTrackId(),"] set save encode bitrate ratio, ").concat(e)),this._saveEncodeBitrateRatio=1;try{await gc(this,R_.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(TY)}}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new Sx(SU.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if(e=Rs(e),TR("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),e.width||e.height||e.frameRate){let t=CE({encoderConfig:e});(Ss()||Sh()||SA())&&(t.deviceId=void 0),TY.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(t));try{await this._originMediaStreamTrack.applyConstraints(t),this.updateMediaStreamTrackResolution()}catch(t){let e=new Sx(SU.UNEXPECTED_ERROR,t.toString());throw TY.error("[".concat(this.getTrackId(),"] applyConstraints error"),e.toString()),e}}this._encoderConfig=e,-1===this._hints.indexOf(RE.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await gc(this,R_.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(TY)}}getStats(){return gR(()=>{TY.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")},"localVideoTrackGetStatsWarning"),gd(this,R_.GET_STATS)||RB({},RI)}async setBeautyEffect(e){TY.error("LocalVideoTrack.setBeautyEffect was deprecated, please migrate to agora-extension-beauty-effect")}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameImage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this._player?this._player.getCurrentFrameToUint8Array(e,t):await CT(e)}async findClosestProfile(){let{width:e,height:t,frameRate:i}=this.getMediaStreamTrackSettings(),{width:r,height:n,frameRate:o}=this._encoderConfig||{},a=gU(this._videoWidth||e||r||0),s=gU(this._videoHeight||t||n||0),c=function(e,t,i){if(!Array.isArray(TR("VIDEO_ENCODER_CONFIG_LIST"))||0===TR("VIDEO_ENCODER_CONFIG_LIST").length)return!1;let r=Math.min(e,t);return!(r>=480)&&RB(RB({},TR("VIDEO_ENCODER_CONFIG_LIST").find(e=>e.height>r)),{},{frameRate:i})}(a,s,gU(i||o||15));if(c)return TY.debug("[".concat(this.getTrackId(),"] find closest profile, ").concat(a,"x").concat(s," => ").concat(JSON.stringify(c))),this.setEncoderConfiguration(c)}async setBitrateLimit(e){TY.debug("[".concat(this.getTrackId(),"] set bitrate limit, ").concat(JSON.stringify(e))),e&&(this._forceBitrateLimit=e,this._encoderConfig&&(this._encoderConfig.bitrateMax?this._encoderConfig.bitrateMax=this._encoderConfig.bitrateMax<e.max_bitrate?this._encoderConfig.bitrateMax:e.max_bitrate:this._encoderConfig.bitrateMax=e.max_bitrate,this._encoderConfig.bitrateMin,this._encoderConfig.bitrateMin=e.min_bitrate))}async setOptimizationMode(e){if("motion"!==e&&"detail"!==e&&"balanced"!==e)return void TY.error(SU.INVALID_PARAMS,"optimization mode must be motion, detail or balanced");let t=this._optimizationMode;try{this._optimizationMode=e,await gc(this,R_.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this)}catch(e){throw this._optimizationMode=t,TY.error("[".concat(this.getTrackId(),"] set optimization mode failed"),e.toString()),e}TY.info("[".concat(this.getTrackId(),"] set optimization mode success (").concat(e,")"))}
1setScalabiltyMode(e){if(1===e.numSpatialLayers&&1!==e.numTemporalLayers)return TY.error(SU.INVALID_PARAMS,"scalability mode currently not supported, no SVC."),void(this._scalabilityMode={numSpatialLayers:1,numTemporalLayers:1});this._scalabilityMode=e,TY.info("[".concat(this.getTrackId(),"] set scalability mode success (").concat(e,")"))}updateMediaStreamTrackResolution(){C_(this._originMediaStreamTrack).then(e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t}).catch(gD)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:"contain"}}async setSenderConfiguration(e){if(!this._enabled)throw new Sx(SU.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");TY.debug("[".concat(this.getTrackId(),"] setSenderConfiguration applyConstraints"),JSON.stringify(e)),e=Rs(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),this._encoderConfig=e,-1===this._hints.indexOf(RE.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await gc(this,R_.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(TY)}}updateBitrateFromProfile(){if(!this._encoderConfig)return;let{width:e,height:t,frameRate:i}=this.getMediaStreamTrackSettings();if(!e||!t||!i)return;let{bitrateMax:r,bitrateMin:n}=this._encoderConfig;if(null==n||null==r){let{max:o,min:a}=function(e,t,i,r,n){let o=TR("BITRATE_ADAPTER_TYPE");if("DEFAULT_BITRATE"===o)return{min:r,max:n};if(void 0===n){let a=Math.floor(200*Math.pow(i/15,.6)*Math.pow(e*t/640/360,.75));n="STANDARD_BITRATE"===o?4*a:2*a,r=null!=r?r:a}else r=null!=r?r:Math.floor(n/10);return{min:r,max:n}}(e,t,i,n,r);if(this._encoderConfig.bitrateMin=a,this._encoderConfig.bitrateMax=o,TR("VIDEO_STANDARD_BITRATE_VERSION")&&null==n&&null==r){let[r,n]=function(e,t,i){var r,n;let o=4*Math.floor(2e5*Math.pow(i/15,.6)*Math.pow(e*t/230400,.75)),a=e*t,s=new Map([[19200,.9],[230400,.85],[518400,.75],[921600,.7],[2073600,.6],[3686400,.5]]),c=new Map([[230400,.95],[518400,.9],[921600,.85],[2073600,.8]]),d=d1(s).call(s).next().value,l=1;if(s.has(a))d=s.get(a);else{let e=ll(r=Array.from(s.entries())).call(r,(e,t)=>{let[i]=e,[r]=t;return i-r}),t=e.find(e=>{let[t]=e;return t>a});if(t){let i=e.indexOf(t);if(i>0){let r=e[i-1],n=(a-r[0])/(t[0]-r[0]);d=r[1]+n*(t[1]-r[1])}else d=t[1]}else d=e[e.length-1][1]}if(c.has(a))l=c.get(a);else{let e=ll(n=Array.from(c.entries())).call(n,(e,t)=>{let[i]=e,[r]=t;return i-r}),t=e.find(e=>{let[t]=e;return t>a});if(t){let i=e.indexOf(t);if(i>0){let r=e[i-1],n=(a-r[0])/(t[0]-r[0]);l=r[1]+n*(t[1]-r[1])}else l=t[1]}else l=e[e.length-1][1]}let h=TR("VIDEO_NEW_BITRATE_RATIO");h&&h>0&&(d=h/100);let u=Math.floor(o*d),p=Math.floor(65e4*Math.pow(e*t/230400,.5)*Math.pow(i/15,.69)),_=u,E=TR("VIDEO_STANDARD_BITRATE_VERSION");return E&&E>0&&(1===E?_=o:2===E?_=u:3===E&&(_=p)),[Math.floor(_/1e3),l]}(e,t,i);this._encoderConfig.bitrateMax=r,this._encoderConfig.bitrateMin=a?Math.min(a,r):r,this._saveEncodeBitrateRatio=n,TY.debug("[".concat(this.getTrackId(),"] update new bitrate from profile, [w: ").concat(e,", h: ").concat(t,", fps: ").concat(i,"] => [brMax: ").concat(this._encoderConfig.bitrateMax,", brMin: ").concat(this._encoderConfig.bitrateMin,", save_bitrate_ratio: ").concat(this._saveEncodeBitrateRatio,"]"))}else TY.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(e,", h: ").concat(t,", fps: ").concat(i,"] => [brMax: ").concat(o,", brMin: ").concat(a,"]")),this._saveEncodeBitrateRatio=1}}getVideoElementVisibleStatus(){try{var e,t;let i=null==this||null==(e=this._player)?void 0:e.getContainerElement(),{element:r,slot:n}={track:this,element:null==this||null==(t=this._player)?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement};if(this.isPlaying&&r instanceof HTMLVideoElement&&n instanceof HTMLElement){let e=SJ.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;let e=T$.reportApiInvoke(null,{tag:S5.TRACER,name:S3.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(t.reason))}return t}return}catch(e){throw new Sx(SU.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}async renewMediaStreamTrack(e){}pipe(e){if(this.processor===e)return e;if(e._source)throw new Sx(SU.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;let e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset()}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe()}clone(t){let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],r=this._encoderConfig;t&&(r=RB(RB({},r),Rs(t))),r=gg(r);let n=gw(8,"track-video-cloned-"),o=new e(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,r,gg(this._scalabilityMode),this._optimizationMode,n,gg(this._hints));return t&&r&&o.setEncoderConfiguration(r),TY.debug("clone video track from ".concat(this.getTrackId()," to ").concat(n,", clone ").concat(i)),o}async replaceTrack(e,t){if(!(e instanceof MediaStreamTrack))throw new Sx(SU.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if("video"!==e.kind)throw new Sx(SU.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(e,t,!0),this.updateMediaStreamTrackResolution()}sendSeiData(e){if(gR(()=>{T$.reportApiInvoke(null,{name:S3.LOCAL_VIDEO_SEND_SEI_DATA,options:[],tag:S5.TRACER}).onSuccess("")},this._mediaStreamTrack.id||this.getTrackId()),!TR("ENABLE_VIDEO_SEI")||!TR("ENABLE_ENCODED_TRANSFORM"))return void TY.warning('To send/receive SEI, please call AgoraRTC.setParameter("ENABLE_VIDEO_SEI", true) before instantiate IAgoraRtcClient');if(e instanceof Uint8Array==0)return new Sx(SU.INVALID_PARAMS,"Invalid argument type, ILocalVideoTrack.sendSeiData() only accept Uint8Array argument.").throw();let t=this.getRTCRtpTransceiver();if(!t)return void TY.warning("Video track is not published, SEI can not be send");let i=t.sender.getParameters();if(0===i.codecs.length)return;let r=i.codecs[0].mimeType.toLocaleLowerCase();"video/h264"===r||"video/h265"===r?this.safeEmit("sei-to-send",e):TY.warning("SEI is not supported by ".concat(r))}bindProcessorDestinationEvents(){this.processorDestination.on(Rw.ON_TRACK,async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),await gc(this,R_.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await gc(this,R_.NEED_REPLACE_TRACK,this))})}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(Rw.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(RN.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(RN.REQUEST_CONSTRAINTS)}constructor(e,t,i,r,n,o){if(super(e,n),RV(this,"trackMediaType",RC.VIDEO),RV(this,"_player",void 0),RV(this,"isUseScaleResolutionDownBy",!1),RV(this,"_videoVisibleTimer",null),RV(this,"_previousVideoVisibleStatus",void 0),RV(this,"_clearPreviousVideoVisibleStatus",()=>this._previousVideoVisibleStatus=void 0),RV(this,"_encoderConfig",void 0),RV(this,"_scalabilityMode",{numSpatialL
1ayers:1,numTemporalLayers:1}),RV(this,"_optimizationMode",void 0),RV(this,"_saveEncodeBitrateRatio",1),RV(this,"_videoHeight",void 0),RV(this,"_videoWidth",void 0),RV(this,"_forceBitrateLimit",void 0),RV(this,"_enabled",!0),RV(this,"_processorDestination",void 0),RV(this,"_processorContext",void 0),Ss()){let{width:t,height:i}=e.getSettings();this._videoWidth=t,this._videoHeight=i}else this.updateMediaStreamTrackResolution();if(this._scalabilityMode=i,this._optimizationMode=r,this._hints=o||[],t&&-1!==this._hints.indexOf(RE.CUSTOM_TRACK)?this._encoderConfig=gS(t):this._encoderConfig=t,-1===this._hints.indexOf(RE.SCREEN_TRACK))this.updateBitrateFromProfile();else if(S_(f8.CHROME,115)&&-1!==Sr().indexOf("Windows")){let t=function(e,t){if("VideoFrame"in window&&"TransformStream"in window&&T1.supportWebRTCInsertableStream){let t=new MediaStreamTrackProcessor(e),i=new MediaStreamTrackGenerator({kind:"video"}),r,n,o=Date.now(),a=()=>{s&&(clearInterval(s),s=void 0),r&&(r.close(),r=void 0),e.stop(),n=void 0,i.removeEventListener("ended",a)},s=window.setInterval(()=>{if(n&&r&&Date.now()-o>1e3)try{"live"===i.readyState?n.enqueue(r.clone()):a()}catch(e){a()}},1e3),c=new TransformStream({transform:(e,t)=>{"live"===i.readyState?(n=t,o=Date.now(),void 0===r?(r=e,t.enqueue(e.clone())):(t.enqueue(r),r=e)):e.close()}});return i.addEventListener("ended",a),t.readable.pipeThrough(c).pipeTo(i.writable),i}}(e);t&&(TY.info("local screen video track begin to inject frame"),this._mediaStreamTrack=t)}t&&-1!==this._hints.indexOf(RE.CUSTOM_TRACK)&&this.setEncoderConfiguration(t),this._processorContext=new Cd(this.getTrackId(),"local"),this._processorDestination=new Cc(this.processorContext),this.bindProcessorDestinationEvents()}}).prototype,"play",[t0,t1],Object.getOwnPropertyDescriptor(iT.prototype,"play"),iT.prototype),Rx(iT.prototype,"stop",[t2],Object.getOwnPropertyDescriptor(iT.prototype,"stop"),iT.prototype),Rx(iT.prototype,"setEnabled",[t3,t5,t4],Object.getOwnPropertyDescriptor(iT.prototype,"setEnabled"),iT.prototype),Rx(iT.prototype,"setMuted",[t6,t8,t9],Object.getOwnPropertyDescriptor(iT.prototype,"setMuted"),iT.prototype),Rx(iT.prototype,"setSaveEncodeBitrateRatio",[t7,ie],Object.getOwnPropertyDescriptor(iT.prototype,"setSaveEncodeBitrateRatio"),iT.prototype),Rx(iT.prototype,"setEncoderConfiguration",[it,ii],Object.getOwnPropertyDescriptor(iT.prototype,"setEncoderConfiguration"),iT.prototype),Rx(iT.prototype,"getStats",[ir],Object.getOwnPropertyDescriptor(iT.prototype,"getStats"),iT.prototype),Rx(iT.prototype,"setBeautyEffect",[io,ia],Object.getOwnPropertyDescriptor(iT.prototype,"setBeautyEffect"),iT.prototype),Rx(iT.prototype,"getCurrentFrameData",[is],Object.getOwnPropertyDescriptor(iT.prototype,"getCurrentFrameData"),iT.prototype),Rx(iT.prototype,"getCurrentFrameImage",[ic],Object.getOwnPropertyDescriptor(iT.prototype,"getCurrentFrameImage"),iT.prototype),Rx(iT.prototype,"findClosestProfile",[id,il],Object.getOwnPropertyDescriptor(iT.prototype,"findClosestProfile"),iT.prototype),Rx(iT.prototype,"setBitrateLimit",[ih],Object.getOwnPropertyDescriptor(iT.prototype,"setBitrateLimit"),iT.prototype),Rx(iT.prototype,"setOptimizationMode",[iu],Object.getOwnPropertyDescriptor(iT.prototype,"setOptimizationMode"),iT.prototype),Rx(iT.prototype,"setScalabiltyMode",[ip],Object.getOwnPropertyDescriptor(iT.prototype,"setScalabiltyMode"),iT.prototype),Rx(iT.prototype,"updateMediaStreamTrackResolution",[i_],Object.getOwnPropertyDescriptor(iT.prototype,"updateMediaStreamTrackResolution"),iT.prototype),Rx(iT.prototype,"pipe",[iE],Object.getOwnPropertyDescriptor(iT.prototype,"pipe"),iT.prototype),Rx(iT.prototype,"unpipe",[im],Object.getOwnPropertyDescriptor(iT.prototype,"unpipe"),iT.prototype),Rx(iT.prototype,"close",[iS],Object.getOwnPropertyDescriptor(iT.prototype,"close"),iT.prototype),Rx(iT.prototype,"replaceTrack",[ig],Object.getOwnPropertyDescriptor(iT.prototype,"replaceTrack"),iT.prototype),iT),CL=(iR=TZ({argsMap:(e,t)=>[e.getTrackId(),t]}),iC=Cs(),iv=gW("CameraVideoTrack","_enabledMutex"),iy=TZ({argsMap:(e,t)=>[e.getTrackId(),t]}),iI=Cs(),iA=TZ({argsMap:(e,t)=>[e.getTrackId(),t]}),ib=Cs(),iO=TZ({argsMap:e=>[e.getTrackId()]}),Rx((iw=class e extends CP{get __className__(){return"CameraVideoTrack"}async setDevice(e){return"string"==typeof e?this._setDeviceById(e):e.deviceId?this._setDeviceById(e.deviceId):e.facingMode?this._setDeviceByFacingModel(e.facingMode):void 0}
1async _setDeviceById(e){if(TY.info("[".concat(this.getTrackId(),"] set device to ").concat(e)),this._enabled)try{let t=await Ce.getDeviceById(e),i={};i.video=RB({},this._constraints),i.video.deviceId={exact:e},i.video.facingMode=void 0,this._originMediaStreamTrack.stop();let r=null;try{r=await R6(i,this.getTrackId())}catch(e){throw TY.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),r=await R6({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(r.getVideoTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(r.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution(),this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw TY.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{let t=await Ce.getDeviceById(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw TY.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}TY.info("[".concat(this.getTrackId(),"] setDevice success"))}async _setDeviceByFacingModel(e){TY.info("[".concat(this.getTrackId(),"] set facingMode ").concat(e));let t={video:RB(RB({},this._constraints),{},{deviceId:void 0,facingMode:{exact:e}})};if(this._enabled){this._originMediaStreamTrack.stop();let e=null;try{e=await R6(t,this.getTrackId())}catch(t){throw TY.error("[".concat(this.getTrackId(),"] setDeviceByFacingModel failed"),t.toString()),e=await R6({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),t}await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution()}this._deviceName="",this._config.facingMode=e,this._config.cameraId=void 0,this._constraints=RB({},t.video),TY.info("[".concat(this.getTrackId(),"] setDeviceByFacingModel success"))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(TY.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{let e=await R6({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1)}await gc(this,R_.NEED_ENABLE_TRACK,this)}catch(e){throw TY.error("[".concat(this.getTrackId(),"] setEnabled true error"),e.toString()),e}this.updateMediaStreamTrackResolution(),TY.info("[".concat(this.getTrackId(),"] setEnabled to true success")),t||(this._enabled=!0)}else{this.isExternalTrack?this._originMediaStreamTrack.enabled=!1:(this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop()),t||(this._enabled=!1);try{await gc(this,R_.NEED_DISABLE_TRACK,this)}catch(e){throw TY.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}TY.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new Sx(SU.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");e=Rs(e),TR("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate||e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate||e.bitrateMin);let i=gS(this._config);i.encoderConfig=e;let r=CE(i);(Ss()||Sh()||SA())&&(r.deviceId=void 0),TY.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(r));try{await this._originMediaStreamTrack.applyConstraints(r),this.updateMediaStreamTrackResolution()}catch(t){let e=new Sx(SU.UNEXPECTED_ERROR,t.toString());throw TY.error("[".concat(this.getTrackId(),"] applyConstraints error"),e.toString()),e}this._config=i,this._constraints=r,this._originalConstraints=r,this._encoderConfig=e,-1===this._hints.indexOf(RE.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await gc(this,R_.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(TY)}}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((Sh()||SA())&&this._enabled&&!this._isClosed&&RY.duringInterruption){let e=async()=>{RY.off(T7.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(TY.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};RY.on(T7.IOS_INTERRUPTION_END,e)}else TY.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(RT.TRACK_ENDED)}async renewMediaStreamTrack(e){let t=e||this._constraints,i=Ce.searchDeviceId
1ByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId={exact:i}),this._enabled){let e=await R6({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),RY.off(T7.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),RY.off(T7.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat)}clone(t){let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],r=this._encoderConfig;t&&(r=RB(RB({},r),Rs(t))),r=gg(r);let n=gw(8,"track-cam-cloned-"),o=new e(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,gg(RB(RB({},this._config),{},{encoderConfig:r})),gg(this._constraints),gg(this._scalabilityMode),this._optimizationMode,n);return t&&r&&o.setEncoderConfiguration(r),TY.debug("clone track from ".concat(this.getTrackId()," to ").concat(n,", clone ").concat(i)),o}bindProcessorContextEvents(){this.processorContext.on(RN.REQUEST_UPDATE_CONSTRAINTS,async(e,t,i)=>{try{let i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t()}catch(e){i(e)}}),this.processorContext.on(RN.REQUEST_CONSTRAINTS,async e=>{e(this._originMediaStreamTrack.getSettings())})}constructor(e,t,i,r,n,o){super(e,Rs(t.encoderConfig),r,n,o),RV(this,"_config",void 0),RV(this,"_originalConstraints",void 0),RV(this,"_constraints",void 0),RV(this,"_enabled",!0),RV(this,"_deviceName","default"),RV(this,"tryResumeVideoForIOS15_16WeChat",async()=>{(Sv()||Sy())&&!function(){let e=St();if(e.os!==f6.IOS||!e.osVersion)return!1;let t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=2}()&&Sb()&&this._enabled&&!this._isClosed&&(TY.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS 15 device on WeChat.")),await this.renewMediaStreamTrack())}),this._config=t,this._originalConstraints=i,this._constraints=i,this._deviceName=e.label,this._encoderConfig=Rs(this._config.encoderConfig),RY.on(T7.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),RY.on(T7.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),this.bindProcessorContextEvents()}}).prototype,"setDevice",[iR,iC],Object.getOwnPropertyDescriptor(iw.prototype,"setDevice"),iw.prototype),Rx(iw.prototype,"setEnabled",[iv,iy,iI],Object.getOwnPropertyDescriptor(iw.prototype,"setEnabled"),iw.prototype),Rx(iw.prototype,"setEncoderConfiguration",[iA,ib],Object.getOwnPropertyDescriptor(iw.prototype,"setEncoderConfiguration"),iw.prototype),Rx(iw.prototype,"close",[iO],Object.getOwnPropertyDescriptor(iw.prototype,"close"),iw.prototype),iw);function Ck(e){let t=gw(8,"track-cus-"),i=T$.reportApiInvoke(null,{id:t,tag:S5.TRACER,name:S3.CREATE_CUSTOM_AUDIO_TRACK,options:[e]}),r=new CC(e.mediaStreamTrack,e.encoderConfig?Rh(e.encoderConfig):{},t,!1);return TY.info("create custom audio track success with config",e,"trackId",r.getTrackId()),i.onSuccess(r.getTrackId()),r}function CM(e,t,i,r){i.optimizationMode&&(r&&r.width&&r.height?(i.encoderConfig=RB(RB({},r),{},{bitrateMin:r.bitrateMin,bitrateMax:r.bitrateMax}),"motion"!==i.optimizationMode&&"detail"!==i.optimizationMode||(t.contentHint=i.optimizationMode,t.contentHint===i.optimizationMode?TY.debug("[".concat(e,"] set content hint to"),i.optimizationMode):TY.debug("[".concat(e,"] set content hint failed")))):TY.warning("[".concat(e,"] can not apply optimization mode bitrate config, no encoderConfig")))}class CU extends Rj{getUserId(){return this._userId}_updateOriginMediaStreamTrack(e){this._originMediaStreamTrack=e,this._mediaStreamTrack=e,this._updatePlayerSource(),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext})}_destroy(){this._isDestroyed=!0,TY.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}constructor(e,t,i,r){super(e,"track-".concat(e.kind,"-").concat(t,"-").concat(r.clientId,"_").concat(gw(5,""))),RV(this,"_userId",void 0),RV(this,"_uintId",void 0),RV(this,"_isDestroyed",!1),RV(this,"store",void 0),RV(this,"processor",void 0),RV(this,"processorContext",void 0),this._userId=t,this._uintId=i,this.store=r}}let Cx=(iN=TZ({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),iD=TZ({argsMap:e=>[e.getTrackId()]}),iP=TZ({argsMap:(e,t)=>[e.getTrackId(),t.name]}),iL=TZ({argsMap:e=>[e.getTrackId()]}),Rx((ik=class extends CU{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==RL.PLAYING)}get __className__(){return"RemoteVideoTrack"}getStats(){return gR(()=>{TY.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")},"remoteVideoTrackGetStatsWarning"),gd(this,R_.GET_STATS)||RB({},RO)}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.safeEmit(RR.PLAY_START),"string"==typeof e){let t=document.getElementById(e);t?e=t:(TY.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}TY.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));let i=RB(RB({fit:"cover"},t),{},{trackId:this.getTrackId(),element:e});if(this._player)this._player.updateConfig(i);else{let t=!1,r=!1;e instanceof HTMLVideoElement?(this._player=new Cw(i),this._prePlayer&&(this._prePlayer.destroy(),this._prePlayer=void 0,r=!0)):this._prePlayer&&!this._prePlayer.isDestroyed?(this._player=this._prePlayer,this._prePlayer=void 0,t=this._player.videoState>0,this._player.updateConfig(i)):this._player=new CD(i),this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.safeEmit(RR.FIRST_FRAME_DECODED),r&&this.safeEmit(RR.FIRST_FRAME_RENDER)},this._player.onVideoStateChanged=e=>{this.safeEmit(RR.VIDEO_STATE_CHANGED,e)},t&&(this._player.onFirstVideoFrameDecoded(),this._player.onVideoStateChanged(this._player.videoState))}this._player.play(this.store.sessionId||void 0),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval(()=>{try{let e=this.getVideoElementVisibleStatus();this.safeEmit(RR.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}},TR("CHECK_VIDEO_VISIBLE_INTERVAL")),this.safeEmit(RR.PLAY_END)}stop(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(e),this._player=void 0,TY.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){C_(this._originMediaStreamTrack).then(e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t}).catch(gD)}_updatePlayerSource(){TY.debug("[".concat(this.getTrackId(),"] update player source track")),this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}getVideoElementVisibleStatus(){try{var e,t;let i=null==this||null==(e=this._player)?void 0:e.getContainerElement(),{element:r,slot:n}={track:this,element:null==this||null==(t=this._player)?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement};if(this.isPlaying&&r instanceof HTMLVideoElement&&n instanceof HTMLElement){let e=SJ.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;let e=T$.reportApiInvoke(null,{tag:S5.TRACER,name:S3.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(t.reason))}return t}return}catch(e){throw new Sx(SU.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}pipe(e){if(this.processor===e)return e;if(e._source)throw new Sx(SU.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;let e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(Rw.ON_TRACK,async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource()):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())})}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(Rw.ON_TRACK)}_destroy(){this._prePlayer&&(this._prePlayer.destroy(),this._prePlayer=void 0),super._destroy(),this.unbindProcessorDestinationEvents()}
1_onSei(e){this.emit(Rg.SEI_RECEIVED,e)}constructor(e,t,i,r,n){super(e,t,i,r),RV(this,"_videoVisibleTimer",null),RV(this,"_previousVideoVisibleStatus",void 0),RV(this,"_clearPreviousVideoVisibleStatus",()=>this._previousVideoVisibleStatus=void 0),RV(this,"trackMediaType",RC.VIDEO),RV(this,"_videoWidth",void 0),RV(this,"_videoHeight",void 0),RV(this,"_player",void 0),RV(this,"_prePlayer",void 0),RV(this,"processorDestination",void 0),RV(this,"processorContext",void 0),this._prePlayer=n,this.updateMediaStreamTrackResolution(),this.processorContext=new Cd(this.getTrackId(),"remote"),this.processorDestination=new Cc(this.processorContext),this.bindProcessorDestinationEvents()}}).prototype,"play",[iN],Object.getOwnPropertyDescriptor(ik.prototype,"play"),ik.prototype),Rx(ik.prototype,"stop",[iD],Object.getOwnPropertyDescriptor(ik.prototype,"stop"),ik.prototype),Rx(ik.prototype,"pipe",[iP],Object.getOwnPropertyDescriptor(ik.prototype,"pipe"),ik.prototype),Rx(ik.prototype,"unpipe",[iL],Object.getOwnPropertyDescriptor(ik.prototype,"unpipe"),ik.prototype),ik),CV=(iM=TZ({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),iU=TZ({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),ix=TZ({argsMap:(e,t)=>[e.getTrackId(),t]}),iV=TZ({argsMap:e=>[e.getTrackId()]}),iF=TZ({argsMap:e=>[e.getTrackId()]}),iB=TZ({argsMap:(e,t)=>[e.getTrackId(),t.name]}),ij=TZ({argsMap:e=>[e.getTrackId()]}),Rx((iG=class extends CU{get isPlaying(){return this._useAudioElement?Ca.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(Rv.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(Rv.ON_AUDIO_BUFFER),this._source.on(Rv.ON_AUDIO_BUFFER,t=>e(t))}setVolume(e){this._volume=e,this._useAudioElement?Ca.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}setAmplifiedVolume(e){this._useAudioElement&&this._played&&(Ca.stop(this.getTrackId()),this._source.play()),this._useAudioElement=!1,e=Math.min(e,TR("MAX_WEBAUDIO_VOLUME")),this._volume=e,this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement||!T2())throw new Sx(SU.NOT_SUPPORTED,"your browser does not support setting the audio output device");await Ca.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getVolume(){return this._useAudioElement?Ca.getVolume(this.getTrackId()):this._source instanceof R$?this._source.getAudioVolume():0}getStats(){return gR(()=>{TY.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")},"remoteAudioTrackGetStatsWarning"),gd(this,R_.GET_STATS)||RB({},RA)}play(){TY.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement?(TY.debug("[".concat(this.getTrackId(),"] use audio element to play")),Ca.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):(TY.debug("[".concat(this.getTrackId(),"] use audio context to play")),this._source.play())}stop(){TY.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?Ca.stop(this.getTrackId()):this._source.stop()}_destroy(){super._destroy(),this._played=!1,this.unbindProcessorDestinationEvents(),this._source.destroy()}_isFreeze(){return this._source.isFreeze}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];TY.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&Ca.updateTrack(this.getTrackId(),this._mediaStreamTrack)}pipe(e){if(this._bypassWebAudio)throw new Sx(SU.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new Sx(SU.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(this._bypassWebAudio)throw new Sx(SU.NOT_SUPPORTED,"can not unpipe extension when WebAudio disabled");if(!this.processor)return;let t=this.processor;null==(e=this._source.processSourceNode)||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(Rw.ON_TRACK,async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())}
1),this.processorDestination.on(Rw.ON_NODE,e=>{this._source.processedNode=e;let t=!e;this._useAudioElement!==t&&(this._played?(this.stop(),this._useAudioElement=t,this.play()):this._useAudioElement=t)})}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(Rw.ON_TRACK),this.processorDestination.removeAllListeners(Rw.ON_NODE)}constructor(e,t,i,r){super(e,t,i,r),RV(this,"trackMediaType",RC.AUDIO),RV(this,"_source",void 0),RV(this,"_useAudioElement",!0),RV(this,"_volume",100),RV(this,"processorContext",void 0),RV(this,"processorDestination",void 0),RV(this,"_played",!1),RV(this,"_bypassWebAudio",!1),TR("DISABLE_WEBAUDIO")?(this._source=new Cu,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new R$(e,!0),TR("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once(Rv.RECEIVE_TRACK_BUFFER,()=>{this.safeEmit(RR.FIRST_FRAME_DECODED)}),this.processorContext=new Ch(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new Cl(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(Rv.UPDATE_SOURCE,()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})})}}).prototype,"setVolume",[iM],Object.getOwnPropertyDescriptor(iG.prototype,"setVolume"),iG.prototype),Rx(iG.prototype,"setAmplifiedVolume",[iU],Object.getOwnPropertyDescriptor(iG.prototype,"setAmplifiedVolume"),iG.prototype),Rx(iG.prototype,"setPlaybackDevice",[ix],Object.getOwnPropertyDescriptor(iG.prototype,"setPlaybackDevice"),iG.prototype),Rx(iG.prototype,"play",[iV],Object.getOwnPropertyDescriptor(iG.prototype,"play"),iG.prototype),Rx(iG.prototype,"stop",[iF],Object.getOwnPropertyDescriptor(iG.prototype,"stop"),iG.prototype),Rx(iG.prototype,"pipe",[iB],Object.getOwnPropertyDescriptor(iG.prototype,"pipe"),iG.prototype),Rx(iG.prototype,"unpipe",[ij],Object.getOwnPropertyDescriptor(iG.prototype,"unpipe"),iG.prototype),iG),CF=new class extends S0{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}startCollectStats(){this.isCollectingStats=!0,this.needUploadStats.push(+("visible"===this.visibility))}stopCollectStats(){this.isCollectingStats=!1,this.needUploadStats.length=0}constructor(){super(),RV(this,"_lastHiddenTime",0),RV(this,"_lastVisibleTime",0),RV(this,"needUploadStats",[]),RV(this,"isCollectingStats",!1),document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),this.isCollectingStats&&this.needUploadStats.push(+("visible"===document.visibilityState)),TY.debug("current web page is ".concat(document.visibilityState)),this.emit("VISIBILITY_CHANGE",document.visibilityState)})}};class CB extends S0{useDataStream(e){this._dataStreamPacketHandler=e}get id(){return this._config.id}get ordered(){return this._config.ordered}get maxRetransmits(){return TR("DATASTREAM_MAX_RETRANSMITS")}get metadata(){return this._config.metadata}get readyState(){var e,t;return null!=(e=null==(t=this._originDataChannel)?void 0:t.readyState)?e:"connecting"}get _originDataChannelId(){var e,t;return null!=(e=null==(t=this._originDataChannel)?void 0:t.id)?e:null}getChannelId(){return this.id}getConfig(){return this._config}_close(){this._originDataChannel&&(this._unbindDataChannelEvents(this._originDataChannel),this._originDataChannel=void 0)}async _waitTillOpen(){return new dQ((e,t)=>{if(this._originDataChannel){"open"===this._originDataChannel.readyState&&e();let i=setTimeout(()=>{var e;t(new Sx(SU.DATACHANNEL_CONNECTION_TIMEOUT,"Cannot create datachannel, id: ".concat(null==(e=this._originDataChannel)?void 0:e.id)))},1e4);this._originDataChannel.onopen=()=>{clearTimeout(i),this._originDataChannel&&this._bandDataChannelEvents(this._originDataChannel),e()},this._originDataChannel.onerror=()=>{throw clearTimeout(i),new Sx(SU.DATACHANNEL_CONNECTION_TIMEOUT)}}else t(new Sx(SU.DATACHANNEL_CONNECTION_TIMEOUT,"cannot find dataChannel"))})}
1_updateOriginDataChannel(e){this._originDataChannel=e,this._bandDataChannelEvents(e)}_initPacketHeader(){let e=new DataView(this._dataStreamPacketHeader);e.setUint16(0,this._version),e.setUint8(2,this._type),e.setUint8(3,this._config.id)}_bandDataChannelEvents(e){this._unbindDataChannelEvents(e),[RU.OPEN,RU.CLOSE,RU.ERROR].forEach(t=>{let i=()=>{this.emit(t)};this._datachannelEventMap.set(t,i),e.addEventListener(t,i)})}_unbindDataChannelEvents(e){Array.from(this._datachannelEventMap.entries()).forEach(t=>{let[i,r]=t;e.removeEventListener(i,r)}),this._datachannelEventMap.clear()}constructor(e,t){super(),RV(this,"trackMediaType",RC.DATA),RV(this,"_version",1),RV(this,"_type",3),RV(this,"_config",void 0),RV(this,"_originDataChannel",void 0),RV(this,"_dataStreamPacketHeader",new ArrayBuffer(4)),RV(this,"_dataStreamPacketHandler",{serialize:e=>e,deserialize:e=>e}),RV(this,"_datachannelEventMap",new Map),this._config=e,t&&(this._originDataChannel=t,this._bandDataChannelEvents(t)),this._initPacketHeader()}}class Cj extends CB{_updateOriginDataChannel(e){super._updateOriginDataChannel(e),this._bandRemoteDataChannelEvents()}_close(){this._originDataChannel&&(this._originDataChannel.removeEventListener("message",this._messageListener),super._close())}_bandRemoteDataChannelEvents(){this._originDataChannel&&this._originDataChannel.addEventListener("message",this._messageListener)}constructor(e){super(e),RV(this,"_messageListener",void 0),this._messageListener=e=>{if(e.data.byteLength<this._dataStreamPacketHeader.byteLength)throw Error("invalid byteLength: the byte length must exceed "+this._dataStreamPacketHeader.byteLength);let t=new DataView(e.data.slice(0,this._dataStreamPacketHeader.byteLength)).getUint8(3);if(t!==this.id)return void(TR("SHOW_DATASTREAM2_LOG")&&TY.debug("invalid datachannel id: ".concat(t," !== ").concat(this.id)));let i=e.data.slice(this._dataStreamPacketHeader.byteLength);i=this._dataStreamPacketHandler.deserialize(i),this.emit(RU.MESSAGE,i)}}}class CG extends CB{send(e){if(this._originDataChannel){let t=e;t=this._dataStreamPacketHandler.serialize(e);let i=new Uint8Array(this._dataStreamPacketHeader.byteLength+t.byteLength);i.set(new Uint8Array(this._dataStreamPacketHeader),0),i.set(new Uint8Array(t),this._dataStreamPacketHeader.byteLength),this._originDataChannel.send(i.buffer)}}}function CW(){let e=new Blob([atob("Y29uc3QgdD0idmlkZW8vaDI2NCIsZT0idmlkZW8vaDI2NSI7ZnVuY3Rpb24gbih0LGUsbil7bGV0IGE9bmV3IFVpbnQ4QXJyYXkodCxlLG4pLHI9W10sbz0wO2Zvcig7ci5sZW5ndGg8bjspbyszPG4mJjA9PT1hW29dJiYwPT09YVtvKzFdJiYzPT09YVtvKzJdJiYoMD09PWFbbyszXXx8MT09PWFbbyszXXx8Mj09PWFbbyszXXx8Mz09PWFbbyszXSk/KHIucHVzaChhW29dLGFbbysxXSxhW28rM10pLG8rPTQpOihyLnB1c2goYVtvXSksbysrKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkocil9ZnVuY3Rpb24gYShhLHIpe3N3aXRjaChyKXtjYXNlIHQ6cmV0dXJuIGZ1bmN0aW9uKHQpe2NvbnN0IGU9bmV3IERhdGFWaWV3KHQuZGF0YSk7bGV0IGE9MDtmb3IoO2ErNDx0LmRhdGEuYnl0ZUxlbmd0aDspe2lmKDA9PT1lLmdldFVpbnQ4KGErMCkmJjA9PT1lLmdldFVpbnQ4KGErMSkmJjA9PT1lLmdldFVpbnQ4KGErMikmJjE9PT1lLmdldFVpbnQ4KGErMykmJjY9PT1lLmdldFVpbnQ4KGErNCkpe2xldCByPWErNixvPTAsaT0wO2Zvcig7MjU1PT09KGk9ZS5nZXRVaW50OChyKyspKTspbys9MjU1O28rPWk7Y29uc3Qgcz1uKHQuZGF0YSxyLG8pO3JldHVybiBuZXcgVWludDhBcnJheShzKX1hKyt9cmV0dXJuIG51bGx9KGEpO2Nhc2UgZTpyZXR1cm4gZnVuY3Rpb24odCl7Y29uc3QgZT1uZXcgRGF0YVZpZXcodC5kYXRhKTtsZXQgYT0wO2Zvcig7YSs1PHQuZGF0YS5ieXRlTGVuZ3RoOyl7aWYoMD09PWUuZ2V0VWludDgoYSswKSYmMD09PWUuZ2V0VWludDgoYSsxKSYmMD09PWUuZ2V0VWludDgoYSsyKSYmMT09PWUuZ2V0VWludDgoYSszKSYmNzg9PT1lLmdldFVpbnQ4KGErNCkmJjE9PT1lLmdldFVpbnQ4KGErNSkmJjEwMT09PWUuZ2V0VWludDgoYSs2KSl7bGV0IHI9YSs3LG89MCxpPTA7Zm9yKDsyNTU9PT0oaT1lLmdldFVpbnQ4KHIrKykpOylvKz0yNTU7bys9aTtjb25zdCBzPW4odC5kYXRhLHIsbyk7cmV0dXJuIG5ldyBVaW50OEFycmF5KHMpfWErK31yZXR1cm4gbnVsbH0oYSk7ZGVmYXVsdDpyZXR1cm4gbnVsbH19ZnVuY3Rpb24gcih0KXtjb25zdCBlPXQubGVuZ3RoO2xldCBuPVtdLGE9MDtmb3IoO2E8ZTspYSsyPGUmJjA9PT10W2FdJiYwPT09dFthKzFdJiYoMD09PXRbYSsyXXx8MT09PXRbYSsyXXx8Mj09PXRbYSsyXXx8Mz09PXRbYSsyXSk/KG4ucHVzaCh0W2FdLHRbYSsxXSwzLHRbYSsyXSksYSs9Myk6KG4ucHVzaCh0W2FdKSxhKyspO3JldHVybiBuZXcgVWludDhBcnJheShuKX1mdW5jdGlvbiBvKG4sYSxvKXtzd2l0Y2gobyl7Y2FzZSB0OnJldHVybiBmdW5jdGlvbih0LGUpe2NvbnN0IG49cihlKSxhPW4ubGVuZ3RoLG89TWF0aC5mbG9vcihhLzI1NSksaT1hJTI1NSxzPW5ldyBVaW50OEFycmF5KDYrbysxK2ErdC5ieXRlTGVuZ3RoKTtzWzBdPTAsc1sxXT0wLHNbMl09MCxzWzNdPTEsc1s0XT02LHNbNV09MTAxO2xldCBmPTA7Zm9yKDtmPG87KXNbNitmXT0yNTUsZisrO3JldHVybiBzWzYrZl09aSxmKysscy5zZXQobiw2K2YpLHMuc2V0KG5ldyBVaW50OEFycmF5KHQpLDYrZithKSxzLmJ1ZmZlcn0obixhKTtjYXNlIGU6cmV0dXJuIGZ1bmN0aW9uKHQsZSl7Y29uc3Qgbj1yKGUpLGE9bi5sZW5ndGgsbz1NYXRoLmZsb29yKGEvMjU1KSxpPWElMjU1LHM9bmV3IFVpbnQ4QXJyYXkoNytvKzErYSsxK3QuYnl0ZUxlbmd0aCk7c1swXT0wLHNbMV09MCxzWzJdPTAsc1szXT0xLHNbNF09Nzgsc1s1XT0xLHNbNl09MTAxO2xldCBmPTA7Zm9yKDtmPG87KXNbNytmXT0yNTUsZisrO3JldHVybiBzWzcrZl09aSxmKysscy5zZXQobiw3K2YpLGYrPWEsc1s3K2ZdPTEyOCxmKysscy5zZXQobmV3IFVpbnQ4QXJyYXkodCksNytmKSxzLmJ1ZmZlcn0obixhKTtkZWZhdWx0OnJldHVybi
1BudWxsfX1mdW5jdGlvbiBpKG4pe2lmKG4ubGVuZ3RoPDUpcmV0dXJuIiI7bGV0IGE9LTE7Zm9yKGxldCB0PTA7dDxuLmxlbmd0aC0zO3QrKyl7aWYoMD09PW5bdF0mJjA9PT1uW3QrMV0mJjE9PT1uW3QrMl0pe2E9dDticmVha31pZih0PG4ubGVuZ3RoLTQmJjA9PT1uW3RdJiYwPT09blt0KzFdJiYwPT09blt0KzJdJiYxPT09blt0KzNdKXthPXQ7YnJlYWt9fWlmKC0xPT09YSlyZXR1cm4iIjtjb25zdCByPWErKDA9PT1uW2ErMl0/NDozKTtpZihyPj1uLmxlbmd0aClyZXR1cm4iIjtjb25zdCBvPW5bcl07aWYoMTI4Jm8pcmV0dXJuIiI7aWYoKG8+PjEmNjMpPj0zMilyZXR1cm4gZTtpZihyKzE8bi5sZW5ndGgpe2lmKDA9PSgyNDgmbltyKzFdKSlyZXR1cm4gZX1yZXR1cm4oMzEmbyk8PTMxP3Q6IiJ9Y29uc3Qgcz03MSxmPTEsbD0yLHU9MSxnPTI7dmFyIGM7ZnVuY3Rpb24gZCh0LGU9ITEpe2NvbnN0IG49dC5nZXRVaW50OCgwKTtpZihuIT09cylyZXR1cm47Y29uc3QgYT10LmdldFVpbnQxNigxKSxyPWYrbCthLG89bmV3IFVpbnQ4QXJyYXkodC5ieXRlTGVuZ3RoLXIpO28uc2V0KG5ldyBVaW50OEFycmF5KHQuYnVmZmVyLHIsdC5ieXRlTGVuZ3RoLXIpKTtjb25zdCBpPXttOm4sdGx2TGVuOmEsdGx2OltdLGZyYW1lOm99O2xldCBkPWYrbDtmb3IoO2Q8cjspe2NvbnN0IG49dC5nZXRVaW50OChkKSxhPXQuZ2V0VWludDE2KGQrdSkscj11K2c7aWYobj09PWMuQVVESU9fTEVWRUwpe2xldCBvPXQuZ2V0VWludDgoZCtyKTtmb3IobGV0IGU9MTtlPGE7ZSsrKW89bzw8OHx0LmdldFVpbnQ4KGQrcitlKTtpLnRsdi5wdXNoKHt0YWc6bixsZW5ndGg6YSx2YWx1ZTplPzEyN15vPj4xOjEyNyZvfSl9ZWxzZSBpZihuPT09Yy5NRVRBREFUQXx8bj09PWMuQVVESU9fNjRfQklUX1BUUyl7Y29uc3QgZT1uZXcgVWludDhBcnJheShhKTtmb3IobGV0IG49MDtuPGE7bisrKWVbbl09dC5nZXRVaW50OChkK3Irbik7aS50bHYucHVzaCh7dGFnOm4sbGVuZ3RoOmEsdmFsdWU6ZX0pfWQrPXIrYX1yZXR1cm4gaX0hZnVuY3Rpb24odCl7dFt0LkFVRElPX0xFVkVMPTFdPSJBVURJT19MRVZFTCIsdFt0Lk1FVEFEQVRBPTJdPSJNRVRBREFUQSIsdFt0LkFVRElPXzY0X0JJVF9QVFM9M109IkFVRElPXzY0X0JJVF9QVFMifShjfHwoYz17fSkpLHNlbGYub25ydGN0cmFuc2Zvcm09dD0+e2NvbnN0IGU9dC50cmFuc2Zvcm1lcixuPVtdLHI9W107bGV0IGg9bnVsbDtlLm9wdGlvbnMucG9ydC5vbm1lc3NhZ2U9dD0+e3QuZGF0YS5zZWkmJm4ucHVzaCh0LmRhdGEuc2VpKSx0LmRhdGEubWV0YWRhdGEmJnIucHVzaCh0LmRhdGEubWV0YWRhdGEpfSxzZWxmLnBvc3RNZXNzYWdlKCJzdGFydGVkIik7Y29uc3QgcD1lLnJlYWRhYmxlLmdldFJlYWRlcigpLFU9ZS53cml0YWJsZS5nZXRXcml0ZXIoKTsic2VpLXJ4Ij09PWUub3B0aW9ucy5uYW1lP2Z1bmN0aW9uIHQoZSl7cC5yZWFkKCkudGhlbigobj0+e2lmKCFuLmRvbmUpe2lmKG4udmFsdWUgaW5zdGFuY2VvZiBSVENFbmNvZGVkVmlkZW9GcmFtZSl7Y29uc3QgdD1pKG5ldyBVaW50OEFycmF5KG4udmFsdWUuZGF0YSkpLHI9YShuLnZhbHVlLHQpO2lmKHImJmUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHtzZWk6cn0pLCFoKXtjb25zdCB0PW4udmFsdWUuZ2V0TWV0YWRhdGEoKXx8e307aD17dHlwZTpuLnZhbHVlLnR5cGUscnRwVGltZXN0YW1wOm4udmFsdWUudGltZXN0YW1wLHBheWxvYWRUeXBlOnQucGF5bG9hZFR5cGV8fDAsc3NyYzp0LnN5bmNocm9uaXphdGlvblNvdXJjZXx8MCxsZW5ndGg6bi52YWx1ZS5kYXRhLmJ5dGVMZW5ndGgsLi4uIm1pbWVUeXBlImluIHQ/e21pbWVUeXBlOnQubWltZVR5cGV9Ont9fSxlLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7Zmlyc3RGcmFtZUluZm86aH0pfX1VLndyaXRlKG4udmFsdWUpLGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQoZSl9fSkpfShlKToic2VpLXR4Ij09PWUub3B0aW9ucy5uYW1lP2Z1bmN0aW9uIHQoZSl7cC5yZWFkKCkudGhlbigoYT0+e2lmKCFhLmRvbmUpe2lmKGEudmFsdWUgaW5zdGFuY2VvZiBSVENFbmNvZGVkVmlkZW9GcmFtZSl7Y29uc3QgdD1pKG5ldyBVaW50OEFycmF5KGEudmFsdWUuZGF0YSkpLGU9bi5zaGlmdCgpO2lmKGUpe2NvbnN0IG49byhhLnZhbHVlLmRhdGEsZSx0KTtuJiYoYS52YWx1ZS5kYXRhPW4pfX1VLndyaXRlKGEudmFsdWUpLGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQoZSl9fSkpfShlKToiYXVkaW8tbWV0YWRhdGEtcngiPT09ZS5vcHRpb25zLm5hbWU/ZnVuY3Rpb24gdChlKXtwLnJlYWQoKS50aGVuKChuPT57aWYoIW4uZG9uZSl7aWYobi52YWx1ZSBpbnN0YW5jZW9mIFJUQ0VuY29kZWRBdWRpb0ZyYW1lKXtjb25zdCB0PW5ldyBEYXRhVmlldyhuLnZhbHVlLmRhdGEpLGE9dC5nZXRVaW50OCgwKTtsZXQgcjtpZigwIT0oMTI4JmEpJiY3MSE9PWEpe2NvbnN0IGU9ZnVuY3Rpb24odCl7aWYodC5ieXRlTGVuZ3RoPD0wKXJldHVybltdO2NvbnN0IGU9W107bGV0IG49MDtmb3IoO248dC5ieXRlTGVuZ3RoOyl7Y29uc3QgYT0oMTI4JnQuZ2V0VWludDgobikpPj43LHI9MTI3JnQuZ2V0VWludDgobik7aWYoIShhJiZuKzQ8PXQuYnl0ZUxlbmd0aCkpe24rKzticmVha317Y29uc3QgYT10LmdldFVpbnQzMihuLCExKSxvPSgxNjc3NjE5MiZhKT4+MTAsaT0xMDIzJmE7ZS5wdXNoKHtwdDpyLHRzX29mZnNldDpvLGxlbmd0aDppLGRhdGE6bmV3IFVpbnQ4QXJyYXl9KSxuKz00fX1sZXQgYT10LmJ5dGVMZW5ndGgtbjtmb3IoY29uc3QgciBvZiBlKXtpZihyLmxlbmd0aD5hKXJldHVybiBjb25zb2xlLndhcm4oIkJyb2tlbiByZWQgcGF5bG9hZCIpLFtdO3IubGVuZ3RoPjAmJihyLmRhdGE9bmV3IFVpbnQ4QXJyYXkodC5idWZmZXIsdC5ieXRlT2Zmc2V0K24sci5sZW5ndGgpLG4rPXIubGVuZ3RoLGEtPXIubGVuZ3RoKX1pZihhPjApe2NvbnN0IHI9e3B0OmUubGVuZ3RoPjA/ZVtlLmxlbmd0aC0xXS5wdDowLHRzX29mZnNldDowLGxlbmd0aDphLGRhdGE6bmV3IFVpbnQ4QXJyYXkodC5idWZmZXIsdC5ieXRlT2Zmc2V0K24sYSl9O2UucHVzaChyKX1yZXR1cm4gZX0odCk7aWYoZS5sZW5ndGg+MCl7Y29uc3QgdD1mdW5jdGlvbih0KXtsZXQgZT0wO2ZvcihsZXQgbj0wO248dC5sZW5ndGg7bisrKWUrPW48dC5sZW5ndGgtMT80OjEsZSs9dFtuXS5sZW5ndGg7Y29uc3Qgbj1uZXcgVWludDhBcnJheShlKTtsZXQgYT0wO2ZvcihsZXQgZT0wO2U8dC5sZW5ndGg7ZSsrKWlmKGU8dC5sZW5ndGgtMSl7Y29uc3Qgcj0oMjE0NzQ4MzY0OHwoMTI3JnRbZV0ucHQpPDwyNHwoMjYyMTQzJnRbZV0udHNfb2Zmc2V0KT
1w8MTB8MTAyMyZ0W2VdLmxlbmd0aCk+Pj4wO25bYSsrXT1yPj4yNCYyNTUsblthKytdPXI+PjE2JjI1NSxuW2ErK109cj4+OCYyNTUsblthKytdPTI1NSZyfWVsc2UgblthKytdPTEyNyZ0W2VdLnB0O2Zvcihjb25zdCBlIG9mIHQpbi5zZXQoZS5kYXRhLGEpLGErPWUubGVuZ3RoO3JldHVybiBufShlLm1hcCgodD0+e2NvbnN0IGU9bmV3IFVpbnQ4QXJyYXkodC5sZW5ndGgpO2Uuc2V0KHQuZGF0YSk7Y29uc3Qgbj1kKG5ldyBEYXRhVmlldyhlLmJ1ZmZlcikpO3JldHVybiBuPy5mcmFtZSYmKHQuZGF0YT1uPy5mcmFtZSkscj1uLHR9KSkpO24udmFsdWUuZGF0YT10LmJ1ZmZlcn19ZWxzZSByPWQodCksciYmKG4udmFsdWUuZGF0YT1yLmZyYW1lLmJ1ZmZlcik7aWYocil7bGV0IHQ9ci50bHYuZmluZCgodD0+dC50YWc9PT1jLk1FVEFEQVRBKSk7aWYodCYmdC52YWx1ZSBpbnN0YW5jZW9mIFVpbnQ4QXJyYXkmJmUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHttZXRhZGF0YTp0LnZhbHVlfSksdD1yLnRsdi5maW5kKCh0PT50LnRhZz09PWMuQVVESU9fNjRfQklUX1BUUykpLHQmJnQudmFsdWUgaW5zdGFuY2VvZiBVaW50OEFycmF5JiY4PT10LnZhbHVlLmxlbmd0aCl7Y29uc3Qgbj1uZXcgRGF0YVZpZXcodC52YWx1ZS5idWZmZXIpLmdldEJpZ1VpbnQ2NCgwLCEwKTt0JiZ0LnZhbHVlIGluc3RhbmNlb2YgVWludDhBcnJheSYmZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe3B0czpufSl9fX1VLndyaXRlKG4udmFsdWUpLGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQoZSl9fSkpfShlKToiYXVkaW8tbWV0YWRhdGEtdHgiPT09ZS5vcHRpb25zLm5hbWUmJmZ1bmN0aW9uIHQoZSl7cC5yZWFkKCkudGhlbigobj0+e2lmKCFuLmRvbmUpe2lmKGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHtnZXRNZXRhZGF0YTohMH0pLG4udmFsdWUgaW5zdGFuY2VvZiBSVENFbmNvZGVkQXVkaW9GcmFtZSl7Y29uc3QgdD1yLnNoaWZ0KCk7dCYmKG4udmFsdWUuZGF0YT1mdW5jdGlvbih0LGUsbil7Y29uc3QgYT1uLmJ5dGVMZW5ndGgscj1hK3UrZyxvPWYrbCtyLGk9bmV3IEFycmF5QnVmZmVyKHQuYnl0ZUxlbmd0aCtvKSxjPW5ldyBEYXRhVmlldyhpKTtjLnNldFVpbnQ4KDAscyksYy5zZXRVaW50MTYoMSxyKSxjLnNldFVpbnQ4KDMsZSksYy5zZXRVaW50MTYoNCxhKTtmb3IobGV0IHQ9MDt0PGE7dCsrKWMuc2V0VWludDgoNit0LG5bdF0pO2NvbnN0IGQ9bmV3IFVpbnQ4QXJyYXkoYy5idWZmZXIpO3JldHVybiBkLnNldChuZXcgVWludDhBcnJheSh0KSxvKSxkLmJ1ZmZlcn0obi52YWx1ZS5kYXRhLGMuQVVESU9fNjRfQklUX1BUUyx0KSl9VS53cml0ZShuLnZhbHVlKSxlLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7dHJhbnNmb3JtZWQ6ITB9KSx0KGUpfX0pKX0oZSl9LHNlbGYucG9zdE1lc3NhZ2UoInJlZ2lzdGVyZWQiKTsK")],{type:"text/javascript"});return setTimeout(()=>uk.revokeObjectURL(e),0),new Worker(uk.createObjectURL(e))}var CH=((eh=CH||{})[eh.AUDIO_LEVEL=1]="AUDIO_LEVEL",eh[eh.METADATA=2]="METADATA",eh[eh.AUDIO_64_BIT_PTS=3]="AUDIO_64_BIT_PTS",eh);function CK(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=e.getUint8(0);if(71!==i)return;let r=e.getUint16(1),n=3+r,o=new Uint8Array(e.byteLength-n);o.set(new Uint8Array(e.buffer,n,e.byteLength-n));let a={m:i,tlvLen:r,tlv:[],frame:o},s=3;for(;s<n;){let i=e.getUint8(s),r=e.getUint16(s+1);if(i===CH.AUDIO_LEVEL){let n=e.getUint8(s+3);for(let t=1;t<r;t++)n=n<<8|e.getUint8(s+3+t);a.tlv.push({tag:i,length:r,value:t?127^n>>1:127&n})}else if(i===CH.METADATA||i===CH.AUDIO_64_BIT_PTS){let t=new Uint8Array(r);for(let i=0;i<r;i++)t[i]=e.getUint8(s+3+i);a.tlv.push({tag:i,length:r,value:t})}s+=3+r}return a}let CY=new Map,Cz=139/13,Cq=new Map;function CX(e,t,i){let r="".concat(e,"-").concat(t,"-").concat(i),n=0;return Cq.has(r)?n=Cq.get(r):(n=Math.log(function(e,t){let i=e-t;t<i&&(t=i);let r=1;for(let i=e,n=1;i>t;i--,n++)r=r*i/n;return r}(t,e))+e*Math.log(.5)+(t-e)*Math.log(.5)-Math.log(i)+i*e,Cq.set(r,n)),n<1e-10&&(n=1e-10),n}function CJ(e,t,i){let r=t.length,n=e.length/r,o=!1;for(let a=0,s=0;a<r;a++){let r=0;for(let t=s+n;s<t;s++)e[s]>i&&r++;t[a]!==r&&(t[a]=r,o=!0)}return o}window.cache=Cq;let CQ=0;class CZ{computeImmediates(){let e=this.immediates,t=this.levels,i=this.minLevel+Cz,r=!1;for(let n=0;n<e.length;++n){let o=t[n];o<i&&(o=0);let a=Math.floor(o/Cz);e[n]!==a&&(e[n]=a,r=!0)}return r}computeLongs(){return CJ(this.mediums,this.longs,4)}computeMediums(){return CJ(this.immediates,this.mediums,7)}evaluateImmediateSpeechActivityScore(){this.immediateSpeechActivityScore=CX(this.immediates[0],13,.78)}evaluateLongSpeechActivityScore(e){this.longSpeechActivityScore=CX(this.longs[0],10,47),this.longSpeechActivityScore>1e-10&&(this.lastNonSilence=e)}evaluateMediumSpeechActivityScore(){this.mediumSpeechActivityScore=CX(this.mediums[0],5,24)}evaluateSpeechActivityScores(e){this.computeImmediates()&&(this.evaluateImmediateSpeechActivityScore(),this.computeMediums()&&(this.evaluateMediumSpeechActivityScore(),this.computeLongs()&&this.evaluateLongSpeechActivityScore(e)))}getLastLevelChangedTime(){return this.lastLevelChangedTime}getLevels(){var e;return"[".concat(a_(e=[...this.levels]).call(e).join(),"]")}getSpeechActivityScore(e){switch(e){case 0:return this.immediateSpeechActivityScore;case 1:return this.mediumSpeechActivityScore;case 2:return this.longSpeechActivityScore;default:throw Error("interval "+e)}}levelChanged(e,t){if(this.lastLevelChangedTime<=t){this.lastLevelChangedTime=t;let i=e;return e<0&&(i=0),e>127&&(i=127),this.levels.unshift(i),this.levels.length>this.immediates.length&&this.levels.pop(),this.updateMinLevel(i),i>=this.minLevel+Cz?i:i/2}return -1}levelTimedOut(){this.levelChanged(0,this.lastLevelChangedTime)}updateMinLevel(e){if(0!==e){if(0===this.minLevel||this.minLevel>e)return this.minLevel=e,this.nextMinLevel=0,void(this.nextMinLevelWindowLength=0);if(0===this.nextMinLevel)return this.nextMinLevel=e,void(this.nextMinLevelWindowLength=1);if(this.nextMinLevel>e&&(this.nextMinLevel=e),this.nextMinLevelWindowLength++,this.nextMinLevelWindowLength>=750){let e=Math.sqrt(this.minLevel*this.nextMinLevel);e<0?e=0:e>127&&(e=127),this.minLevel=e,this.nextMinLevel=0,this.nextMinLevelWindowLength=0}}}constructor(e){RV(this,"id",void 0),RV(this,"immediates",[]),RV(this,"lastNonSilence",-1),RV(this,"immediateSpeechActivityScore",1e-10),RV(this,"lastLevelChangedTime",Date.now()),RV(this,"levels",[]),RV(this,"longs",[]),RV(this,"longSpeechActivityScore",1e-10),RV(this,"mediums",[]),RV(this,"mediumSpeechActivityScore",1e-10),RV(this,"minLevel",0),RV(this,"nextMinLevel",0),RV(this,"nextMinLevelWindowLength",0),RV(this,"energyScore",0),this.id=e||"".concat(CQ++),this.immediates.length=50,this.mediums.length=10,this.longs.length=1,this.levels.length=this.immediates.length}}class C${execute(){let e=!this.algorithm;if(!e)try{let t=this.algorithm.runInDecisionMaker(this);t<=0?e=!0:setTimeout(this.execute.bind(this),t)}catch(t){e=!0}e&&this.algorithm&&this.algorithm.decisionMakerExited(this)}constructor(e){RV(this,"algorithm",void 0),this.algorithm=e}}class C0{constructor(e,t,i){RV(this,"isDominant",void 0),RV(this,"energyRanking",void 0),RV(this,"energyScore",void 0),this.isDominant=e,this.energyRanking=t,this.energyScore=i}}class C1 extends S0{setLoudestConfig(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3,t=arguments.length>1?arguments[1]:void 0,i=arguments.length>2?arguments[2]:void 0;this.numLoudestToTrack=e,null!=t&&(this.energyExpireTimeMs=t),null!=i&&(this.energyAlphaPct=i),this.loudest.length>e&&this.loudest.splice(e)}getDominantSpeaker(){return this.dominantId}isAmongLoudest(e){return this.loudest.some(t=>t.id===e)}levelChanged(e,t){let i=Date.now(),r=this.getOrCreateSpeaker(e);this.lastLevelChangedTime<i&&(this.lastLevelChangedTime=i,this.maybeStartDecisionMaker());let n=r.levelChanged(t,i);return this.updateLoudestList(r,n,i)}runInDecisionMaker(e){return this.decisionMaker!==e||this.lastDecisionTime>0&&this.lastDecisionTime-this.lastLevelChangedTime>=15e3?-1:this._runInDecisionMaker()}decisionMakerExited(e){this.decisionMaker===e&&(this.decisionMaker=null)}destroy(){this.decisionMaker=null,this.loudest.length=0,this.speakers.clear(),this.removeAllListeners()}
1addSpeakers(e){e.forEach(e=>{this.speakers.has(e.id)||this.speakers.set(e.id,e)})}removeSpeakers(e){e.forEach(e=>{this.speakers.delete(e.id)})}getOrCreateSpeaker(e){let t=this.speakers.get(e);return t||(t=new CZ(e),this.speakers.set(e,t),this.maybeStartDecisionMaker()),t}updateLoudestList(e,t,i){let r=e.id===this.dominantId;if(t<0){let t=0;for(;t<this.loudest.length&&this.loudest[t]!==e;)++t;return new C0(r,t,e.energyScore)}if(e.energyScore=Math.floor((this.energyAlphaPct*t+(100-this.energyAlphaPct)*e.energyScore+50)/100),0===this.numLoudestToTrack)return new C0(r,0,e.energyScore);let n=i-this.energyExpireTimeMs,o=0;for(;o<this.loudest.length;){let t=this.loudest[o];if(t.getLastLevelChangedTime()<n&&this.loudest.length>=this.numLoudestToTrack)this.loudest.splice(o,1);else if(t.id!==e.id)++o;else if(this.loudest.splice(o,1),this.loudest.length<this.numLoudestToTrack)break}let a=0;for(;a<this.loudest.length&&!(this.loudest[a].energyScore<e.energyScore);)++a;return a<this.numLoudestToTrack&&(this.loudest.splice(a,0,e),this.loudest.length>this.numLoudestToTrack&&this.loudest.splice(this.numLoudestToTrack,1)),new C0(r,a,e.energyScore)}maybeStartDecisionMaker(){!this.decisionMaker&&this.speakers.size>0&&(this.decisionMaker=new C$(this),this.decisionMaker.execute())}makeDecision(e){let t=null,i=null,r=this.speakers.size,n=null;if(0===r)n=null;else if(1===r){var o;let t=d1(o=this.speakers).call(o).next().value;this.enableSilence&&t&&(n=t.id,t.evaluateSpeechActivityScores(e),e-t.lastNonSilence>this.timeoutToSilenceInterval&&(n=null))}else{let t=null==this.dominantId?null:this.speakers.get(this.dominantId);if(null==t){let e=this.speakers.entries().next();e.value&&(n=e.value[0],t=e.value[1])}else n=t.id;null!=t&&t.evaluateSpeechActivityScores(e);let i=this.relativeSpeechActivities,r=2;for(let o of this.speakers.entries()){let[a,s]=o;if(s===t)continue;s.evaluateSpeechActivityScores(e);for(let e=0;e<i.length;++e){let r=null==t?1e-10:t.getSpeechActivityScore(e);i[e]=Math.log(s.getSpeechActivityScore(e)/r)}let c=i[0],d=i[1],l=i[2];c>3&&d>2&&l>0&&d>r&&(r=d,n=a)}this.enableSilence&&null!=t&&n===t.id&&e-t.lastNonSilence>this.timeoutToSilenceInterval&&(n=null)}(null!=n||this.enableSilence)&&n!==this.dominantId&&(t=this.dominantId,this.dominantId=n,i=this.dominantId),(null!=i||this.enableSilence)&&i!==t&&this.emit("ActiveSpeakerChanged",i)}_runInDecisionMaker(){let e=Date.now(),t=300-(e-this.lastLevelIdleTime),i=0;t<=0?(0!==this.lastLevelIdleTime&&this.timeoutIdleLevels(e),this.lastLevelIdleTime=e):i=t;let r=300-(e-this.lastDecisionTime);return r<=0&&(this.lastDecisionTime=e,this.makeDecision(e),r=300-(Date.now()-e)),r>0&&i>r&&(i=r),i}timeoutIdleLevels(e){let t=[];for(let r of d1(i=this.speakers).call(i)){var i;let n=e-r.getLastLevelChangedTime();36e5<n&&(null==this.dominantId||r.id!==this.dominantId)?t.push(r.id):300<n&&r.levelTimedOut()}t.forEach(e=>this.speakers.delete(e))}constructor(e){super(),RV(this,"dominantId",null),RV(this,"lastDecisionTime",0),RV(this,"lastLevelChangedTime",0),RV(this,"lastLevelIdleTime",0),RV(this,"relativeSpeechActivities",[]),RV(this,"speakers",new Map),RV(this,"enableSilence",!1),RV(this,"timeoutToSilenceInterval",0),RV(this,"decisionMaker",null),RV(this,"loudest",[]),RV(this,"numLoudestToTrack",3),RV(this,"energyExpireTimeMs",250),RV(this,"energyAlphaPct",50),this.timeoutToSilenceInterval=e,this.enableSilence=e>0,this.relativeSpeechActivities.length=3}}let C2=new Map,C3=null,C5=null,C4=[],C6=new Map,C8=new Map;class C9{get samples(){return this.actives+this.inactives}get activeRate(){return this.actives/this.samples}autoCheckActive(){this.autoSetActive(),this.autoAdjustActive(),this.resetTimer(),this.actives=0,this.inactives=0}autoSetActive(){let e=this.active;this.active=this.activeRate>=.8;let{actives:t,inactives:i}=function(){let e=[],t=[];return Array.from(d1(C6).call(C6)).forEach(i=>{i.active?e.push(i):t.push(i)}),{actives:e,inactives:t}}();if(t.length>3){let e;t.forEach(t=>{(!e||e.score>t.score)&&(e=t)}),e&&e.setActive(!1)}if(t.length<3&&i.length>0){let t;i.forEach(e=>{(!t||t.score<e.score)&&e.id!==this.id&&(t=e)}),t&&e&&!this.active&&(t.samples>40&&t.activeRate-this.activeRate>.4?t.setActive(!0):this.active=!0)}this.setMuted(!this.active)}setActive(e){this.active=e,this.resetTimer(),this.setMuted(!e)}autoAdjustActive(){this.active?this.autoSwitchToInactive():this.autoSwitchToActive()}autoSwitchToActive(){var e;
1let t,i=(e=this.id,Array.from(d1(C6).call(C6)).forEach(i=>{!i.active||i.id===e||i.samples<40||(!t||i.score<t.score)&&(t=i)}),t);i&&this.activeRate-i.activeRate>.4&&(i.setActive(!1),this.setActive(!0))}autoSwitchToInactive(){var e;let t,i=(e=this.id,Array.from(d1(C6).call(C6)).forEach(i=>{i.active||i.id===e||i.samples<40||(!t||i.score>t.score)&&(t=i)}),t);i&&i.activeRate-this.activeRate>.4&&(i.setActive(!0),this.setActive(!1))}addSample(e){e?this.actives+=1:this.inactives+=1,this.samples>66.66666666666667&&this.autoCheckActive()}setMuted(e){this.track&&(this.track.enabled=!e,this.muted=e)}resetTimer(){this.clearTimer(),this.timer=window.setTimeout(()=>{if(0!==this.samples)return this.samples<50?this.resetTimer():void this.autoCheckActive()},1e3)}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=0)}constructor(e,t){RV(this,"id",void 0),RV(this,"track",void 0),RV(this,"score",0),RV(this,"active",!0),RV(this,"muted",!1),RV(this,"timer",0),RV(this,"actives",0),RV(this,"inactives",0),this.id=e,this.track=t,this.setActive(C6.size<3)}}function C7(e){let t=C6.get(e);t&&(C6.delete(e),t.clearTimer())}let ve=new Map,vt=new Map,vi="video/h264",vr="video/h265";function vn(e,t,i){let r=new Uint8Array(e,t,i),n=[],o=0;for(;n.length<i;)o+3<i&&0===r[o]&&0===r[o+1]&&3===r[o+2]&&(0===r[o+3]||1===r[o+3]||2===r[o+3]||3===r[o+3])?(n.push(r[o],r[o+1],r[o+3]),o+=4):(n.push(r[o]),o++);return new Uint8Array(n)}function vo(e){let t=e.length,i=[],r=0;for(;r<t;)r+2<t&&0===e[r]&&0===e[r+1]&&(0===e[r+2]||1===e[r+2]||2===e[r+2]||3===e[r+2])?(i.push(e[r],e[r+1],3,e[r+2]),r+=3):(i.push(e[r]),r++);return new Uint8Array(i)}function va(e){if(e.length<5)return"";let t=-1;for(let i=0;i<e.length-3;i++)if(0===e[i]&&0===e[i+1]&&1===e[i+2]||i<e.length-4&&0===e[i]&&0===e[i+1]&&0===e[i+2]&&1===e[i+3]){t=i;break}if(-1===t)return"";let i=t+(0===e[t+2]?4:3);if(i>=e.length)return"";let r=e[i];return 128&r?"":(r>>1&63)>=32||i+1<e.length&&0==(248&e[i+1])?vr:(31&r)<=31?vi:""}let vs=new Map,vc=new Map,vd=St();T1.getDisplayMedia=!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia),T1.getStreamFromExtension=vd.name===f8.CHROME&&Number(vd.version)>34,T1.supportUnifiedPlan=function(){if(!window.RTCRtpTransceiver||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=new RTCPeerConnection,t=!1;try{e.addTransceiver("audio"),t=!0}catch(e){}return e.close(),t}(),T1.supportMinBitrate=vd.name===f8.CHROME||vd.name===f8.EDGE,T1.supportSetRtpSenderParameters=function(){let e=St();return!!(window.RTCRtpSender&&window.RTCRtpSender.prototype.setParameters&&window.RTCRtpSender.prototype.getParameters)&&(!!SN()||!(!Ss()&&!So())||e.name===f8.FIREFOX&&Number(e.version)>=64)}(),vd.name===f8.SAFARI&&(Number(vd.version)>=14?T1.supportDualStream=!0:T1.supportDualStream=!1),T1.webAudioMediaStreamDest=function(){let e=St();return!(e.name===f8.SAFARI&&12>Number(e.version))}(),T1.supportReplaceTrack=!!window.RTCRtpSender&&"function"==typeof RTCRtpSender.prototype.replaceTrack,T1.supportWebGL="undefined"!=typeof WebGLRenderingContext,T1.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,SN()||(T1.webAudioWithAEC=!0),T1.supportShareAudio=function(){let e=St();return(e.os===f6.WIN_10||e.os===f6.WIN_81||e.os===f6.WIN_7||e.os===f6.LINUX||e.os===f6.MAC_OS||e.os===f6.CHROMIUM_OS)&&e.name===f8.CHROME&&Number(e.version)>=74}(),T1.supportDataChannel=!!(Su(76)||Sm(68)||Sf(14)),T1.supportPCSetConfiguration=function(){let e=window.RTCPeerConnection;return!Sl()&&!!e&&e.prototype.setConfiguration instanceof Function}(),T1.supportWebRTCEncodedTransform=Su(87)||Sc()||Sm(117),T1.supportWebRTCInsertableStream=function(){let e=St();return(e.name===f8.CHROME||e.name===f8.EDGE)&&Number(e.version)>=94&&"MediaStreamTrackGenerator"in window&&"MediaStreamTrackProcessor"in window}(),T1.supportRequestVideoFrameCallback="requestVideoFrameCallback"in HTMLVideoElement.prototype,T1.supportWebCrypto="undefined"!=typeof window&&void 0!==window.crypto&&void 0!==window.crypto.subtle,T1.supportSuppressLocalAudioPlayback=T8(),T1.supportRestrictOwnAudio=T9(),gf(()=>{T1.supportDualStreamEncoding=function(){let e=St();return!!TR("DISABLE_WEBAUDIO")||"Safari"===e.name&&Number(e.version)>=14||!!("Chrome"===e.name&&/Windows/i.test(e.os||"")&&Number(e.version)>=100&&TR("CHROME_DUAL_STREAM_USE_ENCODING"))}(),TY.debug("browser ua: ",navigator.userAgent),TY.info("browser info: ",vd),TY.info("browser compatibility: ",T1)});let vl=["CHINA","GLOBAL"],vh=[[0,1,2,3,4,5,5],[0,2,2,3,4,5,5],[0,3,3,3,4,5,5],[0,4,4,4,4,5,5],[0,5,5,5,5,5,5]],vu=[],vp=[];function v_(e,t){return!!t&&vu.some(i=>i.uid===e&&i.channelName===t)}function vE(){return vp.length>0}
1var vm=Eg.forEach,vf=o7("forEach")?[].forEach:function(e){return vm(this,e,arguments.length>1?arguments[1]:void 0)};oI({target:"Array",proto:!0,forced:[].forEach!==vf},{forEach:vf});var vS=oF("Array","forEach"),vg=Array.prototype,vT={DOMTokenList:!0,NodeList:!0},vR=rW(function(e){var t=e.forEach;return e===vg||rJ(vg,e)&&t===vg.forEach||nq(vT,oX(e))?vS:t});oI({target:"Object",stat:!0,forced:rH(function(){aV(1)})},{keys:function(e){return aV(nY(e))}});var vC=rW(nf.Object.keys),vv=rW(aa),vy=rW(ap),vI=Eo("slice"),vA=n2("species"),vb=Array,vO=Math.max;oI({target:"Array",proto:!0,forced:!vI},{slice:function(e,t){var i,r,n,o=nE(this),a=oM(o),s=oP(e,a),c=oP(void 0===t?a:t,a);if(ac(o)&&((cs(i=o.constructor)&&(i===vb||ac(i.prototype))||nm(i)&&null===(i=i[vA]))&&(i=void 0),i===vb||void 0===i))return cu(o,s,c);for(r=new(void 0===i?vb:i)(vO(c-s,0)),n=0;s<c;s++,n++)s in o&&hr(r,n,o[s]);return r.length=n,r}});var vw=oF("Array","slice"),vN=Array.prototype,vD=rW(function(e){var t=e.slice;return e===vN||rJ(vN,e)&&t===vN.slice?vw:t});function vP(e,t,i,r,n){var o,a,s,c={};return vR(o=vC(r)).call(o,function(e){c[e]=r[e]}),c.enumerable=!!c.enumerable,c.configurable=!!c.configurable,("value"in c||c.initializer)&&(c.writable=!0),c=vv(a=vy(s=vD(i).call(i)).call(s)).call(a,function(i,r){return r(e,t,i)||i},c),n&&void 0!==c.initializer&&(c.value=c.initializer?c.initializer.call(n):void 0,c.initializer=void 0),void 0===c.initializer?(_9(e,t,c),null):c}let vL=((eu={})[eu.ACCESS_POINT=101]="ACCESS_POINT",eu[eu.UNILBS=201]="UNILBS",eu[eu.STRING_UID_ALLOCATOR=901]="STRING_UID_ALLOCATOR",eu),vk=((ep={})[ep.IIIEGAL_APPID=1]="IIIEGAL_APPID",ep[ep.IIIEGAL_UID=2]="IIIEGAL_UID",ep[ep.INTERNAL_ERROR=3]="INTERNAL_ERROR",ep),vM=((e_={})[e_.INVALID_VENDOR_KEY=5]="INVALID_VENDOR_KEY",e_[e_.INVALID_CHANNEL_NAME=7]="INVALID_CHANNEL_NAME",e_[e_.INTERNAL_ERROR=8]="INTERNAL_ERROR",e_[e_.NO_AUTHORIZED=9]="NO_AUTHORIZED",e_[e_.DYNAMIC_KEY_TIMEOUT=10]="DYNAMIC_KEY_TIMEOUT",e_[e_.NO_ACTIVE_STATUS=11]="NO_ACTIVE_STATUS",e_[e_.DYNAMIC_KEY_EXPIRED=13]="DYNAMIC_KEY_EXPIRED",e_[e_.STATIC_USE_DYNAMIC_KEY=14]="STATIC_USE_DYNAMIC_KEY",e_[e_.DYNAMIC_USE_STATIC_KEY=15]="DYNAMIC_USE_STATIC_KEY",e_[e_.USER_OVERLOAD=16]="USER_OVERLOAD",e_[e_.FORBIDDEN_REGION=18]="FORBIDDEN_REGION",e_[e_.CANNOT_MEET_AREA_DEMAND=19]="CANNOT_MEET_AREA_DEMAND",e_[e_.REQ_DOWNGRADE_FALLBACK=27]="REQ_DOWNGRADE_FALLBACK",e_),vU=((eE={})[eE.NO_FLAG_SET=100]="NO_FLAG_SET",eE[eE.FLAG_SET_BUT_EMPTY=101]="FLAG_SET_BUT_EMPTY",eE[eE.INVALID_FALG_SET=102]="INVALID_FALG_SET",eE[eE.FLAG_SET_BUT_NO_RE=103]="FLAG_SET_BUT_NO_RE",eE[eE.INVALID_SERVICE_ID=104]="INVALID_SERVICE_ID",eE[eE.NO_SERVICE_AVAILABLE=200]="NO_SERVICE_AVAILABLE",eE[eE.NO_SERVICE_AVAILABLE_P2P=201]="NO_SERVICE_AVAILABLE_P2P",eE[eE.NO_SERVICE_AVAILABLE_VOICE=202]="NO_SERVICE_AVAILABLE_VOICE",eE[eE.NO_SERVICE_AVAILABLE_WEBRTC=203]="NO_SERVICE_AVAILABLE_WEBRTC",eE[eE.NO_SERVICE_AVAILABLE_CDS=204]="NO_SERVICE_AVAILABLE_CDS",eE[eE.NO_SERVICE_AVAILABLE_CDN=205]="NO_SERVICE_AVAILABLE_CDN",eE[eE.NO_SERVICE_AVAILABLE_TDS=206]="NO_SERVICE_AVAILABLE_TDS",eE[eE.NO_SERVICE_AVAILABLE_REPORT=207]="NO_SERVICE_AVAILABLE_REPORT",eE[eE.NO_SERVICE_AVAILABLE_APP_CENTER=208]="NO_SERVICE_AVAILABLE_APP_CENTER",eE[eE.NO_SERVICE_AVAILABLE_ENV0=209]="NO_SERVICE_AVAILABLE_ENV0",eE[eE.NO_SERVICE_AVAILABLE_VOET=210]="NO_SERVICE_AVAILABLE_VOET",eE[eE.NO_SERVICE_AVAILABLE_STRING_UID=211]="NO_SERVICE_AVAILABLE_STRING_UID",eE[eE.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS=212]="NO_SERVICE_AVAILABLE_WEBRTC_UNILBS",eE[eE.NO_SERVICE_AVAILABLE_UNILBS_FLV=213]="NO_SERVICE_AVAILABLE_UNILBS_FLV",eE),vx=((em={})[em.K_TIMESTAMP_EXPIRED=2]="K_TIMESTAMP_EXPIRED",em[em.K_CHANNEL_PERMISSION_INVALID=3]="K_CHANNEL_PERMISSION_INVALID",em[em.K_CERTIFICATE_INVALID=4]="K_CERTIFICATE_INVALID",em[em.K_CHANNEL_NAME_EMPTY=5]="K_CHANNEL_NAME_EMPTY",em[em.K_CHANNEL_NOT_FOUND=6]="K_CHANNEL_NOT_FOUND",em[em.K_TICKET_INVALID=7]="K_TICKET_INVALID",em[em.K_CHANNEL_CONFLICTED=8]="K_CHANNEL_CONFLICTED",em[em.K_SERVICE_NOT_READY=9]="K_SERVICE_NOT_READY",em[em.K_SERVICE_TOO_HEAVY=10]="K_SERVICE_TOO_HEAVY",em[em.K_UID_BANNED=14]="K_UID_BANNED",em[em.K_IP_BANNED=15]="K_IP_BANNED",em[em.K_CHANNEL_BANNED=16]="K_CHANNEL_BANNED",em[em.DATASTREAM2_NOT_AVAILABLE=27]="DATASTREAM2_NOT_AVAILABLE",em[em.K_AUTO_REBALANCE=28]="K_AUTO_REBALANCE",em[em.K_VOS_FALLBACK=30]="K_VOS_FALLBACK",em[em.WARN_NO_AVAILABLE_CHANNEL=103]="WARN_NO_AVAILABLE_CHANNEL",em[em.WARN_LOOKUP_CHANNEL_TIMEOUT=104]="WARN_LOOKUP_CHANNEL_TIMEOUT",em[em.WARN_LOOKUP_CHANNEL_REJECTED=105]="WARN_LOOKUP_CHANNEL_REJECTED",em[em.WARN_OPEN_CHANNEL_TIMEOUT=106]="WARN_OPEN_CHANNEL_TIMEOUT",em[em.WARN_OPEN_CHANNEL_REJECTED=107]="WARN_OPEN_CHANNEL_REJECTED",em[em.WARN_REQUEST_DEFERRED=108]="WARN_REQUEST_DEFERRED",em[em.ERR_DYNAMIC_KEY_TIMEOUT=109]="ERR_DYNAMIC_KEY_TIMEOUT",em[em.ERR_NO_AUTHORIZED=110]="ERR_NO_AUTHORIZED",em[em.ERR_VOM_SERVICE_UNAVAILABLE=111]="ERR_VOM_SERVICE_UNAVAILABLE",em[em.ERR_NO_CHANNEL_AVAILABLE_CODE=112]="ERR_NO_CHANNEL_AVAILABLE_CODE",em[em.ERR_MASTER_VOCS_UNAVAILABLE=114]="ERR_MASTER_VOCS_UNAVAILABLE",em[em.ERR_INTERNAL_ERROR=115]="ERR_INTERNAL_ERROR",em[em.ERR_NO_ACTIVE_STATUS=116]="ERR_NO_ACTIVE_STATUS",em[em.ERR_INVALID_UID=117]="ERR_INVALID_UID",em[em.ERR_DYNAMIC_KEY_EXPIRED=118]="ERR_DYNAMIC_KEY_EXPIRED",em[em.ERR_STATIC_USE_DYANMIC_KE=119]="ERR_STATIC_USE_DYANMIC_KE",em[em.ERR_DYNAMIC_USE_STATIC_KE=120]="ERR_DYNAMIC_USE_STATIC_KE",em[em.ERR_NO_VOCS_AVAILABLE=2e3]="ERR_NO_VOCS_AVAILABLE",em[em.ERR_NO_VOS_AVAILABLE=2001]="ERR_NO_VOS_AVAILABLE",em[em.ERR_JOIN_CHANNEL_TIMEOUT=2002]="ERR_JOIN_CHANNEL_TIMEOUT",em[em.ERR_REPEAT_JOIN_CHANNEL=2003]="ERR_REPEAT_JOIN_CHANNEL",em[em.ERR_JOIN_BY_MULTI_IP=2004]="ERR_JOIN_BY_MULTI_IP",em[em.ERR_NOT_JOINED=2011]="ERR_NOT_JOINED",em[em.ERR_REPEAT_JOIN_REQUEST=2012]="ERR_REPEAT_JOIN_REQUEST",em[em.ERR_INVALID_VENDOR_KEY=2013]="ERR_INVALID_VENDOR_KEY",em[em.ERR_INVALID_CHANNEL_NAME=2014]="ERR_INVALID_CHANNEL_NAME",em[em.ERR_INVALID_STRINGUID=2015]="ERR_INVALID_STRINGUID",em[em.ERR_TOO_MANY_USERS=2016]="ERR_TOO_MANY_USERS",em[em.ERR_SET_CLIENT_ROLE_TIMEOUT=2017]="ERR_SET_CLIENT_ROLE_TIMEOUT",em[em.ERR_SET_CLIENT_ROLE_NO_PERMISSION=2018]="ERR_SET_CLIENT_ROLE_NO_PERMISSION",em[em.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE=2019]="ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",em[em.ERR_PUBLISH_REQUEST_INVALID=2020]="ERR_PUBLISH_REQUEST_INVALID",em[em.ERR_SUBSCRIBE_REQUEST_INVALID=2021]="ERR_SUBSCRIBE_REQUEST_INVALID",em[em.ERR_NOT_SUPPORTED_MESSAGE=2022]="ERR_NOT_SUPPORTED_MESSAGE",em[em.ERR_ILLEAGAL_PLUGIN=2023]="ERR_ILLEAGAL_PLUGIN",em[em.ERR_REJOIN_TOKEN_INVALID=2024]="ERR_REJOIN_TOKEN_INVALID",em[em.ERR_REJOIN_USER_NOT_JOINED=2025]="ERR_REJOIN_USER_NOT_JOINED",em[em.ERR_INVALID_OPTIONAL_INFO=2027]="ERR_INVALID_OPTIONAL_INFO",em[em.ILLEGAL_AES_PASSWORD=2028]="ILLEGAL_AES_PASSWORD",em[em.ILLEGAL_CLIENT_ROLE_LEVEL=2029]="ILLEGAL_CLIENT_ROLE_LEVEL",em[em.ERR_TOO_MANY_BROADCASTERS=2031]="ERR_TOO_MANY_BROADCASTERS",em[em.ERR_TOO_MANY_SUBSCRIBERS=2032]="ERR_TOO_MANY_SUBSCRIBERS",em[em.ERR_LICENSE_MISSING=32769]="ERR_LICENSE_MISSING",em[em.ERR_LICENSE_EXPIRED=32771]="ERR_LICENSE_EXPIRED",em[em.ERR_LICENSE_MINUTES_EXCEEDED=32773]="ERR_LICENSE_MINUTES_EXCEEDED",em[em.ERR_LICENSE_PERIOD_INVALID=32774]="ERR_LICENSE_PERIOD_INVALID",em[em.ERR_LICENSE_MULTIPLE_SDK_SERVICE=32778]="ERR_LICENSE_MULTIPLE_SDK_SERVICE",em[em.ERR_LICENSE_ILLEGAL=32783]="ERR_LICENSE_ILLEGAL",em[em.ERR_TEST_RECOVER=9e3]="ERR_TEST_RECOVER",em[em.ERR_TEST_TRYNEXT=9001]="ERR_TEST_TRYNEXT",em[em.ERR_TEST_RETRY=9002]="ERR_TEST_RETRY",em),vV=((ef={}).CONNECTING="connecting",ef.CONNECTED="connected",ef.RECONNECTING="reconnecting",ef.CLOSED="closed",ef),vF=((eS={}).WS_CONNECTED="ws_connected",eS.WS_RECONNECTING="ws_reconnecting",eS.WS_CLOSED="ws_closed",eS.WS_RECONNECT_CREATE_CONNECTION="ws_reconnect_create_connection",eS.ON_BINARY_DATA="on_binary_data",eS.REQUEST_RECOVER="request_recover",eS.REQUEST_JOIN_INFO="request_join_info",eS.REQUEST_REJOIN_INFO="req_rejoin_info",eS.IS_P2P_DISCONNECTED="is_p2p_dis",eS.DISCONNECT_P2P="dis_p2p",eS.ABORT_P2P_EXECUTION="abort_p2p_execution",eS.NEED_RENEW_SESSION="need-sid",eS.REPORT_JOIN_GATEWAY="report_join_gateway",eS.REQUEST_TIMEOUT="request_timeout",eS.REQUEST_SUCCESS="request_success",eS.JOIN_RESPONSE="join_response",eS.PRE_CONNECT_PC="pre_connect_pc",eS.DATACHANNEL_PRECONNECT="datachannel_preconnect",eS.DATACHANNEL_CONNECTING="datachannel_c
1onnecting",eS.DATACHANNEL_FAILBACK="datachannel_failback",eS.P2P_CONNECTION="p2p_connection",eS.P2P_REMOTE_CANDIDATE_UPDATE="p2p_remote_candidate_update",eS.P2P_SUBSCRIBE="p2p_subscribe",eS.P2P_UNSUBSCRIBE="p2p_unsubscribe",eS.P2P_EXCHANGE_SDP="p2p_exchange_sdp",eS.P2P_ON_ADD_VIDEO_STREAM="p2p_on_add_video_stream",eS.P2P_ON_ADD_AUDIO_STREAM="p2p_on_add_audio_stream",eS.RECOVER_NOTIFICATION="recover_notification",eS.VOS_FALLBACK="vos_fallback",eS.VOS_FALLBACK_PROMISE="vos_fallback_promise",eS),vB=((eg={}).PING="ping",eg.PING_BACK="ping_back",eg.JOIN="join_v3",eg.REJOIN="rejoin_v3",eg.LEAVE="leave",eg.SET_CLIENT_ROLE="set_client_role",eg.PUBLISH="publish",eg.PUBLISH_DATASTREAM="publish_datastream",eg.UNPUBLISH="unpublish",eg.UNPUBLISH_DATASTREAM="unpublish_datastream",eg.SUBSCRIBE="subscribe",eg.PRE_SUBSCRIBE="pre_subscribe",eg.SUBSCRIBE_DATASTREAM="subscribe_datastream",eg.SUBSCRIBE_STREAMS="subscribe_streams",eg.UNSUBSCRIBE="unsubscribe",eg.UNSUBSCRIBE_DATASTREAM="unsubscribe_datastream",eg.UNSUBSCRIBE_STREAMS="unsubscribe_streams",eg.SUBSCRIBE_CHANGE="subscribe_change",eg.TRAFFIC_STATS="traffic_stats",eg.RENEW_TOKEN="renew_token",eg.SET_DUAL_STREAM_MODE="set_dual_stream_mode",eg.SWITCH_VIDEO_STREAM="switch_video_stream",eg.DEFAULT_VIDEO_STREAM="default_video_stream",eg.SET_FALLBACK_OPTION="set_fallback_option",eg.CONFIGURE="configure",eg.GATEWAY_INFO="gateway_info",eg.CONTROL="control",eg.SEND_METADATA="send_metadata",eg.DATA_STREAM="data_stream",eg.PICK_SVC_LAYER="pick_svc_layer",eg.RESTART_ICE="restart_ice",eg.CONNECT_PC="connect_pc",eg.SET_VIDEO_PROFILE="set_video_profile",eg.SET_PARAMETER="set_parameter",eg.SET_RTM2_FLAG="set_rtm2_flag",eg.DOWNGRADE_CODEC="downgrade_codec",eg),vj=((eT={}).WRTC_STATS="wrtc_stats",eT.WS_INFLATE_DATA_LENGTH="ws_inflate_data_length",eT.DENOISER_STATS="denoiser_stats",eT.EXTENSION_USAGE_STATS="extension_usage_stats",eT),vG=((eR={}).ON_USER_ONLINE="on_user_online",eR.ON_USER_OFFLINE="on_user_offline",eR.ON_STREAM_FALLBACK_UPDATE="on_stream_fallback_update",eR.ON_PUBLISH_STREAM="on_publish_stream",eR.ON_UPLINK_STATS="on_uplink_stats",eR.ON_P2P_LOST="on_p2p_lost",eR.ON_REMOVE_STREAM="on_remove_stream",eR.ON_ADD_AUDIO_STREAM="on_add_audio_stream",eR.ON_ADD_VIDEO_STREAM="on_add_video_stream",eR.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="on_token_privilege_will_expire",eR.ON_TOKEN_PRIVILEGE_DID_EXPIRE="on_token_privilege_did_expire",eR.ON_USER_BANNED="on_user_banned",eR.ON_USER_LICENSE_BANNED="on_user_license_banned",eR.ON_NOTIFICATION="on_notification",eR.ON_CRYPT_ERROR="on_crypt_error",eR.MUTE_AUDIO="mute_audio",eR.MUTE_VIDEO="mute_video",eR.UNMUTE_AUDIO="unmute_audio",eR.UNMUTE_VIDEO="unmute_video",eR.ON_P2P_OK="on_p2p_ok",eR.RECEIVE_METADATA="receive_metadata",eR.ON_DATA_STREAM="on_data_stream",eR.ON_RTP_CAPABILITY_CHANGE="on_rtp_capability_change",eR.ON_REMOTE_DATASTREAM_UPDATE="on_remote_datastream_update",eR.ON_REMOTE_FULL_DATASTREAM_INFO="on_remote_full_datastream_info",eR.ENABLE_LOCAL_VIDEO="enable_local_video",eR.DISABLE_LOCAL_VIDEO="disable_local_video",eR.ENABLE_LOCAL_AUDIO="enable_local_audio",eR.DISABLE_LOCAL_AUDIO="disable_local_audio",eR.ON_PUBLISHED_USER_LIST="on_published_user_list",eR.ENABLE_MULTI_STREAM="enable_multi_stream",eR),vW=((eC={}).SEND_ONLY="SEND_ONLY",eC.RECEIVE_ONLY="RECEIVE_ONLY",eC),vH=((ev={}).CONNECTED="websocket:connected",ev.RECONNECTING="websocket:reconnecting",ev.WILL_RECONNECT="websocket:will_reconnect",ev.CLOSED="websocket:closed",ev.FAILED="websocket:failed",ev.ON_MESSAGE="websocket:on_message",ev.REQUEST_NEW_URLS="websocket:request_new_urls",ev.RECONNECT_CREATE_CONNECTION="websocket:reconnect_create_connection",ev.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire",ev.ON_FALLBACK="websocket:on_fallback",ev);function vK(e){if("string"!=typeof e||!/^[a-zA-Z0-9 \!\#\$\%\&\(\)\+\-\:\;\<\=\.\>\?\@\[\]\^\_\{\}\|\~\,]{1,64}$/.test(e))throw TY.error("Invalid Channel Name ".concat(e)),new T0(SU.INVALID_PARAMS,"The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _, {, }, |, ~, ,")}function vY(e){if(!("number"==typeof e&&Math.floor(e)===e&&0<=e&&e<=0xffffffff||SK(e,1,255)))throw new T0(SU.INVALID_PARAMS,"[String uid] Length of the string: [1,255]. ASCII characters only. [Number uid] The value range is [0,10000]");"string"==typeof e&&TY.warn("You input a string as the user ID, to ensure better end-user experience, Agora highly suggests not using a string as the user ID.")}let vz=((ey={}).TRANSCODE="mix_streaming",ey.RAW="raw_streaming",ey),vq={alpha:1,height:640,width:360,x:0,y:0,zOrder:0,audioChannel:0},vX={x:0,y:0,width:160,height:160,zOrder:255,alpha:1};function vJ(e,t){SG(e.url,"".concat(t,".url"),1,1e3,!1),SH(e.x)||SB(e.x,"".concat(t,".x"),0,1e4),SH(e.y)||SB(e.y,"".concat(t,".y"),0,1e4),SH(e.width)||SB(e.width,"".concat(t,".width"),0,1e4),SH(e.height)||SB(e.height,"".concat(t,".height"),0,1e4),SH(e.zOrder)||SB(e.zOrder,"".concat(t,".zOrder"),0,255),SH(e.alpha)||SB(e.alpha,"".concat(t,".alpha"),0,1,!1)}let vQ={audioBitrate:48,audioChannels:1,audioSampleRate:48e3,backgroundColor:0,height:360,lowLatency:!1,videoBitrate:400,videoCodecProfile:100,videoCodecType:1,videoFrameRate:15,videoGop:30,width:640,images:[],userConfigs:[],userConfigExtraInfo:""},vZ=((eI={}).WARNING="@live_uap-warning",eI.ERROR="@line_uap-error",eI.PUBLISH_STREAM_STATUS="@live_uap-publish-status",eI.WORKER_STATUS="@live_uap-worker-status",eI.REQUEST_NEW_ADDRESS="@live_uap-request-address",eI),v$=((eA={}).REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager",eA),v0=((eb={})[eb.LIVE_STREAM_RESPONSE_SUCCEED=200]="LIVE_STREAM_RESPONSE_SUCCEED",eb[eb.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM=454]="LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM",eb[eb.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR=450]="LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR",eb[eb.LIVE_STREAM_RESPONSE_BAD_STREAM=451]="LIVE_STREAM_RESPONSE_BAD_STREAM",eb[eb.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR=400]="LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR",eb[eb.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST=404]="LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST",eb[eb.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED=456]="LIVE_STREAM_RESPONSE_NOT_AUTHORIZED",eb[eb.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE=457]="LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE",eb[eb.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN=429]="LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN",eb[eb.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH=452]="LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH",eb[eb.LIVE_STREAM_RESPONSE_NOT_SUPPORTED=453]="LIVE_STREAM_RESPONSE_NOT_SUPPORTED",eb[eb.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM=455]="LIVE_STREAM_RESPONSE_MAX_STREAM_NUM",eb[eb.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR=500]="LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR",eb[eb.LIVE_STREAM_RESPONSE_WORKER_LOST=501]="LIVE_STREAM_RESPONSE_WORKER_LOST",eb[eb.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT=502]="LIVE_STREAM_RESPONSE_RESOURCE_LIMIT",eb[eb.LIVE_STREAM_RESPONSE_WORKER_QUIT=503]="LIVE_STREAM_RESPONSE_WORKER_QUIT",eb[eb.ERROR_FAIL_SEND_MESSAGE=504]="ERROR_FAIL_SEND_MESSAGE",eb[eb.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE=30]="PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE",eb[eb.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT=31]="PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT",eb[eb.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH=32]="PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH",eb[eb.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN=33]="PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN",eb);function v1(e){if(!e.channelName)throw new T0(SU.INVALID_PARAMS,"invalid channelName in info");if("number"!=typeof e.uid)throw new T0(SU.INVALID_PARAMS,"invalid uid in info, uid must be a number");return e.token&&SG(e.token,"info.token",1,2047),vY(e.uid),vK(e.channelName),!0}let v2=((eO={})[eO.SetSdkProfile=0]="SetSdkProfile",eO[eO.SetSourceChannel=1]="SetSourceChannel",eO[eO.SetSourceUserId=2]="SetSourceUserId",eO[eO.SetDestChannel=3]="SetDestChannel",eO[eO.StartPacketTransfer=4]="StartPacketTransfer",eO[eO.StopPacketTransfer=5]="StopPacketTransfer",eO[eO.UpdateDestChannel=6]="UpdateDestChannel",eO[eO.Reconnect=7]="Reconnect",eO[eO.SetVideoProfile=8]="SetVideoProfile",eO),v3=((ew={}).NETWORK_DISCONNECTED="NETWORK_DISCONNECTED",ew.NETWORK_CONNECTED="NETWORK_CONNECTED",ew.PACKET_JOINED_SRC_CHANNEL="PACKET_JOINED_SRC_CHANNEL",ew.PACKET_JOINED_DEST_CHANNEL="PACKET_JOINED_DEST_CHANNEL",ew.PACKET_SENT_TO_DEST_CHANNEL="PACKET_SENT_TO_DEST_CHANNEL",ew.PACKET_RECEIVED_VIDEO_FROM_SRC="PACKET_RECEIVED_VIDEO_FROM_SRC",ew.PACKET_RECEIVED_AUDIO_FROM_SRC="PACKET_RECEIVED_AUDIO_FROM_SRC",ew.PACKET_UPDATE_DEST_CHANNEL="PACKET_UPDATE_DEST_CHANNEL",ew.PACKET_UPDATE_DEST_CHANNEL_REFUSED="PACKET_UPDATE_DEST_CHANNEL_REFUSED",ew.PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE="PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE",ew),v5=((eN={}).RELAY_STATE_IDLE="RELAY_STATE_IDLE",eN.RELAY_STATE_CONNECTING="RELAY_STATE_CONNECTING",eN.RELAY_STATE_RUNNING="RELAY_STATE_RUNNING",eN.RELAY_STATE_FAILURE="RELAY_STATE_FAILURE",eN),v4=((eD={}).RELAY_OK="RELAY_OK",eD.SERVER_CONNECTION_LOST="SERVER_CONNECTION_LOST",eD.SRC_TOKEN_EXPIRED="SRC_TOKEN_EXPIRED",eD.DEST_TOKEN_EXPIRED="DEST_TOKEN_EXPIRED",eD),v6=((eP={}).High="high",eP.Low="low",eP.Audio="audio",eP.Screen="screen",eP.ScreenLow="screen_low",eP),v8=((eL={}).DISCONNECT="disconnect",eL.CONNECTION_STATE_CHANGE="connection-state-change",eL.NETWORK_QUALITY="network-quality",eL.STREAM_TYPE_CHANGE="stream-type-change",eL.IS_P2P_DISCONNECTED="is-p2p-dis",eL.DISCONNECT_P2P="dis-p2p",eL.REQUEST_NEW_GATEWAY_LIST="req-gate-url",eL.NEED_RENEW_SESSION="need-sid",eL.REQUEST_P2P_CONNECTION_PARAMS="request-p2p-connection-params",eL.JOIN_RESPONSE="join-response",eL.RESET_CONNECTION_EVENTS="reset-connection-events",eL.PRE_CONNECT_PC="pre-connect_pc",eL.UPDATE_GATEWAY_CONFIG="update-gateway-config",eL.VOS_FALLBACK="vos-fallback",eL.VOS_FALLBACK_PROMISE="vos-fallback-promise",eL.RESET_SIGNAL="reset-signal",eL.DATACHANNEL_FAILBACK="datachannel-failback",eL),v9=((ek={}).P2P_DISCONNECTED="P2P_DISCONNECTED",ek.A_ROUND_WS_FAILED="A_ROUND_WS_FAILED",ek.TIMEOUT="TIMEOUT",ek.UNKNOWN_REASON="UNKNOWN_REASON",ek),v7=((eM={})[eM.Nothing=0]="Nothing",eM[eM.Audio=1]="Audio",eM[eM.LwoVideo=2]="LwoVideo",eM[eM.Video=4]="Video",eM[eM.Data=8]="Data",eM[eM.DataStream0=256]="DataStream0",eM[eM.DataStream1=512]="DataStream1",eM[eM.DataStream2=1024]="DataStream2",eM[eM.DataStream3=2048]="DataStream3",eM[eM.DataStream4=4096]="DataStream4",eM[eM.DataStream5=8192]="DataStream5",eM[eM.DataStream6=16384]="DataStream6",eM[eM.DataStream7=32768]="DataStream7",eM),ye=((eU={}).CHINA="CHINA",eU.ASIA="ASIA",eU.NORTH_AMERICA="NORTH_AMERICA",eU.EUROPE="EUROPE",eU.JAPAN="JAPAN",eU.INDIA="INDIA",eU.KOREA="KOREA",eU.HKMC="HKMC",eU.US="US",eU.OCEANIA="OCEANIA",eU.SOUTH_AMERICA="SOUTH_AMERICA",eU.AFRICA="AFRICA",eU.OVERSEA="OVERSEA",eU.GLOBAL="GLOBAL",eU.EXTENSIONS="EXTENSIONS",eU),yt=[ye.AFRICA,ye.ASIA,ye.CHINA,ye.EUROPE,ye.GLOBAL,ye.INDIA,ye.JAPAN,ye.NORTH_AMERICA,ye.OCEANIA,ye.OVERSEA,ye.SOUTH_AMERICA],yi=((ex={}).CHINA="CN",ex.ASIA="AS",ex.NORTH_AMERICA="NA",ex.EUROPE="EU",ex.JAPAN="JP",ex.INDIA="IN",ex.KOREA="KR",ex.HKMC="HK",ex.US="US",ex.OCEANIA="OC",ex.SOUTH_AMERICA="SA",ex.AFRICA="AF",ex.OVERSEA="OVERSEA",ex.GLOBAL="GLOBAL",ex.EXTENSIONS="GLOBAL",ex),yr={CHINA:{},ASIA:{CODE:yi.ASIA,WEBCS_DOMAIN:["ap-web-1-asia.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-asia.agora.io"],PROXY_CS:["proxy-ap-web-asia.agora.io"],CDS_AP:["cds-ap-web-asia.agora.io","cds-ap-web-asia2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-asia.agora.io","sua-ap-web-asia2.agora.io"],UAP_AP:["uap-ap-web-asia.agora.io","uap-ap-web-asia2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-asia.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-asia.agora.io"],LOG_UPLOAD_SERVER:["logservice-asia.agora.io"],PROXY_SERVER_TYPE3:["southeast-asia.webrtc-cloud-proxy.sd-rtn.com"]},NORTH_AMERICA:{CODE:yi.NORTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-north-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-north-america.agora.io"],PROXY_CS:["proxy-ap-web-america.agora.io"],CDS_AP:["cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],UAP_AP:["uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-north-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-north-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-north-america.agora.io"],PROXY_SERVER_TYPE3:["east-usa.webrtc-cloud-proxy.sd-rtn.com"]},EUROPE:{CODE:yi.EUROPE,WEBCS_DOMAIN:["ap-web-1-europe.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-europe.agora.io"],PROXY_CS:["proxy-ap-web-europe.agora.io"],CDS_AP:["cds-ap-web-europe.agora.io","cds-ap-web-europe2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-europe.agora.io","sua-ap-web-europe.agora.io"],UAP_AP:["uap-ap-web-europe.agora.io","uap-ap-web-europe2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-europe.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-europe.agora.io"],LOG_UPLOAD_SERVER:["logservice-europe.agora.io"],PROXY_SERVER_TYPE3:["europe.webrtc-cloud-proxy.sd-rtn.com"]},JAPAN:{CODE:yi.JAPAN,WEBCS_DOMAIN:["ap-web-1-japan.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-japan.agora.io"],PROXY_CS:["proxy-ap-web-japan.agora.io"],CDS_AP:["cds-ap-web-japan.agora.io","cds-ap-web-japan2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-japan.agora.io","sua-ap-web-japan2.agora.io"],UAP_AP:["uap-ap-web-japan.agora.io","uap-ap-web-japan2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-japan.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-japan.agora.io"],LOG_UPLOAD_SERVER:["logservice-japan.agora.io"],PROXY_SERVER_TYPE3:["japan.webrtc-cloud-proxy.sd-rtn.com"]},INDIA:{CODE:yi.INDIA,WEBCS_DOMAIN:["ap-web-1-india.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-india.agora.io"],PROXY_CS:["proxy-ap-web-india.agora.io"],CDS_AP:["cds-ap-web-india.agora.io","cds-ap-web-india2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-india.agora.io","sua-ap-web-india2.agora.io"],UAP_AP:["uap-ap-web-india.agora.io","uap-ap-web-india2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-india.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-india.agora.io"],LOG_UPLOAD_SERVER:["logservice-india.agora.io"],PROXY_SERVER_TYPE3:["india.webrtc-cloud-proxy.sd-rtn.com"]},KOREA:{CODE:yi.KOREA,WEBCS_DOMAIN:["ap-web-1-korea.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-korea.agora.io"],PROXY_CS:["proxy-ap-web-korea.agora.io"],CDS_AP:["cds-ap-web-korea.agora.io","cds-ap-web-korea2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-korea.agora.io","sua-ap-web-korea2.agora.io"],UAP_AP:["uap-ap-web-korea.agora.io","uap-ap-web-korea2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-korea.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-korea.agora.io"],LOG_UPLOAD_SERVER:["logservice-korea.agora.io"],PROXY_SERVER_TYPE3:["korea.webrtc-cloud-proxy.sd-rtn.com"]},HKMC:{CODE:yi.HKMC,WEBCS_DOMAIN:["ap-web-1-hkmc.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-hkmc.agora.io"],PROXY_CS:["proxy-ap-web-hkmc.agora.io"],CDS_AP:["cds-ap-web-hkmc.agora.io","cds-ap-web-hkmc2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-hkmc.agora.io","sua-ap-web-hkmc2.agora.io"],UAP_AP:["uap-ap-web-hkmc.agora.io","uap-ap-web-hkmc2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-hkmc.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-hkmc.agora.io"],LOG_UPLOAD_SERVER:["logservice-hkmc.agora.io"],PROXY_SERVER_TYPE3:["hkmc.webrtc-cloud-proxy.sd-rtn.com"]},US:{CODE:yi.US,WEBCS_DOMAIN:["ap-web-1-us.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-us.agora.io"],PROXY_CS:["proxy-ap-web-us.agora.io"],CDS_AP:["cds-ap-web-us.agora.io","cds-ap-web-us2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-us.agora.io","sua-ap-web-us2.agora.io"],UAP_AP:["uap-ap-web-us.agora.io","uap-ap-web-us2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-us.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-us.agora.io"],LOG_UPLOAD_SERVER:["logservice-us.agora.io"],PROXY_SERVER_TYPE3:["us.webrtc-cloud-proxy.sd-rtn.com"]},OVERSEA:{CODE:yi.OVERSEA,WEBCS_DOMAIN:["ap-web-1-oversea.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oversea.agora.io"],PROXY_CS:["proxy-ap-web-oversea.agora.io"],CDS_AP:["cds-ap-web-oversea.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oversea.agora.io"],UAP_AP:["uap-ap-web-oversea.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oversea.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscol
1lector-2-oversea.agora.io"],LOG_UPLOAD_SERVER:["logservice-oversea.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.agora.io"]},GLOBAL:{CODE:yi.GLOBAL,WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-ap-web-3.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-ap-web-3.agora.io"],UAP_AP:["uap-ap-web-1.agora.io","uap-ap-web-3.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2.agora.io"],LOG_UPLOAD_SERVER:["logservice.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.sd-rtn.com"]},OCEANIA:{CODE:yi.OCEANIA,WEBCS_DOMAIN:["ap-web-1-oceania.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oceania.agora.io"],PROXY_CS:["proxy-ap-web-oceania.agora.io"],CDS_AP:["cds-ap-web-oceania.agora.io","cds-ap-web-oceania2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oceania.agora.io","sua-ap-web-oceania2.agora.io"],UAP_AP:["uap-ap-web-oceania.agora.io","uap-ap-web-oceania2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oceania.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-oceania.agora.io"],LOG_UPLOAD_SERVER:["logservice-oceania.agora.io"],PROXY_SERVER_TYPE3:["oceania.webrtc-cloud-proxy.sd-rtn.com"]},SOUTH_AMERICA:{CODE:yi.SOUTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-south-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-south-america.agora.io"],PROXY_CS:["proxy-ap-web-south-america.agora.io"],CDS_AP:["cds-ap-web-south-america.agora.io","cds-ap-web-south-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-south-america.agora.io","sua-ap-web-south-america2.agora.io"],UAP_AP:["uap-ap-web-south-america.agora.io","uap-ap-web-south-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-south-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-south-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-america.agora.io"],PROXY_SERVER_TYPE3:["south-america.webrtc-cloud-proxy.sd-rtn.com"]},AFRICA:{CODE:yi.AFRICA,WEBCS_DOMAIN:["ap-web-1-africa.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-africa.agora.io"],PROXY_CS:["proxy-ap-web-africa.agora.io"],CDS_AP:["cds-ap-web-africa.agora.io","cds-ap-web-africa2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-africa.agora.io","sua-ap-web-africa2.agora.io"],UAP_AP:["uap-ap-web-africa.agora.io","uap-ap-web-africa2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-africa.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-africa.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-africa.agora.io"],PROXY_SERVER_TYPE3:["africa.webrtc-cloud-proxy.sd-rtn.com"]},EXTENSIONS:{}};Tu&&(yr.CHINA={CODE:yi.CHINA,WEBCS_DOMAIN:["webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-4.ap.sd-rtn.com"],PROXY_CS:["proxy-web.ap.sd-rtn.com"],CDS_AP:["cds-web-2.ap.sd-rtn.com","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-web-2.ap.sd-rtn.com","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-web-2.ap.sd-rtn.com","uap-web-4.ap.sd-rtn.com"],EVENT_REPORT_DOMAIN:["web-3.statscollector.sd-rtn.com"],EVENT_REPORT_BACKUP_DOMAIN:["web-4.statscollector.sd-rtn.com"],LOG_UPLOAD_SERVER:["logservice-china.agora.io"],PROXY_SERVER_TYPE3:["east-cn.webrtc-cloud-proxy.sd-rtn.com"]});let yn=((eV={}).UPDATE_BITRATE_LIMIT="update_bitrate_limit",eV.UPDATE_CLIENT_ROLE_OPTIONS="update_client_role_options",eV.UPDATE_REMOTE_VIDEO_STREAM_TYPE="update_remote_video_stream_type",eV.FALLBACK_TO_HLS="fallback_to_hls",eV.UPDATE_VOS_CONFIGURE="update_vos_configure",eV);function yo(e){return!!e&&!(!e.uplink||!e.id)&&void 0!==e.uplink.max_bitrate&&void 0!==e.uplink.min_bitrate}class ya extends S0{constructor(e,t){super(),mb(this,"onICEConnectionStateChange",void 0),mb(this,"onConnectionStateChange",void 0),mb(this,"onDTLSTransportStateChange",void 0),mb(this,"onDTLSTransportError",void 0),mb(this,"onICETransportStateChange",void 0),mb(this,"onFirstAudioReceived",void 0),mb(this,"onFirstVideoReceived",void 0),mb(this,"onFirstAudioDecoded",void 0),mb(this,"onFirstVideoDecoded",void 0),mb(this,"onFirstVideoRender",void 0),mb(this,"onFirstVideoBufferReady",void 0),mb(this,"onFirstVideoDecodedTimeout",void 0),mb(this,"onSelectedLocalCandidateChanged",void 0),mb(this,"onSelectedRemoteCandidateChanged",void 0),mb(this,"onICECandidateError",void 0),mb(this,"getLocalVideoStats",void 0)}}class ys extends ya{constructor(e,t){super(e,t),mb(this,"establishPromise",void 0)}}let yc=((eF={}).VIDEO="video",eF.AUDIO="audio",eF),yd=((eB={}).UDP_RELAY="udp_relay",eB.UDP_TCP_RELAY="udp_tcp_relay",eB.TCP_RELAY="tcp_relay",eB.RELAY="relay",eB),yl=((ej={})[ej.FIRST_CONNECTION=0]="FIRST_CONNECTION",ej[ej.UDP_TCP_RESTART=1]="UDP_TCP_RESTART",ej[ej.RELAY_RESTART=2]="RELAY_RESTART",ej[ej.TCP_RESTART=3]="TCP_RESTART",ej[ej.OLD_FIRST_CONNECTION=10]="OLD_FIRST_CONNECTION",ej[ej.OLD_RESTART=11]="OLD_RESTART",ej[ej.DISCONNECTED_OR_FAILED=20]="DISCONNECTED_OR_FAILED",ej),yh=["disconnected","failed"],yu=((eG={}).LocalVideoTrack="videoTrack",eG.LocalAudioTrack="audioTrack",eG.LocalVideoLowTrack="videoLowTrack",eG),yp=((eW={}).New="new",eW.Connected="connected",eW.Reconnecting="reconnecting",eW.Disconnected="disconnected",eW),y_=((eH={}).AudioMetadata="audioMetadata",eH.AudioPts="audioPts",eH.StateChange="stateChange",eH.IceConnectionStateChange="iceConnectionStateChange",eH.RequestMuteLocal="requestMuteLocal",eH.RequestUnmuteLocal="requestUnmuteLocal",eH.RequestRePublish="requestRePublish",eH.RequestRePublishDataChannel="requestRePublishDataChannel",eH.RequestReSubscribe="requestReSubscribe",eH.RequestUploadStats="requestUploadStats",eH.RequestUpload="requestUpload",eH.MediaReconnectStart="MediaReconnectStart",eH.MediaReconnectEnd="MediaReconnectEnd",eH.NeedSignalRTT="NeedSignalRTT",eH.RequestRestartICE="RequestRestartIce",eH.PeerConnectionStateChange="PeerConnectionStateChange",eH.RequestReconnect="RequestReconnect",eH.RequestReconnectPC="RequestReconnectPC",eH.RequestUnpublishForReconnectPC="RequestUnpublishForReconnectPC",eH.P2PLost="P2PLost",eH.UpdateVideoEncoder="UpdateVideoEncoder",eH.ConnectionTypeChange="ConnectionTypeChange",eH.RequestLowStreamParameter="RequestLowStreamParameter",eH.QueryClientConnectionState="QueryClientConnectionState",eH.LocalCandidate="LocalCandidate",eH.RequestP2PMuteLocal="requestP2PMuteLocal",eH.RequestP2PUnPublish="RequestP2PUnPublish",eH.RequestP2PUnmuteRemote="RequestP2PUnmuteRemote",eH.RequestP2PMuteRemote="RequestP2PMuteRemote",eH.RequestP2PRestartICE="RequestP2PRestartICE",eH.FirstVideoPreRender="FirstVideoPreRender",eH.FirstVideoBufferReady="FirstVideoBufferReady",eH),yE=((eK={}).CONNECTING="CONNECTING",eK.RECONNECTING="RECONNECTING",eK.CONNECTED="CONNECTED",eK.
1CLOSED="CLOSED",eK),ym=((eY={})[eY.CONNECT_AP=0]="CONNECT_AP",eY[eY.AP_CONNECTED=1]="AP_CONNECTED",eY[eY.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",eY[eY.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",eY[eY.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",eY[eY.CONNECT_WORKER=5]="CONNECT_WORKER",eY[eY.WORKER_CONNECTED=6]="WORKER_CONNECTED",eY[eY.CLOSED=7]="CLOSED",eY),yf=((ez={}).CONNECTION_STATE_CHANGE="connection-state-change",ez.STATE_CHANGE="state-change",ez.INSPECT_RESULT="inspect-result",ez.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",ez.REQUEST_NEW_WORKER_URL="request-new-worker-url",ez),yS=((eq={}).NETWORK_ERROR="NETWORK_ERROR",eq.SERVER_ERROR="SERVER_ERROR",eq.MULTI_IP="MULTI_IP",eq.TIMEOUT="TIMEOUT",eq.OFFLINE="OFFLINE",eq.LEAVE="LEAVE",eq.P2P_FAILED="P2P_FAILED",eq.FALLBACK="FALLBACK",eq),yg=((eX={}).CONNECTED="transmitter:connected",eX.RECONNECTING="transmitter:reconnecting",eX.WILL_RECONNECT="transmitter:will_reconnect",eX.CLOSED="transmitter:closed",eX.FAILED="transmitter:failed",eX.ON_MESSAGE="transmitter:on_message",eX.REQUEST_NEW_URLS="transmitter:request_new_urls",eX.RECONNECT_CREATE_CONNECTION="transmitter:reconnect_create_connection",eX.ON_TOKEN_PRIVILEGE_DID_EXPIRE="transmitter:on_token_privilege_did_expire",eX.TO_CONNECT_DATACHANNEL="transmitter:to_connect_datachannel",eX.FAILBACK="transmitter:failback",eX.PRE_CONNECT_PC="transmitter:pre_connect_pc",eX),yT=((eJ={}).CAMERA_CHANGED="camera-changed",eJ.MICROPHONE_CHANGED="microphone-changed",eJ.PLAYBACK_DEVICE_CHANGED="playback-device-changed",eJ.AUDIO_AUTOPLAY_FAILED="audio-autoplay-failed",eJ.AUTOPLAY_FAILED="autoplay-failed",eJ.AUDIO_CONTEXT_STATE_CHANGED="audio-context-state-changed",eJ.SECURITY_POLICY_VIOLATION="security-policy-violation",eJ),yR=((eQ={}).CONNECTING="CONNECTING",eQ.RECONNECTING="RECONNECTING",eQ.CONNECTED="CONNECTED",eQ.CLOSED="CLOSED",eQ),yC=((eZ={}).CONNECTION_STATE_CHANGE="connection-state-change",eZ.STATE_CHANGE="state-change",eZ.INSPECT_RESULT="inspect-result",eZ.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",eZ.REQUEST_NEW_WORKER_URL="request-new-worker-url",eZ),yv=((e$={})[e$.CONNECT_AP=0]="CONNECT_AP",e$[e$.AP_CONNECTED=1]="AP_CONNECTED",e$[e$.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e$[e$.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e$[e$.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e$[e$.CONNECT_WORKER=5]="CONNECT_WORKER",e$[e$.WORKER_CONNECTED=6]="WORKER_CONNECTED",e$[e$.CLOSED=7]="CLOSED",e$),yy=((e0={}).CALL="call",e0.CANDIDATE="candidate",e0.PUBLISH="publish",e0.UNPUBLISH="unpublish",e0.CONTROL="control",e0.RESTART_ICE="restart_ice",e0.ACK="ack",e0.RESPONSE="response",e0.JOIN="join",e0.CHECK="check",e0),yI=((e1={}).ABORT="abort",e1),yA=((e2={}).MUTE_LOCAL_AUDIO="mute_local_audio",e2.MUTE_LOCAL_VIDEO="mute_local_video",e2.UNMUTE_LOCAL_AUDIO="unmute_local_audio",e2.UNMUTE_LOCAL_VIDEO="unmute_local_video",e2),yb=((e3={}).P2P_TOKEN_TIMEOUT="p2p_token_timeout",e3.P2P_TOKEN_CHANGED="p2p_token_changed",e3),yO={[vL.ACCESS_POINT]:{[vU.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[vU.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[vU.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[vU.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[vU.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[vU.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[vU.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[vU.NO_SERVICE_AVAILABLE_VOICE]:{desc:"no unilbs voice service available",retry:!0},[vU.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[vU.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[vU.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[vU.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[vU.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[vU.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[vU.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[vU.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[vU.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[vU.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[vL.UNILBS]:{[vM.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[vM.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[vM.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[vM.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[vM.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[vM.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[vM.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[vM.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[vM.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[vM.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1}
1,[vM.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[vM.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1},[vM.REQ_DOWNGRADE_FALLBACK]:{desc:"request downgrade fallback",retry:!1}},[vL.STRING_UID_ALLOCATOR]:{[vk.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[vk.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[vk.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function yw(e){let t=yO[Math.floor(e/1e4)];if(!t)return{desc:"unknown error",retry:!1};let i=t[e%1e4];if(!i){if(Math.floor(e/1e4)===vL.ACCESS_POINT){let t=e%1e4;if("1"===t.toString()[0])return{desc:e.toString(),retry:!1};if("2"===t.toString()[0])return{desc:e.toString(),retry:!0}}return{desc:"unknown error",retry:!1}}return i}let yN={[vx.K_TIMESTAMP_EXPIRED]:{desc:"K_TIMESTAMP_EXPIRED",action:"failed"},[vx.K_CHANNEL_PERMISSION_INVALID]:{desc:"K_CHANNEL_PERMISSION_INVALID",action:"failed"},[vx.K_CERTIFICATE_INVALID]:{desc:"K_CERTIFICATE_INVALID",action:"failed"},[vx.K_CHANNEL_NAME_EMPTY]:{desc:"K_CHANNEL_NAME_EMPTY",action:"failed"},[vx.K_CHANNEL_NOT_FOUND]:{desc:"K_CHANNEL_NOT_FOUND",action:"failed"},[vx.K_TICKET_INVALID]:{desc:"K_TICKET_INVALID",action:"failed"},[vx.K_CHANNEL_CONFLICTED]:{desc:"K_CHANNEL_CONFLICTED",action:"failed"},[vx.K_SERVICE_NOT_READY]:{desc:"K_SERVICE_NOT_READY",action:"tryNext"},[vx.K_SERVICE_TOO_HEAVY]:{desc:"K_SERVICE_TOO_HEAVY",action:"tryNext"},[vx.K_UID_BANNED]:{desc:"K_UID_BANNED",action:"failed"},[vx.K_IP_BANNED]:{desc:"K_IP_BANNED",action:"failed"},[vx.DATASTREAM2_NOT_AVAILABLE]:{desc:"DATASTREAM2_NOT_AVAILABLE",action:"quit"},[vx.K_AUTO_REBALANCE]:{desc:"k_AUTO_REBALANCE",action:"recover"},[vx.K_VOS_FALLBACK]:{desc:"K_VOS_FALLBACK",action:"tryNext"},[vx.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[vx.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[vx.WARN_NO_AVAILABLE_CHANNEL]:{desc:"WARN_NO_AVAILABLE_CHANNEL",action:"failed"},[vx.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:"WARN_LOOKUP_CHANNEL_TIMEOUT",action:"tryNext"},[vx.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:"WARN_LOOKUP_CHANNEL_REJECTED",action:"failed"},[vx.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:"WARN_OPEN_CHANNEL_TIMEOUT",action:"tryNext"},[vx.WARN_OPEN_CHANNEL_REJECTED]:{desc:"WARN_OPEN_CHANNEL_REJECTED",action:"failed"},[vx.WARN_REQUEST_DEFERRED]:{desc:"WARN_REQUEST_DEFERRED",action:"failed"},[vx.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:"ERR_DYNAMIC_KEY_TIMEOUT",action:"failed"},[vx.ERR_NO_AUTHORIZED]:{desc:"ERR_NO_AUTHORIZED",action:"failed"},[vx.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:"ERR_VOM_SERVICE_UNAVAILABLE",action:"tryNext"},[vx.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:"ERR_NO_CHANNEL_AVAILABLE_CODE",action:"failed"},[vx.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:"ERR_MASTER_VOCS_UNAVAILABLE",action:"tryNext"},[vx.ERR_INTERNAL_ERROR]:{desc:"ERR_INTERNAL_ERROR",action:"tryNext"},[vx.ERR_NO_ACTIVE_STATUS]:{desc:"ERR_NO_ACTIVE_STATUS",action:"failed"},[vx.ERR_INVALID_UID]:{desc:"ERR_INVALID_UID",action:"failed"},[vx.ERR_DYNAMIC_KEY_EXPIRED]:{desc:"ERR_DYNAMIC_KEY_EXPIRED",action:"failed"},[vx.ERR_STATIC_USE_DYANMIC_KE]:{desc:"ERR_STATIC_USE_DYANMIC_KE",action:"failed"},[vx.ERR_DYNAMIC_USE_STATIC_KE]:{desc:"ERR_DYNAMIC_USE_STATIC_KE",action:"failed"},[vx.ERR_NO_VOCS_AVAILABLE]:{desc:"ERR_NO_VOCS_AVAILABLE",action:"tryNext"},[vx.ERR_NO_VOS_AVAILABLE]:{desc:"ERR_NO_VOS_AVAILABLE",action:"tryNext"},[vx.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:"ERR_JOIN_CHANNEL_TIMEOUT",action:"tryNext"},[vx.ERR_JOIN_BY_MULTI_IP]:{desc:"ERR_JOIN_BY_MULTI_IP",action:"recover"},[vx.ERR_NOT_JOINED]:{desc:"ERR_NOT_JOINED",action:"failed"},[vx.ERR_REPEAT_JOIN_REQUEST]:{desc:"ERR_REPEAT_JOIN_REQUEST",action:"quit"},[vx.ERR_REPEAT_JOIN_CHANNEL]:{desc:"ERR_REPEAT_JOIN_CHANNEL",action:"quit"},[vx.ERR_INVALID_STRINGUID]:{desc:"ERR_INVALID_STRINGUID",action:"failed"},[vx.ERR_TOO_MANY_USERS]:{desc:"ERR_TOO_MANY_USERS",action:"tryNext"},[vx.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[vx.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[vx.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",action:"success"},[vx.ERR_PUBLISH_REQUEST_INVALID]:{desc:"ERR_PUBLISH_REQUEST_INVALID",action:"failed"},[vx.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:"ERR_SUBSCRIBE_REQUEST_INVALID",action:"failed"},[vx.ERR_NOT_SUPPORTED_MESSAGE]:{desc:"ERR_NOT_SUPPORTED_MESSAGE",action:"failed"},[vx.ERR_ILLEAGAL_PLUGIN]:{desc:"ERR_ILLEAGAL_PLUGIN",action:"failed"},[vx.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:"ILLEGAL_CLIENT_ROLE_LEVEL",action:"failed"},[vx.ERR_REJOIN_TOKEN_INVALID]:{desc:"ERR_REJOIN_TOKEN_INVALID",action:"failed"},[vx.ERR_REJOIN_USER_NOT_JOINED]:{desc:"ERR_REJOIN_NOT_JOINED",action:"failed"},[vx.ERR_INVALID_OPTIONAL_INFO]:{desc:"ERR_INVALID_OPTIONAL_INFO",action:"quit"},[vx.ERR_TEST_RECOVER]:{desc:"ERR_TEST_RECOVER",action:"recover"},[vx.ERR_TEST_TRYNEXT]:{desc:"ERR_TEST_TRYNEXT",action:"recover"},[vx.ERR_TEST_RETRY]:{desc:"ERR_TEST_RETRY",action:"recover"},[vx.ILLEGAL_AES_PASSWORD]:{desc:"ERR_TEST_RETRY",action:"failed"},[vx.ERR_TOO_MANY_BROADCASTERS]:{desc:"ERR_TOO_MANY_BROADCASTERS",action:"failed"},[vx.ERR_TOO_MANY_SUBSCRIBERS]:{desc:"ERR_TOO_MANY_SUBSCRIBERS",action:"failed"},[vx.ERR_LICENSE_ILLEGAL]:{desc:"ERR_LICENSE_ILLEGAL",action:"quit"},[vx.ERR_LICENSE_MISSING]:{desc:"ERR_LICENSE_MISSING",action:"quit"},[vx.ERR_LICENSE_EXPIRED]:{desc:"ERR_LICENSE_EXPIRED",action:"quit"},[vx.ERR_LICENSE_MINUTES_EXCEEDED]:{desc:"ERR_LICENSE_MINUTES_EXCEEDED",action:"quit"},[vx.ERR_LICENSE_PERIOD_INVALID]:{desc:"ERR_LICENSE_PERIOD_INVALID",action:"quit"},[vx.ERR_LICENSE_MULTIPLE_SDK_SERVICE]:{desc:"ERR_LICENSE_MULTIPLE_SDK_SERVICE",action:"quit"}};function yD(e){return yN[e]||{desc:"UNKNOWN_ERROR_".concat(e),action:"failed"}}function yP(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function yL(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
1t%2?yP(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):yP(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}function yk(e,t){if("string"==typeof e)return e;let{proxy:i,host:r,port:n}=e;if(t){let e=TR("JOIN_GATEWAY_FALLBACK_PORT")||443;return 443===e?"wss://".concat(r,"/ws/?p=").concat(Number(n)+150):"wss://".concat(r,":").concat(e,"/ws/?p=").concat(Number(n)+150)}return i?"wss://".concat(i,"/ws/?h=").concat(r,"&p=").concat(n):"wss://".concat(r,":").concat(n)}let yM=/wss:\/\/(.+)\/ws\/\?h=(.+)&p=([0-9]+)\/?/,yU=/wss:\/\/(.+)\/ws\/\?p=([0-9]+)\/?/,yx=/wss:\/\/(.+):([0-9]+)\/?/,yV=/wss:\/\/(.[^\/]+)\/?/,yF=0;class yB{closeAllWebsockets(){this.websockets.forEach(e=>{e.onopen=null,e.onclose=null,e.onmessage=null,e.close()}),this.websockets.length=0}clearTimeout(){this.forceCloseTimeout&&clearTimeout(this.forceCloseTimeout),this.try443PortTimeout&&clearTimeout(this.try443PortTimeout),this.forceCloseTimeout=null,this.try443PortTimeout=null}logger(){var e;let t=Date.now()-this.startTime;for(var i=arguments.length,r=Array(i),n=0;n<i;n++)r[n]=arguments[n];TY.debug("[choose-best-ws ".concat(null==(e=this.store)?void 0:e.clientId," ").concat(this.id,"] ").concat(t,"ms:"),...r)}createWebSocket(e,t,i){this.logger("createWebSocket:",e,{isTry443Port:t,hasTimeoutDetection:i});let r=TR("GATEWAY_DOMAINS"),n=Date.now(),o=[],a=r.find(t=>{var i;return o5(i=e.host).call(i,t)});a||(this.useDoubleDomain=!1);let s=[];if(this.useDoubleDomain)r.forEach(i=>{s.push(yk(yL(yL({},e),{},{host:e.host.replace(a,i)}),t))});else{let i=yL({},e);if(t&&a){let e=r.find(e=>e!==a);e&&(i.host=i.host.replace(a,e))}s.push(yk(i,t))}try{s.forEach(e=>{let t=new WebSocket(e);t.binaryType="arraybuffer",o.push(t),this.logger("ws is connecting:",t.url)})}catch(r){if(this.logger("ws create failed"),o.forEach(e=>e.close()),o.length=0,this.useDoubleDomain)return this.useDoubleDomain=!1,this.createWebSocket(e,t,i);if(!t&&443!==Number(e.port))return this.createWebSocket(e,!0,i);throw new T0(SU.WS_ERR,"init websocket failed! Error: ".concat(r.toString()))}let c=f2();this.store&&this.store.recordJoinChannelService({urls:o.map(e=>e.url),service:"gateway"},this.recordIndex),o.forEach(e=>{e.onopen=()=>{this.logger("onopen: ws ".concat(e.url," open cost ").concat(Date.now()-n,"ms")),this.websockets.forEach(t=>{t!==e&&(t.onopen=null,t.onclose=null,t.onmessage=null,t.close(),this.logger("close backup websocket: ".concat(t.url)))}),this.websockets.length=0,c.resolve(e)},e.onclose=i=>{this.logger("onclose: ws ".concat(e.url," closed cost ").concat(Date.now()-n,"ms state: ").concat(e.readyState));let r=o.every(e=>e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING);this.logger("".concat(t?"443":"47xx"," websocket closed, all failed: ").concat(r)),r&&(t||this.isTry443PortFailed||this.useProxy)?(this.logger("onclose: all websocket is closed, ".concat(i.reason)),c.reject({code:i.code,reason:v9.A_ROUND_WS_FAILED})):!t&&r&&!this.isNormalPortFailed&&this.try443PortTimeout&&(this.logger("all 47xx websocket is closed, try 443 port"),this.clearTimeout(),l()),t?this.isTry443PortFailed=r:this.isNormalPortFailed=r},e.onmessage=t=>this.logger("".concat(e.url," onmessage: ").concat(t.data))}),this.websockets.push(...o);let d=()=>{this.websockets.forEach(e=>e.readyState!==WebSocket.OPEN&&e.close())},l=()=>{if(c.isResolved)return d();St().os===f6.MAC_OS&&Sl()&&d(),this.createWebSocket(e,!0,!0).then(e=>{c.resolve(e)}).catch(e=>{this.isNormalPortFailed&&c.reject(e),this.logger("try 443 port to create ws failed")}),this.forceCloseTimeout=window.setTimeout(()=>{this.logger("5s timeout close un-opens, isWebsocket created: ",c.isResolved),this.forceCloseTimeout=null,d()},this.forceCloseWSDuration)};return i||(()=>{if(t||this.useProxy)return this.logger("add 5s timeout at ".concat(t?"try-443":"proxy"," condition")),this.forceCloseTimeout=window.setTimeout(()=>{this.forceCloseTimeout=null,d()},this.forceCloseWSDuration);this.try443PortTimeout=window.setTimeout(()=>{this.logger("2s timeout, isWebsocket created: ",c.isResolved),this.try443PortTimeout=null,l()},this.try443PortDuration)})(),c.promise}chooseBestWebsocket(e,t,i,r){var n;let o,a,s;return this.useDoubleDomain=!!t,"string"==typeof e&&(n=e,[,o,a,s]=n.match(yM)||[],o||([,a,s]=n.match(yU)||[]),a&&s||([,a,s]=n.match(yx)||[]),a&&s||([,a]=n.match(yV)||[]),a||TY.warning("un-destructible url: ",n),e={proxy:o,host:a,port:s||"443"}),this.recordIndex=r,this.useProxy=!!e.proxy,i&&this.useProxy&&(TY.warn("cannot use 443 only when use proxy"),i=!1),this.createWebSocket(e,!!i,!1).finally(()=>this.clearTimeout())}constructor(e,t){mb(this,"id",0),mb(this,"store",void 0),mb(this,"recordIndex",void 0),mb(this,"websockets",[]),mb(this,"try443PortDuration",2e3),mb(this,"forceCloseWSDuration",5e3),mb(this,"try443PortTimeout",null),mb(this,"forceCloseTimeout",null),mb(this,"isTry443PortFailed",!1),mb(this,"isNormalPortFailed",!1),mb(this,"useDoubleDomain",!1),mb(this,"useProxy",!1),mb(this,"startTime",Date.now()),this.id=++yF,this.try443PortDuration=TR("JOIN_GATEWAY_TRY_443PORT_DURATION")||2e3,this.forceCloseWSDuration=e||5e3,this.store=t}}function yj(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}class yG extends S0{get url(){return this.websocket&&this.websocket.url||this._websocketUrl}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){var t;o5(t=["tryNext","recover"]).call(t,e)&&this.resetReconnectCount(e),this._reconnectMode=e}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit
1(vH.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(vH.CONNECTED):"closed"===this._state?this.emit(vH.CLOSED):"failed"===this._state&&this.emit(vH.FAILED))}resetReconnectCount(e){TY.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}getConnection(){return this.websocket||void 0}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3,i=await this._initMutex.lock();this._reconnectMode="tryNext",this.forceCloseTimeout=t,this.urls=e,this.state="connecting";try{var r,n;let e=f2(),t=this.urls[this.currentURLIndex];null==(r=this.store)||r.beforeConnect(),n=this.store,T3()||TR("USE_NEW_TOKEN")||!TR("ENABLE_PREALLOC_PC")&&(null==n||!n.autoSubscribe||TR("FORCE_DISABLE_AUTO_SUB"))||this.emit(yg.PRE_CONNECT_PC),this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(vH.CLOSED,()=>{e.reject(new Sx(SU.WS_DISCONNECT))}),this.once(vH.CONNECTED,e.resolve),await e.promise}catch(e){}finally{i()}}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this.reconnectInterrupter&&this.reconnectInterrupter(),this.websocket){this.websocket.onclose=null,this.websocket.onopen=null,this.websocket.onmessage=null;let e=this.websocket;t?setTimeout(()=>e.close(),500):e.close(),this.websocket=void 0,this._websocketUrl=null}this.state=e?"failed":"closed",this.closeEstablishingWs&&this.closeEstablishingWs()}reconnect(e,t){if(!this.websocket)return void TY.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),TY.debug("[".concat(this.name,"] reconnect is triggered initiative")),"number"==typeof this.joinGatewayRecordIndex&&this.store&&this.store.recordJoinChannelService({status:"error",errors:[Error(t)]},this.joinGatewayRecordIndex);let i=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),i&&i.bind(this.websocket)({code:9999,reason:t})}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Sx(SU.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new Sx(SU.WS_ERR,"send websocket message error"+e.toString())}}setWsInflateData(e){this.wsDeflateLength=this.wsDeflateLength+e.originLength,this.wsInflateLength=this.wsInflateLength+e.compressedLength}getWsInflateData(){let e=this.wsInflateLength,t=this.wsDeflateLength;return this.clearWsInflateData(),{wsInflateLength:e,wsDeflateLength:t}}clearWsInflateData(){this.wsInflateLength=0,this.wsDeflateLength=0}async createWebSocketConnection(e){var t,i;let r=f2();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;let n=e=>{var t;null==(t=this.store)||t.signalChannelOpen(),TY.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),r.resolve()},o=async e=>{var t;if(TY.debug("[".concat(this.name,"] websocket close ").concat(null==(t=this.websocket)?void 0:t.url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)r.reject(new Sx(SU.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");let t=gd(this,vH.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,i=await this.reconnectWithAction(t);if("closed"===this.state)return void TY.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!i)return r.reject(new Sx(SU.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);r.resolve()}},a=e=>{this.emit(vH.ON_MESSAGE,e)},s=e=>{TY.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),TR("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=TR("GATEWAY_WSS_ADDRESS")),TY.debug("[".concat(this.name,"] start connect, url:"),e);let c=null==(t=this.store)?void 0:t.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{this._websocketUrl=yk(e);let t=await this.chooseBestWebsocketConnection(e);this.websocket=t,n&&n(this.websocket.url),this.websocket.onclose=o,this.websocket.onmessage=a,this.websocket.onerror=s,null==(i=this.store)||i.recordJoinChannelService({endTs:Date.now(),status:"success"},c),this.joinGatewayRecordIndex=c}catch(s){let e="closed"===this.state,t=s instanceof Sx,i=t&&s.code===SU.WS_ABORT,n=t&&s.code===SU.WS_ERR,a=t?s.message:s&&(s.reason||s.toString());TY.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(a)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:i?"aborted":"error",errors:[s]},c),e||n?(r.reject(e?new Sx(SU.WS_DISCONNECT,"websocket is closed: ".concat(a)):new Sx(SU.WS_ERR,"init websocket failed: ".concat(a))),n&&TY.error("[".concat(this.name,"] init websocket failed: ").concat(a))):o&&o(s)}return r.promise}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this.reconnectCount>=this.retryConfig.maxRetryCount||0===this.urls.length||"closed"===this.state)return!1;TY.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||gh.isOnline||!gh.onlineWaiter||(this.onlineReconnectListener=gh.onlineWaiter.then(()=>{this.onlineReconnectListener=void 0}));let i=!0;if(this.reconnectInterrupter=()=>i=!1,t){let t=gK(this.reconnectCount,this.retryConfig);TY.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await dQ.race([gO(t),this.onlineReconnectListener||new dQ(()=>{})])}if("closed"===this._state||!i)return!1;this.reconnectCount+=1;let r=async(e,t)=>
1{this.emit(vH.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)await r(this.urls[this.currentURLIndex],e);else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);TY.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),await r(this.urls[this.currentURLIndex],e)}else"recover"===e&&(TY.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.urls=await gs(this,vH.REQUEST_NEW_URLS),this.currentURLIndex=0,await r(this.urls[this.currentURLIndex],e))}catch(r){var n;TY.error("[".concat(this.name,"] reconnect failed ").concat(r&&r.toString()));let i=null==r||null==(n=r.data)?void 0:n.desc;if(Array.isArray(i)){if(o5(i).call(i,"dynamic key expired"))return this.emit(vH.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1;if(o5(i).call(i,"request downgrade fallback"))return this.emit(vH.ON_FALLBACK),!1}return this.reconnectWithAction(e,t)}return!0}constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],n=arguments.length>4&&void 0!==arguments[4]&&arguments[4],o=arguments.length>5?arguments[5]:void 0;super(),mb(this,"_websocketUrl",null),mb(this,"connectionID",0),mb(this,"currentURLIndex",0),mb(this,"urls",[]),mb(this,"_reconnectMode","tryNext"),mb(this,"reconnectReason",void 0),mb(this,"_initMutex",void 0),mb(this,"name",void 0),mb(this,"_state","closed"),mb(this,"reconnectInterrupter",void 0),mb(this,"websocket",void 0),mb(this,"retryConfig",void 0),mb(this,"reconnectCount",0),mb(this,"forceCloseTimeout",5e3),mb(this,"onlineReconnectListener",void 0),mb(this,"useCompress",void 0),mb(this,"tryDoubleDomain",!1),mb(this,"use443PortOnly",!1),mb(this,"wsInflateLength",0),mb(this,"wsDeflateLength",0),mb(this,"closeEstablishingWs",()=>{}),mb(this,"store",void 0),mb(this,"joinGatewayRecordIndex",void 0),this.store=o,this.name=e,this.retryConfig=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?yj(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):yj(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}({},t),this.useCompress=i,this.tryDoubleDomain=r,this.use443PortOnly=n,this._initMutex=new gG("websocket",o?o.clientId:void 0);let{timeout:a,timeoutFactor:s}=t,c=Math.max(300,Math.floor(3*a/5)),d=Math.max(1.2,Math.floor(8*s)/10);go.ONLINE&&(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d),gh.on(ga.NETWORK_STATE_CHANGE,(e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===go.ONLINE?(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d):(this.retryConfig.timeout=a,this.retryConfig.timeoutFactor=s))})}}class yW extends yG{async chooseBestWebsocketConnection(e,t){let i=f2(),r=new yB(this.forceCloseTimeout,this.store);this.closeEstablishingWs=()=>{TY.debug("[choose-best-ws] close establishing websockets"),r.closeAllWebsockets(),i.reject(new Sx(SU.WS_ABORT,"choose best websocket aborted"))};let n=TR("GATEWAY_DOMAINS");return TY.debug("[choose-best-ws] currentDomain: ",e,", domains: ",n,"total: ".concat(this.urls.length),"current: ".concat(this.currentURLIndex+1)),r.chooseBestWebsocket(e,this.tryDoubleDomain,this.use443PortOnly,t).then(i.resolve).catch(i.reject),i.promise.finally(()=>{this.closeEstablishingWs=void 0})}constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0)}}class yH extends yG{async chooseBestWebsocketConnection(e,t){return new dQ((i,r)=>{var n,o;let a=!1,s=[];this.closeEstablishingWs=()=>{TY.debug("[choose-best-ws] close establishing websockets"),s.forEach(e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()}),r(new Sx(SU.WS_ABORT,"choose best websocket aborted"))};let c=TR("GATEWAY_DOMAINS"),d=e.indexOf("?h="),l=c.find(t=>-1!==d?o5(e).call(e,t,d):o5(e).call(e,t));TY.debug("[choose-best-ws] currentDomain: ",l,", domains: ",c);let h=!this.tryDoubleDomain||!l;if(!h&&l){let o=Date.now();
1try{c.forEach(t=>{let i=-1===d?e.replace(l,t):e.substr(0,d)+e.substr(d).replace(l,t),r=new WebSocket(i);r.binaryType="arraybuffer",s.push(r),TY.debug("[choose-best-ws] ws is connecting:",r.url)})}catch(e){for(TY.debug("[choose-best-ws] ws create failed, fallback to single url"),s.forEach(e=>e.close());s.length;)s.pop();h=!0}null==(n=this.store)||n.recordJoinChannelService({urls:s.map(e=>e.url),service:"gateway"},t),s.forEach(e=>{e.onopen=()=>{if(a)return;let t=Date.now()-o;TY.debug("[choose-best-ws] ws open cost ".concat(t,"ms")),s.filter(t=>t!==e).forEach(e=>{TY.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()}),a=!0,i(e)},e.onclose=e=>{!a&&(s.find(e=>e.readyState!==WebSocket.CLOSED&&e.readyState!==WebSocket.CLOSING)||(TY.debug("[choose-best-ws] all websocket is closed"),a=!0,r(e)))},e.onmessage=t=>{TY.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}}),gO(this.forceCloseTimeout).then(()=>{s.forEach(e=>{e.readyState!==WebSocket.OPEN&&e.close()})})}if(h){let n;TY.debug("[choose-best-ws] use single url: ",e),null==(o=this.store)||o.recordJoinChannelService({urls:[e],service:"gateway"},t);try{n=new WebSocket(e),s.push(n),n.binaryType="arraybuffer"}catch(t){let e=new Sx(SU.WS_ERR,"init websocket failed! Error: ".concat(t.toString()));return TY.error("[".concat(this.name,"]").concat(e)),void r(e)}n.onopen=()=>{i(n)},n.onclose=e=>{r(e)},n.onmessage=e=>{TY.debug("[choose-best-ws]".concat(n.url," onmessage: ").concat(e.data))},gO(this.forceCloseTimeout).then(()=>{n&&n.readyState!==WebSocket.OPEN&&n.close()})}}).then(e=>(this.closeEstablishingWs=void 0,e)).catch(e=>{throw this.closeEstablishingWs=void 0,e})}constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0)}}class yK extends S0{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===vV.CONNECTED?this.emit(vF.WS_CONNECTED):e===vV.RECONNECTING?this.emit(vF.WS_RECONNECTING,this._websocketReconnectReason):e===vV.CLOSED&&this.emit(vF.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get rtt(){return this.rttRolling.mean()}async request(e,t,i,r){let n=gw(6,""),o=this.websocket.connectionID,a=()=>new dQ((t,i)=>{if(this.connectionState===vV.CONNECTED)return t();let r=()=>{this.off(vF.WS_CLOSED,n),t()},n=()=>{this.off(vF.WS_CONNECTED,r),i(new T0(SU.WS_ABORT))};this.once(vF.WS_CONNECTED,r),this.once(vF.WS_CLOSED,n),e!==vB.PUBLISH&&e!==vB.PUBLISH_DATASTREAM&&e!==vB.SUBSCRIBE&&e!==vB.SUBSCRIBE_DATASTREAM&&e!==vB.UNSUBSCRIBE&&e!==vB.UNSUBSCRIBE_DATASTREAM&&e!==vB.UNPUBLISH&&e!==vB.UNPUBLISH_DATASTREAM&&e!==vB.CONTROL&&e!==vB.RESTART_ICE||this.once(vF.DISCONNECT_P2P,()=>{i(new T0(SU.DISCONNECT_P2P))}),e!==vB.PUBLISH&&e!==vB.RESTART_ICE||this.once(vF.ABORT_P2P_EXECUTION,()=>{i(new T0(SU.DISCONNECT_P2P))})});if(this.connectionState!==vV.CONNECTING&&this.connectionState!==vV.RECONNECTING||e===vB.JOIN||e===vB.REJOIN||await a(),this.websocket.sendMessage({_id:n,_type:e,_message:t},!0),r)return;let s=new dQ((i,r)=>{let a=!1,s=(r,n)=>{a=!0,i({isSuccess:"success"===r,message:n||{}}),this.off(vF.WS_CLOSED,c),this.off(vF.WS_RECONNECTING,c),this.emit(vF.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(n),s);let c=()=>{r(new T0(SU.WS_ABORT,"type: ".concat(e))),this.off(vF.WS_CLOSED,c),this.off(vF.WS_RECONNECTING,c),this.off("res-@".concat(n),s)};this.once(vF.WS_CLOSED,c),this.once(vF.WS_RECONNECTING,c),gO(TR("SIGNAL_REQUEST_TIMEOUT")).then(()=>{this.websocket.connectionID!==o||a||(TY.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(vF.REQUEST_TIMEOUT,e,t))})}),c=null;try{c=await s}catch(r){if(this.connectionState===vV.CLOSED||e===vB.LEAVE)throw new T0(SU.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?r.throw():e===vB.JOIN||e===vB.REJOIN?null:(await a(),await this.request(e,t))}if(c.isSuccess)return c.message;let d=Number(c.message.error_code||c.message.code),l=yD(d),h=new T0(SU.UNEXPECTED_RESPONSE,"".concat(l.desc,": ").concat(c.message.error_str),{code:d,data:c.message,desc:l.desc});return"success"===l.action?c.message:(TY.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(d,", message: ").concat(l.desc,", action: ").concat(l.action)),d===vx.ERR_TOO_MANY_BROADCASTERS?((e===vB.JOIN||e===vB.REJOIN)&&(this.initError=h,this.close()),h.throw()):"failed"===l.action?h.throw():"quit"===l.action?(this.initError=h,this.close(),h.throw()):(d===vx.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=c.message.option,TY.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",gn.MULTI_IP)):this.reconnect(l.action,gn.SERVER_ERROR),e===vB.JOIN||e===vB.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new dQ(i=>{let r=n=>{(!t||t(n))&&(this.off(e,r),i(n))};this.on(e,r)})}uploadWRTCStats(e){if(!this.store.sessionId)return void TY.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));let t={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(vj.WRTC_STATS,t)}upload(e,t){let i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(t){let e=TR("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>e&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval(()=>{if(this.connectionState!==vV.CONNECTED)return;let e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message)},TR("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){this.websocket.sendMessage({_type:e,_message:t})}init(e){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new dQ((t,i)=>{this.once(vF.WS_CONNECTED,()=>t(this.joinResponse)),this.once(vF.WS_CLOSED,e=>i(this.initError||new T0(SU.WS_ABORT,e))),this.connectionState=vV.CONNECTING,this.websocket.init(e).catch(i),this.wsInflateDataTimer&&window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=window.setInterval(()=>{this.handleWsInflateData()},2e4)})}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.wsInflateDataTimer&&(this.handleWsInflateData(),window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._disconnectedReason=e||S8.LEAVE,this.connectionState=vV.CLOSED,TY.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close()}
1async join(){if(!this.joinResponse){this.emit(vF.ABORT_P2P_EXECUTION),this.store.signalConnected();let e=await gs(this,vF.REQUEST_JOIN_INFO);this.store.joinReq();let t=await this.request(vB.JOIN,e);if(this.ortc=null==e?void 0:e.ortc,this.store.joinRep(),!t)return this.emit(vF.REPORT_JOIN_GATEWAY,v9.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(vF.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=vV.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new T0(SU.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");let e=gl(this,vF.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;let t=await this.request(vB.REJOIN,e);return!!t&&(this.connectionState=vV.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach(e=>{this.emit(vG.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(vG.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(vG.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(vG.MUTE_AUDIO,{uid:e.uid}):this.emit(vG.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(vG.MUTE_VIDEO,{uid:e.uid}):this.emit(vG.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(vG.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(vG.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(vG.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(vG.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(vG.ON_REMOVE_STREAM,{uid:e.uid,uint_id:e.uint_id})}),!0)}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}async downgradeCodec(e){if(!this.ortc)return!1;let t={downgrade_codec:e,ortc:this.ortc};return!!await this.request(vB.DOWNGRADE_CODEC,t)}handleNotification(e){TY.debug("[".concat(this.clientId,"] receive notification: "),e);let t=yD(e.code);if(28===e.code&&"detail"in e&&(TY.info("[".concat(this.clientId,"] receive recover notification: "),e.detail),this.emit(vF.RECOVER_NOTIFICATION,e.detail)),"success"!==t.action){if("failed"!==t.action)return"quit"===t.action?e.code===vx.ERR_REPEAT_JOIN_CHANNEL&&TR("IGNORE_UID_CHECK")?void this.close(S8.UID_CONFLICT):("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(S8.UID_BANNED),void this.close()):e.code===vx.K_VOS_FALLBACK&&"detail"in e?(TY.info("[".concat(this.clientId,"] receive vos fallback notification: "),e.detail),"FALLBACKCN"===e.detail&&TR("ENABLE_QUALITY_FALLBACK")?void gs(this,vF.VOS_FALLBACK_PROMISE,e.detail).then(()=>{this.reconnect("recover",t.desc)}).catch(e=>{TY.debug("[".concat(this.clientId,"] cancel vos fallback cn, error: "),e)}):"fallback_hls"===e.detail&&TR("ENABLE_FALLBACK_TO_HLS")?(this.emit(vF.VOS_FALLBACK,e.detail),void this.close(S8.FALLBACK_TO_HLS)):this.reconnect(t.action,t.desc)):void this.reconnect(t.action,gn.SERVER_ERROR);TY.error("[".concat(this.clientId,"] ignore error: "),t.desc)}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;let e=TR("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(TY.warning("[".concat(this.clientId,"] PING-PONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>TR("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",gn.TIMEOUT):this.request(vB.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;let e=Date.now()-t;this.rttRolling.add(e),TR("REPORT_STATS")&&this.send(vB.PING_BACK,{pingpongElapse:e})}).catch(e=>{})}handleWsInflateData(){let{wsInflateLength:e,wsDeflateLength:t}=this.websocket.getWsInflateData();0!==e&&0!==t&&this.upload(vj.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(vH.RECONNECT_CREATE_CONNECTION,e=>
1{this.emit(vF.WS_RECONNECT_CREATE_CONNECTION,e)}),this.websocket.on(vH.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(vH.CLOSED,()=>{this.connectionState=vV.CLOSED}),this.websocket.on(vH.FAILED,()=>{this._disconnectedReason=S8.NETWORK_ERROR,this.connectionState=vV.CLOSED}),this.websocket.on(vH.RECONNECTING,e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===vV.CONNECTED?this.connectionState=vV.RECONNECTING:this.connectionState=vV.CONNECTING}),this.websocket.on(vH.WILL_RECONNECT,(e,t,i)=>{let r=gl(this,vF.IS_P2P_DISCONNECTED),n=r||"retry"!==e;r&&"retry"===e&&(TY.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),e="tryNext",t=v9.P2P_DISCONNECTED),n&&(TY.debug("".concat(this.clientId," will renewSession, reconnect mode: ").concat(e)),this.emit(vF.REPORT_JOIN_GATEWAY,t||v9.UNKNOWN_REASON,this.url||""),this.reconnectToken=void 0,this.emit(vF.DISCONNECT_P2P)),i(e)}),this.websocket.on(vH.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch(e=>{TY.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",gn.SERVER_ERROR)}):this.join().catch(e=>{if(this.emit(vF.REPORT_JOIN_GATEWAY,e,this.url||""),e instanceof T0){if(e.code===SU.UNEXPECTED_RESPONSE&&e.data.code===vx.ERR_NO_AUTHORIZED)return this.initError=new T0(SU.TOKEN_EXPIRE,"dynamic key expired"),void this.close(S8.TOKEN_EXPIRE);TY.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",gn.SERVER_ERROR):(this.initError=e,this.close())}})}),this.websocket.on(vH.REQUEST_NEW_URLS,(e,t)=>{gs(this,vF.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)}),this.websocket.on(vH.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(vG.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}),this.websocket.on(yg.PRE_CONNECT_PC,()=>{this.emit(vF.PRE_CONNECT_PC)}),this.websocket.on(vH.ON_FALLBACK,()=>{TR("ENABLE_FALLBACK_TO_HLS")&&this.emit(vF.VOS_FALLBACK,"fallback_hls")})}constructor(e,t){super(),mb(this,"__name__","AgoraRTCSignal"),mb(this,"_disconnectedReason",void 0),mb(this,"_websocketReconnectReason",void 0),mb(this,"_connectionState",vV.CLOSED),mb(this,"reconnectToken",void 0),mb(this,"websocket",void 0),mb(this,"openConnectionTime",void 0),mb(this,"clientId",void 0),mb(this,"lastMsgTime",Date.now()),mb(this,"uploadCache",[]),mb(this,"uploadCacheInterval",void 0),mb(this,"rttRolling",new gq(5)),mb(this,"pingpongTimer",void 0),mb(this,"wsInflateDataTimer",void 0),mb(this,"pingpongTimeoutCount",0),mb(this,"ortc",void 0),mb(this,"joinResponse",void 0),mb(this,"multiIpOption",void 0),mb(this,"initError",void 0),mb(this,"spec",void 0),mb(this,"store",void 0),mb(this,"onWebsocketMessage",e=>{if(e.data instanceof ArrayBuffer)return void this.emit(vF.ON_BINARY_DATA,e.data);let t=JSON.parse(e.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){let e="res-@".concat(t._id);this.emit(e,t._result,t._message)}else if(Object.prototype.hasOwnProperty.call(t,"_type")){if(this.emit(t._type,t._message),t._type===vG.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===vG.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(S8.UID_BANNED);break;case 15:this.close(S8.IP_BANNED);break;case 16:this.close(S8.CHANNEL_BANNED)}if(t._type===vG.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case vx.ERR_LICENSE_MISSING:this.close(S8.LICENSE_MISSING);break;case vx.ERR_LICENSE_EXPIRED:this.close(S8.LICENSE_EXPIRED);break;case vx.ERR_LICENSE_MINUTES_EXCEEDED:this.close(S8.LICENSE_MINUTES_EXCEEDED);break;case vx.ERR_LICENSE_PERIOD_INVALID:this.close(S8.LICENSE_PERIOD_INVALID);break;case vx.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(S8.LICENSE_MULTIPLE_SDK_SERVICE);break;case vx.ERR_LICENSE_ILLEGAL:this.close(S8.LICENSE_ILLEGAL);break;default:this.close()}}}),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new yW("gateway-".concat(this.clientId),this.spec.retryConfig,!0,TR("JOIN_GATEWAY_USE_DUAL_DOMAIN"),TR("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===vV.CONNECTED&&this.reconnect("retry",gn.OFFLINE)})}}let yY=((e5={}).NATIVE_RTC="native_rtc",e5.NATIVE_RTM="native_rtm",e5.WEB_RTC="web_rtc",e5.WEB_RTM="web_rtm",e5),yz=((e4={})[e4.CHOOSE_SERVER=11]="CHOOSE_SERVER",e4[e4.CLOUD_PROXY=18]="CLOUD_PROXY",e4[e4.CLOUD_PROXY_5=20]="CLOUD_PROXY_5",e4[e4.CLOUD_PROXY_FALLBACK=26]="
1CLOUD_PROXY_FALLBACK",e4);function yq(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function yX(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?yq(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):yq(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let yJ=0;function yQ(e){let t=TR("TURN_DOMAINS");yJ=(yJ+1)%t.length;let i=t[yJ]||"edge.agora.io";return e.match(/^[\.\:\d]+$/)?"".concat(e.replace(/[^\d]/g,"-"),".").concat(i):(TY.debug("Cannot recognized as ip address: ".concat(e,", use as host2")),e)}function yZ(e){try{let t=TR("TURN_DOMAINS"),i=TR("GATEWAY_DOMAINS").concat(t).find(t=>o5(e).call(e,t));if(i)return e.split(".".concat(i))[0].replace(/-/g,".");return e}catch(t){return TY.debug("serverUrlToIp error, fallback to url",e),e}}function y$(e,t){let i;e.addresses||(e.addresses=[]);let r=function(e,t){if(TR("CONNECT_GATEWAY_WITHOUT_DOMAIN"))return e.map(e=>{let{ip:t,port:i}=e;return{address:"".concat(t,":").concat(i)}});let i=TR("GATEWAY_DOMAINS"),r=i[1]&&o5(t).call(t,i[1])?1:0;return e.map(e=>{let{domain_prefix:t,port:n,ip:o}=e;if(t)return{address:"".concat(t,".").concat(i[r++%i.length],":").concat(n)};let a=/^[\.\:\d]+$/.test(o),s=a?"".concat(o.replace(/[^\d]/g,"-"),".").concat(i[r++%i.length],":").concat(n):"".concat(o,":").concat(n);return a||TY.debug("Cannot recognized as ip address: ".concat(o,", use as host3")),{ip:o,port:n,address:s}})}(e.addresses,t),n=Array.isArray(e.detail)&&e.detail[18];if(n&&"string"==typeof n){let e=n.split(";");for(let t=0;t<e.length;t++){var o;let i=py(o=e[t]).call(o);r[t]&&i&&(r[t].ip6=i)}}let a=e.detail&&e.detail.candidate;if(a){let[e,t]=a.split(":");e&&t&&(i={port:Number(t),ip:e,address:"".concat(e,":").concat(t)})}return{gatewayAddrs:r,apGatewayAddress:i,uid:e.uid,cid:e.cid,cert:e.cert,vid:e.detail&&e.detail[8],uni_lbs_ip:e.detail&&e.detail[1],res:e,csIp:e.detail&&e.detail[502]}}function y0(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function y1(e){let t=e._encoderConfig;if(!t)return{};let i={resolution:t.width&&t.height?"".concat(y0(t.width),"x").concat(y0(t.height)):void 0,maxVideoBW:t.bitrateMax,minVideoBW:t.bitrateMin};return"number"==typeof t.frameRate?(i.maxFrameRate=t.frameRate,i.minFrameRate=t.frameRate):t.frameRate&&(i.maxFrameRate=t.frameRate.max||t.frameRate.ideal||t.frameRate.exact||t.frameRate.min,i.minFrameRate=t.frameRate.min||t.frameRate.ideal||t.frameRate.exact||t.frameRate.max),i}function y2(e){return e>=0&&e<.17?1:e>=.17&&e<.36?2:e>=.36&&e<.59?3:e>=.59&&e<=1?4:5*(e>1)}function y3(e,t){let i,r,n;switch(t){case yz.CHOOSE_SERVER:r=4096,n="choose server";break;case yz.CLOUD_PROXY:r=1048576,n="proxy";break;case yz.CLOUD_PROXY_5:r=4194304,n="proxy5";break;case yz.CLOUD_PROXY_FALLBACK:r=4194310,n="proxy fallback";break;default:throw new T0(SU.UNEXPECTED_ERROR,"multi unlibs response transformer get unknown service id",{csIp:e.detail&&e.detail[502],retry:!1})}if(e.response_body.forEach(t=>{t.buffer&&t.buffer.flag===r&&(i={code:t.buffer.code,addresses:(t.buffer.edges_services||[]).map(e=>yX(yX({},e),{},{ticket:t.buffer.cert})),server_ts:e.enter_ts,uid:t.buffer.uid,cid:t.buffer.cid,cname:t.buffer.cname,detail:yX(yX({},t.buffer.detail),e.detail),flag:t.buffer.flag,opid:e.opid,cert:t.buffer.cert})}),!i)throw new T0(SU.MULTI_UNILBS_RESPONSE_ERROR,"cannot parse response ".concat(n," from multi unilbs response"),{csIp:e.detail&&e.detail[502]});return i}async function y5(e,t){return await dQ.all(e.addresses.map(async e=>({address:yQ(e.ip),tcpport:e.port,udpport:e.port,username:t&&TR("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?t.toString():T_.username,password:t&&TR("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?await S$(t.toString()):T_.password})))}function y4(e,t){let i=t.getMediaStreamTrack(!0).getSettings(),r=t.videoHeight||i.height,n=t.videoWidth||i.width;return r&&n?Math.max(Math.min(r,n)/Math.min(y0(e.height),y0(e.width)),1):(TY.warning("can't get ori-track's height, default scale down 4 times for low stream"),4)}function y6(e){let{candidateType:t,relayProtocol:i,type:r,address:n,port:o,protocol:a}=e,s={candidateType:t,relayProtocol:i,protocol:a};if("local-candidate"!==r){let e=n.split(".");e.length>
1=4&&(e[1]="*",e[2]="*"),s.address=e.join("."),s.port=o}return s}function y8(e){let t=e.split(":"),i=e.split(/[-.]/),r=o5(e).call(e,"-")?"-":".",n=e;return t.length>1?i.length>1?(i[1]="**",n=i[0]+r+"**:"+t[t.length-1]):n=t.length>2?t[0]+r+"**:"+t[t.length-1]:"**:"+t[t.length-1]:i.length>1&&(n=i[0]+r+"**"),n}function y9(e,t){return e.getTransceivers().find(e=>e.sender.track===t||e.receiver.track===t)}function y7(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:TR("SVC_MODE");if(TR("ENABLE_SVC"))return e in Tt?e:Tt.L1T3}let Ie={[yc.VIDEO]:[{key:"abs-send-time",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"},{key:"video-orientation",extensionName:"urn:3gpp:video-orientation"},{key:"draft-holmer-rmcat-transport-wide-cc-extensions-01",extensionName:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"},{key:"playout-delay",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"},{key:"video-content-type",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type"},{key:"color-space",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/color-space"},{key:"video-timing",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/video-timing"}],[yc.AUDIO]:[{key:"ssrc-audio-level",extensionName:"urn:ietf:params:rtp-hdrext:ssrc-audio-level"},{key:"draft-holmer-rmcat-transport-wide-cc-extensions-01",extensionName:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"},{key:"abs-send-time",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"}]};function It(e){e.send&&(In(yc.VIDEO,e.send.videoExtensions),In(yc.AUDIO,e.send.audioExtensions)),e.recv&&(In(yc.VIDEO,e.recv.videoExtensions),In(yc.AUDIO,e.recv.audioExtensions)),e.sendrecv&&(In(yc.VIDEO,e.sendrecv.videoExtensions),In(yc.AUDIO,e.sendrecv.audioExtensions))}function Ii(e,t){e.send&&(Ir(yc.VIDEO,e.send.videoExtensions,t.send.videoExtensions),Ir(yc.AUDIO,e.send.audioExtensions,t.send.audioExtensions)),e.recv&&(Ir(yc.VIDEO,e.recv.videoExtensions,t.recv.videoExtensions),Ir(yc.AUDIO,e.recv.audioExtensions,t.recv.audioExtensions))}function Ir(e,t,i){t.forEach(t=>{var r;let n=Ie[e].find(e=>{var i;let{key:r}=e;return o5(i=t.extensionName).call(i,r)});if(!n)return;let o=i.find(e=>{let{extensionName:t}=e;return o5(t).call(t,n.key)});o&&o5(r=o.extensionName).call(r,"gdpr_forbidden")&&(t.extensionName=o.extensionName)})}function In(e,t){t.forEach(t=>{var i;let r=Ie[e].find(e=>{var i;let{key:r}=e;return o5(i=t.extensionName).call(i,r)});o5(i=t.extensionName).call(i,"gdpr_forbidden")&&r&&(t.extensionName=r.extensionName)})}function Io(e){return"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e||o5(e).call(e,"abs-send-time")}function Ia(e){return"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e||o5(e).call(e,"draft-holmer-rmcat-transport-wide-cc-extensions-01")}function Is(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function Ic(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Is(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Is(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}function Id(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=arguments.length>3?arguments[3]:void 0,{filterRTX:n,filterVideoFec:o,filterAudioFec:a,filterAudioCodec:s,filterVideoCodec:c,unsupportedVideoUplinkCodec:d,unsupportedVideoDownlinkCodec:l}=t,{useXR:h}=i,u=[],p=[],_=[],E=[],m=!1,f=!1;if(TO(e).mediaDescriptions.forEach(e=>{r&&r!==e.attributes.direction||("video"!==e.media.mediaType||m||(p=e.attributes.payloads,E=e.attributes.extmaps,m=!0),"audio"!==e.media.mediaType||f||(u=e.attributes.payloads,_=e.attributes.extmaps,f=!0))}),!E||0===p.length)throw Error("Cannot get video capabilities from SDP.");if(!_||0===u.length)throw Error("Cannot get audio capabilities from SDP.");
1if(p.forEach(e=>{var t;null!=(t=e.rtpMap)&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),h&&e.rtcpFeedbacks.push({type:"rrtr"})}),u.forEach(e=>{var t;null!=(t=e.rtpMap)&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),h&&e.rtcpFeedbacks.push({type:"rrtr"})}),n&&(u=u.filter(e=>{var t;return"rtx"!==(null==(t=e.rtpMap)?void 0:t.encodingName.toLowerCase())}),p=p.filter(e=>{var t;return"rtx"!==(null==(t=e.rtpMap)?void 0:t.encodingName.toLowerCase())})),o){let e=p.filter(e=>{var t;return/(red)|(ulpfec)|(flexfec)/i.test((null==(t=e.rtpMap)?void 0:t.encodingName)||"")}),t=IO(e,p).map(e=>e.payloadType),i=[...e.map(e=>e.payloadType),...t];p=p.filter(e=>!o5(i).call(i,e.payloadType))}if(a&&(u=u.filter(e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null==(t=e.rtpMap)?void 0:t.encodingName)||"")})),s&&(null==s?void 0:s.length)>0&&(u=u.filter(e=>{var t;return o5(s).call(s,(null==(t=e.rtpMap)?void 0:t.encodingName.toLowerCase())||"")})),c&&(null==c?void 0:c.length)>0){let e=p.filter(e=>{var t;return o5(c).call(c,(null==(t=e.rtpMap)?void 0:t.encodingName.toLowerCase())||"")});p=e.concat(n?[]:IO(e,p))}let S=TR("UNSUPPORTED_VIDEO_CODEC");if(S&&S.length>0){let e=p.filter(e=>e.rtpMap&&o5(S).call(S,e.rtpMap.encodingName.toLowerCase())),t=IO(e,p),i=e.concat(t).map(e=>e.payloadType);p=p.filter(e=>!o5(i).call(i,e.payloadType)),TY.debug("unsupportedVideoCodec: ".concat(S,", toBeRemoved: ").concat(i))}if(d&&d.length>0&&"sendonly"===r){let e=p.filter(e=>e.rtpMap&&o5(d).call(d,e.rtpMap.encodingName.toLowerCase())),t=IO(e,p),i=e.concat(t).map(e=>e.payloadType);p=p.filter(e=>!o5(i).call(i,e.payloadType)),TY.debug("unsupportedVideoUplinkCodec: ".concat(d,", toBeRemoved: ").concat(i))}if(l&&l.length>0&&"recvonly"===r){let e=p.filter(e=>e.rtpMap&&o5(l).call(l,e.rtpMap.encodingName.toLowerCase())),t=IO(e,p),i=e.concat(t).map(e=>e.payloadType);p=p.filter(e=>!o5(i).call(i,e.payloadType)),TY.debug("unsupportedVideoDownlinkCodec: ".concat(l,", toBeRemoved: ").concat(i))}return{audioCodecs:u,videoCodecs:p,audioExtensions:_,videoExtensions:E}}function Il(e){let t,i,r=TO(e);for(let e of r.mediaDescriptions){if(!t){let i=e.attributes.iceUfrag,r=e.attributes.icePwd;if(!i||!r)throw Error("Cannot get iceUfrag or icePwd from SDP.");t={iceUfrag:i,icePwd:r}}if(!i){let t=e.attributes.fingerprints;t.length>0&&(i={fingerprints:t})}}if(!i&&r.attributes.fingerprints.length>0&&(i={fingerprints:r.attributes.fingerprints}),!i||!t)throw Error("Cannot get iceParameters or dtlsParameters from SDP.");return{iceParameters:t,dtlsParameters:i}}function Ih(e,t){let i=[],r=e.attributes.ssrcGroups.filter(e=>"FID"===e.semantic),n=e.attributes.ssrcGroups.find(e=>"SIM"===e.semantic),o=e.attributes.ssrcs;if(n)n.ssrcIds.forEach(e=>{var n;let o=null==(n=r.find(t=>t.ssrcIds[0]===e))?void 0:n.ssrcIds[1];i.push({ssrcId:e,rtx:t?o:void 0})});else if(r.length>0){let e=r[0].ssrcIds[0],n=r[0].ssrcIds[1];i.push({ssrcId:e,rtx:t?n:void 0})}else{if(0===o.length)throw Error("No ssrcs found on local media description.");i.push({ssrcId:o[0].ssrcId})}return i}function Iu(e,t,i){let r,{cname:n}=e,o=[];t&&(o=Ip(t)),0===o.length&&(o=e.iceParameters.candidates.map(e=>({foundation:e.foundation,componentId:"1",transport:e.protocol,priority:e.priority.toString(),connectionAddress:e.ip,port:e.port.toString(),type:e.type,extension:{}})),TY.debug("Using candidates from gateway."));let a={fingerprints:e.dtlsParameters.fingerprints.map(e=>({hashFunction:e.algorithm,fingerprint:e.fingerprint}))},s={iceUfrag:e.iceParameters.iceUfrag,icePwd:e.iceParameters.icePwd};switch(e.dtlsParameters.role){case"server":r="passive";break;case"client":r="active";break;case"auto":r="actpass"}let c=II(e.rtpCapabilities),d=[];return Array.isArray(i)&&i.length>0&&i.forEach(e=>{d.push({kind:yc.VIDEO,ssrcMsg:[{ssrcId:e.v,rtx:e.v_rtx}],mslabel:"".concat(e.v,"_").concat(e.a)},{kind:yc.AUDIO,ssrcMsg:[{ssrcId:e.a}],mslabel:"".concat(e.v,"_").concat(e.a)})}),{dtlsParameters:a,iceParameters:s,candidates:o,rtpCapabilities:c,setup:r,cname:n,preSSRCs:d}}function Ip(e){let t=[];return e.ip&&"number"==typeof e.port&&(t=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:e.ip,port:e.port.toString(),type:"host",extension:{}}],TY.debug("Using remote candidate from AP ".concat(y8(e.ip),":").concat(e.port)),e.ip6&&(t.push({foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:e.ip6,port:e.port.toString(),type:"host",extension:{}}),TY.debug("Using IPV6 remote candidate from AP ".concat(y8(e.ip6),":").concat(e.port)))),t}function I_(e,t,i){let r=[],n=[];
1return e.forEach(e=>{let{ssrcId:o,rtx:a}=e,s=gw(8,"track-"),c={ssrcId:o,attributes:Ic({label:s,mslabel:i=i||gw(10,""),msid:"".concat(i," ").concat(s)},t&&{cname:t})};if(r.push(c),void 0!==a){let e={ssrcId:a,attributes:Ic({label:s,mslabel:i,msid:"".concat(i," ").concat(s)},t&&{cname:t})};r.push(e),n.push({semantic:"FID",ssrcIds:[o,a]})}}),e.length>1&&n.push({semantic:"SIM",ssrcIds:e.map(e=>{let{ssrcId:t}=e;return t})}),{ssrcs:r,ssrcGroups:n}}function IE(e,t){t instanceof CC&&e.attributes.payloads.forEach(e=>{var i;let r=null==(i=e.rtpMap)?void 0:i.encodingName.toLowerCase();if(!r||-1===["opus","pcmu","pcma","g722"].indexOf(r))return;e.fmtp||(e.fmtp={parameters:{}}),"opus"===r&&"number"==typeof TR("OPUS_PTIME")?e.fmtp.parameters.ptime=TR("OPUS_PTIME"):e.fmtp.parameters.minptime="10",e.fmtp.parameters.useinbandfec="1";let n=t._encoderConfig;n&&("pcmu"!==r&&"pcma"!==r&&"g722"!==r&&(n.bitrate&&!Sl()&&(e.fmtp.parameters.maxaveragebitrate="".concat(Math.floor(1e3*n.bitrate))),n.sampleRate&&(e.fmtp.parameters.maxplaybackrate="".concat(n.sampleRate),e.fmtp.parameters["sprop-maxcapturerate"]="".concat(n.sampleRate)),n.stereo&&(e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1")),t instanceof Cv&&"opus"===r&&t._config.DTX&&(e.fmtp.parameters.usedtx="1"))})}function Im(e){let t=e.attributes.unrecognized.findIndex(e=>"x-google-flag"===e.attField&&"conference"===e.attValue);-1!==t&&e.attributes.unrecognized.splice(t,1)}function If(e,t){var i;if(e.attributes.payloads.forEach(e=>{var t;"h264"===(null==(t=e.rtpMap)?void 0:t.encodingName.toLowerCase())&&e.fmtp&&e.fmtp.parameters&&TR("ENABLE_UP_SPS_PPS")&&(e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1")}),!(t instanceof CP&&t._encoderConfig&&-1===t._hints.indexOf(RE.SCREEN_TRACK)))return;let r=t._encoderConfig;T1.supportMinBitrate&&r.bitrateMin&&e.attributes.payloads.forEach(e=>{var t,i;o5(t=["h264","h265","vp8","vp9","av1"]).call(t,(null==(i=e.rtpMap)?void 0:i.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-min-bitrate"]="".concat(r.bitrateMin))}),T1.supportMinBitrate&&!o5(i=t._hints).call(i,RE.LOW_STREAM)&&r.bitrateMax&&e.attributes.payloads.forEach(e=>{var t,i;o5(t=["h264","h265","vp8","vp9","av1"]).call(t,(null==(i=e.rtpMap)?void 0:i.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-start-bitrate"]="".concat(TR("X_GOOGLE_START_BITRATE")||Math.floor(r.bitrateMax)))})}function IS(e){if("video"!==e.media.mediaType)return;let t=St();if(t.name!==f8.SAFARI&&t.os!==f6.IOS)return;let i=e.attributes.extmaps.findIndex(e=>/video-orientation/g.test(e.extensionName));-1!==i&&e.attributes.extmaps.splice(i,1)}function Ig(e,t,i){let r,n;if(t){var o,a;if("video"===e.media.mediaType?(r=i.videoExtensions,n=i.videoCodecs):(r=i.audioExtensions,n=i.audioCodecs),!0===t.twcc){let t=r.find(e=>Ia(e.extensionName));if(t){let i=t.extensionName;e.attributes.extmaps.find(e=>Ia(e.extensionName))||e.attributes.extmaps.push({entry:t.entry,extensionName:i}),(o=n,e.attributes.payloads.filter(e=>!!o.find(t=>t.payloadType===e.payloadType&&!!t.rtcpFeedbacks.find(e=>"transport-cc"===e.type)))).forEach(e=>{e.rtcpFeedbacks.find(e=>"transport-cc"===e.type)||e.rtcpFeedbacks.push({type:"transport-cc"})})}}else if(!1===t.twcc){let t=e.attributes.extmaps.findIndex(e=>Ia(e.extensionName));-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach(e=>{let t=e.rtcpFeedbacks.findIndex(e=>"transport-cc"===e.type);-1!==t&&e.rtcpFeedbacks.splice(t,1)})}if(!0===t.remb){let t=r.find(e=>Io(e.extensionName));if(t){let i=t.extensionName;e.attributes.extmaps.find(e=>e.extensionName===i)||e.attributes.extmaps.push({entry:t.entry,extensionName:i}),(a=n,e.attributes.payloads.filter(e=>!!a.find(t=>t.payloadType===e.payloadType&&!!t.rtcpFeedbacks.find(e=>"goog-remb"===e.type)))).forEach(e=>{e.rtcpFeedbacks.find(e=>"goog-remb"===e.type)||e.rtcpFeedbacks.push({type:"goog-remb"})})}}else if(!1===t.remb){let t=e.attributes.extmaps.findIndex(e=>Io(e.extensionName));-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach(e
1=>{let t=e.rtcpFeedbacks.findIndex(e=>"goog-remb"===e.type);-1!==t&&e.rtcpFeedbacks.splice(t,1)})}}}function IT(e,t,i){if(Sl()||"video"!==e.media.mediaType||!(t instanceof CP)||"vp9"!==i&&"vp8"!==i||"vp8"===i&&!TR("SIMULCAST")||"vp9"===i&&TR("ENABLE_SVC")||void 0===t._scalabilityMode||t._scalabilityMode.numSpatialLayers<=1)return;let r="vp8"===i?2:t._scalabilityMode.numSpatialLayers,n=e.attributes.ssrcs[0],o=e.attributes.ssrcGroups.find(e=>"FID"===e.semantic&&e.ssrcIds[0]===n.ssrcId),a={semantic:"SIM",ssrcIds:[n.ssrcId]};for(let t=1;t<r;t++)e.attributes.ssrcs.push({ssrcId:n.ssrcId+t,attributes:gS(n.attributes)}),a.ssrcIds.push(n.ssrcId+t),o&&(e.attributes.ssrcs.push({ssrcId:o.ssrcIds[1]+t,attributes:gS(n.attributes)}),e.attributes.ssrcGroups.push({semantic:"FID",ssrcIds:[n.ssrcId+t,o.ssrcIds[1]+t]}));e.attributes.ssrcGroups.unshift(a)}async function IR(){try{let e=new RTCPeerConnection;e.addTransceiver("video",{direction:"sendonly",sendEncodings:[{scalabilityMode:Tt.L1T3}]});let t=await e.createOffer();if(!t.sdp)return void e.close();let i=TO(t.sdp).mediaDescriptions[0];if(!i)return;let r=i.attributes.extmaps.find(e=>"https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension"===e.extensionName);return e.close(),r}catch(e){return}}async function IC(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=new RTCPeerConnection;i.addTransceiver("video",{direction:"sendonly"}),i.addTransceiver("audio",{direction:"sendonly"}),i.addTransceiver("video",{direction:"recvonly"}),i.addTransceiver("audio",{direction:"recvonly"});let{send:r,recv:n,sendrecv:o}=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0,r=Id(i,e,t,"sendonly"),n=Id(i,e,t,"recvonly"),o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},a={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(Iy(r,n,"videoExtensions",o,a,s),Iy(r,n,"videoCodecs",o,a,s),Iy(r,n,"audioExtensions",o,a,s),Iy(r,n,"audioCodecs",o,a,s),TR("RAISE_H264_BASELINE_PRIORITY")){let e=[],t=[];if(s.videoCodecs.forEach((i,r)=>{var n,o,a;if("h264"===(null==(n=i.rtpMap)?void 0:n.encodingName.toLocaleLowerCase())){let n=s.videoCodecs[r+1],c=n&&IL(i,n),d=null==(o=i.fmtp)?void 0:o.parameters["profile-level-id"],l=null==(a=i.fmtp)?void 0:a.parameters["packetization-mode"];!d||d!==TR("FIRST_H264_PROFILE_LEVEL_ID")||TR("FIRST_PACKETIZATION_MODE")&&l!==TR("FIRST_PACKETIZATION_MODE")?c?t.push([i,n]):t.push([i]):c?e.push([i,n]):e.push([i])}}),e.length>0&&t.length>0){TY.debug("raising H264 baseline profile priority"),s.videoCodecs.forEach((i,r)=>{var n;if("h264"===(null==(n=i.rtpMap)?void 0:n.encodingName.toLocaleLowerCase())){let n=IL(i,s.videoCodecs[r+1]),o=e.shift()||t.shift()||[];o.length>0&&(n?s.videoCodecs.splice(r,2,...o):s.videoCodecs.splice(r,1,...o))}});let i=a.videoCodecs.filter(e=>{var t,i;return"h264"===(null==(t=e.rtpMap)?void 0:t.encodingName.toLocaleLowerCase())&&(null==(i=e.fmtp)?void 0:i.parameters["profile-level-id"])!==TR("FIRST_H264_PROFILE_LEVEL_ID")});if(i.length>0){let e=IO(i,a.videoCodecs).map(e=>e.payloadType),t=[...i.map(e=>e.payloadType),...e];a.videoCodecs=a.videoCodecs.filter(e=>!o5(t).call(t,e.payloadType))}TR("FILTER_SEND_H264_BASELINE")&&(o.videoCodecs=o.videoCodecs.filter(e=>{var t,i;return"h264"!==(null==(t=e.rtpMap)?void 0:t.encodingName.toLocaleLowerCase())||(null==(i=e.fmtp)?void 0:i.parameters["profile-level-id"])===TR("FIRST_H264_PROFILE_LEVEL_ID")}))}}return{send:o,recv:a,sendrecv:s}}(e,t,(await i.createOffer()).sdp);try{i.close()}catch(e){}return{send:r,recv:n,sendrecv:o}}function Iv(){let e={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},t=Id(arguments.length>2?arguments[2]:void 0,arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},"recvonly"),i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(Iy(e,t,"videoExtensions",i,r,n),Iy(e,t,"videoCodecs",i,r,n),Iy(e,t,"audioExtensions",i,r,n),Iy(e,t,"audioCodecs",i,r,n),TR("RAISE_H264_BASELINE_PRIORITY")){let e=n.videoCodecs.findIndex(e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"===e.fmtp.parameters["profile-level-id"]);if(-1!==e){let t=n.videoCodecs.findIndex(e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase());if(t<e){TY.debug("raising H264 baseline profile priority");let i=n.videoCodecs[e];n.videoCodecs.splice(e,1),n.videoCodecs.splice(t,0,i)}-1!==t&&(r.videoCodecs=r.videoCodecs.filter(e=>!(e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"!==e.fmtp.parameters["profile-level-id"])))}}return{send:i,recv:r,sendrecv:n}}function Iy(e,t,i,r,n,o){if("videoExtensions"===i||"audioExtensions"===i){let a=[];
1return e[i].forEach(e=>{t[i].some((t,i)=>{if(e.entry===t.entry&&e.extensionName===t.extensionName)return a.push(i),!0})?o[i].push(e):r[i].push(e)}),void t[i].forEach((e,t)=>{-1===a.indexOf(t)&&n[i].push(e)})}if("videoCodecs"===i||"audioCodecs"===i){let a=[];return e[i].forEach(e=>{t[i].some((t,i)=>{if(e.payloadType===t.payloadType&&JSON.stringify(e)===JSON.stringify(t))return a.push(i),!0})?o[i].push(e):r[i].push(e)}),void t[i].forEach((e,t)=>{-1===a.indexOf(t)&&n[i].push(e)})}}function II(e){let t,i,{send:r,recv:n,sendrecv:o}=e;if(!o){if(!r||!n)throw Error("cannot merge rtp capabilities because one of send or recv is empty!");return{send:r,recv:n}}return r?((t={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]}).audioCodecs=[...r.audioCodecs,...o.audioCodecs],t.videoCodecs=[...r.videoCodecs,...o.videoCodecs],t.audioExtensions=[...r.audioExtensions,...o.audioExtensions],t.videoExtensions=[...r.videoExtensions,...o.videoExtensions]):t=gS(o),n?((i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]}).audioCodecs=[...n.audioCodecs,...o.audioCodecs],i.videoCodecs=[...n.videoCodecs,...o.videoCodecs],i.audioExtensions=[...n.audioExtensions,...o.audioExtensions],i.videoExtensions=[...n.videoExtensions,...o.videoExtensions]):i=gS(o),{send:t,recv:i}}function IA(e){"audio"===e.media.mediaType&&e.attributes.payloads.filter(e=>{var t;return"opus"===(null==(t=e.rtpMap)?void 0:t.encodingName.toLowerCase())}).forEach(e=>{e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1"})}function Ib(e,t,i,r){let n=[];if(e===yc.VIDEO){if(TR("H264_PROFILE_LEVEL_ID")&&"h264"===r&&(n=t.videoCodecs.filter(e=>{var t;return o5(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,r)&&e&&e.fmtp&&e.fmtp.parameters["profile-level-id"]===TR("H264_PROFILE_LEVEL_ID")})),!Array.isArray(n)||0===n.length){let e=[],o=[],a=[],s=[];if(i.videoCodecs.forEach(t=>{let i=t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"";o5(i).call(i,r)?e.push(t):o5(i).call(i,"vp9")?o.push(t):o5(i).call(i,"vp8")?a.push(t):o5(i).call(i,"h264")&&s.push(t)}),0===e.length){let t="";0!==o.length?(e=o,t="vp9"):0!==a.length?(e=a,t="vp8"):0!==s.length&&(e=s,t="h264"),TY.warning("codec ".concat(r," not included in rtpCapabilities, fallback to default payloads: ").concat(t))}0!==e.length&&(n=t.videoCodecs.filter(t=>e.some(e=>e.payloadType===t.payloadType)))}if(0===n.length&&(TY.warning("codec ".concat(r," not included in rtpCapabilities, fallback to default payloads: ").concat(t.videoCodecs[0].rtpMap&&t.videoCodecs[0].rtpMap.encodingName)),n=t.videoCodecs),TR("USE_PUB_RTX")||TR("USE_SUB_RTX")){let e=IO(n,t.videoCodecs);n=[...n,...e]}}else{n=t.audioCodecs.filter(e=>{var t;return o5(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,r)});let e=t.audioCodecs.filter(e=>{var t;return o5(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,"red")});0===n.length&&(TY.warning("codec ".concat(r," not included in rtpCapabilities, fallback to opus")),n=t.audioCodecs.filter(e=>{var t;return o5(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,"opus")})),TR("ENABLE_AUDIO_RED")&&0!==e.length&&(n=[...e,...n])}return n}function IO(e,t){let i=e.map(e=>e.payloadType.toString());return t.filter(e=>e.rtpMap&&"rtx"===e.rtpMap.encodingName&&e.fmtp&&e.fmtp.parameters.apt&&o5(i).call(i,e.fmtp&&e.fmtp.parameters.apt))}async function Iw(e,t,i){let r=t.toString(),n=function e(t,i,r,n){if(TR("SDP_LOGGING"))return TY.upload("exchanging ".concat(r," ").concat(i," SDP during P2PConnection.").concat(n,"\n"),t),"offer"===i?t=>{e(t,"answer","local"===r?"remote":"local",n)}:void 0}(r,"offer","remote","exchangeSDP");await e.setRemoteDescription({type:"offer",sdp:r});let o=await e.createAnswer();if(!o.sdp)throw Error("cannot get answer sdp");let a=o.sdp;a=IN(a,i||{}),null==n||n(a||""),await e.setLocalDescription({type:"answer",sdp:a})}function IN(e,t,i){if(TR("FORBID_MODIFY_LOCAL_OFFER_SDP"))return e;let r=TO(e),{useXR:n}=t;return r.mediaDescriptions.forEach(e=>{var t,r;e.attributes.mid&&(Array.isArray(i)&&!o5(i).call(i,e.attributes.mid)||("audio"===e.media.mediaType&&IA(e),"video"===e.media.mediaType&&"video"===(r=e).media.mediaType&&TR("ENABLE_DOWN_SPS_PPS")&&r.attributes.payloads.filter(e=>{var t;return"h264"===(null==(t=e.rtpMap)?void 0:t.encodingName.toLowerCase())}
1).forEach(e=>{e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1"}),n&&o5(t=["audio","video"]).call(t,e.media.mediaType)&&e.attributes.payloads.forEach(e=>{-1===e.rtcpFeedbacks.findIndex(e=>"rrtr"===e.type)&&e.rtcpFeedbacks.push({type:"rrtr"})})))}),Tw(r)}async function ID(e,t,i){try{var r;if(!T1.supportSetRtpSenderParameters||"vp9"!==e&&"av1"!==e||!TR("ENABLE_SVC"))return;let n={},o=t.getParameters(),a=null==(r=o.encodings)?void 0:r[0];n.scalabilityMode=y7(i),a&&Object.assign(a,n),Object.assign(o,{}),await t.setParameters(o),TY.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode success: ".concat(JSON.stringify(o.encodings)))}catch(e){TY.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode failed",e)}}function IP(e){let t=TR("COMPATIBLE_SDP_EXTENSION");return!!(Array.isArray(t)&&t.length>0)&&t.some(t=>o5(e).call(e,t))}function IL(e,t){try{var i;return(null==(i=e.fmtp)?void 0:i.parameters.apt)===t.payloadType.toString()}catch(e){return!1}}function Ik(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function IM(e,t){return typeof TR(e)===t?TR(e):void 0}let IU={};function Ix(e){(!(arguments.length>1&&void 0!==arguments[1])||arguments[1])&&TY.debug("install service ".concat(e.name)),IU[e.name]=e}function IV(e){let t=IU[e];if(!t)throw new Sx(SU.INVALID_OPERATION,"".concat(e," not found, please use AgoraRTC.use(").concat(e,"Service) to load it first"));return t}function IF(e,t){return IV("DataStream").create(e,t)}function IB(){return IV("InterceptFrame").create()}function Ij(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function IG(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Ij(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Ij(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let IW=new Map;class IH extends S0{get state(){return this._state}set state(e){if(e===this._state)return;let t=this._state;this._state=e,"DISCONNECTED"===e&&this._disconnectedReason?this.emit(v8.CONNECTION_STATE_CHANGE,e,t,this._disconnectedReason):this.emit(v8.CONNECTION_STATE_CHANGE,e,t)}get joinGatewayStartTime(){return this._joinGatewayStartTime}set joinGatewayStartTime(e){TY.debug("[".concat(this.store.clientId,"] set joinGatewayStartTime at ").concat(e)),this._joinGatewayStartTime=e}setUsingProxy(e){this.usingProxy=e}async join(e,t,i){if(this.store.useDcSignal){let t=!1;"disabled"!==e.cloudProxyServer?(TY.debug("[".concat(this.store.clientId,"] Dc is not supported, because cloudProxyServer are not supported (").concat(e.cloudProxyServer,")")),t=!0):"".concat(e.apResponse.cid,"_").concat(e.apResponse.cert).length>255||"".concat(e.apResponse.cid,"_").concat(e.apResponse.cert).length<22?(TY.debug("[".concat(this.store.clientId,"] Dc is not supported, because ticket length is incorrect, it has to be between 22 and 255")),t=!0):e.apResponse.addresses.some(e=>e.fingerprint)||TR("FINGERPRINT")||(TY.debug("[".concat(this.store.clientId,"] Dc is not supported, because fingerprint does not exist")),t=!0),t&&this.resetSignal()}this.store.joinGatewayStart(),"disabled"!==e.cloudProxyServer&&(this.hasChangeBGPAddress=!0);let r=Date.now(),n=IW.get(e.cname);if(n||(n=new Map,IW.set(e.cname,n)),this._isProactiveJoin=!0,n.has(e.uid)){let t=new T0(SU.UID_CONFLICT);throw T$.joinGateway(e.sid,{lts:r,succ:!1,ec:t.code,addr:null,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,isProxy:!!e.proxyServer||this.usingProxy,signalChannel:this.store.useDcSignal?"1":"0",preload:e.preload}),t}n.set(e.uid,!0),this.joinInfo=e,this.key=t;let o=0;this.joinGatewayStartTime=r;let a=e.proxyServer,s=this.store.useDcSignal?"datachannel":"websocket";try{TY.debug("[".concat(this.store.clientId,"] use ").concat(s," join uid ").concat(o));let t=e.gatewayAddrs.map(t=>{let{address:i}=t,[r,n]=i.split(":"),o={host:r,port:n};return e.proxyServer&&(o.proxy=e.proxyServer),o});o=(this.store.useDcSignal?await this.signal.init(e.apResponse.addresses):await this.signal.init(t)).uid,TY.debug("[".concat(this.store.clientId,"] ").concat(s," join uid ").concat(o," cost ").concat(Date.now()-this.joinGatewayStartTime))}catch(t){var c;if(t.code===SU.INIT_DATACHANNEL_TIMEOUT&&"AgoraRTCSignal"===this.signal.__name__||T$.joinGateway(e.sid,{lts:r,succ:!1,ec:(null==(c=t.data)?void 0:c.desc)||t.code,errorMsg:t.message,addr:this.signal.url,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,isProxy:!!a||this.usingProxy,signalChannel:"DataChannelSignal"===this.signal.__name__?"1":"0",preload:e.preload}),t&&t.code===SU.INIT_DATACHANNEL_TIMEOUT)throw TY.warning("[".concat(this.store.clientId,"] User join datachannel failed"),t.toString()),this.resetSignal(),t;throw TY.error("[".concat(this.store.clientId,"] User join failed"),t.toString()),n.delete(e.uid),this.signal.close(),t}return this.state="CONNECTED",this.inChannelInfo.joinAt=Date.now(),TY.debug("[".concat(this.store.clientId,"] Connected to gateway server")),this.trafficStatsInterval=window.setInterval(()=>{this.updateTrafficStats().catch(e=>{TY.warning("[".concat(this.store.clientId,"] get traffic stats error"),e.toString())})},3e3),this.networkQualityInterval=window.setInterval(()=>{navigator&&void 0!==navigator.onLine&&!navigator.onLine?this.emit
1(v8.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6}):this._signalTimeout?this.emit(v8.NETWORK_QUALITY,{downlinkNetworkQuality:5,uplinkNetworkQuality:5}):"CONNECTED"===this.state&&this._statsCollector.trafficStats?this.emit(v8.NETWORK_QUALITY,{uplinkNetworkQuality:y2(this._statsCollector.trafficStats.B_unq),downlinkNetworkQuality:y2(this._statsCollector.trafficStats.B_dnq)}):this.emit(v8.NETWORK_QUALITY,{uplinkNetworkQuality:0,downlinkNetworkQuality:0})},2e3),this.store.joinGatewayEnd(),o}async leave(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0;if("DISCONNECTED"!==this.state){t!==S8.FALLBACK&&(this.state="DISCONNECTING");try{var i;e||this.signal.connectionState!==vV.CONNECTED||await (i=this.signal.request(vB.LEAVE,void 0,!0),3e3==1/0?i:dQ.race([i,function(e){let t=new Sx(SU.TIMEOUT,"timeout");return new dQ((e,i)=>{window.setTimeout(()=>i(t),3e3)})}(3e3)]))}catch(e){TY.warning("[".concat(this.store.clientId,"] leave request failed, ignore"),e)}this.signal.close(t),t!==S8.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}}async publish(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new T0(SU.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));let r={state:"offer",p2p_id:this.store.p2pId,ortc:t,mode:this.spec.mode,extend:TR("PUB_EXTEND"),twcc:!!TR("PUBLISH_TWCC"),rtx:!!TR("USE_PUB_RTX")};try{return(await this.signal.request(vB.PUBLISH,r,!0))._message}catch(r){if(i&&r.data&&r.data.code===vx.ERR_PUBLISH_REQUEST_INVALID)return TY.warning("[".concat(this.store.clientId,"] receive publish error code, retry"),r.toString()),await this.tryUnpubBeforeRepub(e,t),this.publish(e,t,!1);throw r}}async publishDataChannel(e,t,i){var r;if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new T0(SU.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));let n={stream_id:t.streamId,ordered:+!!t.ordered,max_retrans_times:null!=(r=t.maxRetransmits)?r:10,channel_id:t.channelId,metadata:t.metadata};try{await this.signal.request(vB.PUBLISH_DATASTREAM,n,!0)}catch(r){if(i&&r.data&&r.data.code===vx.ERR_PUBLISH_REQUEST_INVALID)return TY.warning("[".concat(this.store.clientId,"] receive publish datachannels error code, retry"),r.toString()),await this.tryUnpubDataChannelBeforeRepub(e,t),this.publishDataChannel(e,t,!1);throw r}}async unpublish(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new T0(SU.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await this.signal.request(vB.UNPUBLISH,{stream_id:t,ortc:e},!0)}catch(e){TY.warning("[".concat(this.store.clientId,"] unpublish warning: "),e)}}async unpublishDataChannel(e){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new T0(SU.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await dQ.all(e.map(e=>this.signal.request(vB.UNPUBLISH_DATASTREAM,{channel_id:e},!0)))}catch(e){TY.warning("unpublish datachannels warning: ",e)}}async presubscribe(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new T0(SU.INVALID_OPERATION,"can not presubscribe when connection state is ".concat(this.state));let r={stream_id:e,stream_type:t,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!TR("SUBSCRIBE_TWCC"),rtx:!!TR("USE_SUB_RTX")||void 0,extend:TR("SUB_EXTEND"),svc:Array.isArray(TR("SVC"))&&0!==TR("SVC").length?TR("SVC"):void 0};try{return await this.signal.request(vB.PRE_SUBSCRIBE,r,!0)}catch(r){if(i&&r.data&&r.data.code===vx.ERR_SUBSCRIBE_REQUEST_INVALID)return TY.warning("[".concat(this.store.clientId,"] pre-subscribe error, retry"),r.toString()),this.presubscribe(e,t,!1);throw r}}async subscribe(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new T0(SU.INVALID_OPERATION,"can not subscribe when connection state is ".concat(this.state));let r={stream_id:e,stream_type:t.stream_type,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!TR("SUBSCRIBE_TWCC"),rtx:!!TR("USE_SUB_RTX"),extend:TR("SUB_EXTEND"),ssrcId:t.ssrcId,svc:Array.isArray(TR("SVC"))&&0!==TR("SVC").length?TR("SVC"):void 0};try{return(await this.signal.request(vB.SUBSCRIBE,r,!0))._message}catch(r){if(i&&r.data&&r.data.code===vx.ERR_SUBSCRIBE_REQUEST_INVALID)return TY.warning("[".concat(this.store.clientId,"] receiver subscribe error code, retry"),r.toString()),await this.tryUnsubBeforeResub(e,t),await this.subscribe(e,t,!1);throw r}}
vendor: 4,811 bytes, line 1
1async subscribeDataChannel(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new T0(SU.INVALID_OPERATION,"can not subscribe datachannel when connection state is ".concat(this.state));let r={uid:e,stream_id:t.id,channel_id:t.datachannelId};try{return void await this.signal.request(vB.SUBSCRIBE_DATASTREAM,r,!0)}catch(r){if(i&&r.data&&r.data.code===vx.ERR_SUBSCRIBE_REQUEST_INVALID)return TY.warning("[".concat(this.store.clientId,"] receiver subscribe datachannel error code, retry"),r.toString()),await this.tryUnsubDataChannelBeforeResub(e,t),await this.subscribeDataChannel(e,t,!1);throw r}}async subscribeAll(e,t){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new T0(SU.INVALID_OPERATION,"can not massSubscribe when connection state is ".concat(this.state));let i={p2p_id:this.store.p2pId,users:e,dtx:!1,rtx:!!TR("USE_SUB_RTX"),twcc:!!TR("SUBSCRIBE_TWCC"),svc:Array.isArray(TR("SVC"))&&0!==TR("SVC").length?TR("SVC"):void 0};try{return await this.signal.request(vB.SUBSCRIBE_STREAMS,i,!0)}catch(i){if(t&&i.data&&i.data.code===vx.ERR_SUBSCRIBE_REQUEST_INVALID)return TY.warning("[".concat(this.store.clientId,"] receiver massSubscribe error code, retry"),i.toString()),await this.tryMassUnsubBeforeResub(e),await this.subscribeAll(e,!1);throw i}}async setVideoProfile(e){let t=function(e){if(!(e.bitrateMax&&e.bitrateMin&&e.frameRate&&e.height&&e.width))return;let t=e.frameRate,i=e.width,r=e.height,n=!0;return"number"!=typeof t&&((t=t.exact||t.ideal||t.max||t.min||0)||(n=!1)),"number"!=typeof i&&((i=i.exact||i.ideal||i.max||i.min||0)||(n=!1)),"number"!=typeof r&&(r=r.exact||r.ideal||r.max||r.min||0,t||(n=!1)),n?{stream_type:0,width:i,height:r,fps:t,start_bps:1e3*e.bitrateMax,min_bps:1e3*e.bitrateMin,target_bps:1e3*e.bitrateMax}:void 0}(e);if(t)return this.signal.request(vB.SET_VIDEO_PROFILE,t);TY.debug("[".concat(this.store.clientId,"] encoder config is not complete, do not report to gateway"))}async unsubscribe(e,t){try{await this.signal.request(vB.UNSUBSCRIBE,{p2p_id:this.store.p2pId,ortc:e,stream_id:t},!0)}catch(e){TY.warning("[".concat(this.store.clientId,"] unsubscribe warning: "),e)}}async unsubscribeDataChannel(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new T0(SU.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await dQ.all(e.map(e=>this.signal.request(vB.UNSUBSCRIBE_DATASTREAM,{stream_id:e,uid:t},!0)))}catch(e){TY.warning("unsubscribeDataChannel warning: ",e)}}async massUnsubscribe(e){try{await this.signal.request(vB.UNSUBSCRIBE_STREAMS,e,!0)}catch(e){TY.warning("[".concat(this.store.clientId,"] massUnsubscribeAll warning: "),e)}}async reconnectPC(e){let{iceParameters:t,dtlsParameters:i,rtpCapabilities:r}=e;return{gatewayEstablishParams:await this.signal.request(vB.CONNECT_PC,{p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:{iceParameters:t,dtlsParameters:i,rtpCapabilities:r}},!0),gatewayAddress:this.getCurrentGatewayAddress()}}getGatewayInfo(){return this.signal.request(vB.GATEWAY_INFO)}async renewToken(e){await this.signal.request(vB.RENEW_TOKEN,e),this.key=e.token}updateClientRole(e,t){t&&(this._clientRoleOptions=Object.assign({},t)),TR("CLIENT_ROLE_OPTIONS")&&(TY.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(TR("CLIENT_ROLE_OPTIONS"))," instead of ").concat(JSON.stringify(this._clientRoleOptions)," ")),this._clientRoleOptions=Object.assign({},TR("CLIENT_ROLE_OPTIONS"))),this.role=e}async setClientRole(e,t){if(t&&(this._clientRoleOptions=Object.assign({},t)),TR("CLIENT_ROLE_OPTIONS")&&(this._clientRoleOptions=Object.assign({},TR("CLIENT_ROLE_OPTIONS")),TY.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(TR("CLIENT_ROLE_OPTIONS"))," instead of ").concat(JSON.stringify(this._clientRoleOptions)," "))),"CONNECTED"!==this.state)return void(this.role=e);let i,r=0;"audience"===e?this._clientRoleOptions&&this._clientRoleOptions.delay?(i=this._clientRoleOptions.delay,r=1):r=this._clientRoleOptions&&this._clientRoleOptions.level?this._clientRoleOptions.level:2:r=0;let n=Object.assign({},t);delete n.delay,delete n.level,await this.signal.request(vB.SET_CLIENT_ROLE,IG(IG({role:e,level:r,delay:i},n),{},{client_ts:Date.now()})),this.role=e}async setDualStreamMode(e,t,i){await this.signal.request(vB.SET_DUAL_STREAM_MODE,{mode:e},i,t)}async setRemoteVideoStreamType(e,t){await this.signal.request(vB.SWITCH_VIDEO_STREAM,{stream_id:e,stream_type:t})}async setDefaultRemoteVideoStreamType(e){await this.signal.request(vB.DEFAULT_VIDEO_STREAM,{stream_type:e})}async setStreamFallbackOption(e,t){await this.signal.request(vB.SET_FALLBACK_OPTION,{stream_id:e,fallback_type:t})}async pickSVCLayer(e,t){await this.signal.request(vB.PICK_SVC_LAYER,{stream_id:e,spatial_layer:t.spatialL
1ayer,temporal_layer:t.temporalLayer})}async setRTM2Flag(e){await this.signal.request(vB.SET_RTM2_FLAG,{rtm2_flag:e})}async sendExtensionMessage(e,t,i){if(this.store.useP2P)return this.signal.sendExtensionMessage(e,t,i)}getInChannelInfo(){return this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt),IG({},this.inChannelInfo)}async setConfigure(e){if(e&&Array.isArray(e)&&0!==e.length)return this.signal.request(vB.CONFIGURE,e)}async getGatewayVersion(){return(await this.signal.request(vB.GATEWAY_INFO)).version}reset(){if(this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt,this.inChannelInfo.joinAt=null),this.trafficStatsInterval&&(window.clearInterval(this.trafficStatsInterval),this.trafficStatsInterval=void 0),this.joinInfo){let e=IW.get(this.joinInfo.cname);e&&e.delete(this.joinInfo.uid)}this.joinInfo=void 0,this.key=void 0,this.networkQualityInterval&&(window.clearInterval(this.networkQualityInterval),this.networkQualityInterval=void 0),this.usingProxy=!1}updateTurnConfigFromSignal(){var e;let t;if(!this.joinInfo)return;let i=(t=(e=("disabled"===this.joinInfo.cloudProxyServer?this.signal.url:this.joinInfo.gatewayAddrs[this.signal.currentURLIndex].address)||"").startsWith("dc")?e.match(/(dc\:\/\/)?([^:]+):(\d+)/):e.match(/(wss\:\/\/)?([^:]+):(\d+)/))?{username:T_.username,password:T_.password,turnServerURL:t[2],tcpport:parseInt(t[3])+30,udpport:parseInt(t[3])+30,forceturn:!1}:null;this.joinInfo.turnServer.serversFromGateway=[],i&&"off"!==this.joinInfo.turnServer.mode&&"disabled"===this.joinInfo.cloudProxyServer&&this.joinInfo.turnServer.serversFromGateway.push(IG(IG({},T_),{},{turnServerURL:i.turnServerURL,tcpport:i.tcpport,udpport:i.udpport,username:this.joinInfo.uid.toString(),password:this.joinInfo.token}))}async updateTrafficStats(){if("CONNECTED"!==this.state)return;let e=await this.signal.request(vB.TRAFFIC_STATS,void 0,!0);e.timestamp=Date.now(),null!=e.ntp_offset&&(this.ntpOffset=e.ntp_offset),e.peer_delay.forEach(e=>{let t=this._statsCollector.trafficStats&&this._statsCollector.trafficStats.peer_delay.find(t=>t.peer_uid===e.peer_uid);t&&t.B_st!==e.B_st&&gf(()=>{this.emit(v8.STREAM_TYPE_CHANGE,e.peer_uid,e.B_st)})}),this._statsCollector.updateTrafficStats(e)}getJoinMessage(e){var t,i,r,n,o;if(!this.joinInfo||!this.key)throw new T0(SU.UNEXPECTED_ERROR,"can not generate join message, no join info");let a=Object.assign({},this.joinInfo.apResponse),s=TR("REPORT_APP_SCENARIO");if("string"!=typeof s)try{s=JSON.stringify(s)}catch(e){s=void 0}s&&s.length>128&&(s=void 0),this.store.hasStartJoinChannel=!0,this.store.isABTestSuccess||this.emit(v8.UPDATE_GATEWAY_CONFIG),o=this.store.clientId,o5(vp).call(vp,o)||vp.push(o);let c=T5(this.store),d=!(null==(t=this.isPreallocation)||!t.call(this)),l=T4(this.store),h=function(){try{let e=TR("EXPERIMENTS")||{};return"string"==typeof e||Array.isArray(e)?{}:function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Ik(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Ik(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}({},e)}catch(e){return TY.debug("handle gateway attributes failed: ",e),{}}}(),u=Su(87)||Sc()||Sm(117),p=(function(){let e=St();if(e.name!==f8.SAFARI||!e.browserVersion)return!1;let t=e.browserVersion.split(".");return Number(t[0])>18||18===Number(t[0])&&Number(t[1])>=4}()||SS(18,4,!1))&&ST(18,6,!0)&&"h264"===this.spec.codec&&TR("ENABLE_ABSSENDTIME_AS_SENTTS"),_=!("CN"!==(null==(i=a.detail)?void 0:i[3])||!TR("ENABLE_QUALITY_FALLBACK"))&&TR("ENABLE_QUALITY_FALLBACK"),E=!!TR("ENABLE_AP_MULTI_IP")&&"multi-ip"===(null==(r=a.detail)?void 0:r[5]),m=IG({license:this.joinInfo.license,p2p_id:this.store.p2pId,session_id:this.joinInfo.sid,app_id:this.joinInfo.appId,channel_key:this.key,channel_name:this.joinInfo.cname,sdk_version:Th,browser:navigator.userAgent,process_id:TR("PROCESS_ID"),mode:this.store.useP2P?"p2p":this.spec.mode,codec:this.spec.codec,role:this.role,has_changed_gateway:E||this.hasChangeBGPAddress,ap_response:a,extend:TR("JOIN_EXTEND"),details:{6:this.joinInfo.stringUid,cservice_map:"proxy3"===this.joinInfo.cloudProxyServer?"1":"proxy5"===this.joinInfo.cloudProxyServer?"2":void 0},features:{rejoin:!0},optionalInfo:this.joinInfo.optionalInfo,appScenario:s,attributes:{userAttributes:IG(IG({enableEncodedTransform:(!!TR("ENABLE_AUDIO_METADATA")||!!TR("ENABLE_AUDIO_PTS"))&&u||!!TR("ENABLE_AUDIO_TOPN")&&S_(f8.CHROME,87,116)||void 0,enableAudioMetadata:!!TR("ENABLE_AUDIO_METADATA")&&u,enableAudioPts:!!TR("ENABLE_AUDIO_PTS")&&u,topnSmoothLevel:TR("TOPN_SMOOTH_LEVEL"),topnNewSpeakerDelay:TR("TOPN_NEW_SPEAKER_DELAY"),topnSwitchHoldMs:TR("TOPN_SWITCH_HOLD_MS"),topnAudioGain:TR("TOPN_AUDIO_GAIN"),enableNetworkQualityProbe:this.store.networkQualityProbe,enablePublishedUserList:TR("ENABLE_PUBLISHED_USER_LIST"),maxSubscription:TR("MAX_SUBSCRIPTION"),subscribeAudioFilterTopN:IM("SUBSCRIBE_AUDIO_FILTER_TOPN","number"),enablePublishAudioFilter:IM("ENABLE_PUBLISH_AUDIO_FILTER","boolean"),enableUserLicenseCheck:IM("ENABLE_USER_LICENSE_CHECK","boolean"),enableRTX:!0===TR("USE_PUB_RTX")||!0===TR("USE_SUB_RTX")||void 0,disableFEC:TR("DISABLE_FEC"),enableNTPReport:!!TR("ENABLE_NTP_REPORT")||void 0,enableInstantVideo:l,enableFulllinkAvSync:!!TR("ENABLE_FULL_LINK_AV_SYNC")||void 0,enableDataStream2:IM("ENABLE_DATASTREAM_2","boolean"),enableAutFeedback:!!TR("FORCE_ENABLE_AUT_CC")||!T3()&&(!!TR("ENABLE_AUT_FEEDBACK")||void 0),rtm2Flag:"number"==typeof this.joinInfo.rtmFlag?this.joinInfo.rtmFlag:void 0,enableUserAutoRebalanceCheck:!!TR("ENABLE_USER_AUTO_REBALANCE_CHECK"),enableXR:IM("USE_XR","boolean"),enableLossbasedBwe:IM("ENABLE_LOSSBASED_BWE","boolean"),enableAutCC:!!TR("FORCE_ENABLE_AUT_CC")||!T3()&&(!!TR("ENABLE_AUT_CC")||void 0),enableCCF
1allback:IM("ENABLE_CC_FALLBACK","boolean"),enablePreallocPC:d,preSubNum:c?IM("PRE_SUB_NUM","number"):void 0,enablePubTWCC:IM("PUBLISH_TWCC","boolean"),enableSubTWCC:IM("SUBSCRIBE_TWCC","boolean"),enablePubRTX:IM("USE_PUB_RTX","boolean"),enableSubRTX:IM("USE_SUB_RTX","boolean"),enableSubSVC:TR("ENABLE_SVC")?TR("ENABLE_SVC_DEFAULT_CODECS"):Array.isArray(TR("SVC"))&&0!==TR("SVC").length?TR("SVC"):void 0,enableSvcExtended:TR("ENABLE_SVC")&&Array.isArray(TR("SVC_EXTENDED"))&&0!==TR("SVC_EXTENDED").length?TR("SVC_EXTENDED"):void 0,enableVosFallback:TR("ENABLE_VOS_FALLBACK"),enableQualityFallback:_},h),{},{audioDuplicate:IM("ENABLE_AUDIO_RED","boolean")?null!=(n=IM("AUDIO_DUPLICATE_NUM","number"))?n:2:void 0,senttsUsesAbsSendTime:!!p||void 0,enableDualStreamFlag:IM("ENABLE_DUAL_STREAM_FLAG","boolean")})},join_ts:this.joinGatewayStartTime},e);return this.joinInfo.stringUid&&(m.string_uid=this.joinInfo.stringUid),this.joinInfo.aesmode&&this.joinInfo.aespassword&&(m.aes_mode=this.joinInfo.aesmode,TR("ENCRYPT_AES")?(m.aes_secret=this.joinInfo.aespassword,m.aes_encrypt=!0):m.aes_secret=this.joinInfo.aespassword,this.joinInfo.aessalt&&(m.aes_salt=this.joinInfo.aessalt)),a.addresses[this.signal.websocket.currentURLIndex]&&(m.ap_response.ticket=a.addresses[this.signal.websocket.currentURLIndex].ticket,delete a.addresses),void 0!==this.joinInfo.defaultVideoStream&&(m.default_video_stream=this.joinInfo.defaultVideoStream),m}getRejoinMessage(){if(!this.joinInfo)throw new T0(SU.UNEXPECTED_ERROR,"can not generate rejoin message, no join info");return{session_id:this.joinInfo.sid,channel_name:this.joinInfo.cname,cid:this.joinInfo.cid,uid:this.joinInfo.uid,vid:Number(this.joinInfo.vid)}}handleSignalEvents(){this.signal.on(vF.WS_RECONNECT_CREATE_CONNECTION,e=>{this.joinGatewayStartTime=Date.now()}),this.signal.on(vF.WS_RECONNECTING,e=>{this.joinInfo&&T$.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:e||gn.NETWORK_ERROR}),this.joinInfo&&(this.state="RECONNECTING",T$.sessionInit(this.joinInfo.sid,{lts:(new Date).getTime(),extend:this.isSignalRecover?{recover:!0}:{rejoin:!0}
1,cname:this.joinInfo.cname,appid:this.joinInfo.appId,mode:this.spec.mode,stringUid:this.joinInfo.stringUid,channelProfile:+("live"===this.spec.mode),channelMode:0,lsid:this.joinInfo.sid,clientRole:"audience"===this.role?2:1,buildFormat:1}),this.isSignalRecover=!1,this.joinGatewayStartTime=Date.now())}),this.signal.on(vF.WS_CLOSED,e=>{let t;switch(e){case S8.LEAVE:t=gn.LEAVE;break;case S8.UID_BANNED:case S8.IP_BANNED:case S8.CHANNEL_BANNED:case S8.SERVER_ERROR:t=gn.SERVER_ERROR;break;case S8.FALLBACK:t=gn.FALLBACK;break;case S8.LICENSE_MISSING:case S8.LICENSE_EXPIRED:case S8.LICENSE_MINUTES_EXCEEDED:case S8.LICENSE_PERIOD_INVALID:case S8.LICENSE_MULTIPLE_SDK_SERVICE:case S8.LICENSE_ILLEGAL:case S8.TOKEN_EXPIRE:t=e;break;default:t=gn.NETWORK_ERROR}TY.debug("[".concat(this.store.clientId,"] [signal] websocket closed, reason: ").concat(t||"undefined -> "+gn.NETWORK_ERROR)),this.joinInfo&&T$.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:e===S8.LEAVE?1:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:t}),this._disconnectedReason=e,e!==S8.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}),this.signal.on(vF.WS_CONNECTED,()=>{if(this.updateTurnConfigFromSignal(),this.state="CONNECTED",this.joinInfo){if("audience"===this.role){let e=TR("CLIENT_ROLE_OPTIONS")||this._clientRoleOptions;e&&(e.level||e.delay)&&(TY.debug("[".concat(this.store.clientId,"] patch to send set client role, role: ").concat(this.role,", mode: ").concat(this.spec.mode,", level: ").concat(e.level,", delay: ").concat(e.delay)),this.setClientRole(this.role,e))}if(T$.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!0,ec:null,vid:this.joinInfo.vid,addr:this.signal.url,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,isProxy:!!this.joinInfo.proxyServer||this.usingProxy,signalChannel:"DataChannelSignal"===this.signal.__name__?"1":"0",preload:this.joinInfo.preload,isABTestSuccess:this.store.isABTestSuccess}),this._isProactiveJoin=!1,this.joinInfo.useLocalAccessPoint&&1===this.joinInfo.setLocalAPVersion){let e=this.signal.url&&this.signal.url.match(/wss\:\/\/([^:]+):(\d+)/);if(!e)return void TY.error("[".concat(this.store.clientId,"] set local access point after joined failed: ").concat(e));TT("EVENT_REPORT_DOMAIN",e[1]),TT("EVENT_REPORT_BACKUP_DOMAIN",e[1]),TT("LOG_UPLOAD_SERVER","".concat(e[1],":6444"))}}}),this.signal.on(vG.ON_UPLINK_STATS,e=>{this._statsCollector.updateUplinkStats(e)}),this.signal.on(vF.REQUEST_RECOVER,(e,t,i)=>{if(!this.joinInfo)return i(new T0(SU.UNEXPECTED_ERROR,"gateway: can not recover, no join info"));e&&(this.joinInfo.multiIP=e,this.hasChangeBGPAddress=!0),this.isSignalRecover=!0,gs(this,v8.REQUEST_NEW_GATEWAY_LIST).then(t).catch(i)}),this.signal.on(vF.REQUEST_JOIN_INFO,async(e,t,i)=>{var r,n,o,a;if(this.updateTurnConfigFromSignal(),this.store.useP2P)return void e(this.getJoinMessage({ortc:{}}));let s=gS(null==(r=this.joinInfo)?void 0:r.turnServer);if(TR("NEW_TURN_MODE")&&s&&"disabled"===(null==(n=this.joinInfo)?void 0:n.cloudProxyServer)){let e=s.servers.map(e=>"turnServerURL"in e&&TR("USE_TURN_IP")?IG(IG({},e),{},{turnServerURL:yZ(e.turnServerURL)}):e),t=null==(a=s.serversFromGateway)?void 0:a.map(e=>TR("USE_TURN_IP")?IG(IG({},e),{},{turnServerURL:yZ(e.turnServerURL)}):e),i=this.signal.currentURLIndex;e.length>0&&(s.servers=e=[e[i%e.length]]),Array.isArray(t)&&t.length>0&&(s.serversFromGateway=t=[t[0]]),TY.debug("[".concat(this.store.clientId,"] use single turn, use turn server index: ").concat(i))}let{iceParameters:c,dtlsParameters:d,rtpCapabilities:l}=await gs(this,v8.REQUEST_P2P_CONNECTION_PARAMS,{turnServer:s,cloudProxyServer:null==(o=this.joinInfo)?void 0:o.cloudProxyServer});try{e(this.getJoinMessage({ortc:{iceParameters:c,dtlsParameters:d,rtpCapabilities:l,version:"2"}}))}catch(e){t(e)}}),this.signal.on(vF.REQUEST_REJOIN_INFO,e=>{e(this.getRejoinMessage())}),this.signal.on(vF.REPORT_JOIN_GATEWAY,(e,t)=>{var i;if(!this.joinInfo)return;let r,n="";e instanceof T0?(r=(null==(i=e.data)?void 0:i.desc)||e.code,n=e.message):r=e,T$.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!1,ec:r,errorMsg:n,addr:t,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,isProxy:!!this.joinInfo.proxyServer||this.usingProxy,signalChannel:"DataChannelSignal"===this.signal.__name__?"1":"0",preload:this.joinInfo.preload})}),this.signal.on(vF.IS_P2P_DISCONNECTED,e=>{e(gl(this,v8.IS_P2P_DISCONNECTED))}),this.signal.on(vF.DISCONNECT_P2P,()=>
1{this.emit(v8.DISCONNECT_P2P)}),this.signal.on(vF.REQUEST_SUCCESS,()=>{this._signalTimeout=!1}),this.signal.on(vF.REQUEST_TIMEOUT,()=>{this._signalTimeout=!0}),this.signal.on(vF.JOIN_RESPONSE,e=>{let t=this.getCurrentGatewayAddress();this.emit(v8.JOIN_RESPONSE,e,t)}),this.signal.on(vF.PRE_CONNECT_PC,async(e,t)=>{if(this.joinInfo){var i,r,n;this.updateTurnConfigFromSignal();let o=this.getCurrentGatewayAddress(),a=gS(null==(i=this.joinInfo)?void 0:i.turnServer);if(TR("NEW_TURN_MODE")&&a&&"disabled"===(null==(r=this.joinInfo)?void 0:r.cloudProxyServer)){let e=a.servers.map(e=>"turnServerURL"in e&&TR("USE_TURN_IP")?IG(IG({},e),{},{turnServerURL:yZ(e.turnServerURL)}):e),t=null==(n=a.serversFromGateway)?void 0:n.map(e=>TR("USE_TURN_IP")?IG(IG({},e),{},{turnServerURL:yZ(e.turnServerURL)}):e),i=this.signal.currentURLIndex;e.length>0&&(a.servers=e=[e[i%e.length]]),Array.isArray(t)&&t.length>0&&(a.serversFromGateway=t=[t[0]]),TY.debug("[".concat(this.store.clientId,"] use single turn, use turn server index: ").concat(i,",in pre pc"))}let s=TR("FINGERPRINT")||this.joinInfo.apResponse.addresses[this.signal.currentURLIndex].fingerprint;if(o&&s){let i=Ip(o);gs(this,v8.PRE_CONNECT_PC,{candidates:i,fingerprint:s,turnServer:a}).then(t=>{null==e||e(t)}).catch(t||(()=>{}))}}}),this.signal.on(vF.RECOVER_NOTIFICATION,e=>{this.joinInfo&&"string"==typeof TR("AP_REQUEST_DETAIL")&&(this.joinInfo.apRequestDetail="".concat(TR("AP_REQUEST_DETAIL"),";").concat(e))}),this.signal.on(vF.VOS_FALLBACK,e=>{this.emit(v8.VOS_FALLBACK,e)}),this.signal.on(vF.DATACHANNEL_FAILBACK,e=>{TY.warning("[".concat(this.store.clientId,"] User join datachannel failed")),this.reset(),this.resetSignal(),this.emit(v8.DATACHANNEL_FAILBACK)})}async tryUnsubBeforeResub(e,t){try{await this.signal.request(vB.UNSUBSCRIBE,{p2p_id:this.store.p2pId,stream_id:e,ortc:[t]},!0)}catch(e){throw TY.warning("[".concat(this.store.clientId,"] tryUnsubBeforeResub warning"),e),e}}async tryUnsubDataChannelBeforeResub(e,t){try{await this.signal.request(vB.UNSUBSCRIBE,{stream_id:t.id},!0)}catch(e){throw TY.warning("unsubscribe datachannel warning",e),e}}async tryUnpubBeforeRepub(e,t){try{await this.signal.request(vB.UNPUBLISH,{stream_id:e,ortc:t},!0)}catch(e){throw TY.warning("[".concat(this.store.clientId,"] tryUnpubBeforeRepub warning: "),e),e}}async tryUnpubDataChannelBeforeRepub(e,t){try{await this.signal.request(vB.UNPUBLISH_DATASTREAM,{channnel_id:t.channelId},!0)}catch(e){throw TY.warning("unpublish datastream warning: ",e),e}}async tryMassUnsubBeforeResub(e){let t={users:e.map(e=>({stream_id:e.stream_id,stream_type:e.stream_type}))};try{await this.signal.request(vB.UNSUBSCRIBE_STREAMS,t,!0)}catch(e){throw TY.warning("[".concat(this.store.clientId,"] tryMassUnsubBeforeResub warning"),e),e}}async muteLocal(e,t){let i={action:e.find(e=>e.stream_type===v6.Audio)?"mute_local_audio":"mute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(vB.CONTROL,i,!0,!0)}catch(e){throw TY.warning("[".concat(this.store.clientId,"] gateway muteLocal warning: "),e),e}}async unmuteLocal(e,t){let i={action:e.find(e=>e.stream_type===v6.Audio)?"unmute_local_audio":"unmute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(vB.CONTROL,i,!0,!0)}catch(e){throw TY.warning("[".concat(this.store.clientId,"] gateway unmuteLocal warning: "),e),e}}async muteRemote(e,t){let i={action:e===yc.AUDIO?"mute_remote_audio":"mute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(vB.CONTROL,i,!0,!0)}catch(e){throw TY.warning("[".concat(this.store.clientId,"] gateway muteRemote warning: "),e),e}}async unmuteRemote(e,t){let i={action:e===yc.AUDIO?"unmute_remote_audio":"unmute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(vB.CONTROL,i,!0,!0)}catch(e){throw TY.warning("[".concat(this.store.clientId,"] gateway unmuteRemote warning: "),e),e}}uploadWRTCStats(e){this.signal.uploadWRTCStats(e)}upload(e,t){this.signal.upload(e,t)}getSignalRTT(){return this.signal.rtt}async restartICE(e){let t={p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:e};try{return await this.signal.request(vB.RESTART_ICE,t,!0)}catch(e){throw TY.warning("[".concat(this.store.clientId,"] P2PChannel.restartICE warning: "),e),e}}reconnect(e,t){"CONNECTED"===this.state&&this.signal.reconnect(e||void 0,t||gn.P2P_FAILED)}getCurrentGatewayAddress(){var e,t;
1if(!TR("GATEWAY_WSS_ADDRESS"))return TR("USE_CANDIDATE_FROM_AP_DETAIL")&&null!=(e=this.joinInfo)&&e.apGatewayAddress?(TY.debug("[".concat(this.store.clientId,"] use candidate from ap detail, ").concat(JSON.stringify(this.joinInfo.apGatewayAddress))),this.joinInfo.apGatewayAddress):null!=(t=this.joinInfo)&&t.gatewayAddrs?this.joinInfo.gatewayAddrs[this.signal.currentURLIndex]:void 0}async setPublishAudioFilterEnabled(e){await this.signal.request(vB.SET_PARAMETER,{enablePublishAudioFilter:e})}downgradeCodec(e){this.signal.downgradeCodec(e)}resetSignal(){this.signal&&(this.signal.removeAllListeners(),this.signal.close(S8.FALLBACK)),this.store.useDcSignal=!1,this.signal=new yK(IG(IG({},this.spec),{},{retryConfig:this.spec.websocketRetryConfig}),this.store),this.handleSignalEvents(),this.emit(v8.RESET_SIGNAL)}constructor(e,t){var i,r,n,o;super(),mb(this,"store",void 0),mb(this,"joinInfo",void 0),mb(this,"key",void 0),mb(this,"ntpOffset",0),mb(this,"usingProxy",!1),mb(this,"signal",void 0),mb(this,"role",void 0),mb(this,"isPreallocation",void 0),mb(this,"isPreSub",void 0),mb(this,"inChannelInfo",{joinAt:null,duration:0}),mb(this,"spec",void 0),mb(this,"_state","DISCONNECTED"),mb(this,"_statsCollector",void 0),mb(this,"_disconnectedReason",void 0),mb(this,"isSignalRecover",!1),mb(this,"hasChangeBGPAddress",!1),mb(this,"trafficStatsInterval",void 0),mb(this,"networkQualityInterval",void 0),mb(this,"_joinGatewayStartTime",0),mb(this,"_signalTimeout",!1),mb(this,"_clientRoleOptions",void 0),mb(this,"_isProactiveJoin",!1),this.store=e,this.spec=t,this.signal=this.store.useP2P?(i={spec:IG(IG({},t),{},{retryConfig:t.websocketRetryConfig}),store:e},null==(r=(n=IV("P2PChannel")).createSubmodule)?void 0:r.call(n,i)):this.store.useDcSignal?(o={spec:IG(IG({},t),{},{retryConfig:t.websocketRetryConfig}),store:e},IV("DataChannelSignal").create(o)):new yK(IG(IG({},t),{},{retryConfig:t.websocketRetryConfig}),e),this._statsCollector=t.statsCollector,this.role=t.role||"audience",this._clientRoleOptions=t.clientRoleOptions,this.handleSignalEvents()}}let IK=0,IY=0;function Iz(e,t,i,r){return new dQ((n,o)=>{t.timeout=t.timeout||TR("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),IK+=gA(t.data)):i&&(t.data.size?IK+=t.data.size:t.data instanceof FormData?IK+=gb(t.data):IK+=gA(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,f0.request(t).then(e=>{"string"==typeof e.data?IY+=gA(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?IY+=e.data.byteLength:IY+=gA(JSON.stringify(e.data)),r&&n({data:e.data,headers:e.headers}),n(e.data)}).catch(e=>{f0.isCancel(e)?o(new T0(SU.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?o(new T0(SU.NETWORK_TIMEOUT,e.message)):e.response?o(new T0(SU.NETWORK_RESPONSE_ERROR,e.response.status)):o(new T0(SU.NETWORK_ERROR,e.message))})})}!function(){function e(e){var t=0;return function(){return t<e.length?{done:!1,value:e[t++]}:{done:!0}}}var t,i,r,n="function"==typeof Object.defineProperties?Object.defineProperty:function(e,t,i){return e==Array.prototype||e==Object.prototype||(e[t]=i.value),e},o=function(e){e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof rG&&rG];for(var t=0;t<e.length;++t){var i=e[t];if(i&&i.Math==Math)return i}throw Error("Cannot find global object")}(this);function a(e,t){if(t)e:{var i=o;e=e.split(".");for(var r=0;r<e.length-1;r++){var a=e[r];if(!(a in i))break e;i=i[a]}(t=t(r=i[e=e[e.length-1]]))!=r&&null!=t&&n(i,e,{configurable:!0,writable:!0,value:t})}}function s(t){var i="undefined"!=typeof Symbol&&Symbol.iterator&&t[Symbol.iterator];return i?i.call(t):{next:e(t)}}if(a("Symbol",function(e){function t(e,t){this.A=e,n(this,"description",{configurable:!0,writable:!0,value:t})}if(e)return e;t.prototype.toString=function(){return this.A};var i="jscomp_symbol_"+(1e9*Math.random()>>>0)+"_",r=0;return function e(n){if(this instanceof e)throw TypeError("Symbol is not a constructor");return new t(i+(n||"")+"_"+r++,n)}}),a("Symbol.iterator",function(t){if(t)return t;t=Symbol("Symbol.iterator");for(var i="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),r=0;r<i.length;r++){var a=o[i[r]];"function"==typeof a&&"function"!=typeof a.prototype[t]&&n(a.prototype,t,{configurable:!0,writable:!0,value:function(){var t;return(t={next:t=e(this)})[Symbol.iterator]=function(){return this},t}})}return t}),"function"==typeof Object.setPrototypeOf)r=Object.setPrototypeOf;else{e:{var c={};try{c.__proto__={a:!0},t=c.a;break e}catch(e){}t=!1}r=t?function(e,t){if(e.__proto__=t,e.__proto__!==t)throw TypeError(e+" is not extensible");return e}:null}var d=r;function l(){this.m=!1,this.j=null,this.v=void 0,this.h=1,this.u=this.C=0,this.l=null}function h(e){if(e.m)throw TypeError("Generator is already running");e.m=!0}function u(e,t){return e.h=3,{value:t}}function p(e){this.g=new l,this.G=e}function _(e,t,i,r){try{var n=t.call(e.g.j,i);if(!(n instanceof Object))throw TypeError("Iterator result "+n+" is not an object");
1if(!n.done)return e.g.m=!1,n;var o=n.value}catch(t){return e.g.j=null,e.g.s(t),E(e)}return e.g.j=null,r.call(e.g,o),E(e)}function E(e){for(;e.g.h;)try{var t=e.G(e.g);if(t)return e.g.m=!1,{value:t.value,done:!1}}catch(t){e.g.v=void 0,e.g.s(t)}if(e.g.m=!1,e.g.l){if(t=e.g.l,e.g.l=null,t.F)throw t.D;return{value:t.return,done:!0}}return{value:void 0,done:!0}}function m(e){this.next=function(t){return e.o(t)},this.throw=function(t){return e.s(t)},this.return=function(t){var i;return h(e.g),(i=e.g.j)?_(e,"return"in i?i.return:function(e){return{value:e,done:!0}},t,e.g.return):(e.g.return(t),E(e))},this[Symbol.iterator]=function(){return this}}function f(e,t){return t=new m(new p(t)),d&&e.prototype&&d(t,e.prototype),t}if(l.prototype.o=function(e){this.v=e},l.prototype.s=function(e){this.l={D:e,F:!0},this.h=this.C||this.u},l.prototype.return=function(e){this.l={return:e},this.h=this.u},p.prototype.o=function(e){return h(this.g),this.g.j?_(this,this.g.j.next,e,this.g.o):(this.g.o(e),E(this))},p.prototype.s=function(e){return h(this.g),this.g.j?_(this,this.g.j.throw,e,this.g.o):(this.g.s(e),E(this))},a("Array.prototype.entries",function(e){return e||function(){var e,t,i,r,n;return e=this,t=function(e,t){return[e,t]},e instanceof String&&(e+=""),i=0,r=!1,(n={next:function(){if(!r&&i<e.length){var n=i++;return{value:t(n,e[n]),done:!1}}return r=!0,{done:!0,value:void 0}}})[Symbol.iterator]=function(){return n},n}}),"undefined"!=typeof Blob&&("undefined"==typeof FormData||!FormData.prototype.keys)){var S=function(e,t){for(var i=0;i<e.length;i++)t(e[i])},g=function(e){return e.replace(/\r?\n|\r/g,"\r\n")},T=function(e,t,i){return t instanceof Blob?(i=void 0!==i?String(i+""):"string"==typeof t.name?t.name:"blob",t.name===i&&"[object Blob]"!==Object.prototype.toString.call(t)||(t=new File([t],i)),[String(e),t]):[String(e),String(t)]},R=function(e,t){if(e.length<t)throw TypeError(t+" argument required, but only "+e.length+" present.")},C="object"==typeof globalThis?globalThis:"object"==typeof window?window:"object"==typeof self?self:this,v=C.FormData,y=C.XMLHttpRequest&&C.XMLHttpRequest.prototype.send,I=C.Request&&C.fetch,A=C.navigator&&C.navigator.sendBeacon,b=C.Element&&C.Element.prototype,O=C.Symbol&&Symbol.toStringTag;O&&(Blob.prototype[O]||(Blob.prototype[O]="Blob"),"File"in C&&!File.prototype[O]&&(File.prototype[O]="File"));try{new File([],"")}catch(e){C.File=function(e,t,i){return Object.defineProperties(e=new Blob(e,i||{}),{name:{value:t},lastModified:{value:+(i&&void 0!==i.lastModified?new Date(i.lastModified):new Date)},toString:{value:function(){return"[object File]"}}}),O&&Object.defineProperty(e,O,{value:"File"}),e}}var w=function(e){return e.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22")},N=function(e){this.i=[];var t=this;e&&S(e.elements,function(e){if(e.name&&!e.disabled&&"submit"!==e.type&&"button"!==e.type&&!e.matches("form fieldset[disabled] *"))if("file"===e.type){var i=e.files&&e.files.length?e.files:[new File([],"",{type:"application/octet-stream"})];S(i,function(i){t.append(e.name,i)})}else"select-multiple"===e.type||"select-one"===e.type?S(e.options,function(i){!i.disabled&&i.selected&&t.append(e.name,i.value)}):"checkbox"===e.type||"radio"===e.type?e.checked&&t.append(e.name,e.value):(i="textarea"===e.type?g(e.value):e.value,t.append(e.name,i))})};if((i=N.prototype).append=function(e,t,i){R(arguments,2),this.i.push(T(e,t,i))},i.delete=function(e){R(arguments,1);var t=[];e=String(e),S(this.i,function(i){i[0]!==e&&t.push(i)}),this.i=t},i.entries=function e(){var t,i=this;return f(e,function(e){if(1==e.h&&(t=0),3!=e.h)return t<i.i.length?e=u(e,i.i[t]):(e.h=0,e=void 0),e;t++,e.h=2})},i.forEach=function(e,t){R(arguments,1);for(var i=s(this),r=i.next();!r.done;r=i.next()){var n=s(r.value);r=n.next().value,n=n.next().value,e.call(t,n,r,this)}},i.get=function(e){R(arguments,1);var t=this.i;e=String(e);for(var i=0;i<t.length;i++)if(t[i][0]===e)return t[i][1];return null},i.getAll=function(e){R(arguments,1);var t=[];return e=String(e),S(this.i,function(i){i[0]===e&&t.push(i[1])}),t}
1,i.has=function(e){R(arguments,1),e=String(e);for(var t=0;t<this.i.length;t++)if(this.i[t][0]===e)return!0;return!1},i.keys=function e(){var t,i,r=this;return f(e,function(e){if(1==e.h&&(i=(t=s(r)).next()),3!=e.h)return i.done?void(e.h=0):u(e,s(i.value).next().value);i=t.next(),e.h=2})},i.set=function(e,t,i){R(arguments,2);var r=[],n=T(e=String(e),t,i),o=!0;S(this.i,function(t){t[0]===e?o&&(o=!r.push(n)):r.push(t)}),o&&r.push(n),this.i=r},i.values=function e(){var t,i,r,n=this;return f(e,function(e){if(1==e.h&&(i=(t=s(n)).next()),3!=e.h)return i.done?void(e.h=0):((r=s(i.value)).next(),u(e,r.next().value));i=t.next(),e.h=2})},N.prototype._asNative=function(){for(var e=new v,t=s(this),i=t.next();!i.done;i=t.next()){var r=s(i.value);i=r.next().value,r=r.next().value,e.append(i,r)}return e},N.prototype._blob=function(){var e="----formdata-polyfill-"+Math.random(),t=[],i="--"+e+'\r\nContent-Disposition: form-data; name="';return this.forEach(function(e,r){return"string"==typeof e?t.push(i+w(g(r))+'"\r\n\r\n'+g(e)+"\r\n"):t.push(i+w(g(r))+'"; filename="'+w(e.name)+'"\r\nContent-Type: '+(e.type||"application/octet-stream")+"\r\n\r\n",e,"\r\n")}),t.push("--"+e+"--"),new Blob(t,{type:"multipart/form-data; boundary="+e})},N.prototype[Symbol.iterator]=function(){return this.entries()},N.prototype.toString=function(){return"[object FormData]"},b&&!b.matches&&(b.matches=b.matchesSelector||b.mozMatchesSelector||b.msMatchesSelector||b.oMatchesSelector||b.webkitMatchesSelector||function(e){for(var t=(e=(this.document||this.ownerDocument).querySelectorAll(e)).length;0<=--t&&e.item(t)!==this;);return -1<t}),O&&(N.prototype[O]="FormData"),y){var D=C.XMLHttpRequest.prototype.setRequestHeader;C.XMLHttpRequest.prototype.setRequestHeader=function(e,t){D.call(this,e,t),"content-type"===e.toLowerCase()&&(this.B=!0)},C.XMLHttpRequest.prototype.send=function(e){e instanceof N&&(e=e._blob(),this.B||this.setRequestHeader("Content-Type",e.type)),y.call(this,e)}}I&&(C.fetch=function(e,t){return t&&t.body&&t.body instanceof N&&(t.body=t.body._blob()),I.call(this,e,t)}),A&&(C.navigator.sendBeacon=function(e,t){return t instanceof N&&(t=t._asNative()),A.call(this,e,t)}),C.FormData=N}}();let Iq=()=>{let e=TR("AREAS");return 0===e.length&&e.push(ye.GLOBAL),as(e).call(e,(e,t,i)=>{let r=IX(t);return r?0===i?r:"".concat(e,",").concat(r):e},"")},IX=e=>e===ye.OVERSEA?"".concat(yi.ASIA,",").concat(yi.EUROPE,",").concat(yi.AFRICA,",").concat(yi.NORTH_AMERICA,",").concat(yi.SOUTH_AMERICA,",").concat(yi.OCEANIA):yi[e],IJ={GLOBAL:{ASIA:[ye.CHINA,ye.JAPAN,ye.INDIA,ye.KOREA,ye.HKMC],EUROPE:[],NORTH_AMERICA:[ye.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}},IQ=Object.keys(IJ[ye.GLOBAL]),IZ=[ye.CHINA,ye.NORTH_AMERICA,ye.EUROPE,ye.ASIA,ye.JAPAN,ye.INDIA,ye.OCEANIA,ye.SOUTH_AMERICA,ye.AFRICA,ye.KOREA,ye.HKMC,ye.US],I$=function(e,t){let i=[];if(o5(e).call(e,ye.GLOBAL)){let r=[ye.GLOBAL,ye.OVERSEA],n=Object.keys(yr);if(t===ye.GLOBAL)throw new T0(SU.INVALID_PARAMS,"GLOBAL is an invalid excludedArea value");if(t===ye.CHINA)i=[ye.OVERSEA];else if(o5(IQ).call(IQ,t)){let e=IJ[ye.GLOBAL][t]||[],o=[...r,t,...e];i=n.filter(e=>!o5(o).call(o,e))}else{let o;if(o=!1,IQ.forEach(e=>{var i;o5(i=IJ[ye.GLOBAL][e]).call(i,t)&&(o=!0)}),o){let e,o=[...r,(IQ.forEach(i=>{var r;o5(r=IJ[ye.GLOBAL][i]).call(r,t)&&(e=i)}),e),t];i=n.filter(e=>!o5(o).call(o,e))}else i=e}i=function(e){let t=[];return IZ.forEach(i=>{o5(e).call(e,i)&&t.push(i)}),t.concat(e.filter(e=>!o5(IZ).call(IZ,e)))}(i)}else i=e;return i};function I0(e){var t,i;if(!e&&o5(t=TR("AREAS")).call(t,ye.EXTENSIONS))return TY.debug("update area from ap : reset"),void I1(vl,!0);if(!o5(i=TR("AREAS")).call(i,ye.GLOBAL)||!e)return;let r=yr.EXTENSIONS;r&&(r={CODE:IX(ye.EXTENSIONS),WEBCS_DOMAIN:["ap-web-1-".concat(e,".agora.io")],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-".concat(e,".ap.sd-rtn.com")],PROXY_CS:["proxy-ap-web-".concat(e,".agora.io")],CDS_AP:["cds-ap-web-1-".concat(e,".agora.io"),"cds-ap-web-2-".concat(e,".ap.sd-rtn.com")],ACCOUNT_REGISTER:["sua-ap-web-1-".concat(e,".agora.io"),"sua-ap-web-2-".concat(e,".ap.sd-rtn.com")],UAP_AP:["uap-ap-web-1-".concat(e,".agora.io"),"uap-ap-web-2-".concat(e,".ap.sd-rtn.com")],EVENT_REPORT_DOMAIN:["statscollector-1-".concat(e,".agora.io")],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-".concat(e,".agora.io")],LOG_UPLOAD_SERVER:["logservice-".concat(e,".agora.io")],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy-".concat(e,".agora.io")]},TY.debug("update area from ap success: ".concat(e,",config is "),r),TT("AREAS",[ye.EXTENSIONS],!0),Ob
1ject.keys(r).map(e=>{"LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e?TT(e,r[e][0]):TT(e,r[e])}))}function I1(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=T$.reportApiInvoke(null,{name:S3.SET_AREA,options:e,tag:S5.TRACER});try{let r=[];if("string"==typeof e&&(r=[e]),Array.isArray(e)&&(e.forEach(e=>{if(!o5(yt).call(yt,e))throw new T0(SU.INVALID_PARAMS,"invalid area code")}),r=e),"[object Object]"===Object.prototype.toString.call(e)){let{areaCode:t,excludedArea:i}=e;if(!t)throw new T0(SU.INVALID_PARAMS,"area code is needed");let n=t;"string"==typeof t&&(n=[t]),r=i?I$(n,i):n}if(!t){if(Tv.AREAS){let e=new T0(SU.PROHIBITED_OPERATION,"setArea is prohibited because of config-distribute");return i.onError(e),void TY.warning("setArea is prohibited because of config-distribute")}if(o5(r).call(r,ye.GLOBAL)&&TR("AREAS")===ye.EXTENSIONS){let e=new T0(SU.PROHIBITED_OPERATION,"setArea is prohibited because of ap extensions");return i.onError(e),void TY.warning("setArea is prohibited because of ap extensions")}}TT("AREAS",r,t);let n=(e=>{let t={CODE:"",WEBCS_DOMAIN:[],WEBCS_DOMAIN_BACKUP_LIST:[],PROXY_CS:[],CDS_AP:[],ACCOUNT_REGISTER:[],UAP_AP:[],EVENT_REPORT_DOMAIN:[],EVENT_REPORT_BACKUP_DOMAIN:[],LOG_UPLOAD_SERVER:[],PROXY_SERVER_TYPE3:[]};return e.map(e=>{let i=yr[e],r=Object.keys(i);r&&r.map(e=>{"CODE"!==e&&(t[e]=t[e].concat(i[e]))})}),t})(r);Object.keys(n).map(e=>{"LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e?TT(e,n[e][0]):TT(e,n[e])}),TY.debug("set area success:",r.join(","))}catch(e){throw i.onError(e),e}i.onSuccess()}function I2(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function I3(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?I2(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):I2(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let I5=1,I4=1;function I6(e,t,i,r){let n,{url:o,areaCode:a}=e,{clientId:s,sid:c}=t,d=Date.now(),l=t.role,[h,u]=Ae(t,a,[yz.CHOOSE_SERVER]),p=gh.networkState;return gY(async()=>{p&&gh.networkState===go.OFFLINE&&gh.onlineWaiter&&await dQ.race([gh.onlineWaiter,gO(r&&r.maxRetryTimeout||gH.maxRetryTimeout)]),p=gh.networkState;let{data:e,headers:a}=await Iz(o,{data:h,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);n="1"===a.http3?1:-1,T$.reportResourceTiming(o,c),I9(e,o,t,d,[yz.CHOOSE_SERVER],n);let s=y3(e,yz.CHOOSE_SERVER);return I7(s),y$(s,o)},e=>(e&&T$.joinChooseServer(c,{role:l,lts:d,succ:!0,csAddr:o,opid:u,serverList:e.gatewayAddrs.map(e=>e.address),ec:null,cid:e.cid.toString(),uid:e.uid.toString(),csIp:e.csIp,unilbsServerIds:[yz.CHOOSE_SERVER].toString(),isHttp3:n,corssRegionTagReq:t.apRequestDetail,corssRegionTagRes:e.res.detail&&e.res.detail[38],vid:e.vid}),!1),e=>e.code!==SU.OPERATION_ABORTED&&(e.code===SU.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(T$.joinChooseServer(c,{role:l,lts:d,succ:!1,csAddr:o,serverList:null,opid:u,ec:e.code,csIp:e.data&&e.data.csIp,unilbsServerIds:[yz.CHOOSE_SERVER].toString(),extend:JSON.stringify({networkState:p}),isHttp3:n,corssRegionTagReq:t.apRequestDetail}),TY.warning("[".concat(s||"sid-".concat(c.slice(0,6)),"] Choose server network error, retry"),e),!0)),r)}function I8(e,t,i,r){let n,o,{url:a,areaCode:s,serviceIds:c}=e,d=Date.now(),l=t.role,[h,u]=Ae(t,s,c);return gY(async()=>{let e;n&&gh.networkState===go.OFFLINE&&gh.onlineWaiter&&await dQ.race([gh.onlineWaiter,gO(r&&r.maxRetryTimeout||gH.maxRetryTimeout)]),n=gh.networkState;let{data:s,headers:l}=await Iz(a,{data:h,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);o="1"===l.http3?1:-1,T$.reportResourceTiming(a,t.sid),I9(s,a,t,d,c,o);let u=y3(s,yz.CHOOSE_SERVER),p=y3(s,"proxy5"===t.cloudProxyServer?yz.CLOUD_PROXY_5:"proxy3"===t.cloudProxyServer||"proxy4"===t.cloudProxyServer?yz.CLOUD_PROXY:yz.CLOUD_PROXY_FALLBACK),_=performance.getEntriesByName(a),E=_[_.length-1];return E&&(e={name:E.name,protocol:"nextHopProtocol"in E?E.nextHopProtocol:"",dnscost:"domainLookupEnd"in E&&"domainLookupStart"in E&&"number"==typeof E.domainLookupEnd&&"number"==typeof E.domainLookupStart?E.domainLookupEnd-E.domainLookupStart:-1,tcpTlsCost:"connectEnd"in E&&"connectStart"in E&&"number"==typeof E.connectEnd&&"number"==typeof E.connectStart?E.connectEnd-E.connectStart:-1,reqCost:"requestStart"in E&&"number"==typeof E.requestStart&&"responseEnd"in E&&"number"==typeof E.responseEnd?E.responseEnd-E.requestStart:-1,handleCost:"leave_ts"in s&&"enter_ts"in s&&"number"==typeof s.leave_ts&&"number"==typeof s.enter_ts?s.leave_ts-s.enter_ts:-1}),I7(u),{gatewayInfo:y$(u,a),proxyInfo:p,url:a,resourceTimingInfo:e}},e=>{var i;return e.gatewayInfo&&T$.joinChooseServer(t.sid,{role:l,lts:d,succ:!0,csAddr:a,serverList:e.gatewayInfo.gatewayAddrs.map(e=>e.address),ec:null,opid:u,cid:e.gatewayInfo.cid.toString(),uid:e.gatewayInfo.uid.toString(),csIp:e.gatewayInfo.csIp,unilbsServerIds:c.toString(),isHttp3:o,corssRegionTagReq:t.apRequestDetail,corssRegionTagRes:e.gatewayInfo.res.detail&&e.gatewayInfo.res.detail[38],vid:null==(i=e.gatewayInfo)?void 0:i.vid,resourceTimingInfo:e.resourceTimingInfo?JSON.stringify(e.resourceTimingInfo):void 0}),e.proxyInfo&&T$.joinWebProxyAP(t.sid,{lts:d,sucess:1,apServerAddr:a,turnServerAddrList:e.proxyInfo.addresses.map(e=>e.ip).join(","),errorCode:null,eventType:t.cloudProxyServer,unilbsServerIds:c.toString()}),!1},e=>e.code!==SU.OPERATION_ABORTED&&(e.code===SU.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(T$.joinWebProxyAP(t.sid,{lts:d,sucess:0,apServerAddr:a,turnServerAddrList:null,errorCode:e.code,eventType:t.cloudProxyServer,unilbsServerIds:c.toString(),extend:JSON.stringify({networkState:n})}),TY.warning("[".concat(t.clientId,"] multi unilbs network error, retry"),e),!0)),r)}let I9=(e,t,i,r,n,o)=>{let{sid:a,clientId:s,cloudProxyServer:c}=i,d=[],l=s=>{4096===s.flag?T$.joinChooseServer(a,{role:i.role,lts:r,succ:!1,csAddr:t,opid:e.opid,serverList:null,ec:s.error.message,csIp:s.error.data&&s.error.data.csIp,unilbsServerIds:n.toString(),isHttp3:o,corssRegionTagReq:i.apRequestDetail}
1):1048576!==s.flag&&4194304!==s.flag&&4194310!==s.flag||T$.joinWebProxyAP(a,{lts:r,sucess:0,apServerAddr:t,turnServerAddrList:null,errorCode:s.error.code,eventType:c,unilbsServerIds:n.toString()})};if(e.response_body.forEach(t=>{let i=t.buffer.code;if(23===t.uri&&0===i&&!t.buffer.edges_services)if(4194310===t.buffer.flag)TY.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers"),t.buffer.edges_services=[];else{let i={error:new T0(SU.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:TR("NO_EDGES_RETRY"),csIp:e.detail[502]}),flag:t.buffer.flag};d.push(i),l(i)}if(0!==i){let r=yw(i),n={error:new T0(SU.CAN_NOT_GET_GATEWAY_SERVER,r.desc,{desc:r.desc,retry:r.retry,csIp:e.detail[502]}),flag:t.buffer.flag};4194310===t.buffer.flag?TY.warning(n.error.toString()):d.push(n),l(n)}}),d.length)throw TY.warning("[".concat(s||"sid-".concat(a.slice(0,6)),"] multi unilbs ").concat(t," failed, ").concat(d.map(e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message,", retry: ").concat(e.error.data.retry)).join(" | "))),new T0(SU.CAN_NOT_GET_GATEWAY_SERVER,d.map(e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message)).join(" | "),{retry:!!d.find(e=>e.error.data.retry),csIp:e.detail[502],desc:[...new Set(d.map(e=>{var t;return null==e||null==(t=e.error)||null==(t=t.data)?void 0:t.desc}).filter(e=>!!e))]})},I7=e=>{var t,i,r,n,o;if(e.addresses&&0===e.addresses.length&&0===e.code)throw new T0(SU.CAN_NOT_GET_GATEWAY_SERVER,"void gateway address",{retry:!0,csIp:e.detail&&e.detail[502]});if(TR("AP_AREA")&&(null!=(r=e.detail)&&r[23]&&"string"==typeof(null==(n=e.detail)?void 0:n[23])?I0(e.detail[23].toLowerCase()):I0()),null!=(t=e.detail)&&t[19]&&"string"==typeof(null==(i=e.detail)?void 0:i[19])){let t=e.detail[19],i=null==t?void 0:t.split(";");for(let t=0;t<i.length;t++){let r=py(o=i[t]).call(o);e.addresses[t]&&i&&(e.addresses[t].fingerprint=r)}}if(TR("GATEWAY_ADDRESS")&&TR("GATEWAY_ADDRESS").length>0){TY.debug("assign gateway address to",TR("GATEWAY_ADDRESS"));let t=TR("GATEWAY_ADDRESS").map(t=>{var i,r;let n=null!=(i=null==(r=e.addresses.find(e=>e.ip===t.ip&&e.port===t.port))?void 0:r.fingerprint)?i:"";return{ip:t.ip,port:t.port,ticket:e.addresses[0]&&e.addresses[0].ticket,fingerprint:t.fingerprint||n}});e.addresses=t}},Ae=(e,t,i)=>{let r=Math.floor(1e12*Math.random()),n="host"===e.role?"1":"audience"===e.role?"2":void 0,o={appid:e.appId,client_ts:Date.now(),opid:r,sid:e.sid,request_bodies:[{uri:22,buffer:{cname:e.cname,detail:I3(I3(I3({6:e.stringUid,11:t,12:TR("USE_NEW_TOKEN")?"1":void 0},n?{17:n}:{}),{},{22:t},e.apRequestDetail?{33:e.apRequestDetail}:{}),e.apRTM?{26:"RTM2"}:{}),key:e.token,service_ids:i,uid:e.uid||0}}]};o.request_bodies.forEach(t=>{e.multiIP&&e.multiIP.gateway_ip&&(t.buffer.detail[5]=JSON.stringify({vocs_ip:[e.multiIP.uni_lbs_ip],vos_ip:[e.multiIP.gateway_ip]}))});let a=new FormData;return a.append("request",JSON.stringify(o)),[a,r]},At=0;function Ai(e){return dQ.all(e.map(e=>e.then(e=>{throw e},e=>e))).then(e=>{throw e},e=>e)}let Ar=async e=>{let{fragementLength:t,referenceList:i,asyncMapHandler:r,allFailedhandler:n,promisesCollector:o}=e,a=0,s,c=0,d=async()=>{let e=(()=>{let e=a*t;return i.slice(e,e+t).map(r)})();o&&o.push(...e);try{s=await Ai(e)}catch(e){if(c+=t,a++,!(c>=i.length))return void await d();n(e)}e.forEach(e=>e.cancel())};return await d(),s},An=async e=>{let{referenceList:t,asyncMapHandler:i,closeFn:r}=e,n=t.length,o=0,a=async()=>{let e=i(t.shift());try{return await e}catch(e){if(++o>=n||null!=r&&r(e))throw e;return a()}};return a()};async function Ao(){let e;if("undefined"==typeof VideoDecoder)return!0;let t=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,85,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,149,160,133,4,144,43,122,168,159,120,159,205,39,82,131,57,52,87,187,68,23,248,134,204,226,97,17,49,183,55,236,219,249,221,98,208,215,190,59,179,167,213,47,1,246,150,14,194,245,159,83,35,64,103,218,38,21,82,3,135,21,185,84,248,134],i=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,87,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,148,62,134,140,92,172,141,77,35,94,181,164,65,169,65,156,154,43,221,162,11,252,67,102,113,48,136,137,219,62,43,113,239,23,126,250,186,252,10,138,218,25,193,244,74,68,194,209,107,23,52,206,199,78,72,98,103,151,71,96,62,51,210,158,72,231,158],r=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,87,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,143,233,163,51,196,98,95,151,224,22,134,33,240,150,248,67,18,34,196,142,81,238,173,140,80,205,232,132,144,67,12,131,157,4,171,243,86,122,35,6,166,184,243,85,126,13,206,103,152,62,168,160,187,2,241,138,52,211,72,121,128,151,63,147,128,19,42],n=[18,0,50,138,1,48,192,64,253,248,65,17,67,192,32,0,16,0,0,0,0,0,0,0,195,12,48,144,64,32,0,209,75,61,9,204,25,115,79,226,115,63,63,208,70,210,220,153,126,241,237,37,107,195,153,1,99,112,230,189,209,169,130,10,11,22,167,215,159,205,197,7,183,162,26,48,254,141,134,103,32,16,235,45,1,15,18,119,169,110,206,251,51,115,202,60,148,1,46,39,109,25,28,86,168,15,77,211,239,2,58,43,146,26,230,184,81,48,140,226,226,250,222,146,171,133,164,13,188,180,64,122,142,146,32,208,238,170,193,35,53,44,225],o=[18,0,50,107,48,0,133,125,248,65,26,195,64,62,32,31,16,0,0,0,0,0,1,4,16,64,144,64,32,0,204,24,122,65,56,165,18,52,206,218,4,187,51,97,9,29,191,90,253,106,185,31,197,155,52,205,245,185,203,131,20,226,25,124,95,113,220,113,141,15,15,104,211,144,152,237,150,157,127,51,143,24,231,218,171,255,176,241,128,229,149,150,148,66,245,228,91,27,182,228,136,61,182,237,133,45,220,24,103,214,152],a=[18,0,50,122,48,1,9,253,248,65,26,67,64,62,32,31,16,0,0,0,0,0,1,4,16,64,144,64,32,0,198,182,231,242,220,235,163,140,12,36,36,166,46,132,210,4,71,23,218,132,27,30,17,45,244,79,31,243,195,136,100,169,76,88,142,85,204,217,121,168,29,163,198,17,251,223,73,12,212,244,139,123,151,179,75,216,96,208,136,40,229,42,59,149,10,116,228,85,99,93,221,108,255,140,248,20,30,167,122,109,206,164,108,197,110,251,23,243,133,160,63,13,207,177,12,128];return await new dQ((s,c)=>{let d;!async function(){e&&"closed"!==e.state||await async function(){e=new VideoDecoder({output:e=>{e.close(),clearTimeout(d),s(!0)},error:e=>{clearTimeout(d),s(!1)}}),await e.configure({codec:"av01.0.05M.08",width:160,height:90})}();let c=[t,i,r,n,o,a];for(let t=0;t<c.length;
1t++){let i=new EncodedVideoChunk({type:0==t?"key":"delta",timestamp:33333*t,duration:33333,data:new Uint8Array(c[t])});try{await e.decode(i)}catch(e){return void s(!1)}}}(),d=setTimeout(()=>{s(!1)},5e3)})}async function Aa(e,t,i,r){let n=async function(e,t,i,r){let n=null,o=[],a=async()=>{let n=TR("WEBCS_DOMAIN").slice(0,TR("AJAX_REQUEST_CONCURRENT")).map(t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2"),areaCode:Iq()})),a=r.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:n.map(e=>e.url)}),s=await Ar({fragementLength:TR("FRAGEMENT_LENGTH"),referenceList:n,asyncMapHandler:r=>(TY.debug("[".concat(e.clientId,"] Connect to choose_server:"),r.url),I6(r,e,t,i)),allFailedhandler:e=>{throw r.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},a),e[0]},promisesCollector:o});return r.recordJoinChannelService({endTs:Date.now(),status:"success"},a),s},s=async()=>{if(await gO(1e3),null!==n)return n;let a=TR("WEBCS_DOMAIN_BACKUP_LIST").map(t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2"),areaCode:Iq()})),s=r.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:a.map(e=>e.url)}),c=await Ar({fragementLength:TR("FRAGEMENT_LENGTH"),referenceList:a,asyncMapHandler:r=>(TY.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),r.url),I6(r,e,t,i)),allFailedhandler:e=>{throw r.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},s),e[0]},promisesCollector:o});return r.recordJoinChannelService({endTs:Date.now(),status:"success"},s),c};try{return n=await Ai([a(),s()]),o.length&&o.forEach(e=>e.cancel&&"function"==typeof e.cancel&&e.cancel()),n}catch(e){throw e[0]}}(e,t,i,r);return{gatewayInfo:await n}}async function As(e,t,i,r,n){var o,a;let s=e.cloudProxyServer;if("disabled"===s){if(!r)return;if(e.useLocalAccessPoint)return await Aa(e,t,i,n);if(TR("JOIN_WITH_FALLBACK_MEDIA_PROXY")){let{gatewayInfo:r,proxyInfo:a}=await Au(e,t,i,n);if(e.turnServer&&"auto"!==e.turnServer.mode)return{gatewayInfo:r};let s=a.map(e=>({turnServerURL:e.address,tcpport:e.tcpport||T_.tcpport,udpport:e.udpport||T_.udpport,username:e.username||T_.username,password:e.password||T_.password,forceturn:!1,security:!0}));if(n.useP2P){let t=null!=(o=e.uid)?o:r.uid,i="glb:".concat(t.toString()),n=await S$(i),c=a.map(e=>({turnServerURL:e.address,tcpport:e.tcpport||T_.tcpport,udpport:e.udpport||T_.udpport,username:i,password:n,forceturn:!1,security:!0}));s.push(...c)}return e.turnServer={mode:"manual",servers:s},{gatewayInfo:r}}return await Aa(e,t,i,n)}let{proxyInfo:c,gatewayInfo:d}=await Au(e,t,i,n),l=c.map(e=>({turnServerURL:e.address,tcpport:"proxy3"===s?void 0:e.tcpport?e.tcpport:T_.tcpport,udpport:"proxy4"===s?void 0:e.udpport?e.udpport:T_.udpport,username:e.username||T_.username,password:e.password||T_.password,forceturn:"proxy4"!==s,security:"proxy5"===s}));if(n.useP2P){let t=null!=(a=e.uid)?a:d.uid,i="glb:".concat(t.toString()),r=await S$(i),n=c.map(e=>({turnServerURL:e.address,tcpport:"proxy3"===s?void 0:e.tcpport||T_.tcpport,udpport:"proxy4"===s?void 0:e.udpport||T_.udpport,username:i,password:r,forceturn:"proxy4"!==s,security:"proxy5"===s}));l.push(...n)}return e.turnServer={mode:"manual",servers:l},TY.debug("[".concat(e.clientId,"] set proxy server: ").concat(e.proxyServer,", mode: ").concat(s)),{gatewayInfo:d}}async function Ac(e,t,i,r,n){let o=TR("ACCOUNT_REGISTER").slice(0,TR("AJAX_REQUEST_CONCURRENT")),a=[];a=t.proxyServer?o.map(e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1")):o.map(e=>"https://".concat(e,"/api/v1"));let s=null==n?void 0:n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"stringUID",urls:a});try{let o=await async function(e,t,i,r,n){let o=Date.now(),a={sid:i.sid,opid:10,appid:i.appId,string_uid:t},s=e[0],c=await gY(()=>Iz(s+"".concat(-1===s.indexOf("?")?"?":"&","action=stringuid"),{data:a,cancelToken:r,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}}),(i,r)=>{if(0===i.code){if(i.uid<=0||i.uid>=0x100000000)throw TY.error("Invalid Uint Uid ".concat(t," => ").concat(i.uid),i),T$.reqUserAccount(a.sid,{lts:o,success:!1,serverAddr:s,stringUid:a.string_uid,uid:i.uid,errorCode:SU.INVALID_UINT_UID_FROM_STRING_UID,extend:a}),new T0(SU.INVALID_UINT_UID_FROM_STRING_UID);return T$.reqUserAccount(a.sid,{lts:o,success:!0,serverAddr:s,stringUid:a.string_uid,uid:i.uid,errorCode:null,extend:a}),!1}let n=yw(i.code);return n.retry&&(s=e[(r+1)%e.length]),T$.reqUserAccount(a.sid,{lts:o,success:!1,serverAddr:s,stringUid:a.string_uid,uid:i.uid,errorCode:n.desc,extend:a}),n.retry},(t,i)=>t.code!==SU.OPERATION_ABORTED&&(T$.reqUserAccount(a.sid,{lts:o,success:!1,serverAddr:s,stringUid:a.string_uid,uid:null,errorCode:t.code,extend:a}),s=e[(i+1)%e.length],!0),n);if(0!==c.code){let e=yw(c.code);throw new T0(SU.UNEXPECTED_RESPONSE,e.desc)}return c}(a,e,t,i,r);return null==n||n.recordJoinChannelService({status:"success",endTs:Date.now()},s),o.uid}catch(e){throw null==n||n.recordJoinChannelService({status:"error",endTs:Date.now(),errors:[e]},s),e}}async function Ad(e,t,i){let r=TR("ACCOUNT_REGISTER"),n=[];n=t.proxyServer?r.map(e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1")):r.map(e=>"https://".concat(e,"/api/v1"));try{return await An({referenceList:n,asyncMapHandler:r=>(async function(e,t,i,r){let n=Date.now(),o={sid:i.sid,opid:10,appid:i.appId,string_uid:t};try{let t=await Iz(e+"".concat(-1===e.indexOf("?")?"?":"&","action=stringuid"),{data:o,cancelToken:r,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}});if(0!==t.code){let e=yw(t.code);throw new T0(SU.UNEXPECTED_RESPONSE,"preload sua error:".concat(e.desc),e)}if(t.uid<=0||t.uid>=0x100000000)throw new T0(SU.INVALID_UINT_UID_FROM_STRING_UID);return{requestTime:n,url:e,req:o,uid:t.uid,elapse:Date.now()-n}}catch(e){throw e}})(r,e,t,i),closeFn:e=>e.code===SU.OPERATION_ABORTED||e.code===SU.UNEXPECTED_RESPONSE&&!e.data.retry})}catch(e){throw e}}async function Al(e,t,i){let r=TR("CDS_AP").slice(0,TR("AJAX_REQUEST_CONCURRENT")).map(t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v1"):"https://".concat(t,"/api/v1?action=config")).map(r=>(function(e,t,i,r){let n=St(),o={flag:64,cipher_method:0,features:I3(I3(I3(I3(I3({install_id:Tl(),device:n.name,system:n.os,system_general:navigator.userAgent,vendor:t.appId,version:Th,cname:t.cname,session_id:t.sid,proxyServer:t.proxyServer,sdk_type:yY.WEB_RTC,browser_name:n.name,browser_version:n.version,user_agent:navigator.userAgent,channel_name:t.cname},t.stringUid&&{string_uid:t.stringUid}),t.uid&&{uid:t.uid+""}),n.os&&{os_name:n.os}),n.osVersion&&{os_version:n.osVersion}),{},{detail:""})};return gY(()=>Iz(e,{data:o,timeout:1e3,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":54}}),void 0,e=>e.code!==SU.OPERATION_ABORTED,r)})(r,e,t,i)),n=null,o=null,a={};try{n=await Ai(r)}catch(e){if(e.code===SU.OPERATION_ABORTED)throw e;o=e}
1if(r.forEach(e=>e.cancel()),T$.reportApiInvoke(e.sid,{name:S3.REQUEST_CONFIG_DISTRIBUTE,options:{error:o,res:n}}).onSuccess(),n&&n.test_tags)try{a=function(e){if(!e.test_tags)return{};let t=e.test_tags,i=Object.keys(t),r={};return i.forEach(e=>{var i;let n=py(i=e.slice(4)).call(i),o=JSON.parse(t[e]),a=o[1];r[n]={tag:o[0]||"",value:a}}),r}(n)}catch(e){}return a}async function Ah(e,t){let i=TR("WEBCS_DOMAIN").concat(TR("WEBCS_DOMAIN_BACKUP_LIST")).map(e=>({url:"https://".concat(e,"/api/v2/transpond/webrtc?v=2"),areaCode:Iq(),serviceIds:[yz.CHOOSE_SERVER,yz.CLOUD_PROXY_FALLBACK]}));try{return await An({referenceList:i,asyncMapHandler:i=>(async function(e,t,i){let r,{url:n,areaCode:o,serviceIds:a}=e,s=Date.now(),[c,d]=Ae(t,o,a),l=gh.networkState;try{l&&gh.networkState===go.OFFLINE&&gh.onlineWaiter&&await dQ.race([gh.onlineWaiter,gO(gH.maxRetryTimeout)]),l=gh.networkState;let{data:e,headers:t}=await Iz(n,{data:c,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);r="1"===t.http3?1:-1;let o=[];if(e.response_body.forEach(t=>{let i=t.buffer.code;if(23===t.uri&&0===i&&!t.buffer.edges_services)if(4194310===t.buffer.flag)t.buffer.edges_services=[];else{let i={error:new T0(SU.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:TR("NO_EDGES_RETRY"),csIp:e.detail[502]}),flag:t.buffer.flag};o.push(i)}if(0!==i){let r=yw(i),n={error:new T0(SU.CAN_NOT_GET_GATEWAY_SERVER,r.desc,{desc:r.desc,retry:r.retry,csIp:e.detail[502]}),flag:t.buffer.flag};4194310===t.buffer.flag?TY.warning(n.error.toString()):o.push(n)}}),o.length)throw new T0(SU.CAN_NOT_GET_GATEWAY_SERVER,o.map(e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message)).join(" | "),{retry:!!o.find(e=>e.error.data.retry),csIp:e.detail[502],desc:[...new Set(o.map(e=>{var t;return null==e||null==(t=e.error)||null==(t=t.data)?void 0:t.desc}).filter(e=>!!e))]});let a=y3(e,yz.CHOOSE_SERVER),h=y3(e,yz.CLOUD_PROXY_FALLBACK);return I7(a),{gatewayInfo:y$(a,n),proxyInfo:h,opid:d,requestTime:s,url:n,isHttp3:r,elapse:Date.now()-s}}catch(e){throw e}})(i,e,t),closeFn:e=>e.code===SU.OPERATION_ABORTED||e.code===SU.CAN_NOT_GET_GATEWAY_SERVER&&!e.data.retry})}catch(e){throw e}}async function Au(e,t,i,r){let n,o,a,s=TR("PROXY_SERVER_TYPE3"),c=(e,t,i)=>{let r=i||s;return Array.isArray(r)&&(r=t%2==0&&s[1]||s[0]),"https://".concat(r,"/ap/?url=").concat(e)},d=null,l=[],h=async()=>{let n=TR("WEBCS_DOMAIN").slice(0,TR("AJAX_REQUEST_CONCURRENT")).map((t,i)=>({url:"disabled"===e.cloudProxyServer&&e.proxyServer?c("".concat(t,"/api/v2/transpond/webrtc?v=2"),i,e.proxyServer):"disabled"===e.cloudProxyServer||"fallback"===e.cloudProxyServer?"https://".concat(t,"/api/v2/transpond/webrtc?v=2"):c("".concat(t,"/api/v2/transpond/webrtc?v=2"),i),areaCode:Iq(),serviceIds:[yz.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?yz.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?yz.CLOUD_PROXY:yz.CLOUD_PROXY_FALLBACK]})),o=r.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:n.map(e=>e.url)}),a=await Ar({fragementLength:TR("FRAGEMENT_LENGTH"),referenceList:n,asyncMapHandler:r=>(TY.debug("[".concat(e.clientId,"] Connect to choose_server:"),r.url),I8(r,e,t,i)),allFailedhandler:e=>{throw r.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},o),e[0]},promisesCollector:l});return r.recordJoinChannelService({endTs:Date.now(),status:"success"},o),a},u=async()=>{if(await gO(1e3),null!==d)return d;let n=TR("WEBCS_DOMAIN_BACKUP_LIST").map((t,i)=>({url:"disabled"===e.cloudProxyServer&&e.proxyServer?c("".concat(t,"/api/v2/transpond/webrtc?v=2"),i,e.proxyServer):"disabled"===e.cloudProxyServer||"fallback"===e.cloudProxyServer?"https://".concat(t,"/api/v2/transpond/webrtc?v=2"):c("".concat(t,"/api/v2/transpond/webrtc?v=2"),i),areaCode:Iq(),serviceIds:[yz.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?yz.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?yz.CLOUD_PROXY:yz.CLOUD_PROXY_FALLBACK]})),o=r.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:n.map(e=>e.url)}),a=await Ar({fragementLength:TR("FRAGEMENT_LENGTH"),referenceList:n,asyncMapHandler:r=>(TY.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),r.url),I8(r,e,t,i)),allFailedhandler:e=>{throw r.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},o),e[0]},promisesCollector:l});return r.recordJoinChannelService({endTs:Date.now(),status:"success"},o),a};try{({gatewayInfo:n,proxyInfo:o,url:a}=await Ai([h(),u()]))}catch(e){throw e[0]}
1if(l.length&&l.forEach(e=>e.cancel&&"function"==typeof e.cancel&&e.cancel()),!n||!o)throw new T0(SU.UNEXPECTED_ERROR,"missing gateway or proxy response").print();if(e.apUrl=a,"disabled"!==e.cloudProxyServer&&Array.isArray(s)&&a){let t=/^https?:\/\/(.+?)(\/.*)?$/.exec(a)[1];o5(s).call(s,t)&&(e.proxyServer=t,TY.setProxyServer(t),T$.setProxyServer(t))}return d={gatewayInfo:n,proxyInfo:await y5(o,n.uid)}}async function Ap(e,t,i){let r=TR("UAP_AP").slice(0,TR("AJAX_REQUEST_CONCURRENT")).map(t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v1?action=uap"):"https://".concat(t,"/api/v1?action=uap")).map(r=>(function(e,t,i,r){let n={command:"convergeAllocateEdge",sid:t.sid,appId:t.appId,token:t.token,ts:Date.now(),version:Th,cname:t.cname,uid:t.uid.toString(),requestId:I4,seq:I4};I4+=1;let o={service_name:"tele_channel",json_body:JSON.stringify(n)};return gY(async()=>{let t=await Iz(e,{data:o,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":61}});if(0!==t.code){let e=new T0(SU.UNEXPECTED_RESPONSE,"cross channel ap error, code"+t.code,{retry:!0});throw TY.error(e.toString()),e}let r=JSON.parse(t.json_body);if(200!==r.code){let e=new T0(SU.UNEXPECTED_RESPONSE,"cross channel app center error, code: ".concat(r.code,", reason: ").concat(r.reason));throw TY.error(e.toString()),e}if(!r.servers||0===r.servers.length){let e=new T0(SU.UNEXPECTED_RESPONSE,"cross channel app center empty server");throw TY.error(e.toString()),e}return{vid:r.vid,workerToken:r.workerToken,addressList:(TR("CHANNEL_MEDIA_RELAY_SERVERS")||r.servers).map(e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(TR("WORKER_DOMAIN"),":").concat(e.wss))}},void 0,e=>!!(e.code!==SU.OPERATION_ABORTED&&e.code!==SU.UNEXPECTED_RESPONSE||e.data&&e.data.retry),r)})(r,e,t,i));try{let e=await Ai(r);return r.forEach(e=>e.cancel()),e}catch(e){throw e[0]}}async function A_(e,t,i){let r=null,n=[],o=async o=>{let a=TR(o?"WEBCS_DOMAIN_BACKUP_LIST":"WEBCS_DOMAIN").map(t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2"));return o&&(await gO(1e3),null!==r)?r:await Ar({fragementLength:TR("FRAGEMENT_LENGTH"),referenceList:a,asyncMapHandler:r=>(TY.debug("[".concat(e.clientId,"] update ticket, Connect to ").concat(o?"backup":""," choose_server:"),r),function(e,t,i,r){let[n]=((e,t)=>{let i=Math.floor(1e12*Math.random()),r={appid:e.appId,client_ts:Date.now(),opid:i,sid:e.sid,request_bodies:[{uri:28,buffer:{cname:e.cname,detail:{1:"",6:e.stringUid,12:"1"},token:e.token,service_ids:t,uid:e.uid||0,edges_services:e.apResponse.addresses.map(e=>({ip:e.ip,port:e.port}))}}]},n=new FormData;return n.append("request",JSON.stringify(r)),[n,i]})(t,[yz.CHOOSE_SERVER]),o=gh.networkState;return gY(async()=>{o&&gh.networkState===go.OFFLINE&&gh.onlineWaiter&&await dQ.race([gh.onlineWaiter,gO(r&&r.maxRetryTimeout||gH.maxRetryTimeout)]),o=gh.networkState;var t=await Iz(e,{data:n,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0);if(t.response_body&&t.response_body.length){let e=t.response_body[0];if(0!==e.buffer.code){let t=yw(e.buffer.code);throw new T0(SU.UPDATE_TICKET_FAILED,"[".concat(e.buffer.code,"]: ").concat(t.desc),{retry:t.retry})}return e.buffer.ticket}throw TY.debug("update ticket request received ap response without response body:",e),new T0(SU.UPDATE_TICKET_FAILED,"cannot find response body from ap response",{retry:!1})},()=>!1,e=>e.code!==SU.OPERATION_ABORTED&&(e.code===SU.UPDATE_TICKET_FAILED?e.data.retry:(TY.warning("[".concat(t.clientId,"] update ticket network error, retry"),e),!0)),r)}(r,e,t,i)),allFailedhandler:e=>{throw e[0]},promisesCollector:n})};try{return r=await Ai([o(!1),o(!0)]),n.length&&n.forEach(e=>e.cancel&&"function"==typeof e.cancel&&e.cancel()),r}catch(e){throw e[0]}}function AE(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function Am(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
1t%2?AE(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):AE(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}class Af extends S0{get isSuccess(){return!!this.configs}startGetConfigDistribute(e,t){this.joinInfo=e,this.cancelToken=t,this.interval&&this.stopGetConfigDistribute(),TR("ENABLE_CONFIG_DISTRIBUTE")&&(this.updateConfigDistribute(),this.interval=window.setInterval(()=>{this.updateConfigDistribute()},TR("CONFIG_DISTRIBUTE_INTERVAL")))}stopGetConfigDistribute(){this.interval&&clearInterval(this.interval),this.interval=void 0,this.joinInfo=void 0,this.cancelToken=void 0,this.configs=void 0,this.limit_bitrate=void 0}async awaitConfigDistributeComplete(){this.mutex.isLocked&&(await this.mutex.lock())()}async updateConfigDistribute(){let e;if(this.mutableParamsRead||(this.mutableParamsRead=!0,T$.reportApiInvoke(null,{options:void 0,name:S3.LOAD_CONFIG_FROM_LOCALSTORAGE,tag:S5.TRACER}).onSuccess(JSON.stringify(Tv))),!this.joinInfo||!this.cancelToken||!this.retryConfig)return void TY.debug("[config-distribute] get config distribute interrupted have no joininfo");let t=await this.mutex.lock();try{e=await Al(this.joinInfo,this.cancelToken,this.retryConfig),TY.debug("[config-distribute] get config distribute",JSON.stringify(e));let t=function(e){var t;let i=ll(t=Object.keys(e).filter(e=>/^webrtc_ng_global_parameter/.test(e))).call(t);for(let t=0;t<i.length;t++)for(let r=i.length-1;r>t;r--){let t=i[r],n=e[t].value;if("number"==typeof n.__priority){let o=n.__priority,a=e[i[r-1]].value;if("number"==typeof a.__priority){if(!(o>a.__priority))continue;i[r]=i[r-1],i[r-1]=t}else i[r]=i[r-1],i[r-1]=t}}let r=Date.now(),n={};return i.forEach(t=>{let i=e[t].value.__expires;i&&i<=r||(n[t]=e[t])}),n}(e);this.cacheGlobalParameterConfig(t),this.store.hasStartJoinChannel||(this.store.isABTestSuccess=!0),this.configs=t}catch(t){let e=new T0(SU.NETWORK_RESPONSE_ERROR,t);TY.warning("[config-distribute] ".concat(e.toString()))}finally{t()}}getBitrateLimit(){return this.limit_bitrate||void 0}handleBitrateLimit(e){yo(e)&&(this.limit_bitrate?this.limit_bitrate&&this.limit_bitrate.id!==e.id&&this.emit(yn.UPDATE_BITRATE_LIMIT,e):this.emit(yn.UPDATE_BITRATE_LIMIT,e))}getLowStreamConfigDistribute(){return this.limit_bitrate&&Am({},this.limit_bitrate.low_stream_uplink)}handleABTestConfigDistribute(e){try{let t={},i=Object.keys(e),r=[];i.forEach(i=>{let n=e[i].value;t[i]=n;let o=n.__id;if(o&&this.configCache[i]&&this.configCache[i].__id===o)return;let a=n.__type,s=e[i].value,c=e[i].tag,d=0;a?a===TC.REALTIME&&(d=1):Object.keys(s).some(e=>Object.prototype.hasOwnProperty.call(TS,e)||!vE()&&Object.prototype.hasOwnProperty.call(TE,e)?(d=1,!0):void 0),r.push({tag:c,isApplied:d,feature:i,params:JSON.stringify(n)})}),r.forEach(e=>{let{tag:t,feature:i,params:r,isApplied:n}=e;this.store.sessionId&&T$.abTest(this.store.sessionId,{intSucc:1,isApplied:n,tag:t,feature:i,params:r,cid:this.store.cid,uid:this.store.intUid})}),this.configCache=t}catch(e){TY.debug("handleABTestConfigDistribute error",e)}}cacheGlobalParameterConfig(e){let t=function(e){let t={};return Object.keys(e).forEach(i=>{let r=e[i].value,n=r.__expires,o=r.__type;Object.keys(r).forEach(e=>{"__id"===e||"__type"===e||"__priority"===e||"__expires"===e||Object.prototype.hasOwnProperty.call(t,e)||(t[e]=Am(Am({value:r[e]},n&&{expires:n}),o&&{type:o}))})}),t}(e);try{var i;let r=null==(i=t.LIMIT_BITRATE)?void 0:i.value;delete t.LIMIT_BITRATE,r&&yo(r)&&this.handleBitrateLimit(r),this.limit_bitrate=r,this.handleGlobalParameterConfig(t),this.handleABTestConfigDistribute(e),function(e){try{let t=Date.now();Object.keys(e).forEach(i=>{let{value:r,type:n,expires:o}=e[i];o&&o<=t||((n===TC.REALTIME||Object.prototype.hasOwnProperty.call(TS,i))&&(Tv[i]=r,Tg[i]=r,TY.debug("Update realtime parameters from config distribute",i,r)),n||vE()||!Object.prototype.hasOwnProperty.call(TE,i)||(Tv[i]=r,Tg[i]=r,TY.debug("Update gateway parameters from config distribute",i,r)))})}catch(t){TY.error("Error update config immediately: ".concat(e),t.message)}}(t);let n=JSON.stringify(t),o=window.btoa(n);window.localStorage.setItem("websdk_ng_global_parameter",o),TY.debug("Caching global parameters ".concat(n))}catch(e){TY.error("Error caching global parameters:",e.message)}}handleGlobalParameterConfig(e){try{let t=Date.now();Object.keys(e).forEach(i=>
1{switch(i){case"CLIENT_ROLE_OPTIONS":if(Object.prototype.hasOwnProperty.call(Tg,i)){let{value:r,expires:n}=e[i];if(n&&n<=t)return;gx(Tg[i],r)||(Tv[i]=r,Tg[i]=r,this.emit(yn.UPDATE_CLIENT_ROLE_OPTIONS,r),TY.debug("Updating client role options: ".concat(JSON.stringify(r))))}break;case"REMOTE_VIDEO_STREAM_TYPE":if(Object.prototype.hasOwnProperty.call(Tg,i)){var r;let{value:n,expires:o}=e[i];if(o&&o<=t)return;"number"==typeof n&&o5(r=[0,1,4,5,6,7,8,9]).call(r,n)&&(Tv[i]={value:n},Tg[i]=n,this.emit(yn.UPDATE_REMOTE_VIDEO_STREAM_TYPE,n),TY.debug("Updating client remote stream type: ".concat(JSON.stringify(n))))}break;case"ENABLE_FORCE_HLS":if(Object.prototype.hasOwnProperty.call(Tg,i)){let{value:r,expires:n}=e[i];if(n&&n<=t)return;gx(Tg[i],r)||(Tv[i]=r,Tg[i]=r,this.emit(yn.FALLBACK_TO_HLS,r),TY.debug("Updating enable force hls: ".concat(JSON.stringify(r))))}break;case"VOS_CONFIGURE":if(Object.prototype.hasOwnProperty.call(Tg,i)){let{value:r,expires:n}=e[i];if(n&&n<=t)return;gx(Tg[i],r)||(Tv[i]=r,Tg[i]=r,this.emit(yn.UPDATE_VOS_CONFIGURE,r),TY.debug("Updating vos configure: ".concat(JSON.stringify(r))))}}})}catch(e){TY.error("Error handling global parameter config:",e.message)}}constructor(e,t){super(),mb(this,"configs",void 0),mb(this,"store",void 0),mb(this,"joinInfo",void 0),mb(this,"cancelToken",void 0),mb(this,"retryConfig",{timeout:3e3,timeoutFactor:1.5,maxRetryCount:1,maxRetryTimeout:1e4}),mb(this,"interval",void 0),mb(this,"mutex",void 0),mb(this,"mutableParamsRead",!1),mb(this,"configCache",{}),mb(this,"limit_bitrate",void 0),this.mutex=new gG("config-distribute",e),this.store=t}}class AS extends S0{setLocalAudioStats(e,t,i){this.record("AUDIO_INPUT_LEVEL_TOO_LOW",e,this.checkAudioInputLevel(i,t)),this.record("SEND_AUDIO_BITRATE_TOO_LOW",e,this.checkSendAudioBitrate(i,t))}setLocalVideoStats(e,t,i){this.record("SEND_VIDEO_BITRATE_TOO_LOW",e,this.checkSendVideoBitrate(i,t)),this.record("FRAMERATE_INPUT_TOO_LOW",e,this.checkFramerateInput(i,t)),this.record("FRAMERATE_SENT_TOO_LOW",e,this.checkFramerateSent(i)),t.muted||this.record("VIDEO_ENCODE_FAILED",e,this.checResolutionSent(i))}setRemoteAudioStats(e,t){let i=e.getUserId();this.record("AUDIO_OUTPUT_LEVEL_TOO_LOW",i,this.checkAudioOutputLevel(t))}setRemoteVideoStats(e,t){let i=e.getUserId();this.record("RECV_VIDEO_DECODE_FAILED",i,this.checkVideoDecode(t))}record(e,t,i){if(TR("STATS_UPDATE_INTERVAL")>500)return;this.resultStorage.has(e)||this.resultStorage.set(e,{result:[],isPrevNormal:!0});let r=this.resultStorage.get(e);if(!r)return;r.result.push(i);let n="VIDEO_ENCODE_FAILED"===e?TR("ENCODE_EXCEPTION_TIMES"):5;if(r.result.length>=n){var o;let i=o5(o=r.result).call(o,!0);r.isPrevNormal&&!i&&this.emit("exception",Ag[e],e,t),!r.isPrevNormal&&i&&this.emit("exception",Ag[e]+2e3,e+"_RECOVER",t),r.isPrevNormal=i,r.result=[]}}checkAudioOutputLevel(e){return!(e.receiveBitrate>0&&0===e.receiveLevel)}checkAudioInputLevel(e,t){return t instanceof CI&&!t.isActive||!!t.muted||0!==e.sendVolumeLevel}checkFramerateInput(e,t){let i=null;t._encoderConfig&&t._encoderConfig.frameRate&&(i=y0(t._encoderConfig.frameRate));let r=e.captureFrameRate;return!i||!r||!(i>10&&r<5||i<10&&i>=5&&r<=1)}checkFramerateSent(e){return!(e.captureFrameRate&&e.sendFrameRate&&e.captureFrameRate>5&&e.sendFrameRate<=1)}checResolutionSent(e){var t;return!(!e.codecType||o5(t=TR("ENCODE_EXCEPTION_VALIDATE_CODEC")).call(t,e.codecType.toLocaleLowerCase()))||!e.captureFrameRate||0!==e.sendFrameRate||0!==e.sendResolutionWidth||0!==e.sendResolutionHeight}checkSendVideoBitrate(e,t){return!!t.muted||0!==e.sendBitrate}checkSendAudioBitrate(e,t){return t instanceof CI&&!t.isActive||!!t.muted||0!==e.sendBitrate}checkVideoDecode(e){return 0===e.receiveBitrate||0!==e.decodeFrameRate}constructor(){super(...arguments),mb(this,"resultStorage",new Map)}}let Ag={FRAMERATE_INPUT_TOO_LOW:1001,FRAMERATE_SENT_TOO_LOW:1002,SEND_VIDEO_BITRATE_TOO_LOW:1003,RECV_VIDEO_DECODE_FAILED:1005,AUDIO_INPUT_LEVEL_TOO_LOW:2001,AUDIO_OUTPUT_LEVEL_TOO_LOW:2002,SEND_AUDIO_BITRATE_TOO_LOW:2003,VIDEO_ENCODE_FAILED:2004},AT=new class{markSubscribeStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/subscribe-").concat(t))}markPublishStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/publish-").concat(t))}measureFromSubscribeStart(e,t){let i=performance.getEntriesByName("agora-web-sdk/".concat(e,"/subscribe-").concat(t));if(i.length>0){let e=i[i.length-1];return Math.round(performance.now()-e.startTime)}return 0}measureFromPublishStart(e,t){let i=performance.getEntriesByName("agora-web-sdk/".concat(e,"/publish-").concat(t));if(i.length>0){let e=i[i.length-1];return Math.round(performance.now()-e.startTime)}return 0}};function AR(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function AC(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
1t%2?AR(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):AR(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}class Av{startUpdateStats(){this.updateStatsInterval||(this.updateStatsInterval=window.setInterval(this.updateStats,1e3))}stopUpdateStats(){this.updateStatsInterval&&(window.clearInterval(this.updateStatsInterval),this.updateStatsInterval=void 0)}reset(){this.localStats=new Map,this.remoteStats=new Map,this.trafficStats=void 0,this.trafficStatsPeerList=[],this.uplinkStats=void 0}getLocalAudioTrackStats(){return this.localStats.get(yu.LocalAudioTrack)||AC({},Ry)}getLocalVideoTrackStats(){return this.localStats.get(yu.LocalVideoTrack)||AC({},RI)}getRemoteAudioTrackStats(e){let t=(e,t)=>{if(!this.trafficStats)return t;let i=this.trafficStats.peer_delay.find(t=>t.peer_uid===e);return i&&(t.publishDuration=i.B_ppad+(Date.now()-this.trafficStats.timestamp)),t},i={};if(e){var r;let n=null==(r=this.remoteStats.get(e))?void 0:r.audioStats;n&&(i[e]=t(e,n))}else Array.from(this.remoteStats.entries()).forEach(e=>{let[r,{audioStats:n}]=e;n&&(i[r]=t(r,n))});return i}getRemoteNetworkQualityStats(e){let t={};if(e){var i;let r=null==(i=this.remoteStats.get(e))?void 0:i.networkStats;r&&(t[e]=r)}else Array.from(this.remoteStats.entries()).forEach(e=>{let[i,{networkStats:r}]=e;r&&(t[i]=r)});return t}getNetworkQuality(){let e=0,t=0;return this.trafficStats&&(e=y2(this.trafficStats.B_unq),t=y2(this.trafficStats.B_dnq)),{uplinkNetworkQuality:e,downlinkNetworkQuality:t}}getRemoteVideoTrackStats(e){let t=(e,t)=>{if(!this.trafficStats)return t;let i=this.trafficStats.peer_delay.find(t=>t.peer_uid===e);return i&&(t.publishDuration=i.B_ppvd+(Date.now()-this.trafficStats.timestamp)),t},i={};if(e){var r;let n=null==(r=this.remoteStats.get(e))?void 0:r.videoStats;n&&(i[e]=t(e,n))}else Array.from(this.remoteStats.entries()).forEach(e=>{let[r,{videoStats:n}]=e;n&&(i[r]=t(r,n))});return i}getRTCStats(){let e=0,t=0,i=0,r=0,n=this.localStats.get(yu.LocalAudioTrack);n&&(e+=n.sendBytes,t+=n.sendBitrate);let o=this.localStats.get(yu.LocalVideoTrack);o&&(e+=o.sendBytes,t+=o.sendBitrate);let a=this.localStats.get(yu.LocalVideoLowTrack);
1a&&(e+=a.sendBytes,t+=a.sendBitrate),this.remoteStats.forEach(e=>{let{audioStats:t,videoStats:n}=e;t&&(i+=t.receiveBytes,r+=t.receiveBitrate),n&&(i+=n.receiveBytes,r+=n.receiveBitrate)});let s=1;return this.trafficStats&&(s+=this.trafficStats.peer_delay.length),{Duration:0,UserCount:s,SendBitrate:t,SendBytes:e,RecvBytes:i,RecvBitrate:r,OutgoingAvailableBandwidth:this.uplinkStats?this.uplinkStats.B_uab/1e3:0,RTT:this.trafficStats?2*this.trafficStats.B_acd:0}}addLocalStats(e){this.localStats.set(e,void 0)}removeLocalStats(e){e?this.localStats.delete(e):this.localStats.clear()}addRemoteStats(e){this.remoteStats.set(e,{})}removeRemoteStats(e){e?this.remoteStats.delete(e):this.remoteStats.clear()}addP2PChannel(e){this.p2pChannel=e}updateTrafficStats(e){e.peer_delay=e.peer_delay.filter(e=>void 0!==e.B_ppad||void 0!==e.B_ppvd),e.peer_delay.filter(e=>-1===this.trafficStatsPeerList.indexOf(e.peer_uid)).forEach(e=>{var t;let i=null==(t=this.p2pChannel)?void 0:t.getRemoteMedia(e.peer_uid),r=null!=i&&i.videoSSRC?AT.measureFromSubscribeStart(this.store.clientId,i.videoSSRC):0,n=null!=i&&i.audioSSRC?AT.measureFromSubscribeStart(this.store.clientId,i.audioSSRC):0;void 0!==e.B_ppad&&void 0!==e.B_ppvd&&(this.onUploadPublishDuration&&this.onUploadPublishDuration(e.peer_uid,e.B_ppad,e.B_ppvd,r>n?r:n),this.trafficStatsPeerList.push(e.peer_uid))}),this.trafficStats=e}updateUplinkStats(e){this.uplinkStats&&this.uplinkStats.B_fir!==e.B_fir&&TY.debug("[".concat(this.store.clientId,"]: Period fir changes to ").concat(e.B_fir)),this.uplinkStats=e}static isRemoteVideoFreeze(e,t,i){if(!e)return!1;let r=!!i&&t.framesDecodeFreezeTime>i.framesDecodeFreezeTime,n=!i||t.framesDecodeCount>i.framesDecodeCount;return r||!n}static isRemoteAudioFreeze(e){return!!e&&e._isFreeze()}isLocalVideoFreeze(e){return!(!e.inputFrame||!e.sentFrame)&&e.inputFrame.frameRate>5&&e.sentFrame.frameRate<3}updateLocalStats(e){Array.from(this.localStats.entries()).forEach(t=>{let[i,r]=t;switch(i){case yu.LocalVideoTrack:case yu.LocalVideoLowTrack:{var n,o;let t=AC({},RI),a=e.getStats(),s=e.getLocalMedia(i);if(a){let i=a.videoSend.find(e=>e.ssrc===(null==s?void 0:s.ssrcs[0].ssrcId));if(i){let o=e.getLocalVideoSize(),a=e.getEncoderConfig(yu.LocalVideoTrack);("H264"===i.codec||"H265"===i.codec||"VP8"===i.codec||"VP9"===i.codec||"AV1X"===i.codec||"AV1"===i.codec)&&(t.codecType=i.codec,(null==r?void 0:r.codecType)!==i.codec)&&(null==(n=this.onVideoCodecChanged)||n.call(this,i.codec.toLocaleLowerCase())),t.sendBytes=i.bytes,t.sendBitrate=r?8*Math.max(0,t.sendBytes-r.sendBytes):0,i.inputFrame?(t.captureFrameRate=i.inputFrame.frameRate,t.captureResolutionHeight=i.inputFrame.height,t.captureResolutionWidth=i.inputFrame.width):o&&(t.captureResolutionWidth=o.width,t.captureResolutionHeight=o.height),i.sentFrame?(t.sendFrameRate=i.sentFrame.frameRate,t.sendResolutionHeight=i.sentFrame.height,t.sendResolutionWidth=i.sentFrame.width):o&&(t.sendResolutionWidth=o.width,t.sendResolutionHeight=o.height),i.avgEncodeMs&&(t.encodeDelay=i.avgEncodeMs),a&&a.bitrateMax?t.targetSendBitrate=1e3*a.bitrateMax:i.targetBitrate&&(t.targetSendBitrate=i.targetBitrate),t.sendPackets=i.packets,t.sendPacketsLost=i.packetsLost,t.sendJitterMs=i.jitterMs,t.sendRttMs=i.rttMs,t.totalDuration=r?r.totalDuration+1:1,t.totalFreezeTime=r?r.totalFreezeTime:0,this.isLocalVideoFreeze(i)&&(t.totalFreezeTime+=1),i.scalabilityMode&&this.scalabilityMode!==i.scalabilityMode&&(TY.debug("[".concat(this.store.clientId,"]: The scalabilityMode of the video sending stream is ").concat(i.scalabilityMode)),this.scalabilityMode=i.scalabilityMode)}this.trafficStats&&(t.currentPacketLossRate=(this.trafficStats.B_pvlr4||0)/100)}this.localStats.set(i,t),((null==r?void 0:r.sendResolutionWidth)!==t.sendResolutionWidth||(null==r?void 0:r.sendResolutionHeight)!==t.sendResolutionHeight)&&(null==(o=this.onStatsChanged)||o.call(this,"resolution",{width:t.sendResolutionWidth,height:t.sendResolutionHeight})),t&&s&&this.exceptionMonitor.setLocalVideoStats(this.store.uid,s.track,t);break}case yu.LocalAudioTrack:{let t=AC({},Ry),n=e.getStats(),o=e.getLocalMedia(i);
1if(n){let i=n.audioSend.find(e=>e.ssrc===(null==o?void 0:o.ssrcs[0].ssrcId));if(i){if("opus"!==i.codec&&"aac"!==i.codec&&"PCMU"!==i.codec&&"PCMA"!==i.codec&&"G722"!==i.codec||(t.codecType=i.codec),i.inputLevel)t.sendVolumeLevel=Math.round(32767*i.inputLevel);else{let i=e.getLocalAudioVolume();i&&(t.sendVolumeLevel=Math.round(32767*i))}t.sendBytes=i.bytes,t.sendPackets=i.packets,t.sendPacketsLost=i.packetsLost,t.sendJitterMs=i.jitterMs,t.sendRttMs=i.rttMs,t.sendBitrate=r?8*Math.max(0,t.sendBytes-r.sendBytes):0}}this.trafficStats&&(t.currentPacketLossRate=(this.trafficStats.B_palr4||0)/100),this.localStats.set(yu.LocalAudioTrack,t),t&&o&&this.exceptionMonitor.setLocalAudioStats(this.store.uid,o.track,t)}}})}updateRemoteStats(e){Array.from(this.remoteStats.entries()).forEach(t=>{var i;let r,[n,{videoStats:o,audioStats:a,videoPcStats:s}]=t,c=AC({},RA),d=AC({},RO),l=AC({},Rb),{audioTrack:h,videoTrack:u,audioSSRC:p,videoSSRC:_}=e.getRemoteMedia(n),E=null==(r=this.store.useP2P?e.getStats(!0):e.getStats())?void 0:r.audioRecv.find(e=>e.ssrc===p),m=null==r?void 0:r.videoRecv.find(e=>e.ssrc===_),f=this.trafficStats&&this.trafficStats.peer_delay.find(e=>e.peer_uid===n);if(E&&("opus"!==E.codec&&"aac"!==E.codec&&"PCMU"!==E.codec&&"PCMA"!==E.codec&&"G722"!==E.codec||(c.codecType=E.codec),E.outputLevel?c.receiveLevel=Math.round(32767*E.outputLevel):h&&(c.receiveLevel=Math.round(32767*h.getVolumeLevel())),c.receiveBytes=E.bytes,c.receivePackets=E.packets,c.receivePacketsLost=E.packetsLost,c.receivePacketsDiscarded=E.packetsDiscarded,c.packetLossRate=c.receivePacketsLost/(c.receivePackets+c.receivePacketsLost),c.receiveBitrate=a?8*Math.max(0,c.receiveBytes-a.receiveBytes):0,c.totalDuration=a?a.totalDuration+1:1,c.totalFreezeTime=a?a.totalFreezeTime:0,c.freezeRate=c.totalFreezeTime/c.totalDuration,c.receiveDelay=E.jitterBufferMs,c.totalDuration>10&&Av.isRemoteAudioFreeze(h)&&(c.totalFreezeTime+=1)),m){"H264"!==m.codec&&"H265"!==m.codec&&"VP8"!==m.codec&&"VP9"!==m.codec&&"AV1X"!==m.codec&&"AV1"!==m.codec||(d.codecType=m.codec),d.receiveBytes=m.bytes,d.receiveBitrate=o?8*Math.max(0,d.receiveBytes-o.receiveBytes):0,d.decodeFrameRate=m.decodeFrameRate<0?0:m.decodeFrameRate,d.renderFrameRate=m.decodeFrameRate<0?0:m.decodeFrameRate,m.outputFrame&&(d.renderFrameRate=m.outputFrame.frameRate),m.receivedFrame?(d.receiveFrameRate=m.receivedFrame.frameRate,d.receiveResolutionHeight=m.receivedFrame.height,d.receiveResolutionWidth=m.receivedFrame.width):u&&(d.receiveResolutionHeight=u._videoHeight||0,d.receiveResolutionWidth=u._videoWidth||0),void 0!==m.framesRateFirefox&&(d.receiveFrameRate=Math.round(m.framesRateFirefox)),d.receivePackets=m.packets,d.receivePacketsLost=m.packetsLost,d.packetLossRate=d.receivePacketsLost/(d.receivePackets+d.receivePacketsLost);let t=o?o.totalFreezeTime:0,r=o?o.totalDuration:0;d.totalDuration=o?o.totalDuration+1:1,d.totalFreezeTime=null!=(i=m.totalFreezesDuration)?i:t||0,d.receiveDelay=m.jitterBufferMs||0;let n=!!_&&e.getRemoteVideoIsReady(_);void 0===m.totalFreezesDuration&&u&&n&&Av.isRemoteVideoFreeze(u,m,s)&&(d.totalFreezeTime+=1),d.freezeRate=Math.max(0,Math.min((d.totalFreezeTime-t)/(d.totalDuration-r),1))}f&&(c.end2EndDelay=f.B_ad,d.end2EndDelay=f.B_vd,c.transportDelay=f.B_ed,d.transportDelay=f.B_ed,c.currentPacketLossRate=f.B_ealr4/100,d.currentPacketLossRate=f.B_evlr4/100,l.uplinkNetworkQuality=f.B_punq?f.B_punq:0,l.downlinkNetworkQuality=f.B_pdnq?f.B_pdnq:0),this.remoteStats.set(n,{audioStats:c,videoStats:d,videoPcStats:m,networkStats:l}),h&&this.exceptionMonitor.setRemoteAudioStats(h,c),u&&this.exceptionMonitor.setRemoteVideoStats(u,d)})}constructor(e){mb(this,"store",void 0),mb(this,"onStatsException",void 0),mb(this,"onUploadPublishDuration",void 0),mb(this,"onStatsChanged",void 0),mb(this,"onVideoCodecChanged",void 0),mb(this,"localStats",new Map),mb(this,"remoteStats",new Map),mb(this,"updateStatsInterval",void 0),mb(this,"trafficStats",void 0),mb(this,"trafficStatsPeerList",[]),mb(this,"uplinkStats",void 0),mb(this,"exceptionMonitor",void 0),mb(this,"p2pChannel",void 0),mb(this,"scalabilityMode",Tt.L1T1),mb(this,"updateStats",()=>
1{this.p2pChannel&&(this.updateRemoteStats(this.p2pChannel),this.updateLocalStats(this.p2pChannel))}),this.store=e,this.exceptionMonitor=new AS,this.exceptionMonitor.on("exception",(e,t,i)=>{this.onStatsException&&this.onStatsException(e,t,i)})}}class Ay{setSrcChannelInfo(e){v1(e),this.srcChannelMediaInfo=e}addDestChannelInfo(e){v1(e),this.destChannelMediaInfos.set(e.channelName,e)}removeDestChannelInfo(e){vK(e),this.destChannelMediaInfos.delete(e)}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo}getDestChannelMediaInfo(){return this.destChannelMediaInfos}constructor(){mb(this,"destChannelMediaInfos",new Map),mb(this,"srcChannelMediaInfo",void 0)}}function AI(e){if(!(e instanceof Ay))return new T0(SU.INVALID_PARAMS,"Config should be instance of [ChannelMediaRelayConfiguration]").throw();let t=e.getSrcChannelMediaInfo(),i=e.getDestChannelMediaInfo();return t?0===i.size?new T0(SU.INVALID_PARAMS,"destChannelMediaInfo should not be empty").throw():void 0:new T0(SU.INVALID_PARAMS,"srcChannelMediaInfo should not be empty").throw()}class AA{get hasVideo(){return this._video_enabled_&&!this._video_muted_&&this._video_added_}get hasAudio(){return this._audio_enabled_&&!this._audio_muted_&&this._audio_added_}get audioTrack(){if(this.hasAudio||this._audio_pre_subscribed)return this._audioTrack}get videoTrack(){if(this.hasVideo||this._video_pre_subscribed)return this._videoTrack}get dataChannels(){return this._dataChannels}constructor(e,t){mb(this,"uid",void 0),mb(this,"_uintid",void 0),mb(this,"_trust_in_room_",!0),mb(this,"_trust_audio_enabled_state_",!0),mb(this,"_trust_video_enabled_state_",!0),mb(this,"_trust_audio_mute_state_",!0),mb(this,"_trust_video_mute_state_",!0),mb(this,"_audio_muted_",!1),mb(this,"_video_muted_",!1),mb(this,"_audio_enabled_",!0),mb(this,"_video_enabled_",!0),mb(this,"_audio_added_",!1),mb(this,"_video_added_",!1),mb(this,"_is_pre_created",!1),mb(this,"_video_pre_subscribed",!1),mb(this,"_audio_pre_subscribed",!1),mb(this,"_trust_video_stream_added_state_",!0),mb(this,"_trust_audio_stream_added_state_",!0),mb(this,"_audioTrack",void 0),mb(this,"_videoTrack",void 0),mb(this,"_dataChannels",[]),mb(this,"_audioSSRC",void 0),mb(this,"_videoSSRC",void 0),mb(this,"_audioOrtc",void 0),mb(this,"_videoOrtc",void 0),mb(this,"_cname",void 0),mb(this,"_rtxSsrcId",void 0),mb(this,"_videoMid",void 0),mb(this,"_audioMid",void 0),this.uid=e,this._uintid=t}}function Ab(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function AO(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Ab(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Ab(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let Aw=class{get localCapabilities(){return gS(this._localCapabilities)}get rtpCapabilities(){return gS(this._rtpCapabilities)}get candidates(){return gS(this._candidates)}get iceParameters(){return gS(this._iceParameters)}get dtlsParameters(){return gS(this._dtlsParameters)}checkPreloadSsrcs(e){return e.length===this.preloadSsrcs.length&&e.every(e=>{var t;return o5(t=this.preloadSsrcs).call(t,e)})}preloadRemoteMedia(e){let t=0,i=[],r=[];for(;e>0;){let n=[AO({ssrcId:4e4+t},TR("USE_SUB_RTX")?{rtx:4e4+t+1}:{})],o="".concat(4e4+t,"_").concat(2e4+t),{ssrcs:a,ssrcGroups:s}=I_(n,this.cname,TR("SYNC_GROUP")?o:void 0),c=this.preCreateOrRecycleSendMedia("video",a,s,void 0),d=[{ssrcId:2e4+t}],l="".concat(4e4+t,"_").concat(2e4+t),{ssrcs:h,ssrcGroups:u}=I_(d,this.cname,TR("SYNC_GROUP")?l:void 0),p=this.preCreateOrRecycleSendMedia("audio",h,u,void 0);e--,t+=2,i.push(c,p),r.push(a[0].ssrcId,h[0].ssrcId)}return this.useLocalCodecsMids.push(...i),this.preloadSsrcs=r,{mids:i,preSSRCs:r,isAvailable:!0}}preCreateOrRecycleSendMedia(e,t,i,r){let n=this.rtpCapabilities.send.videoCodecs,o=this._isUseLocalCodecs||0===n.length?this.localCapabilities.recv:this.rtpCapabilities.send;TY.debug("create or recycle send media without remote rtp capabilities, ssrcs ",t[0].ssrcId);let a=e===yc.VIDEO?o.videoCodecs:o.audioCodecs,s=e===yc.VIDEO?o.videoExtensions:o.audioExtensions;this.currentMidIndex+=1;let c="".concat(this.currentMidIndex),d={media:{mediaType:e,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:s,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(c)}};return d=this.mungSendMediaDesc(d,r),this.sessionDesc.mediaDescriptions.push(d),this.updateBundleMids(),c}toString(){return Tw(this.sessionDesc)}send(e,t,i,r){let{ssrcs:n,ssrcGroups:o}=I_(t,this.cname,TR("SYNC_GROUP")?i:void 0),a=this.findPreloadMediaDesc(n);if(a){if(Sl()&&this.firefoxSsrcMidMap.set(n[0].ssrcId,a.attributes.mid),r&&(r.twcc||r.remb)){let e=this.sessionDesc.mediaDescriptions.indexOf(a);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(a,r),{mid:a.attributes.mid,needExchangeSDP:!0}}return{mid:a.attributes.mid,needExchangeSDP:!1}}{let t,i=this.findAvailableMediaIndex(e,n);return -1===i||1===i&&(Ss()||function(){let e=St();return!(e.name!==f8.CHROME||!e.osVersion)&&90>=Number(e.version)}()||Su(143)||SE(143)||TR("RESERVE_MID_1_MLINE")||TR("ENABLE_ENCODED_TRANSFORM")&&Sa())||0===i&&!function(e){let t=St();return!(t.name!==f8.FIREFOX||!t.osVersion)&&138===Number(t.version)}(0)&&TR("USE_SUB_RTX")||SC()?(t=this.createOrRecycleSendMedia(e,n,o,"sendonly",r),this.updateBundleMids()):((t=gS(this.sessionDesc.mediaDescriptions[i])).attributes.direction="sendonly",t.attributes.ssrcs=n,t.attributes.ssrcGroups=o,this.sessionDesc.mediaDescriptions[i]=this.mungSendMediaDesc(t,r)),Sl()&&this.firefoxSsrcMidMap.set(n[0].ssrcId,t.attributes.mid),{mid:t.attributes.mid,needExchangeSDP:!0}}}
1sendDataChannel(){let{mediaDesc:e,needExchangeSDP:t}=this.createOrRecycleDataChannel();return this.updateBundleMids(),{mid:e.attributes.mid,needExchangeSDP:t}}batchSend(e){let t=e.map(e=>{let{kind:t,ssrcMsg:i,mslabel:r}=e;return this.send(t,i,r)}),i=[],r=!1;return t.forEach(e=>{let{mid:t,needExchangeSDP:n}=e;n&&(r=!0),i.push(t)}),{mids:i,needExchangeSDP:r}}stopSending(e){let t=this.sessionDesc.mediaDescriptions.filter(t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid));if(t.length!==e.length)throw Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach(e=>{"0"===e.attributes.mid||Sl()||SC()?e.attributes.ssrcs=[]:(e.attributes.ssrcs=[],e.attributes.direction="inactive",e.media.port="0")}),this.updateBundleMids()}mute(e){let t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive"}unmute(e){let t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly"}muteRemote(e){let t=this.sessionDesc.mediaDescriptions.filter(t=>o5(e).call(e,t.attributes.mid||""));if(t.length!==e.length)throw Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(e=>{e.attributes.direction="inactive"})}unmuteRemote(e){let t=this.sessionDesc.mediaDescriptions.filter(t=>o5(e).call(e,t.attributes.mid||""));if(t.length!==e.length)throw Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(e=>{e.attributes.direction="recvonly"})}receive(e,t,i,r){e.forEach((e,n)=>{this.createOrRecycleRecvMedia(e,[],"recvonly",t,i,r[n])}),this.updateBundleMids()}stopReceiving(e){let t=this.sessionDesc.mediaDescriptions.filter(t=>-1!==e.indexOf(t.attributes.mid));if(t.length!==e.length)throw Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach(e=>{e.media.port="0",e.attributes.direction="inactive"}),this.updateBundleMids()}updateRemoteRTPCapabilities(e){var t,i,r,n;let o=this.sessionDesc||TO((t=this._isUseExtmapAllowMixed,this._isUseDataChannel?"v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1 2\na=msid-semantic: WMS\na=ice-lite".concat(t?"\na=extmap-allow-mixed":"","\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\nc=IN IP4 127.0.0.1\na=mid:2\n"):"v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=ice-lite".concat(t?"\na=extmap-allow-mixed":"","\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n")));this._rtpCapabilities=e;let a=!1,s=this.rtpCapabilities.send,c=this.localCapabilities.send,d=this.localCapabilities.recv,l=d.videoCodecs,h=d.audioCodecs,u=d.videoExtensions,p=d.audioExtensions;for(let e of o.mediaDescriptions)if("sendonly"!==e.attributes.direction||"string"!=typeof e.attributes.mid||!o5(i=this.useLocalCodecsMids).call(i,e.attributes.mid)){if(a=!0,e.attributes.iceUfrag=this._iceParameters.iceUfrag,e.attributes.icePwd=this._iceParameters.icePwd,e.attributes.fingerprints=this._dtlsParameters.fingerprints,e.attributes.candidates=this._candidates,e.attributes.setup=this.setup,"application"===e.media.mediaType&&(e.attributes.sctpPort="5000"),"video"===e.media.mediaType)if(this._isUseLocalCodecs&&"sendonly"===e.attributes.direction){e.media.fmts=l.map(e=>e.payloadType.toString(10)),e.attributes.payloads=l,e.attributes.extmaps=u;let t=e.attributes.mid;"string"!=typeof t||o5(r=this.useLocalCodecsMids).call(r,t)||this.useLocalCodecsMids.push(t)}else if(0===s.videoCodecs.length){let t=c.videoCodecs.filter(e=>{var t,i;return null==(t=e.rtpMap)?void 0:o5(i=t.encodingName.toLowerCase()).call(i,"vp8")});0===t.length&&t.push(c.videoCodecs[0]),e.media.fmts=t.map(e=>e.payloadType.toString(10)),e.attributes.payloads=t,e.attributes.extmaps=[]}else e.media.fmts=s.videoCodecs.map(e=>e.payloadType.toString(10)),e.attributes.payloads=s.videoCodecs,e.attributes.extmaps=s.videoExtensions;
1if("audio"===e.media.mediaType)if(this._isUseLocalCodecs&&"sendonly"===e.attributes.direction){e.media.fmts=h.map(e=>e.payloadType.toString(10)),e.attributes.payloads=h,e.attributes.extmaps=p;let t=e.attributes.mid;"string"!=typeof t||o5(n=this.useLocalCodecsMids).call(n,t)||this.useLocalCodecsMids.push(t)}else if(0===s.audioCodecs.length){let t=c.audioCodecs.filter(e=>{var t,i;return null==(t=e.rtpMap)?void 0:o5(i=t.encodingName.toLowerCase()).call(i,"opus")})||[c.audioCodecs[0]];e.media.fmts=t.map(e=>e.payloadType.toString(10)),e.attributes.payloads=t,e.attributes.extmaps=[]}else e.media.fmts=s.audioCodecs.map(e=>e.payloadType.toString(10)),e.attributes.payloads=s.audioCodecs,e.attributes.extmaps=s.audioExtensions,IA(e)}return this.sessionDesc=o,this.currentMidIndex=o.mediaDescriptions.length-1,[this.sessionDesc,a]}updateCandidates(e){let t=this._originCandidates.filter(e=>"udp"===e.transport),i=[];if(t.forEach(e=>{i.push(AO(AO({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))}),0!==t.length){switch(e){case yd.TCP_RELAY:this._candidates=i;break;case yd.UDP_TCP_RELAY:case yd.RELAY:this._candidates=[...t,...i];break;default:this._candidates=t}for(let e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}}restartICE(e){e=gS(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach(t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd})}predictReceivingMids(e){let t=[];for(let i=0;i<e;i++)t.push((this.currentMidIndex+i+1).toString(10));return t}findAvailableMediaIndex(e,t){return this.sessionDesc.mediaDescriptions.findIndex(i=>{let r=i.media.mediaType===e&&"0"!==i.media.port&&("sendonly"===i.attributes.direction||"sendrecv"===i.attributes.direction)&&0===i.attributes.ssrcs.length;if(Sl()){if(r){let e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return!(e||"0"!==i.attributes.mid&&"1"!==i.attributes.mid)||!(!e||e!==i.attributes.mid)}return!1}return r})}createOrRecycleDataChannel(){for(let e of this.sessionDesc.mediaDescriptions)if("application"===e.media.mediaType)return{mediaDesc:e,needExchangeSDP:!1};this.currentMidIndex+=1;let e="".concat(this.currentMidIndex),t={media:{mediaType:"application",port:"9",protos:["UDP","DTLS","SCTP"],fmts:["webrtc-datachannel"]},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:[],fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[],rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,mid:"".concat(e),sctpPort:"5000"}};return this.sessionDesc.mediaDescriptions.push(t),{mediaDesc:t,needExchangeSDP:!0}}createOrRecycleRecvMedia(e,t,i,r,n,o){let a=e._mediaStreamTrack.kind,s=this.rtpCapabilities.recv,c=Ib(a,s,this.localCapabilities.send,a===yc.VIDEO?r:n),d=a===yc.VIDEO?s.videoExtensions:s.audioExtensions;this.currentMidIndex+=1;let l="".concat(this.currentMidIndex),h={media:{mediaType:a,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:c.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:d,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:c,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(l)}};h=this.mungRecvMediaDsec(h,e,o);let u=this.findFirstClosedMedia(a);if(u){let e=this.sessionDesc.mediaDescriptions.indexOf(u);this.sessionDesc.mediaDescriptions[e]=h}else this.sessionDesc.mediaDescriptions.push(h);return h}updateRemoteDtlsParameters(e){let t=new Set(this._dtlsParameters.fingerprints.map(e=>e.fingerprint)),i=new Set(e.map(e=>e.fingerprint)),r=!1;for(let e of(t.size!==i.size&&(r=!0),t))i.has(e)||(r=!0);return r}updateRemoteCodec(e,t,i){let r,n=[...new Set(this._rtpCapabilities.recv.videoCodecs.map(e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").filter(e=>{var t;return o5(t=Object.keys(TI)).call(t,e)}))],o=new Set(t);if(n.every(e=>o.has(e)))return TY.debug("codecs has not changed, no need to updateRemoteCodec, codecs: ".concat(t)),!1;let a=this._rtpCapabilities.recv.videoCodecs.filter(e=>t.some(t=>{var i;return o5(i=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(i,t)}));if(0===a.length)return TY.debug("updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: ".concat(n," codecs: ").concat(t)),!1;let s=[...new Set(a.map(e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||""))];if(TY.debug("updateRemoteCodec, from ".concat(n," to ").concat(s)),0===e.length)r=this.sessionDesc.mediaDescriptions.filter(e=>"video"===e.media.mediaType&&"recvonly"===e.attributes.direction);else if((r=this.sessionDesc.mediaDescriptions.filter(t=>t.attributes.mid&&"video"===t.media.mediaType&&o5(e).call(e,t.attributes.mid)&&"recvonly"===t.attributes.direction)).length!==e.length)return TY.debug("updateRemoteCodec failed, because cannot find mids, mids: ".concat(e,", codecs: ").concat(t)),!1;if(TR("USE_PUB_RTX")||TR("USE_SUB_RTX")){let e=IO(a,this.rtpCapabilities.recv.videoCodecs);a.push(...e)}this._rtpCapabilities.recv.videoCodecs=a;let c=this.localCapabilities.send,d=this.rtpCapabilities.recv,l=Ib
1(yc.VIDEO,d,c,i);return r.forEach(e=>{let t=l.map(e=>e.payloadType.toString(10));TY.debug("updateRemoteCodec mid: ".concat(e.attributes.mid,", from"),e.attributes.payloads,"to",l),e.attributes.payloads=l,e.media.fmts=t}),TY.debug("updateRemoteCodec success, mids: ".concat(e,", codecs: ").concat(t,", remote recv: ").concat(this._rtpCapabilities.recv.videoCodecs.length,", remote send: ").concat(this._rtpCapabilities.send.videoCodecs.length)),!0}createOrRecycleSendMedia(e,t,i,r,n){let o=this.rtpCapabilities.send.videoCodecs,a=this._isUseLocalCodecs||0===o.length?this.localCapabilities.recv:this.rtpCapabilities.send,s=e===yc.VIDEO?a.videoCodecs:a.audioCodecs,c=e===yc.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;let d="".concat(this.currentMidIndex),l={media:{mediaType:e,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:s.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:s,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:r,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(d)}};l=this.mungSendMediaDesc(l,n);let h=this.findFirstClosedMedia(e);if(h){let e=this.sessionDesc.mediaDescriptions.indexOf(h);this.sessionDesc.mediaDescriptions[e]=l}else this.sessionDesc.mediaDescriptions.push(l);return l}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter(e=>"0"!==e.media.port).map(e=>e.attributes.mid)}mungRecvMediaDsec(e,t,i){let r=gS(e);return Im(r),IE(r,t),If(r,t),IS(r),Ig(r,i,this.localCapabilities.send),r}mungSendMediaDesc(e,t){let i=gS(e);return i.attributes&&i.attributes.payloads&&Array.isArray(i.attributes.payloads)&&i.attributes.payloads.length>0&&i.attributes.payloads.forEach(e=>{e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&TR("ENABLE_DOWN_SPS_PPS")&&(e.fmtp&&e.fmtp.parameters||(e.fmtp={parameters:{}}),e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1")}),Ig(i,t,this.localCapabilities.recv),IA(i),i}updateRecvMedia(e,t){let i=this.sessionDesc.mediaDescriptions.findIndex(t=>t.attributes.mid===e);if(-1!==i){let e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}bumpMid(e){this.currentMidIndex+=e}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find(t=>Sl()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port)}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find(t=>{var i;return(null==(i=t.attributes)||null==(i=i.ssrcs[0])?void 0:i.ssrcId)===e[0].ssrcId})}getSSRC(e){var t;return null==(t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e))?void 0:t.attributes.ssrcs}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];mb(this,"sessionDesc",void 0),mb(this,"_localCapabilities",void 0),mb(this,"_rtpCapabilities",void 0),mb(this,"_candidates",void 0),mb(this,"_originCandidates",void 0),mb(this,"_iceParameters",void 0),mb(this,"_isUseExtmapAllowMixed",void 0),mb(this,"_isUseLocalCodecs",void 0),mb(this,"_isUseDataChannel",void 0),mb(this,"_dtlsParameters",void 0),mb(this,"setup",void 0),mb(this,"currentMidIndex",void 0),mb(this,"cname",void 0),mb(this,"useLocalCodecsMids",[]),mb(this,"preloadSsrcs",[]),mb(this,"firefoxSsrcMidMap",new Map),this._isUseExtmapAllowMixed=t,this._isUseLocalCodecs=i,this._isUseDataChannel=r;let{iceParameters:n,dtlsParameters:o,candidates:a,rtpCapabilities:s,setup:c,localCapabilities:d,cname:l}=e=gS(e);this._rtpCapabilities=s,this._candidates=a,this._originCandidates=gS(a),this._iceParameters=n,this._dtlsParameters=o,this._localCapabilities=d,this.setup=c,this.cname=l,[this.sessionDesc]=this.updateRemoteRTPCapabilities(s),this.currentMidIndex=this.sessionDesc.mediaDescriptions.length-1}};function AN(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function AD(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
1t%2?AN(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):AN(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}var AP=((e6=AP||{})[e6.DOWN=0]="DOWN",e6[e6.UP=1]="UP",e6);let AL=new Map;function Ak(e,t,i,r){let{scale:n}=e;if(0===n&&r===AP.UP||n>=t.length-1&&r===AP.DOWN)return e;let o=AD(AD({},e),{},{scale:r===AP.DOWN?++n:--n});switch(i){case"maintain-framerate":o=AD(AD({},o),t[n].motion);break;case"maintain-resolution":o=AD(AD({},o),t[n].detail);break;case"balanced":o=AD(AD({},o),t[n].balanced)}return o}function AM(e,t){if(t){let i={overUse:0,underUse:0,adaptationList:AU(t)};AL.set(e,i)}else AL.delete(e)}function AU(e){let t=AD({},e),{bitrateMax:i,frameRate:r,scaleResolutionDownBy:n,bitrateMin:o}=t,{MIN_FRAME_RATE:a,MAX_THRESHOLD_FRAMERATE:s,MAX_SCALE:c,BITRATE_MIN_THRESHOLD:d,BITRATE_MAX_THRESHOLD:l,BWE_SCALE_UP_THRESHOLD:h,BWE_SCALE_DOWN_THRESHOLD:u,PERF_SCALE_DOWN_THRESHOLD:p,PERF_SCALE_UP_THRESHOLD:_,BALANCE_BITRATE_FACTOR:E,BALANCE_FRAMERATE_FACTOR:m,BALANCE_RESOLUTION_FACTOR:f,MOTION_RESOLUTION_FACTOR:S,MOTION_BITRATE_FACTOR:g,DETAIL_FRAMERATE_FACTOR:T,DETAIL_BITRATE_FACTOR:R}=Tm,C=Math.min(t.frameRate,s),v=[{scale:0,threshold:{bwe_down:Math.round(Math.pow(u,1)*i),bwe_up:i,fps_down:Math.round(Math.pow(p,1)*C),fps_up:r},balanced:{scaleResolutionDownBy:1,frameRate:r,bitrateMax:i,bitrateMin:o},motion:{scaleResolutionDownBy:1,frameRate:r,bitrateMax:i,bitrateMin:o},detail:{scaleResolutionDownBy:1,frameRate:r,bitrateMax:i,bitrateMin:o}}];for(let e=1;e<=c;e++){let t={bwe_up:Math.round(Math.pow(h,e)*i),bwe_down:Math.round(Math.pow(u,e+1)*i),fps_up:Math.round(Math.pow(_,e)*C),fps_down:Math.round(Math.pow(p,e+1)*C)},s={scaleResolutionDownBy:n/Math.pow(f,e),frameRate:Math.max(Math.round(Math.pow(m,e)*r),a),bitrateMax:Math.max(Math.round(Math.pow(E,e)*i),l),bitrateMin:Math.max(Math.round(Math.pow(E,e)*o),d)},c={scaleResolutionDownBy:n/Math.pow(S,e),frameRate:r,bitrateMax:Math.max(Math.round(Math.pow(g,e)*i),l),bitrateMin:Math.max(Math.round(Math.pow(g,e)*o),d)},y={scaleResolutionDownBy:1,frameRate:Math.max(Math.round(Math.pow(T,e)*r),a),bitrateMax:Math.max(Math.round(Math.pow(R,e)*i),l),bitrateMin:Math.max(Math.round(Math.pow(R,e)*o),d)};v.push({scale:e,threshold:t,balanced:s,motion:c,detail:y})}return v}function Ax(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function AV(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Ax(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Ax(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}function AF(e){var t;return!!TR("ENABLE_AG_ADAPTATION")&&!!(e instanceof CL||o5(t=e._hints).call(t,RE.CUSTOM_TRACK))&&(!!TR("FORCE_SUPPORT_AG_ADAPTATION")||!!(SS(14,0,!1)&&Sg(17,4,!0)||Sf(14)&&ST(17,4,!0)))}let AB=new Map;function Aj(e,t,i,r,n,o){if(AG(e,i),n(t),"balanced"!==r&&"maintain-framerate"!==r&&"maintain-resolution"!==r)return;let a=-1;AM(e,t);let s=window.setInterval(()=>{let s=AB.get(e);if(!TR("ENABLE_AG_ADAPTATION")||!s)return AG(e,i),void n(t);let c=o();if(c.sendPackets>0&&c.OutgoingAvailableBandwidth>0){if(-1===a)return void(a=Date.now());if(Date.now()-a<1e3)return;let o=c.sendFrameRate,d=c.OutgoingAvailableBandwidth,[l,h]=function(e,t,i,r,n,o){let a,s,c=AL.get(e)||{overUse:0,underUse:0,adaptationList:AU(n)},{adaptationList:d}=c;AL.set(e,c);let{OVERUSE_TIMES_THRESHOLD:l,UNDERUSE_TIMES_THRESHOLD:h}=Tm,{scale:u}=r;return"number"==typeof t&&t>0&&function(e,t,i,r){if(t>=i.length)return!1;let{threshold:{fps_down:n}}=i[t];return TR("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===r&&(n=i[0].threshold.fps_down),e<n}(t,u,d,o)&&(c.overUse++,s=Te.CPU,c.overUse>l)||"number"==typeof i&&i>0&&function(e,t,i){if(t>=i.length)return!1;let{threshold:{bwe_down:r}}=i[t];return e<r}(i,u,d)&&(c.overUse++,s=Te.BANDWIDTH,c.overUse>l)?(c.overUse=0,c.underUse=0,[a=Ak(r,d,o,AP.DOWN),s]):("number"==typeof t&&t>0&&"number"==typeof i&&i>0&&function(e,t,i,r){if(0===t)return;let{threshold:{fps_up:n}}=i[t];return TR("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===r&&(n=i[1].threshold.fps_up),e>n}(t,u,d,o)&&function(e,t,i){if(0===t)return;let{threshold:{bwe_up:r}}=i[t];return e>r}(i,u,d)&&(c.underUse++,c.underUse>h&&(c.overUse=0,c.underUse=0,0===(a=Ak(r,d,o,AP.UP)).scale&&(s=Te.NONE))),[a,s])}(e,o,d,s.adaptationConfig,t,r);h&&(i.qualityLimitationReason=h),l&&s.adaptationConfig.scale!==l.scale&&(TY.debug("[".concat(e,"] applyAdaptation: ").concat(i.qualityLimitationReason,"\n sendFps ").concat(o,", bwe ").concat(d,", switch from ").concat(s.adaptationConfig.scale," to ").concat(l.scale," ")),s.adaptationConfig=AV(AV({},s.adaptationConfig),l),n(l))}},TR("CHECK_LOCAL_STATS_INTERVAL")),c=AV({},t);AB.set(e,{timer:s,adaptationConfig:c,originConfig:t,adaptationFunc:n}),TY.debug("[".concat(e,"] start adaptation, originConfig: ").concat(JSON.stringify(t),", degradationPreference: ").concat(r))}function AG(e,t){let i=AB.get(e);if(i){let{timer:t}=i;window.clearTimeout(t),AB.delete(e)}t.qualityLimitationReason=Te.NONE,AM(e)}function AW(e){if(e.some(e=>e._bypassWebAudio))throw new Sx(SU.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");if(!T1.webAudioMediaStreamDest)throw new Sx(SU.NOT_SUPPORTED,"cannot publish multiple tracks because your browser does not support audio mixing")}function AH(e,t){AW(e);let i=t||new CI;
1return e.forEach(e=>i.addAudioTrack(e)),i}let AK=!T1.supportUnifiedPlan||TR("CHROME_FORCE_PLAN_B")&&SN();function AY(e){var t,i;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e.useDcSignal?(t={spec:r,store:e},IV("DataChannelConnection").create(t)):AK?(i={spec:r,store:e},IV("PlanBConnection").create(i)):new AQ(r,e)}function Az(e){return e&&("disconnected"===e.iceConnectionState||"checking"===e.iceConnectionState||"failed"===e.iceConnectionState)}function Aq(e){try{if(e.iceServers)return!1;if(e.turnServer&&"off"!==e.turnServer.mode){if(S9(e.turnServer.servers))return!1;if(TR("FORCE_TURN_TCP")||e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).some(e=>e.forceturn))return!0}return!1}catch(e){return!1}}function AX(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function AJ(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?AX(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):AX(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let AQ=(iW=class e extends ys{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get dtlsTransportState(){var e,t;return null!=(e=null==(t=this.peerConnection.getReceivers()[0])||null==(t=t.transport)?void 0:t.state)?e:null}get localCodecs(){return[...new Set(this.localCapabilities&&this.localCapabilities.send.videoCodecs.map(e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").filter(e=>{var t;return o5(t=Object.keys(TI)).call(t,e)}))]}getPreMedia(e){return this.preMediaMap.get(e)}isPreSub(){return this.preMediaMap.size>0}async updateRemoteRTPCapabilities(e,t){if(this.remoteCodecs=t,!this.remoteSDP)return void TY.debug("[P2PConnection] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: ".concat(this.localCodecs,", codecs: ").concat(t));if(this.remoteSDP.updateRemoteCodec(e,t,this.store.codec)){let e=await this.peerConnection.createOffer(),t=this.logSDPExchange(e.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(e);let i=this.remoteSDP.toString();null==t||t(i),await this.peerConnection.setRemoteDescription({type:"answer",sdp:i})}else TY.debug("[P2PConnection] updateRemoteRTPCapabilities no need to exchange SDP.")}async establish(){try{let t;this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});let i=await this.peerConnection.createOffer();if(!i.sdp)throw Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");let r=Il(i.sdp),n=await IC({filterRTX:!TR("USE_PUB_RTX")&&!TR("USE_SUB_RTX"),filterVideoFec:TR("FILTER_VIDEO_FEC"),filterAudioFec:TR("FILTER_AUDIO_FEC"),filterVideoCodec:TR("FILTER_VIDEO_CODEC"),unsupportedVideoUplinkCodec:TR("UNSUPPORTED_VIDEO_UPLINK_CODEC"),unsupportedVideoDownlinkCodec:TR("UNSUPPORTED_VIDEO_DOWNLINK_CODEC")},this.extension);if(this.localCapabilities=II(n),this.initialOffer=i,TR("ENABLE_SVC")&&"av1"==this.store.codec){var e;let t=await IR();t&&(this.supportAV1RtpSpec=!0,null==(e=n.send)||e.videoExtensions.push(t))}return i.sdp&&IP(i.sdp)&&(t=gS(n),It(t)),AJ(AJ({},r),{},{rtpCapabilities:t||n,offerSDP:i.sdp})}catch(e){throw new Sx(SU.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e){try{if(!this.initialOffer)throw Error("Cannot establish P2PConnection without initial offer.");this.initialOffer.sdp&&IP(this.initialOffer.sdp)&&Ii(e.rtpCapabilities,this.localCapabilities),this.remoteSDP=new Aw(AJ(AJ({},e),{},{localCapabilities:this.localCapabilities}),this.supportAV1RtpSpec,!(!TR("ENABLE_PRE_SUB_WITH_PRE_PC")||!TR("PRE_USE_LOCAL_CODECS"))&&T5(this.store)),e.preallocation&&(this.isPreallocation=!0),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);let t=this.remoteSDP.toString(),i=IN(this.initialOffer.sdp,this.extension),r=this.logSDPExchange(i||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),null==r||r(t),await this.peerConnection.setRemoteDescription({type:"answer",sdp:t});let n=this.peerConnection.getTransceivers()[0];if(null!=n&&n.receiver&&this.tryBindTransportEvents(n.receiver),T5(this.store))if(e.preallocation&&TR("ENABLE_PRE_SUB_WITH_PRE_PC")){let e=TR("PRE_SUB_NUM"),{mids:t,preSSRCs:i}=this.remoteSDP.preloadRemoteMedia(e);await Iw(this.peerConnection,this.remoteSDP,this.extension),TY.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media, in pre pc,add preload ssrcs ").concat(i)),this.presetMedia(t,i)}else{let{preSSRCs:t=[]}=e,i=t.map(e=>e.ssrcMsg[0].ssrcId);if(0===t.length)return;let{mids:r}=this.remoteSDP.batchSend(t.map(e=>Object.assign({},e)));await Iw(this.peerConnection,this.remoteSDP,this.extension),TY.debug("[P2PConnection.connect] preload media, after join, add preload ssrcs ".concat(i)),this.presetMedia(r,i)}}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}presetMedia(e,t){e.forEach((e,i)=>
1{this.peerConnection.getTransceivers().forEach(r=>{if(null!=r.mid&&e===r.mid&&r.receiver.track){let n,o=r.receiver.track;"video"===o.kind&&TR("ENABLE_PRE_RENDER")&&((n=new CD({trackId:"track-".concat(o.kind,"-unknown-").concat(this.store.clientId,"_").concat(gw(5,""))},!0)).updateVideoTrack(o),n.onFirstVideoFrameRender=()=>{var e;let r=this.preMediaMap.get(t[i]);r&&(r.firstVideoRender=Date.now()),null==(e=this.onFirstVideoRender)||e.call(this,t[i])},n.onVideoBufferReady=()=>{var e;null==(e=this.onFirstVideoBufferReady)||e.call(this,t[i])},n.play(this.store.sessionId||void 0),this.isPreRender=!0),this.preMediaMap.set(t[i],{mid:e,track:o,player:n,transceiver:r})}}),this.store.peerReceiver()})}checkDtlsParameters(e){return!!this.remoteSDP&&e.length>0&&this.remoteSDP.updateRemoteDtlsParameters(e)}async updateRemoteConnect(e){try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.updateRemoteConnect before remote SDP created");let t=!1,{rtpCapabilities:i}=e;if([,t]=this.remoteSDP.updateRemoteRTPCapabilities(i),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0){let e=this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);t=t||e}let{preSSRCs:r=[]}=e,n=r.map(e=>e.ssrcMsg[0].ssrcId);if(!this.remoteSDP.checkPreloadSsrcs(n)){let e=[],t=[];if(Array.from(this.preMediaMap.entries()).every(i=>{let[r,{mid:n,player:o,track:a}]=i;return e.push(n),t.push(r),this.preMediaMap.delete(r),o&&o.destroy(),!0}),e.length>0&&(this.remoteSDP.stopSending(e),await Iw(this.peerConnection,this.remoteSDP,this.extension),TY.warn("[P2PConnection.updateRemoteConnect] preload media, failed, del preload ssrcs ".concat(t)),T$.reportApiInvoke(this.store.sessionId,{name:S3.PRELOAD_MEDIA_FAILED,options:[r,t],tag:S5.TRACER}).onSuccess()),r.length>0){let{mids:e}=this.remoteSDP.batchSend(r.map(e=>Object.assign({},e)));await Iw(this.peerConnection,this.remoteSDP,this.extension),TY.debug("[P2PConnection.updateRemoteConnect] preload media, after join, add preload ssrcs ".concat(n)),this.presetMedia(e,n)}}t?(await Iw(this.peerConnection,this.remoteSDP,this.extension),TY.debug("[P2PConnection] updateRemoteConnect by exchanging SDP.")):TY.debug("[P2PConnection] updateRemoteConnect no need to exchange SDP, because no need to update remote codecs (use local codecs)")}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.updateRemoteConnect failed; ".concat(e.toString()))}}send(e,t,i){var r=this;return fT(function*(){let n=yield fC(r.mutex.lock("From P2PConnection.send"));try{let n;if(!r.remoteSDP)throw Error("Cannot call P2PConnection.send before remote SDP created");let o=[],a=y7();e.forEach(e=>{let t=r.peerConnection.addTransceiver(e._mediaStreamTrack,AJ({direction:"sendonly"},"video"===e.trackMediaType&&r.supportAV1RtpSpec&&a?{sendEncodings:[{scalabilityMode:a}]}:{}));o.push(t),e._updateRtpTransceiver(t)}),Sl()&&!0===TR("SIMULCAST")&&(yield fC(r.applySimulcastForFirefox(o,e)));let s=yield fC(r.peerConnection.createOffer()),c=r.remoteSDP.predictReceivingMids(e.length),d=r.mungSendOfferSDP(s.sdp,e,c),l=TO(d),h=c.map(e=>{let t=l.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw Error("Cannot extract ssrc from mediaDescription.");return Ih(t,TR("USE_PUB_RTX"))});try{n=yield h}catch(a){n=[],r.remoteSDP.receive(e,t,i,n);let o=r.remoteSDP.toString();throw yield fC(r.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield fC(r.peerConnection.setRemoteDescription({type:"answer",sdp:o})),yield fC(r.stopSending(c,!0)),a}r.remoteSDP.receive(e,t,i,n);let u=r.remoteSDP.toString(),p=r.logSDPExchange(d,"offer","local","send");return yield fC(r.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield fC(r.applySimulcastEncodings(o,e)),yield fC(r.applySendEncodings(o,e)),null==p||p(u),yield fC(r.peerConnection.setRemoteDescription({type:"answer",sdp:u})),o.map((e,t)=>{let i=c[t];return{localSSRC:h[t],id:i,transceiver:e}})}catch(e){throw e instanceof Sx?e:new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{n()}})()}async createDataChannels(e,t){try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.createDataChannels before remote SDP created");let i=this.dataStreamChannelMap.get(e);if(i&&"open"===i.readyState)TY.debug("[P2PConnection] Channels are already available and can be reused directly.");else{let t=this.currentDataChannelId<1023?this.currentDataChannelId++:this.recoveredDataChannelIds.shift();if("number"!=typeof t)throw Error("create DataChannel error, because cannot get dc id");
1(i=this.peerConnection.createDataChannel("datastream-channel",{id:t,negotiated:!0,ordered:!1,maxRetransmits:TR("DATASTREAM_MAX_RETRANSMITS")})).binaryType="arraybuffer",this.dataStreamChannelMap.set(e,i)}t.forEach(e=>{e._updateOriginDataChannel(i)});let{needExchangeSDP:r}=this.remoteSDP.sendDataChannel();if(r){let e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});let t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t),TY.debug("[P2PConnection] createDataChannels by exchanging SDP.")}else TY.debug("[P2PConnection] createDataChannels no need to exchange SDP.");return}catch(e){throw e instanceof Sx?e:new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.createDataChannels failed; ".concat(e.toString()))}}async stopDataChannels(e){try{let t=this.dataStreamChannelMap.get(e);return t&&(t.id&&this.recoveredDataChannelIds.push(t.id),t.close()),void this.dataStreamChannelMap.delete(e)}catch(e){throw e instanceof Sx?e:new Sx(SU.DATACHANNEL_FAILED,"P2PConnection.stopD
1ataChannels failed; ".concat(e.toString()))}}async stopSending(e,t){let i=t?void 0:await this.mutex.lock("From P2PConnection.stopSending");try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.stopSending before remote SDP created");let t=this.peerConnection.getTransceivers().filter(t=>-1!==e.indexOf(t.mid));if(t.length!==e.length)throw Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");t.map(e=>{var t;AG(this.id+e.mid,this),e.direction="inactive",null==(t=e.stop)||t.call(e)});let i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(i),this.remoteSDP.stopReceiving(e);let n=this.remoteSDP.toString();null==r||r(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}finally{i&&i()}}async receive(e,t,i,r){try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));let{mid:n,needExchangeSDP:o}=this.remoteSDP.send(e,t,i,r);o&&(await Iw(this.peerConnection,this.remoteSDP,this.extension),TY.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP.")));let a=this.peerConnection.getTransceivers().find(e=>e.mid===n);if(!a)throw Error("Cannot get transceiver after setLocalDescription.");return{track:a.receiver.track,id:n,transceiver:a}}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async batchReceive(e){try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");let{mids:t,needExchangeSDP:i}=this.remoteSDP.batchSend(e);return i&&(await Iw(this.peerConnection,this.remoteSDP,this.extension),TY.debug("[".concat(this.store.clientId,"] [P2PConnection] batchReceive by exchanging SDP."))),t.map(e=>{let t=this.peerConnection.getTransceivers().find(t=>t.mid===e);if(!t)throw Error("Cannot get transceiver after setLocalDescription.");return{track:t.receiver.track,id:e,transceiver:t}})}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");e.forEach(e=>{Array.from(this.preMediaMap.entries()).some(t=>{let[i,{mid:r,player:n}]=t;if(r===e)return this.preMediaMap.delete(i),n&&n.destroy(),!0})}),this.remoteSDP.stopSending(e);let t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});let r=await this.peerConnection.createAnswer();null==i||i(r.sdp||""),await this.peerConnection.setLocalDescription(r)}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.muteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.mute(e);let t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});let r=await this.peerConnection.createAnswer();null==i||i(r.sdp||""),await this.peerConnection.setLocalDescription(r)}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.muteRemote failed; ".concat(e.toString()))}}async unmuteRemote(e){try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.unmuteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.unmute(e);let t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});let r=await this.peerConnection.createAnswer();null==i||i(r.sdp||""),await this.peerConnection.setLocalDescription(r)}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteRemote failed; ".concat(e.toString()))}}async muteLocal(e){try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.muteLocal before remote SDP created.");let t=this.peerConnection.getTransceivers().filter(t=>
1t.mid&&-1!==e.indexOf(t.mid));if(t.length!==e.length)throw Error("Transceivers' length doesn't match mids' length.");t.map(e=>{e.direction="inactive"});let i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);let n=this.remoteSDP.toString();null==r||r(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");let t=this.peerConnection.getTransceivers().filter(t=>t.mid&&-1!==e.indexOf(t.mid));if(t.length!==e.length)throw Error("Transceivers' length doesn't match mids' length.");t.map(async(e,t)=>{e.direction="sendonly"});let i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec(e,this.remoteCodecs,this.store.codec);let n=this.remoteSDP.toString();null==r||r(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return fT(function*(){let i=yield fC(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw Error("Cannot restartICE before remoteSDP created.");let i=T1.supportPCSetConfiguration,r=TR("FORCE_TURN_TCP")||t.forceTurn;if(e===yd.RELAY&&!i)return;if(i&&!r){let i=e===yd.RELAY?"relay":"all",r=t.peerConnection.getConfiguration();r.iceTransportPolicy!==i&&(TY.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(r.iceTransportPolicy,"] to [").concat(i,"]")),r.iceTransportPolicy=i,t.peerConnection.setConfiguration(r))}t.remoteSDP.updateCandidates(e);let n=yield fC(t.peerConnection.createOffer({iceRestart:!0}));if(!n.sdp)throw Error("Cannot restartICE because restart offer SDP does not exist.");let o=Il(n.sdp),{remoteIceParameters:a}=yield o.iceParameters;t.remoteSDP.restartICE(a);let s=t.remoteSDP.toString(),c=t.logSDPExchange(n.sdp||"","offer","local","restartICE");t.store.descriptionStart(),yield fC(t.peerConnection.setLocalDescription(n)),null==c||c(s),yield fC(t.peerConnection.setRemoteDescription({type:"answer",sdp:s}))}catch(e){TY.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{i()}})()}async extendCandidate(){if(!this.remoteSDP||this.isFirstConnected)return;let e=await this.mutex.lock("From P2PConnection.extendCandidate");try{this.remoteSDP.updateCandidates(yd.TCP_RELAY),await Iw(this.peerConnection,this.remoteSDP,this.extension)}catch(e){TY.warning("[".concat(this.store.clientId,"] extend candidate failed, abort operation"),e)}finally{e()}}close(){var e;this.peerConnection.getTransceivers().forEach(e=>{AG(this.id+e.mid,this)}),this.preMediaMap.forEach(e=>{let{player:t}=e;t&&t.destroy()}),this.preMediaMap.clear(),this.peerConnection.close(),null==(e=this.onConnectionStateChange)||e.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear(),this.recoveredDataChannelIds=[],this.currentDataChannelId=1}getStats(){return AJ(AJ({},this.statsFilter.getStats()),{},{qualityLimitationReason:this.qualityLimitationReason})}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");let i=await this.peerConnection.createOffer(),r=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);let n=this.remoteSDP.toString(),o=this.logSDPExchange(r,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:r}),null==o||o(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){let i=this.peerConnection.getTransceivers().filter(t=>t.mid===e);1===i.length&&(this.isVP8Simulcast(t)?Sl()||await this.applySimulcastEncodings(i,[t]):await this.applySendEncodings(i,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){let i=this.peerConnection.getTransceivers().find(e=>e.mid===t);i&&await i.sender.replaceTrack(e._mediaStreamTrack)}async getSelectedCandidatePair(){let e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){let{local:t,remote:i}=e[0].transport.iceTransport.getSelectedCandidatePair();return{local:AJ(AJ({},g2),{},{candidateType:t.type,protocol:t.protocol,address:t.address,port:t.port}),remote:AJ(AJ({},g2),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null==(e=this.onICEConnectionStateChange)||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;"connected"===this.peerConnection.connectionState&&(this.isFirstConnected=!0),null==(e=this.onConnectionStateChange)||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidateerror=e=>{if(e&&(e.errorCode||e.errorText)){var t;let i="code: ".concat(e.errorCode,", message: ").concat(e.errorText),r=e.port?"local: ".concat(e.port):"",n=y8(e.url||"");TY.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICECandidateError(").concat(i,"), url: ").concat(n||"",", host_c
1andidate:").concat(r)),null==(t=this.onICECandidateError)||t.call(this,i)}},this.peerConnection.onicegatheringstatechange=e=>{e&&e.target&&"iceGatheringState"in e.target&&TY.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] RTCPeerConnection.onicegatheringstatechange(").concat(e.target.iceGatheringState,")"))},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,TY.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,TY.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))},TR("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){let i={iceServers:[]},r=t.cloudProxyServer||"disabled";return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&(S9(t.turnServer.servers)?i.iceServers=t.turnServer.servers:TR("NEW_TURN_MODE")&&i.iceServers&&"disabled"===r?(TR("USE_TURN_SERVER_OF_GATEWAY")?t.turnServer.serversFromGateway&&i.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.serversFromGateway)):i.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.servers)),TR("NEW_FORCE_TURN")&&(i.iceTransportPolicy="relay")):"off"!==t.turnServer.mode&&(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),TR("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),TR("FORCE_TURN_TCP")?i.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach(e=>{e.forceturn&&(i.iceTransportPolicy="relay")}))),TR("ENABLE_ENCODED_TRANSFORM")&&T1.supportWebRTCEncodedTransform&&(i.encodedInsertableStreams=!0),i}static turnServerConfigToIceServers(e){let t=[];return e.forEach(e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(yQ(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!TR("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))}),t}static newTurnServerConfigToIceServers(e){let t=[];return e.forEach(e=>{let i=TR("NEW_TURN_MODE");1===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}):2===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}):3===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(yQ(e.turnServerURL),":443?transport=tcp")}):4===i&&(t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(yQ(e.turnServerURL),":443?transport=tcp")}))}),t}tryBindTransportEvents(e){let t=e.transport;if(t){this.transportEventReceiver=e,t.onstatechange=()=>{var e;null!=t&&t.state&&(null==(e=this.onDTLSTransportStateChange)||e.call(this,t.state))},t.onerror=e=>{var t;null==(t=this.onDTLSTransportError)||t.call(this,"error"in e?e.error:e)};let i=t.iceTransport;i&&(i.onstatechange=()=>{var e;let i=null==t?void 0:t.iceTransport.state;i&&(null==(e=this.onICETransportStateChange)||e.call(this,i))},i.getSelectedCandidatePair&&(i.onselectedcandidatepairchange=()=>{if(i.getSelectedCandidatePair()){let{local:e,remote:t}
1=i.getSelectedCandidatePair()||{};if(e&&t){let i=e.address+":"+e.port,r=t.address+":"+t.port;TY.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(y8(i)),", remote ").concat(JSON.stringify(y8(r))))}}}))}}tryUnbindTransportEvents(){this.transportEventReceiver&&this.transportEventReceiver.transport&&(this.transportEventReceiver.transport.onstatechange=null,this.transportEventReceiver.transport.onerror=null,this.transportEventReceiver.transport.iceTransport&&(this.transportEventReceiver.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var i,r,n,o,a;if(t||(t=this.peerConnection.getSenders().find(t=>t.track===e._mediaStreamTrack)),!t)return TY.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return TY.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!T1.supportSetRtpSenderParameters)return TY.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");let s={},c={};switch(e._optimizationMode){case"motion":s.degradationPreference="maintain-framerate";break;case"detail":s.degradationPreference="maintain-resolution";break;case"balanced":s.degradationPreference="balanced"}let d=y9(this.peerConnection,e._mediaStreamTrack),l=CS(e);if(AF(e)&&d&&t&&l&&this.getLocalVideoStats&&o5(i=["vp8","vp9"]).call(i,this.store.codec)){let i=s.degradationPreference||(o5(n=e._hints).call(n,RE.CUSTOM_TRACK)?TR("CUSTOM_ADAPTATION_DEFAULT_MODE"):"maintain-framerate");Aj(this.id+d.mid,l,this,i,e=>{t&&this.updateAdaptation(t,e)},this.getLocalVideoStats.bind(this))}if(e._encoderConfig){let{bitrateMax:t,frameRate:i,scaleResolutionDownBy:r}=e._encoderConfig;t&&(c.maxBitrate=1e3*t),(o5(o=e._hints).call(o,RE.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(i&&(c.maxFramerate=y0(i)),r&&r>=1&&(c.scaleResolutionDownBy=r))}let{maxFramerate:h}=TR("ENCODER_CONFIG_LIMIT");if(h&&"number"==typeof h&&(c.maxFramerate=c.maxFramerate?Math.min(c.maxFramerate,h):h),TR("DSCP_TYPE")&&SN()){let e=TR("DSCP_TYPE");o5(a=["very-low","low","medium","high"]).call(a,e)&&(c.networkPriority=e)}let u=t.getParameters(),p=null==(r=u.encodings)?void 0:r[0];Sl()&&!p&&(s.encodings=[c]),p&&Object.assign(p,c),Object.assign(u,s),TY.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(u.encodings))),await t.setParameters(u),await ID(this.store.codec,t,TR("SVC_MODE"))}async updateAdaptation(e,t){var i,r;if(!e)return TY.debug("[updateAdaptation] no rtpSender found");if(!T1.supportSetRtpSenderParameters)return TY.debug("[updateAdaptation] Browser not support set rtp-sender parameters");let n={},{bitrateMax:o,frameRate:a,scaleResolutionDownBy:s}=t;o&&(n.maxBitrate=1e3*o),a&&(n.maxFramerate=y0(a)),s&&s>=1&&o5(i=["vp8","vp9"]).call(i,this.store.codec)&&(n.scaleResolutionDownBy=s);let c=e.getParameters(),d=null==(r=c.encodings)?void 0:r[0];d&&Object.assign(d,n),Object.assign(c,{});try{await e.setParameters(c),TY.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(c.encodings)))}catch(t){"transport"in e&&(!e.transport||"connected"!==e.transport.state)?TY.debug("[updateAdaptation] rtpSender transport not connected}"):"connected"!==this.peerConnectionState?TY.debug("[updateAdaptation] peerConnection not connected}"):TY.debug("[updateAdaptation] updateRtpSenderEncodings failed",t)}}async applySendEncodings(e,t){try{if(!T1.supportSetRtpSenderParameters||e.length!==t.length)return;for(let i=0;i<e.length;i++){let r=e[i],n=t[i];n instanceof CP&&!this.isVP8Simulcast(n)&&await this.updateRtpSenderEncodings(n,r.sender)}}catch(e){TY.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,i){if(TR("FORBID_MODIFY_LOCAL_OFFER_SDP"))return e;let r=TO(e);return t.forEach((e,t)=>{let n=i[t],o=r.mediaDescriptions.find(e=>e.attributes.mid===n);o&&(IE(o,e),IT(o,e,this.store.codec))}),Tw(r)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null==(t=this.onFirstAudioReceived)||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null==(t=this.onFirstVideoReceived)||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null==(t=this.onFirstAudioDecoded)||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var r;null==(r=this.onFirstVideoDecoded)||r.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null==(i=this.onSelectedLocalCandidateChanged)||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null==(i=this.onSelectedRemoteCandidateChanged)||i.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null==(t=this.onFirstVideoDecodedTimeout)||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let s=0;s<e.length;s++){var i,r,n,o,a;let c=e[s],d=t[s];if(d instanceof CP&&!o5(i=d._hints).call(i,RE.LOW_STREAM)&&null!=(r=d._encoderConfig)&&r.bitrateMax&&(null==(n=d._encoderConfig)?void 0:n.bitrateMax)>
1200&&null!=(o=d._scalabilityMode)&&o.numSpatialLayers&&(null==(a=d._scalabilityMode)?void 0:a.numSpatialLayers)>1&&"vp8"===this.store.codec){let e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];let i=c.sender.getParameters();await c.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!Sl()&&e.length===t.length)for(let i=0;i<e.length;i++){let r=t[i];if(r instanceof CP&&this.isVP8Simulcast(r)){let t=e[i],n={},o={high:1e3*(r._encoderConfig.bitrateMax-50),medium:5e4};n.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:o.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:o.medium,scaleResolutionDownBy:4}];let a=t.sender.getParameters();await t.sender.setParameters(Object.assign(a,n))}}}isVP8Simulcast(e){var t,i,r,n,o;return!!(e instanceof CP&&TR("SIMULCAST")&&"vp8"===this.store.codec&&!o5(t=e._hints).call(t,RE.LOW_STREAM)&&null!=(i=e._encoderConfig)&&i.bitrateMax&&(null==(r=e._encoderConfig)?void 0:r.bitrateMax)>200&&null!=(n=e._scalabilityMode)&&n.numSpatialLayers&&(null==(o=e._scalabilityMode)?void 0:o.numSpatialLayers)>1)}logSDPExchange(e,t,i,r){if(TR("SDP_LOGGING"))return TY.upload("[".concat(this.store.clientId,"] exchanging ").concat(i," ").concat(t," SDP during P2PConnection.").concat(r,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",r)}:void 0}async getRemoteSSRC(e){if(!this.remoteSDP)return;let t=this.remoteSDP.getSSRC(e);return t&&0!==t.length?t[0].ssrcId:void 0}setConfiguration(t){if(T1.supportPCSetConfiguration){let i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}t.isPreallocation&&(this.isPreallocation=!0)}constructor(t,i){super(t,i),mb(this,"id",gw(5,"connection-")),mb(this,"store",void 0),mb(this,"peerConnection",void 0),mb(this,"forceTurn",!1),mb(this,"remoteSDP",void 0),mb(this,"initialOffer",void 0),mb(this,"transportEventReceiver",void 0),mb(this,"statsFilter",void 0),mb(this,"extension",{useXR:TR("USE_XR")}),mb(this,"localCapabilities",void 0),mb(this,"remoteCodecs",void 0),mb(this,"localCandidateCount",0),mb(this,"allCandidatesReceived",!1),mb(this,"isPreallocation",!1),mb(this,"isPreRender",!1),mb(this,"preMediaMap",new Map),mb(this,"dataStreamChannelMap",new Map),mb(this,"establishPromise",void 0),mb(this,"recoveredDataChannelIds",[]),mb(this,"currentDataChannelId",1),mb(this,"supportAV1RtpSpec",!1),mb(this,"mutex",void 0),mb(this,"qualityLimitationReason",Te.NONE),mb(this,"isFirstConnected",!1),this.store=i,this.forceTurn=Aq(t),this.mutex=new gG("P2PConnection-mutex",i.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.isFirstConnected=!1,this.statsFilter=Tc(this.peerConnection,TR("STATS_UPDATE_INTERVAL"),void 0,Sl()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,t.isPreallocation&&(this.isPreallocation=!0),this.establishPromise=this.establish()}},vP(iW.prototype,"updateRemoteRTPCapabilities",[AZ],Object.getOwnPropertyDescriptor(iW.prototype,"updateRemoteRTPCapabilities"),iW.prototype),vP(iW.prototype,"connect",[AZ],Object.getOwnPropertyDescriptor(iW.prototype,"connect"),iW.prototype),vP(iW.prototype,"updateRemoteConnect",[AZ],Object.getOwnPropertyDescriptor(iW.prototype,"updateRemoteConnect"),iW.prototype),vP(iW.prototype,"createDataChannels",[AZ],Object.getOwnPropertyDescriptor(iW.prototype,"createDataChannels"),iW.prototype),vP(iW.prototype,"receive",[AZ],Object.getOwnPropertyDescriptor(iW.prototype,"receive"),iW.prototype),vP(iW.prototype,"batchReceive",[AZ],Object.getOwnPropertyDescriptor(iW.prototype,"batchReceive"),iW.prototype),vP(iW.prototype,"stopReceiving",[AZ],Object.getOwnPropertyDescriptor(iW.prototype,"stopReceiving"),iW.prototype),vP(iW.prototype,"muteRemote",[AZ],Object.getOwnPropertyDescriptor(iW.prototype,"muteRemote"),iW.prototype),vP(iW.prototype,"unmuteRemote",[AZ],Object.getOwnPropertyDescriptor(iW.prototype,"unmuteRemote"),iW.prototype),vP(iW.prototype,"muteLocal",[AZ],Object.getOwnPropertyDescriptor(iW.prototype,"muteLocal"),iW.prototype),vP(iW.prototype,"unmuteLocal",[AZ],Object.getOwnPropertyDescriptor(iW.prototype,"unmuteLocal"),iW.prototype),vP(iW.prototype,"close",[AZ],Object.getOwnPropertyDescriptor(iW.prototype,"close"),iW.prototype),vP(iW.prototype,"updateEncoderConfig",[AZ],Object.getOwnPropertyDescriptor(iW.prototype,"updateEncoderConfig"),iW.prototype),vP(iW.prototype,"updateSendParameters",[AZ],Object.getOwnPropertyDescriptor(iW.prototype,"updateSendParameters"),iW.prototype),vP(iW.prototype,"replaceTrack",[AZ],Object.getOwnPropertyDescriptor(iW.prototype,"replaceTrack"),iW.prototype),vP(iW.prototype,"updateAdaptation",[AZ],Object.getOwnPropertyDescriptor(iW.prototype,"updateAdaptation"),iW.prototype),vP(iW.prototype,"getRemoteSSRC",[AZ],Object.getOwnPropertyDescriptor(iW.prototype,"getRemoteSSRC"),iW.prototype),iW);function AZ(e,t,i){let r=e[t];if("function"!=typeof r)throw Error("Cannot use mutex on object property.");return i.value=async function(){let e=this.mutex,i=await e.lock("From P2PConnection.".concat(t));try{for(var n=arguments.length,o=Array(n),a=0;a<n;a++)o[a]=arguments[a];return await r.apply(this,o)}finally{i()}},i}function A$(e,t){let i=document.createElement("video"),r=document.createElement("canvas");i.setAttribute("style","display:none"),r.setAttribute("style","display:none"),i.setAttribute("muted",""),i.muted=!0,i.setAttribute("autoplay",""),i.autoplay=!0,i.setAttribute("playsinline",""),r.width=y0(t.width),r.height=y0(t.height);let n=y0(t.framerate||15);document.body.append(i),document.body.append(r);let o=e._mediaStreamTrack;
1i.srcObject=new MediaStream([o]),i.play().catch(gD);let a=r.getContext("2d");if(!a)throw new T0(SU.UNEXPECTED_ERROR,"can not get canvas context");let s=r.captureStream(T1.supportRequestFrame?0:n).getVideoTracks()[0];s.canvas||(s.canvas=r),r.startCapture=()=>{if(!i)return r.stopCapture&&r.stopCapture();if(i.paused&&i.play(),i.videoHeight>2&&i.videoWidth>2){let e=i.videoWidth,t=i.videoHeight/e,n=r.width*t;Math.abs(n-r.height)>=2&&(TY.debug("adjust low stream resolution","".concat(r.width,"x").concat(r.height," -> ").concat(r.width,"x").concat(n)),r.height=n)}a.drawImage(i,0,0,r.width,r.height),s.requestFrame&&s.requestFrame(),o!==e._mediaStreamTrack&&(o=e._mediaStreamTrack,i.srcObject=new MediaStream([o]))},r.stopCapture=RJ(()=>r.startCapture&&r.startCapture(),n);let c=s.stop;return s.stop=()=>{c.call(s),i&&(i.remove(),i.srcObject=null,i=null),r&&(r.width=0,r.remove(),r.stopCapture&&r.stopCapture(),r.startCapture=void 0,r.stopCapture=void 0,r=null),TY.debug("clean low stream renderer")},s}var A0=((e8=A0||{})[e8.Video_Send_Type=190]="Video_Send_Type",e8),A1=((e9=A1||{})[e9.Video_Send_Qp_Sum=2143]="Video_Send_Qp_Sum",e9[e9.Video_Send_Freeze=2082]="Video_Send_Freeze",e9[e9.Video_Recv_Qp_Sum=2144]="Video_Recv_Qp_Sum",e9[e9.Video_Recv_Freeze=2084]="Video_Recv_Freeze",e9[e9.Video_Render_Freeze_Time=2109]="Video_Render_Freeze_Time",e9[e9.Video_Render_Freeze_Time_Render=2147]="Video_Render_Freeze_Time_Render",e9[e9.Video_Render_Freeze_Time_Render2=2223]="Video_Render_Freeze_Time_Render2",e9[e9.Audio_Recv_Freeze=2083]="Audio_Recv_Freeze",e9),A2=((e7=A2||{})[e7.Video_Send_Retransmit=2062]="Video_Send_Retransmit",e7[e7.Video_Send_Target_Encoded=2064]="Video_Send_Target_Encoded",e7[e7.Video_Send_Actual_Encoded=2060]="Video_Send_Actual_Encoded",e7[e7.Video_Send_Transmit=2066]="Video_Send_Transmit",e7[e7.Video_Send_Bandwidth=2061]="Video_Send_Bandwidth",e7[e7.Video_Capture_Height=2033]="Video_Capture_Height",e7[e7.Video_Capture_Width=2035]="Video_Capture_Width",e7[e7.Video_Capture_Frame_Rate=2034]="Video_Capture_Frame_Rate",e7[e7.Video_Send_Low_Height=2073]="Video_Send_Low_Height",e7[e7.Video_Send_Low_Frame_Rate=2075]="Video_Send_Low_Frame_Rate",e7[e7.Video_Send_Low_Width=2077]="Video_Send_Low_Width",e7[e7.Video_Send_Low_Bitrate=2069]="Video_Send_Low_Bitrate",e7[e7.Video_Send_Low_Package_Lost=2070]="Video_Send_Low_Package_Lost",e7[e7.Video_Send_Low_Package_Rate=2071]="Video_Send_Low_Package_Rate",e7[e7.Video_Send_Frame_Rate=2002]="Video_Send_Frame_Rate",e7[e7.Video_Send_Width=2003]="Video_Send_Width",e7[e7.Video_Send_Height=2004]="Video_Send_Height",e7[e7.Video_Send_Disabled=2095]="Video_Send_Disabled",e7[e7.Video_Send_Adaptation=2032]="Video_Send_Adaptation",e7[e7.Video_Send_Player_Status=2128]="Video_Send_Player_Status",e7[e7.Video_Send_Nacks=2009]="Video_Send_Nacks",e7[e7.Video_Send_Plis=2010]="Video_Send_Plis",e7[e7.Video_Send_Firs=2011]="Video_Send_Firs",e7[e7.Video_Send_Avg_Encode=2007]="Video_Send_Avg_Encode",e7[e7.Video_Send_Huge_Frame_Sent=2174]="Video_Send_Huge_Frame_Sent",e7[e7.Video_Send_Bytes_Retransmit=2173]="Video_Send_Bytes_Retransmit",e7[e7.Video_Send_Packages_Retransmit=2172]="Video_Send_Packages_Retransmit",e7[e7.Video_Send_Key_Frames_Encoded=2207]="Video_Send_Key_Frames_Encoded",e7[e7.Video_Send_Bitrate=2012]="Video_Send_Bitrate",e7[e7.Video_Send_Package_Rate=2031]="Video_Send_Package_Rate",e7[e7.Video_Send_Package_Lost=2005]="Video_Send_Package_Lost",e7[e7.Audio_Capture_PCM_Level=2104]="Audio_Capture_PCM_Level",e7[e7.Audio_Send_Level=2038]="Audio_Send_Level",e7[e7.Audio_Send_Bitrate=2039]="Audio_Send_Bitrate",e7[e7.Audio_Send_Package_Rate=2040]="Audio_Send_Package_Rate",e7[e7.Audio_Send_AEC_Return_Loss=2041]="Audio_Send_AEC_Return_Loss",e7[e7.Audio_Send_AEC_Return_Loss_Enhancement=2042]="Audio_Send_AEC_Return_Loss_Enhancement",e7[e7.Audio_Send_Freeze=2081]="Audio_Send_Freeze",e7[e7.Audio_Send_Disabled=2096]="Audio_Send_Disabled",e7[e7.Audio_Send_Bytes_Retransmit=2179]="Audio_Send_Bytes_Retransmit",e7[e7.Audio_Send_Packages_Retransmit=2180]="Audio_Send_Packages_Retransmit",e7[e7.Video_Recv_Height=2019]="Video_Recv_Height",e7[e7.Video_Recv_Width=2018]="Video_Recv_Width",e7[e7.Video_Recv_Frame_Rate_Output=2155]="Video_Recv_Frame_Rate_Output",e7[e7.Video_Recv_Jitter_Buffer=2023]="Video_Recv_Jitter_Buffer",e7[e7.Video_Recv_Current_Delay=2024]="Video_Recv_Current_Delay",e7[e7.Video_Recv_Nacks=2026]="Video_Recv_Nacks",e7[e7.Video_Recv_Plis=2027]="Video_Recv_Plis",e7[e7.Video_Recv_Firs=2028]="Video_Recv_Firs",e7[e7.Video_Recv_Disabled=2101]="Video_Recv_Disabled",e7[e7.Video_Recv_Player_Status=2129]="Video_Recv_Player_Status",e7[e7.Video_Recv_I_Frame_Delay=2149]="Video_Recv_I_Frame_Delay",e7[e7.Video_Render_Frame_Rate_Render=2022]="Video_Render_Frame_Rate_Render",e7[e7.Video_Render_Freeze_Duration=2156]="Video_Render_Freeze_Duration",e7[e7.Audio_Render_Level=2043]="Audio_Render_Level",e7[e7.Audio_Render_Freeze_Time_80ms=2226]="Audio_Render_Freeze_Time_80ms",e7[e7.Audio_Render_Freeze_Time_200ms=2227]="Audio_Render_Freeze_Time_200ms",e7[e7.Audio_Render_Freeze_Samples_80ms=2228]="Audio_Render_Freeze_Samples_80ms",e7[e7.Audio_Render_Freeze_Samples_200ms=2229]="Audio_Render_Freeze_Samples_200ms",e7[e7.Audio_Recv_PCM_Level=2105]="Audio_Recv_PCM_Level",e7[e7.Audio_Recv_Disabled=2102]="Audio_Recv_Disabled",e7[e7.Audio_Recv_Jitter_Buffer=2054]="Audio_Recv_Jitter_Buffer",e7[e7.Audio_Recv_Current_Delay=2047]="Audio_Recv_Current_Delay",e7[e7.Audio_Recv_Player_Status=2130]="Audio_Recv_Player_Status",e7[e7.Audio_Recv_Bitrate=2044]="Audio_Recv_Bitrate",e7[e7.Audio_Recv_Concealed_Samples=2148]="Audio_Recv_Concealed_Samples",e7[e7.Audio_Recv_Total_Samples_Received=2224]="Audio_Recv_Total_Samples_Received",e7),A3=((te=A3||{})[te.Video_Render_Frame_Rate_Decode=2021]="Video_Render_Frame_Rate_Decode",te[te.Video_Recv_Frame_Rate=2020]="Video_Recv_Frame_Rate",te[te.Video_Recv_Frame_Dropped=2181]="Video_Recv_Frame_Dropped",te[te.Video_Recv_Bytes_Retransmit=2175]="Video_Recv_Bytes_Retransmit",te[te.Video_Recv_Packages_Retransmit=2176]="Video_Recv_Packages_Retransmit",te[te.Video_Recv_Packages_Discarded=2198]="Video_Recv_Packages_Discarded",te[te.Video_Recv_Avg_Decode=2200]="Video_Recv_Avg_Decode",te[te.Video_Recv_Avg_Processing_Delay=2202]="Video_Recv_Avg_Processing_Delay",te[te.Video_Recv_Avg_Assembly_Time=2203]="Video_Recv_Avg_Assembly_Time",te[te.Video_Recv_Avg_Inter_Frame_Delay=2204]="Video_Recv_Avg_Inter_Frame_Delay",te[te.Video_Recv_Key_Frames_Decoded=2206]="Video_Recv_Key_Frames_Decoded",te[te.Video_Recv_Package_Lost=2014]="Video_Recv_Package_Lost",te[te.Video_Recv_Bitrate=2029]="Video_Recv_Bitrate",te[te.Video_Recv_Package_Rate=2078]="Video_Recv_Package_Rate",te[te.Audio_Recv_Jitter=2055]="Audio_Recv_Jitter",te[te.Audio_Recv_Bytes_Retransmit=2178]="Audio_Recv_Bytes_Retransmit",te[te.Audio_Recv_Packages_Retransmit=2177]="Audio_Recv_Packages_Retransmit",te[te.Audio_Recv_Packages_Discarded=2199]="Audio_Recv_Packages_Discarded",te[te.Audio_Recv_Avg_Processing_Delay=2201]="Audio_Recv_Avg_Processing_Delay",te[te.Audio_Recv_Package_Rate=2046]="Audio_Recv_Package_Rate",te[te.Audio_Recv_Package_Lost=2045]="Audio_Recv_Package_Lost",te[te.Audio_Recv_AV_Sync_TIME=2237]="Audio_Recv_AV_Sync_TIME",te),A5=((tt=A5||{})[tt.RTT=2006]="RTT",tt[tt.CONN_TYPE=801]="CONN_TYPE",tt[tt.STATS_UPDATE_INTERVAL=2205]="STATS_UPDATE_INTERVAL",tt),A4=((ti=A4||{})[ti.RTC_PEER_CONNECTION_STATE=2219]="RTC_PEER_CONNECTION_STATE",ti[ti.PAGE_VISIBILITY=2233]="PAGE_VISIBILITY",ti),A6=((tr=A6||{})[tr.Transport_Send_Bitrate=2234]="Transport_Send_Bitrate",tr[tr.Transport_Recv_Bitrate=2235]="Transport_Recv_Bitrate",tr);function A8(e,t,i){null!=i&&Number.isFinite(i)&&(e[t]=Math.round(Math.max(0,i)))}function A9(e){let t={[A5.CONN_TYPE]:0,[A5.RTT]:e.rtt,[A5.STATS_UPDATE_INTERVAL]:e.updateInterval?Math.round(Math.max(0,e.updateInterval)):void 0};switch(e.selectedCandidatePair.localCandidate.candidateType){case"relay":{let i=e.selectedCandidatePair.localCandidate.relayProtocol;"udp"===i&&(t[A5.CONN_TYPE]=1),"tcp"===i&&(t[A5.CONN_TYPE]=3),"tls"===i&&(t[A5.CONN_TYPE]=4);break}case"srflx":t[A5.CONN_TYPE]=2;break;case"unknown":t[A5.CONN_TYPE]=5;break;default:t[A5.CONN_TYPE]=0}return t}function A7(e){let t=0;switch(e){case"none":t=0;break;case"cpu":t=1;break;case"bandwidth":t=2;break;case"other":t=3}return t}class be extends S0{uploadWRTCStats(e){let t,i;
1if(!this.requestStats||!this.requestUploadStats)return;let r=e%3==0,n=e%6==0;if(this.uploadTransportStarted&&(t=this.requestStats(),this.store.useP2P&&(i=this.requestStats(!0))),!t&&this.uploadOutboundStarted&&(t=this.requestStats()),!i&&this.uploadInboundStarted&&(i=this.requestStats(!0)),t||i){var o;let a={};if(this.uploadTransportStarted&&t){let e=this.getTransportStats(t,r?this.lastRefSendStats:void 0,i,r);e&&(a.misc=[e])}if(this.uploadOutboundStarted&&t){let i=this.getOutboundStats(t,n?this.lastNormalSendStats:void 0,r?this.lastRefSendStats:void 0,this.lastSendStats,e%60==0);i&&(a.outbound=[i])}if(this.uploadInboundStarted&&i){this.uploadCompensateStats(e);let t=this.getInboundStats(i,n?this.lastNormalRecvStats:void 0,r?this.lastRefRecvStats:void 0,this.lastRecvStats);t&&(a.inbound=t)}let s=null==(o=this.requestTransportStats)?void 0:o.call(this).connectState;if(s&&(Array.isArray(a.misc)?a.misc[0]&&a.misc[0].addition&&(a.misc[0].addition[A4.RTC_PEER_CONNECTION_STATE]=Ti[s]):a.misc=[{addition:{[A4.RTC_PEER_CONNECTION_STATE]:Ti[s]}}]),CF.needUploadStats.length>0||n){let e=CF.needUploadStats.shift()||+("visible"===CF.visibility);Array.isArray(a.misc)?a.misc[0]&&a.misc[0].addition&&(a.misc[0].addition[A4.PAGE_VISIBILITY]=e):a.misc=[{addition:{[A4.PAGE_VISIBILITY]:e}}]}this.needUploadStats.sendType&&(Array.isArray(a.outbound)&&a.outbound[0]&&a.outbound[0].high&&(a.outbound[0].high[A0.Video_Send_Type]=this.needUploadStats.sendType),this.needUploadStats.sendType=void 0),this.requestUploadStats(a)}this.lastRecvStats=i,this.lastSendStats=t,n&&(this.lastNormalRecvStats=i,this.lastNormalSendStats=t),r&&(this.lastRefRecvStats=i,this.lastRefSendStats=t)}startUploadWRTCStats(){if(this.uploadWRTCStatsTimer)return;this.uploadBaseStatsStarted=!0,CF.startCollectStats();let e=1;this.uploadWRTCStatsTimer=window.setInterval(()=>{if(!this.uploadTransportStarted&&!this.uploadInboundStarted&&!this.uploadOutboundStarted){if(this.uploadBaseStatsStarted){var t,i;let e=null==(t=this.requestTransportStats)?void 0:t.call(this);return void(e&&(null==(i=this.requestUploadStats)||i.call(this,{misc:[{addition:{[A4.RTC_PEER_CONNECTION_STATE]:Ti[e.connectState]}}]})))}return this.stopUploadWRTCStats()}this.uploadWRTCStats(e),61==++e&&(e=1)},1e3)}uploadCompensateStats(e){if(!this.requestStats||!this.requestUploadStats||!this.requestRemoteMedia)return;let t=e%3==0&&this.needUploadRenderFreezeTime;if(!this.uploadInboundStarted||!t)return;if(-1===this.lastUploadCompensateTime)return void(this.lastUploadCompensateTime=Date.now());let i=Math.max(-6e3,Date.now()-this.lastUploadCompensateTime-6e3);if(this.uploadCompensateDeltaTime+=i,this.lastUploadCompensateTime=Date.now(),this.uploadCompensateDeltaTime<6e3)return;let r=Math.min(Math.floor(this.uploadCompensateDeltaTime/6e3),10);this.uploadCompensateDeltaTime-=6e3*r;let n=this.requestStats(!0);Array(r).fill(0).forEach(()=>{if(!this.requestStats||!this.requestUploadStats||!this.requestRemoteMedia)return;let e={};if(this.uploadInboundStarted&&n){let t=this.requestRemoteMedia()||[],i=[];t.forEach(e=>{let[t,r]=e,o={peer:t.uid};if(t._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(t._videoSSRC)&&r.has(yc.VIDEO)&&t.videoTrack){let e=function(e,t,i){if(!t.videoRecv.find(t=>t.ssrc===e))return;let r={};if(i&&i._player){let e=i._player,{renderFreezeAccTime2:t,videoElementStatus:n}=e;if("visible"===CF.visibility&&n===RL.PLAYING&&T1.supportRequestVideoFrameCallback){let i=Math.min(6e3,t);e.renderFreezeAccTime2=Math.max(0,t-i),A8(r,A1.Video_Render_Freeze_Time_Render2,i),TR("USE_NEW_RENDER_FREEZE_TIME")&&A8(r,A1.Video_Render_Freeze_Time_Render,i)}}return r}(t._videoSSRC,n,t.videoTrack);e&&(o.video=e)}o.video&&i.push(o)}),i.length>0&&(e.inbound=i,this.requestUploadStats(e))}})}stopUploadWRTCStats(){window.clearInterval(this.uploadWRTCStatsTimer),this.uploadWRTCStatsTimer=void 0,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0),this.lastRefSendStats&&(this.lastRefSendStats.videoSend=[],this.lastRefSendStats.audioSen
1d=[],this.lastRefSendStats=void 0),this.lastRefRecvStats&&(this.lastRefRecvStats.videoRecv=[],this.lastRefRecvStats.audioRecv=[],this.lastRefRecvStats=void 0),this.lastNormalSendStats&&(this.lastNormalSendStats.videoSend=[],this.lastNormalSendStats.audioSend=[],this.lastNormalSendStats=void 0),this.lastNormalRecvStats&&(this.lastNormalRecvStats.videoRecv=[],this.lastNormalRecvStats.audioRecv=[],this.lastNormalRecvStats=void 0),this.lastExtendStats={},this.needUploadStats={},this.lastUploadCompensateTime=-1,this.uploadCompensateDeltaTime=0,this.needUploadRenderFreezeTime=!0}getTransportStats(e,t,i,r){if(!this.requestStats)return;if(!r)return null==e.rtt?void 0:{addition:{[A5.RTT]:e.rtt,[A5.CONN_TYPE]:void 0,[A5.STATS_UPDATE_INTERVAL]:e.updateInterval||void 0}};let n=A9(e);if(this.store.useP2P){if(i){let e=A9(i);n[A5.CONN_TYPE]&&e[A5.CONN_TYPE]&&(n[A5.CONN_TYPE]+=e[A5.CONN_TYPE]<<3)}n[A5.CONN_TYPE]?n[A5.CONN_TYPE]+=110:n[A5.CONN_TYPE]=110}else{n[A5.CONN_TYPE]?n[A5.CONN_TYPE]+=100:n[A5.CONN_TYPE]=100;let i=t?[Math.ceil(8*(e.transport.bytesSent-t.transport.bytesSent)/(e.timestamp-t.timestamp)),Math.ceil(8*(e.transport.bytesReceived-t.transport.bytesReceived)/(e.timestamp-t.timestamp))]:[0,0];n[A6.Transport_Send_Bitrate]=i[0],n[A6.Transport_Recv_Bitrate]=i[1]}return{addition:n}}getOutboundStats(e,t,i,r,n){let o,a,s;if(!this.requestUploadStats||!this.requestLocalMedia)return;let c=this.requestLocalMedia();if(c&&0!==c.length)return c.forEach(r=>{let[c,{track:d,ssrcs:l}]=r;switch(c){case yu.LocalVideoLowTrack:case yu.LocalVideoTrack:if(c===yu.LocalVideoTrack){var h;let r=function(e,t,i,r,n,o){let a=t.videoSend.find(t=>t.ssrc===e);if(!a)return;let s={},{sentFrame:c,inputFrame:d}=a;if(r&&(A8(s,A1.Video_Send_Qp_Sum,a.qpSumPerFrame),d&&c)){let e=d.frameRate,t=c.frameRate;s[A1.Video_Send_Freeze]=+(!(e<=5)&&(e<=10?t<3:e<=20?t<4:t<5))}if(n){switch(c&&(A8(s,A2.Video_Send_Height,c.height),A8(s,A2.Video_Send_Width,c.width),A8(s,A2.Video_Send_Frame_Rate,c.frameRate)),s[A2.Video_Send_Disabled]=i._originMediaStreamTrack&&!i._originMediaStreamTrack.enabled||i._mediaStreamTrack&&!i._mediaStreamTrack.enabled?1:0,a.adaptionChangeReason){case"none":s[A2.Video_Send_Adaptation]=0;break;case"cpu":s[A2.Video_Send_Adaptation]=1;break;case"bandwidth":s[A2.Video_Send_Adaptation]=2;break;case"other":s[A2.Video_Send_Adaptation]=3}let r=0;a.adaptionChangeReason&&(r+=A7(a.adaptionChangeReason)),t.qualityLimitationReason&&(r+=A7(t.qualityLimitationReason)<<3),s[A2.Video_Send_Adaptation]=r,s[A2.Video_Send_Player_Status]=RM[i._player?i._player.videoElementStatus:"uninit"],A8(s,A2.Video_Send_Nacks,a.nacksCount),A8(s,A2.Video_Send_Plis,a.plisCount),A8(s,A2.Video_Send_Firs,a.firsCount),A8(s,A2.Video_Send_Avg_Encode,a.avgEncodeMs),A8(s,A2.Video_Send_Huge_Frame_Sent,a.hugeFramesSent),A8(s,A2.Video_Send_Bytes_Retransmit,a.retransmittedBytesSent),A8(s,A2.Video_Send_Packages_Retransmit,a.retransmittedPacketsSent),A8(s,A2.Video_Send_Key_Frames_Encoded,a.keyFramesEncoded);let o=n.videoSend.find(t=>t.ssrc===e);if(o){let e=3e3;o.timestamp&&a.timestamp&&(e=a.timestamp-o.timestamp),null!=o.packets&&null!=a.packets&&A8(s,A2.Video_Send_Package_Rate,1e3*(a.packets-o.packets)/e),null!=a.packetsLost&&null!=o.packetsLost&&A8(s,A2.Video_Send_Package_Lost,a.packetsLost-o.packetsLost),null!=o.bytes&&null!=a.bytes&&A8(s,A2.Video_Send_Bitrate,8*(a.bytes-o.bytes)/e)}}return s}(l[0].ssrcId,e,d,t,i),o="CameraVideoTrack"===d.__className__?3:o5(h=d._hints).call(h,RE.SCREEN_TRACK)?7:10;(this.lastExtendStats.sendType!==o||n)&&(this.needUploadStats={sendType:o},this.lastExtendStats.sendType=o),a=Object.assign({},r,d&&function(e,t,i,r){let n=t.videoSend.find(t=>t.ssrc===e);if(!n)return null;let o={};if(r){let e=n.inputFrame,t=e&&e.height||i.videoHeight||0,r=e&&e.width||i.videoWidth||0,a=e&&e.frameRate||0;A8(o,A2.Video_Capture_Height,t),A8(o,A2.Video_Capture_Width,r),A8(o,A2.Video_Capture_Frame_Rate,a)}return o}(l[0].ssrcId,e,d,!!i),function(e,t){let i={};return t&&(A8(i,A2.Video_Send_Retransmit,e.bitrate.retransmit),A8(i,A2.Video_Send_Target_Encoded,e.bitrate.targetEncoded),A8(i,A2.Video_Send_Actual_Encoded,e.bitrate.actualEncoded),A8(i,A2.Video_Send_Transmit,e.bitrate.transmit),A8(i,A2.Video_Send_Bandwidth,e.sendBandwidth)),i}(e,!!i))}else s=function(e,t,i,r,n){let o=t.videoSend.find(t=>t.ssrc===e);if(!o)return;let a={};if(r){let t=o.sentFrame;t&&(A8(a,A2.Video_Send_Low_Height,t.height),A8(a,A2.Video_Send_Low_Width,t.width),A8(a,A2.Video_Send_Low_Frame_Rate,t.frameRate));let i=r.videoSend.find(t=>t.ssrc===e);if(i){let e=6e3;i.timestamp&&o.timestamp&&(e=o.timestamp-i.timestamp),null!=i.packets&&null!=o.packets&&A8(
1a,A2.Video_Send_Low_Package_Rate,1e3*(o.packets-i.packets)/e),null!=o.packetsLost&&null!=i.packetsLost&&A8(a,A2.Video_Send_Low_Package_Lost,o.packetsLost-i.packetsLost),null!=i.bytes&&null!=o.bytes&&A8(a,A2.Video_Send_Low_Bitrate,8*(o.bytes-i.bytes)/e)}}return a}(l[0].ssrcId,e,0,i);break;case yu.LocalAudioTrack:o=d&&function(e,t,i,r,n,o){let a=t.audioSend.find(t=>t.ssrc===e);if(!a)return;let s={};if(n){s[A2.Audio_Send_Disabled]=i._originMediaStreamTrack&&!i._originMediaStreamTrack.enabled||i._mediaStreamTrack&&!i._mediaStreamTrack.enabled?1:0;let t=100*i._source.getAccurateVolumeLevel(),r=a.inputLevel;if(null!=r){let e=Math.ceil(50*Math.log10(100*r+1));A8(s,A2.Audio_Send_Level,e)}A8(s,A2.Audio_Capture_PCM_Level,t),A8(s,A2.Audio_Send_AEC_Return_Loss,a.aecReturnLoss),A8(s,A2.Audio_Send_AEC_Return_Loss_Enhancement,a.aecReturnLossEnhancement),A8(s,A2.Audio_Send_Bytes_Retransmit,a.retransmittedBytesSent),A8(s,A2.Audio_Send_Packages_Retransmit,a.retransmittedPacketsSent),s[A2.Audio_Send_Freeze]=0;let o=n.audioSend.find(t=>t.ssrc===e);if(o){let e=6e3;o.timestamp&&a.timestamp&&(e=a.timestamp-o.timestamp),null!=o.bytes&&null!=a.bytes&&A8(s,A2.Audio_Send_Bitrate,8*(a.bytes-o.bytes)/e),null!=o.packets&&null!=a.packets&&A8(s,A2.Audio_Send_Package_Rate,1e3*(a.packets-o.packets)/e)}}return s}(l[0].ssrcId,e,d,0,i)}}),{high:a,low:s,audio:o}}getInboundStats(e,t,i,r){if(!this.requestRemoteMedia)return;let n=this.requestRemoteMedia()||[],o=[];return n.forEach(n=>{let a,[s,c]=n,d={peer:s.uid};if(c.has(yc.VIDEO)&&s.videoTrack){let n=s._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(s._videoSSRC)||!1,o=s.videoTrack?function(e,t,i,r,n,o,a,s){let c=t.videoRecv.find(t=>t.ssrc===e);if(!c)return;let d={},{receivedFrame:l,outputFrame:h,decodeFrameRate:u}=c;A8(d,A3.Video_Render_Frame_Rate_Decode,u),c.framesRateFirefox&&A8(d,A3.Video_Recv_Frame_Rate,c.framesRateFirefox),l&&A8(d,A3.Video_Recv_Frame_Rate,l.frameRate),A8(d,A3.Video_Recv_Frame_Dropped,c.framesDroppedCount),A8(d,A3.Video_Recv_Bytes_Retransmit,c.retransmittedBytesReceived),A8(d,A3.Video_Recv_Packages_Retransmit,c.retransmittedPacketsReceived),A8(d,A3.Video_Recv_Packages_Discarded,c.packetsDiscarded),A8(d,A3.Video_Recv_Avg_Decode,c.avgDecodeMs),A8(d,A3.Video_Recv_Avg_Processing_Delay,c.avgProcessingDelayMs),A8(d,A3.Video_Recv_Avg_Assembly_Time,c.avgFramesAssembledFromMultiplePacketsMs),A8(d,A3.Video_Recv_Avg_Inter_Frame_Delay,c.avgInterFrameDelayMs),A8(d,A3.Video_Recv_Key_Frames_Decoded,c.keyFramesDecoded);let p=s&&s.videoRecv.find(t=>t.ssrc===e);if(p){let e=t.timestamp-s.timestamp||1e3;null!=c.packetsLost&&null!=p.packetsLost&&A8(d,A3.Video_Recv_Package_Lost,c.packetsLost-p.packetsLost),null!=p.bytes&&null!=c.bytes&&A8(d,A3.Video_Recv_Bitrate,8*(c.bytes-p.bytes)/e),null!=p.packets&&null!=c.packets&&A8(d,A3.Video_Recv_Package_Rate,1e3*(c.packets-p.packets)/e)}let _=o&&o.videoRecv.find(t=>t.ssrc===e);if(_&&(A8(d,A1.Video_Recv_Qp_Sum,c.qpSumPerFrame),d[A1.Video_Recv_Freeze]=r&&Av.isRemoteVideoFreeze(i,c,_)?1:0),a){var E;let t=a.videoRecv.find(t=>t.ssrc===e);l?(A8(d,A2.Video_Recv_Height,l.height),A8(d,A2.Video_Recv_Width,l.width)):i&&(A8(d,A2.Video_Recv_Height,i._videoHeight||0),A8(d,A2.Video_Recv_Width,i._videoWidth||0)),h&&A8(d,A2.Video_Recv_Frame_Rate_Output,h.frameRate);let r=null==(E=i._player)?void 0:E.rendFrameRate.toFixed(0);if(r&&A8(d,A2.Video_Render_Frame_Rate_Render,+r),A8(d,A2.Video_Recv_Jitter_Buffer,c.jitterBufferMs),A8(d,A2.Video_Recv_Current_Delay,c.currentDelayMs),A8(d,A2.Video_Recv_Firs,c.firsCount),A8(d,A2.Video_Recv_Nacks,c.nacksCount),A8(d,A2.Video_Recv_Plis,c.plisCount),i){d[A2.Video_Recv_Disabled]=i._originMediaStreamTrack.enabled&&i._mediaStreamTrack.enabled?0:1;let e=i._player;if(e){let{freezeTimeCounterList:i,renderFreezeAccTime:r,renderFreezeAccTime2:o,videoElementStatus:a}=e;if(i&&i.length>0&&A8(d,A1.Video_Render_Freeze_Time,i.splice(0,1)[0]),n&&"visible"===CF.visibility&&a===RL.PLAYING&&T1.supportRequestVideoFrameCallback){let t=Math.min(6e3,o);e.renderFreezeAccTime2=Math.max(0,o-t),A8(d,A1.Video_Render_Freeze_Time_Render2,t);let i=Math.min(6e3,r);e.renderFreezeAccTime=Math.max(0,r-i),A8(d,A1.Video_Render_Freeze_Time_Render,TR("USE_NEW_RENDER_FREEZE_TIME")?t:i)}if("number"==typeof c.totalFreezesDuration){let e=t&&t.totalFreezesDuration?c.totalFreezesDuration-t.totalFreezesDuration:c.totalFreezesDuration;A8(d,A2.Video_Render_Freeze_Duration,1e3*e)}}}if(d[A2.Video_Recv_Player_Status]=RM[i._player?i._player.videoElementStatus:"uninit"],t&&void 0!==c.totalInterFrameDelay&&void 0!==c.totalSquaredInterFrameDelay&&void 0!==t.totalInterFrameDelay&&void 0!==t.totalSquaredInterFrameDelay){let e=c.totalInterFrameDelay-t.totalInterFrameDelay,i=c.totalSquaredInterFrameDelay-t.totalSquaredInterFrameDelay,r=c.framesDecodeCount-t.framesDecodeCount,n=e/r*1e3,o=Math.round(1e3*Math.sqrt((i-Math.pow(e,2)/r)/r));!isNaN(o)&&n+o>Math.max(3*n,n+150)&&(d[A2.Video_Recv_I_Frame_Delay]=o)}}return d}(s._videoSSRC,e,s.videoTrack,!0===n,this.needUploadRenderFreezeTime,t,i,r):void 0;if(o&&(d.video=o),s.videoTrack){let t=e.videoRecv.find(e=>e.ssrc===s._videoSSRC);t&&t.estimatedPlayoutTimestamp&&(a=t.estimatedPlayoutTimestamp)}}if(c.has(yc.AUDIO)&&s.audioTrack){let n=s.audioTrack?function(e,t,i,r,n,o){let a=t.audioRecv.find(t=>t.ssrc===e);if(!a)return;let s={};A8(s,A3.Audio_Recv_Jitter,a.jitterMs),A8(s,A3.Audio_Recv_Bytes_Retransmit,a.retransmittedBytesReceived),A8(s,A3.Audio_Recv_Packages_Retransmit,a.retransmittedPacketsReceived),A8(s,A3.Audio_Recv_Packages_Discarded,a.packetsDiscarded),A8(s,A3.Audio_Recv_Avg_Processing_Delay,a.avgProcessingDelayMs);let c=o&&o.audioRecv.find(t=>t.ssrc===e);if(c&&(null!=a.packets&&null!=c.packets&&A8(s,A3.Audio_Recv_Package_Rate,1e3*(a.packets-c.packets)/1e3),null!=a.packetsLost&&null!=c.packetsLost&&A8(s,A3.Audio_Recv_Package_Lost,a.packetsLost-c.packetsLost)),r){let{receivedFrames:e,droppedFrames:t}=a;null!=e&&null!=t&&(s[A1.Audio_Recv_Freeze]=+(0===e||100*t/e>20))}if(n){let t=100*i._source.getAccurateVolumeLevel(),r=a.outputLevel;if(null!=r){let e=Math.ceil(50*Math.log10(100*r+1));A8(s,A2.Audio_Render_Level,e)}A8(s,A2.Audio_Recv_PCM_Level,t),i&&(s[A2.Audio_Recv_Disabled]=i._originMediaStreamTrack.enabled&&i._mediaStreamTrack.enabled?0:1),A8(s,A2.Audio_Recv_Jitter_Buffer,a.jitterBufferMs),A8(s,A2.Audio_Recv_Current_Delay,a.jitterBufferMs),s[A2.Audio_Recv_Player_Status]=RM[Ca.getPlayerState(i.getTrackId())];let o=n.audioRecv.find(t=>t.ssrc===e);if(o){null!=o.bytes&&null!=a.bytes&&A8(s,A2.Audio_Recv_Bitrate,8*(a.bytes-o.bytes)/3e3);
1let e=a.concealedSamples-o.concealedSamples;e>0&&A8(s,A2.Audio_Recv_Concealed_Samples,e);let t=a.totalSamplesReceived-o.totalSamplesReceived;t>0&&A8(s,A2.Audio_Recv_Total_Samples_Received,t);let i=a.freezeSamples80-o.freezeSamples80;i>0&&A8(s,A2.Audio_Render_Freeze_Samples_80ms,i);let r=a.freezeSamples200-o.freezeSamples200;r>0&&A8(s,A2.Audio_Render_Freeze_Samples_200ms,r);let n=a.freezeMs80-o.freezeMs80;A8(s,A2.Audio_Render_Freeze_Time_80ms,n<0?0:n);let c=a.freezeMs200-o.freezeMs200;A8(s,A2.Audio_Render_Freeze_Time_200ms,c<0?0:c)}}return s}(s._audioSSRC,e,s.audioTrack,t,i,r):void 0;if(n&&(d.audio=n),s.audioTrack&&a){let t=e.audioRecv.find(e=>e.ssrc===s._audioSSRC);if(t&&t.estimatedPlayoutTimestamp){let e=t.estimatedPlayoutTimestamp-a;d.audio?d.audio[A3.Audio_Recv_AV_Sync_TIME]=e:d.audio={[A3.Audio_Recv_AV_Sync_TIME]:e}}}}(d.video||d.audio)&&o.push(d)}),this.needUploadRenderFreezeTime=!this.needUploadRenderFreezeTime,o}startUploadTransportStats(){this.uploadTransportStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats()}stopUploadTransportStats(){this.uploadTransportStarted=!1}startUploadOutboundStats(){this.uploadOutboundStarted||(this.uploadOutboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=window.setInterval(()=>{if(!this.requestAllTracks||!this.requestUpload)return;let e=(this.requestAllTracks()||[]).find(e=>e instanceof Cv);if(e&&e._external.getDenoiserStats){let t=e._external.getDenoiserStats();t&&this.requestUpload(vj.DENOISER_STATS,t)}},2e3),this.uploadExtStatsTimer&&window.clearInterval(this.uploadExtStatsTimer),this.uploadExtStatsTimer=window.setInterval(()=>{this.requestAllTracks&&this.requestUpload&&this.requestAllTracks().forEach(e=>
1{e.getProcessorStats().forEach(e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)})})},2e3))}stopUploadOutboundStats(){this.uploadOutboundStarted&&(this.uploadOutboundStarted=!1,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.lastRefSendStats&&(this.lastRefSendStats.videoSend=[],this.lastRefSendStats.audioSend=[],this.lastRefSendStats=void 0),this.lastNormalSendStats&&(this.lastNormalSendStats.videoSend=[],this.lastNormalSendStats.audioSend=[],this.lastNormalSendStats=void 0),this.lastExtendStats={},this.needUploadStats={},this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=void 0,this.uploadExtStatsTimer&&window.clearInterval(this.uploadExtStatsTimer),this.uploadExtStatsTimer=void 0)}startUploadInboundStats(){this.uploadInboundStarted||(this.uploadInboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadInboundExtStatsTimer&&window.clearInterval(this.uploadInboundExtStatsTimer),this.uploadInboundExtStatsTimer=window.setInterval(()=>{this.requestUpload&&this.requestRemoteMedia&&(this.requestRemoteMedia()||[]).forEach(e=>{let[t,i]=e;i.has(yc.VIDEO)&&t.videoTrack&&t.videoTrack.getProcessorStats().forEac
1h(e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}),i.has(yc.AUDIO)&&t.audioTrack&&t.audioTrack.getProcessorStats().forEach(e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)})})},2e3))}stopUploadInboundStats(){this.uploadInboundStarted&&(this.uploadInboundStarted=!1,this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0),this.lastRefRecvStats&&(this.lastRefRecvStats.videoRecv=[],this.lastRefRecvStats.audioRecv=[],this.lastRefRecvStats=void 0),this.lastNormalRecvStats&&(this.lastNormalRecvStats.videoRecv=[],this.lastNormalRecvStats.audioRecv=[],this.lastNormalRecvStats=void 0),this.lastUploadCompensateTime=-1,this.uploadCompensateDeltaTime=0,this.needUploadRenderFreezeTime=!0,this.uploadInboundExtStatsTimer&&window.clearInterval(this.uploadInboundExtStatsTimer),this.uploadInboundExtStatsTimer=void 0)}startUploadExtensionUsageStats(){if(this.uploadExtensionUsageStarted)return;this.uploadExtensionUsageStarted=!0,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer);let e=new Map;this.uploadExtUsageStatsTimer=window.setInterval(async()=>{let t=Date.now(),i={connectionInterval:TR("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3,details:[],lts:t},r=[];for(let e of this.requestAllTracks&&this.requestAllTracks()||[])!e.muted&&e.enabled&&(r=r.concat(await e.getProcessorUsage()));for(let[e,t]of this.requestRemoteMedia&&this.requestRemoteMedia()||[])t.has(yc.VIDEO)&&e.videoTrack&&(r=r.concat(await e.videoTrack.getProcessorUsage())),t.has(yc.AUDIO)&&e.audioTrack&&(r=r.concat(await e.audioTrack.getProcessorUsage()));if(0===r.length)return;i.details=function(e,t){let i={};for(let{id:a,value:s,level:c,direction:d}of e){var r,n,o;let e=null!=(r=t.get(a))?r:0,l=2===s?e+TR("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3:e;t.set(a,l),i[a]?(2===s&&(i[a].value=s),c>i[a].level&&(i[a].level=c),"remote"===d&&(i[a].remoteUidCount+=1),i[a].totalTs=null!=(n=t.get(a))?n:0):i[a]={value:s,level:c,remoteUidCount:+("local"!==d),totalTs:null!=(o=t.get(a))?o:0}}return Object.keys(i).map(e=>{let{level:t,value:r,totalTs:n}=i[e];return{id:e,level:t,value:r,totalTs:n}})}(r,e);let n=Date.now(),o=n>t?n:t+1;this.requestUpload&&this.requestUpload(vj.EXTENSION_USAGE_STATS,{usageStats:i,sendTs:o})},TR("EXTENSION_USAGE_UPLOAD_INTERVAL"))}stopUploadExtensionUsageStats(){this.uploadExtensionUsageStarted&&(this.uploadExtensionUsageStarted=!1,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer),this.uploadExtUsageStatsTimer=void 0)}stopUploadBaseStats(){this.uploadBaseStatsStarted=!1,CF.stopCollectStats()}constructor(e){super(),mb(this,"store",void 0),mb(this,"uploadWRTCStatsTimer",void 0),mb(this,"uploadOutboundDenoiserStatsTimer",void 0),mb(this,"uploadExtStatsTimer",void 0),mb(this,"uploadExtUsageStatsTimer",void 0),mb(this,"uploadInboundExtStatsTimer",void 0),mb(this,"requestStats",void 0),mb(this,"requestTransportStats",void 0),mb(this,"requestLocalMedia",void 0),mb(this,"requestRemoteMedia",void 0),mb(this,"requestAllTracks",void 0),mb(this,"requestVideoIsReady",void 0),mb(this,"requestUploadStats",void 0),mb(this,"requestUpload",void 0),mb(this,"uploadOutboundStarted",!1),mb(this,"uploadInboundStarted",!1),mb(this,"uploadTransportStarted",!1),mb(this,"uploadBaseStatsStarted",!1),mb(this,"uploadExtensionUsageStarted",!1),mb(this,"lastRecvStats",void 0),mb(this,"lastSendStats",void 0),mb(this,"lastRefRecvStats",void 0),mb(this,"lastRefSendStats",void 0),mb(this,"lastNormalRecvStats",void 0),mb(this,"lastNormalSendStats",void 0),mb(this,"lastExtendStats",{}),mb(this,"needUploadStats",{}),mb(this,"needUploadRenderFreezeTime",!0),mb(this,"lastUploadCompensateTime",-1),mb(this,"uploadCompensateDeltaTime",0),this.store=e}}let bt=TR("ICE_RESTART_INTERVAL"),bi=new Map,br=new Map,bn=[yd.UDP_TCP_RELAY,yd.TCP_RELAY,yd.RELAY],bo=TR("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&T1.supportPCSetConfiguration;function ba(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=bi.get(e.id);i&&(window.clearTimeout(i),bi.delete(e.id));let r=br.get(e.id);t&&r&&r.index===bn.length-1&&(TY.debug("[".concat(e.id,"] reset ICE restart policy")),br.delete(e.id))}function bs(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function bc(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
1t%2?bs(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):bs(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}function bd(e){var t,i,r,n=2;for("undefined"!=typeof Symbol&&(i=fy,r=Symbol.iterator);n--;){if(i&&null!=(t=e[i]))return t.call(e);if(r&&null!=(t=e[r]))return new bl(t.call(e));i="@@asyncIterator",r="@@iterator"}throw TypeError("Object is not async iterable")}function bl(e){function t(e){if(Object(e)!==e)return dQ.reject(TypeError(e+" is not an object."));var t=e.done;return dQ.resolve(e.value).then(function(e){return{value:e,done:t}})}return(bl=function(e){this.s=e,this.n=e.next}).prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var i=this.s.return;return void 0===i?dQ.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?dQ.reject(e):t(i.apply(this.s,arguments))}},new bl(e)}let bh=(vP((iH=class extends S0{get state(){return this._state}set state(e){let t=this._state;this._state=e,this.emit(y_.StateChange,t,this._state)}async startP2PConnection(e,t){var i;this.state=yp.New,this._forceTurn=Aq(e),TY.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] forceTurn: ").concat(this._forceTurn));let r=this.shouldForwardP2PCreation&&"closed"===(null==(i=this.connection)?void 0:i.peerConnectionState);if((!this.shouldForwardP2PCreation||r||t)&&((r||t)&&this.connection&&(TY.warning("[".concat(this.store.clientId,"] P2PChannel.startP2PConnection ForwardP2P closed.")),this.resetConnection(this.connection)),this.connection=AY(this.store,e),this.emit(y_.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection)),!this.connection)throw new Sx(SU.UNEXPECTED_ERROR,"Cannot P2PChannel.startConnection before P2PConnection initialization .");return this._pcStatsUploadType=TR("NEW_ICE_RESTART")?yl.FIRST_CONNECTION:yl.OLD_FIRST_CONNECTION,this._isTryConnecting=!0,this._isStartRestartIce=!1,this._iceError=null,this.connection.setConfiguration(e),this.connection.establishPromise}async connect(e){if(!this.connection)throw new Sx(SU.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");if(!this.isPreallocation()||this.state!==yp.Connected){this.store.peerConnectionStart();let t=await this.connection.connect(e);return this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=yp.Connected,t}if(this.connection instanceof AQ&&this.connection.checkDtlsParameters(e.dtlsParameters.fingerprints))return TY.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] dtls parameters mismatch, try next.")),T$.reportApiInvoke(this.store.sessionId,{name:S3.MISMATCH_DTLS_PARAMETERS,options:[e.dtlsParameters.fingerprints],tag:S5.TRACER}).onSuccess(),void setTimeout(()=>{this.emit(y_.RequestReconnect)});await this.connection.updateRemoteConnect(e)}updateRemoteRTPCapabilities(e){let t=Array.from(this.localTrackMap.entries()).filter(e=>{var t;let[i]=e;return o5(t=[yu.LocalVideoLowTrack,yu.LocalVideoTrack]).call(t,i)}),i=t.map(e=>{let[,{id:t}]=e;return t}),r=t.map(e=>{let[t]=e;return t});if(this.connection instanceof AQ||this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name){if(T$.updateRemoteRTPCapabilities(this.store.sessionId,{trackTypes:JSON.stringify(r),localCodecs:JSON.stringify(this.connection.localCodecs),remoteCodecs:JSON.stringify(e)}),!o5(e).call(e,this.store.codec)){let t=["vp9","vp8","h264"].find(t=>o5(e).call(e,t));t&&(this.store.codec=t,TY.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId," updateRemoteRTPCapabilities] default co
1dec is not available, hence the fallback to ").concat(t,".")))}this.connection.updateRemoteRTPCapabilities(i,e)}}async getEstablishParams(){var e;return this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name&&"closed"!==this.connection.peerConnectionState||this.connection instanceof AQ&&"closed"!==this.connection.peerConnectionState&&o5(e=[yp.New,yp.Connected]).call(e,this.state)?this.connection.establishPromise:void 0}async publishDataChannel(e){if(!this.connection||this.state!==yp.Connected){if(this.state===yp.Disconnected)throw new Sx(SU.UNEXPECTED_ERROR,"PeerConnection already disconnected.");return e.forEach(e=>{var t;o5(t=this.pendingLocalDataChannels).call(t,e)||this.pendingLocalDataChannels.push(e)}),[]}let t=this.filterTobePublishedDataChannels(e);return 0===t.length?[]:(t.forEach(e=>{let t=Date.now();this.store.publish(e.id.toString(),"datachannel",t)}),await this.connection.createDataChannels(this.store.uid,t),t.forEach(e=>{this.localDataChannels.push(e);let t=Date.now();this.store.publish(e.id+"","datachannel",void 0,t)}),e.map(e=>({streamId:e.id,ordered:e.ordered,maxRetransmits:e.maxRetransmits,metadata:e.metadata,channelId:e._originDataChannelId})))}publish(e,t,i){var r=this;return fT(function*(){let n=yield fC(r.mutex.lock("From P2PChannel.publish"));try{var o;let n=r.connection&&o5(o=["disconnected","failed"]).call(o,r.connection.peerConnectionState);if(!r.connection||r.state!==yp.Connected||n){if(r.state===yp.Disconnected)throw new Sx(SU.UNEXPECTED_ERROR,"PeerConnection already disconnected.");r.throwIfTrackTypeNotMatch(e);let t=e.filter(e=>-1===r.pendingLocalTracks.indexOf(e));return r.pendingLocalTracks=r.pendingLocalTracks.concat(t),void(n&&(r._isWaitPcToRePub=!0))}r.store.pubId=r.store.pubId+1,AT.markPublishStart(r.store.clientId,r.store.pubId);let a=r.filterTobePublishedTracks(e,t,i);if(0===a.length)return void(yield fC(r.tryToUnmuteAudio(e)));yield*fv(bd(r.doPublish(r.connection,a)))}finally{n()}})()}doPublish(e,t){var i=this;return fT(function*(){let r;t.forEach(e=>{let{track:t,type:r}=e,n=Date.now();i.store.publish(t.getTrackId(),r===yu.LocalAudioTrack?"audio":"video",n)}),i.bindLocalTrackEvents(t);let n=t.map(e=>{let{track:t}=e;return t}),o=yield fC(e.send(n,i.store.codec,i.store.audioCodec)),a=(yield fC(o.next())).value,s=i.createGatewayPublishMessage(t,a);try{r=yield s}catch(e){throw o.throw(e),(null==e?void 0:e.code)===SU.WS_ABORT&&t.forEach(e=>{let{track:t}=e;-1===i.pendingLocalTracks.indexOf(t)&&i.pendingLocalTracks.push(t)}),i.unbindLocalTrackEvents(t),e}let c=i.mapPubResToRemoteConfig(s,r,n),d=(yield fC(o.next(c))).value;if(i.state===yp.Disconnected)throw new Sx(SU.UNEXPECTED_ERROR,"PeerConnection already disconnected.");TR("ENABLE_VIDEO_SEI");let l=TR("ENABLE_ENCODED_TRANSFORM"),h=TR("ENABLE_AUDIO_METADATA");n.forEach(async e=>{let t=e.getRTCRtpTransceiver();if(!t||!l)return;let{interceptLocalVideoFrame:i,interceptLocalAudioFrame:r}=IB();e.trackMediaType===yc.VIDEO?await i(t.sender,e):e.trackMediaType===yc.AU
1DIO&&await r(t.sender,{metadata:h?()=>{let t=e.metadata.shift();return t&&t.value}:void 0})}),t.forEach(e=>{let{type:t}=e;i.statsCollector.addLocalStats(t)}),i.assignLocalTracks(t,d),i.statsUploader.startUploadOutboundStats(),t.forEach(e=>{let{track:t,type:r}=e,n=Date.now();i.store.publish(t.getTrackId(),r===yu.LocalAudioTrack?"audio":"video",void 0,n)})})()}async updateVideoStreamParameter(e,t){let i=this.localTrackMap.get(t);if(!i||!this.connection)return;if(!(i.track instanceof CP))return TY.warn("[updateVideoStreamParameter]: track is not an instance of LocalVideoTrack");let{track:r}=i,n=function(e,t){let i={};return e.height&&e.width&&(i.scaleResolutionDownBy=y4(e,t)),i.maxFramerate=e.framerate?y0(e.framerate):void 0,i.maxBitrate=e.bitrate?1e3*e.bitrate:void 0,i}(e,r);if(r._encoderConfig||(r._encoderConfig={}),t!==yu.LocalVideoLowTrack||!TR("DISABLE_DUAL_STREAM_USE_ENCODING")&&T1.supportDualStreamEncoding)null!=n.scaleResolutionDownBy&&(r._encoderConfig.scaleResolutionDownBy=n.scaleResolutionDownBy);else{let t=r._originMediaStreamTrack;if(!t.canvas)return TY.warn("[".concat(r.getTrackId(),"] no canvas on track"));let i=t.canvas;e.width&&(i.width=y0(e.width)),e.height&&(i.height=y0(e.height)),e.framerate&&(i.stopCapture&&i.stopCapture(),i.stopCapture=RJ(()=>{!i.startCapture&&i.stopCapture&&i.stopCapture(),i.startCapture&&i.startCapture()},y0(e.framerate)))}null!=n.maxBitrate&&(r._encoderConfig.bitrateMax=n.maxBitrate/1e3),null!=n.maxFramerate&&(r._encoderConfig.frameRate&&"object"==typeof r._encoderConfig.frameRate?r._encoderConfig.frameRate.max=n.maxFramerate:r._encoderConfig.frameRate={max:n.maxFramerate}),TY.debug("[".concat(r.getTrackId(),"] LowStreamEncoderConfig: , ").concat(JSON.stringify(r._encoderConfig))),await this.connection.updateRtpSenderEncodings(r)}publishLowStream(e){var t=this;return fT(function*(){if(!t.connection||t.state!==yp.Connected)return;let i=yield fC(t.mutex.lock("Locking from P2PChannel.publishLowStream"));try{let i=t.localTrackMap.get(yu.LocalVideoTrack);if(!i)throw new Sx(SU.UNEXPECTED_ERROR,"Could not find high stream");if(t.localTrackMap.has(yu.LocalVideoLowTrack))throw new Sx(SU.UNEXPECTED_ERROR,"[".concat(t.store.clientId,"] Can't publish low stream when stream already publish"));let n=[{track:t.getLowVideoTrack(i.track,e),type:yu.LocalVideoLowTrack}];if(yield*fv(bd(t.doPublish(t.connection,n))),i.track.muted||!i.track.enabled){var r;let e=null==(r=t.localTrackMap.get(yu.LocalVideoLowTrack))?void 0:r.id;void 0!==e&&(yield fC(t.connection.muteLocal([e])))}}finally{i()}})()}async republish(){this.pendingLocalTracks.length>0&&(TY.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await gs(this,y_.RequestRePublish,this.pendingLocalTracks),this.emit(y_.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[]),this.pendingLocalDataChannels.length>0&&(TY.debug("Emit P2PChannelEvents.RequestRePublishDataChannel to republish datachannels."),await gs(this,y_.RequestRePublishDataChannel,this.pendingLocalDataChannels),this.pendingLocalDataChannels=[]),this._isWaitPcToRePub=!1}async reSubscribe(e){for(let e=this.pendingRemoteTracks.length-1;e>=0;e--){let{user:t,kind:i}=this.pendingRemoteTracks[e];(i!==yc.AUDIO||t._audio_added_&&t._audioSSRC)&&(i!==yc.VIDEO||t._video_added_&&t._videoSSRC)||this.pendingRemoteTracks.splice(e,1)}if(e)await gs(this,y_.RequestReSubscribe,this.pendingRemoteTracks);else for(let{user:e,kind:t}of this.pendingRemoteTracks)await this.subscribe(e,t,t===yc.VIDEO?e._videoSSRC:e._audioSSRC);this.pendingRemoteTracks.forEach(e=>{let{user:t}=e;this.emit(y_.MediaReconnectEnd,t.uid)}),this.pendingRemoteTracks=[]}async unpublish(e){if(!this.connection||this.state!==yp.Connected)return void e.forEach(e=>{let t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1)});let t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;let i=t.find(e=>"videoLowTrack"===e[0]);return i&&i[1].track.close(),this.doUnpublish(this.connection,t)}async unpublishDataChannel(e){if(!this.connection||this.state!==yp.Connected)return void e.forEach(e
1=>{let t=this.pendingLocalDataChannels.indexOf(e);-1!==t&&this.pendingLocalDataChannels.splice(t,1)});let t=this.filterTobeUnpublishedDataChannels(e);return 0!==t.length?(t.forEach(e=>{let t=this.localDataChannels.indexOf(e);-1!==t&&this.localDataChannels.splice(t,1)}),0===this.localDataChannels.length&&await this.connection.stopDataChannels(this.store.uid),t.map(e=>e.id)):void 0}async unpublishLowStream(){if(!this.connection||this.state!==yp.Connected)return;let e=this.localTrackMap.get(yu.LocalVideoLowTrack);if(!e)return;e.track.close();let t=[[yu.LocalVideoLowTrack,e]];return this.doUnpublish(this.connection,t)}async doUnpublish(e,t){let i=this.createGatewayUnpublishMessage(t);return await e.stopSending(t.map(e=>{let[,{id:t}]=e;return t})),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map(e=>{let[t,{track:i}]=e;return{type:t,track:i}})),t.forEach(e=>{let[t]=e;this.statsCollector.removeLocalStats(t)}),0===this.localTrackMap.size&&this.statsUploader.stopUploadOutboundStats(),i}async subscribeDataChannel(e,t){if(!this.connection||this.state!==yp.Connected)throw new Sx(SU.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");let i=t.filter(t=>{var i;return!(null!=(i=this.remoteDataChannelMap.get(e))&&i.get(t.id))});if(0!==i.length)return await this.connection.createDataChannels(e.uid,i),i.forEac
1h(t=>{var i;this.remoteDataChannelMap.has(e)?null==(i=this.remoteDataChannelMap.get(e))||i.set(t.id,t):this.remoteDataChannelMap.set(e,new Map([[t.id,t]]));let r=this.pendingRemoteDataChannels.findIndex(i=>{let{user:r,id:n}=i;return r.uid===e.uid&&n===t.id});-1!==r&&this.pendingRemoteDataChannels.splice(r,1)}),i.map(e=>e.id)}async subscribe(e,t,i,r,n){var o;let a,s,c,d;if(!this.connection||this.state!==yp.Connected)throw new Sx(SU.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");if(null!=(o=this.remoteUserMap.get(e))&&o.has(t))return;let l=this.connection.getPreMedia(i);if(l)TY.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] preSSRCMap has ssrcId: ").concat(i,", no need to send sub to gateway.")),c=l.transceiver,a=l.track,s=l.mid,d=l.player,l.firstVideoRender&&this.store.firstVideoFrameDecoded(e.uid,{firstPreRender:l.firstVideoRender});else if(n){let i=n.find(e=>{let{stream_type:i}=e;return i===t});if(!i)throw new Sx(SU.UNEXPECTED_ERROR,"Cannot subscribe to remote ".concat(t," for user: ").concat(e.uid," because subscribe answer from gateway does not contain stream_type: ").concat(t,"."));
1let r=await this.connection.receive(t,i.ssrcs,String(e._uintid),i.attributes);(this.connection instanceof AQ||"name"in this.connection&&"DataChannelConnection"===this.connection.name)&&(c=r.transceiver),a=r.track,s=r.id}else{let n=await this.connection.receive(t,[{ssrcId:i,rtx:r}],String(e._uintid),void 0);(this.connection instanceof AQ||"name"in this.connection&&"DataChannelConnection"===this.connection.name)&&(c=n.transceiver),a=n.track,s=n.id}if(t===yc.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(a):(e._audioTrack=new CV(a,e.uid,e._uintid,this.store),TY.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),c&&e._audioTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(a):(e._videoTrack=new Cx(a,e.uid,e._uintid,this.store,d),TY.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId())),e._videoTrack.once(RR.PLAY_START,()=>{this.store.firstVideoFrameDecoded(e.uid,{playStart:Date.now()})}),e._videoTrack.once(RR.PLAY_END,()=>{this.store.firstVideoFrameDecoded(e.uid,{playEnd:Date.now()}),this.reportVideoFirstFrameRender(e)}),d?e._videoTrack.once(RR.FIRST_FRAME_RENDER,()=>{this.store.firstVideoFrameDecoded(e.uid,{firstRender:Date.now()}),this.reportVideoFirstFrameRender(e)}):e._videoTrack.once(RR.FIRST_FRAME_DECODED,()=>{this.store.firstVideoFrameDecoded(e.uid,{firstRender:Date.now()}),this.reportVideoFirstFrameRender(e)})),c&&e._videoTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._videoTrack)),c&&TR("ENABLE_ENCODED_TRANSFORM")){let{interceptRemoteVideoFrame:i,interceptRemoteAudioFrame:r}=IB();t==yc.VIDEO?await i(c.receiver,{onSei:TR("ENABLE_VIDEO_SEI")&&(t=>{var i;return null==(i=e._videoTrack)?void 0:i._onSei(t)}),onFirstFrame:e=>{var t;let i=Array.from(TL(t=this.remoteUserMap).call(t)).find(t=>t._videoSSRC===e.ssrc);i&&this.store.firstVideoFrameDecoded(i.uid,{firstReceivedEncodedFrame:Date.now(),frameType:e.type,rtpTimestamp:e.rtpTimestamp,framePayloadType:e.payloadType,frameDataLength:e.length,mimeType:e.mimeType})}}):t==yc.AUDIO&&await r(c.receiver,{enableTopn:!!TR("ENABLE_AUDIO_TOPN"),enableMetadata:!!TR("ENABLE_AUDIO_METADATA"),enablePts:!!TR("ENABLE_AUDIO_PTS"),onMetadata:e=>{this.safeEmit(y_.AudioMetadata,e)},onPts:e=>{this.safeEmit(y_.AudioPts,e)}})}let h=this.remoteUserMap.get(e);h?h.set(t,s):this.remoteUserMap.set(e,new Map([[t,s]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats();let u=this.pendingRemoteTracks.findIndex(i=>{let{user:r,kind:n}=i;return r.uid===e.uid&&t===n});-1!==u&&(this.pendingRemoteTracks.splice(u,1),this.emit(y_.MediaReconnectEnd,e.uid))}async massSubscribe(e){return this.massSubscribeNoLock(e)}async massSubscribeNoLock(e){if(!this.connection||this.state!==yp.Connected)throw new Sx(SU.INVALID_OPERATION,"Cannot subscribeAll remote users when peerConnection disconnected.");e=e.filter(e=>{var t;let{user:i,mediaType:r}=e;return!(null!=(t=this.remoteUserMap.get(i))&&t.has(r))});let t=[],i=new Map;e.forEach(e=>{if(!this.connection)return;let r=this.connection.getPreMedia(e.ssrcId);if(r){let{track:t,mid:n,transceiver:o,player:a}=r;i.set(e.ssrcId,{track:t,id:n,transceiver:o,player:a})}else t.push(e)});let r=await this.connection.batchReceive(t.map(e=>{let{user:t,mediaType:i,ssrcId:r,rtxSsrcId:n}=e;return{kind:i,ssrcMsg:[{ssrcId:r,rtx:n}],mslabel:String(t._uintid)}}));for(let{user:n,mediaType:o,ssrcId:a}of(t.forEach((e,t)=>{i.set(e.ssrcId,r[t])}),e)){let e=i.get(a);if(!e)return void TY.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] cannot find ").concat(n.uid," subscribe data,").concat(o,", ").concat(a));let{track:t,id:r,transceiver:s,player:c}=e;if(s&&TR("ENABLE_ENCODED_TRANSFORM")){let{interceptRemoteVideoFrame:e,interceptRemoteAudioFrame:t}=IB();o==yc.VIDEO?await e(s.receiver,{onSei:TR("ENABLE_VIDEO_SEI")&&(e=>{var t;return null==(t=n._videoTrack)?void 0:t._onSei(e)}),onFirstFrame:e=>{var t;let i=Array.from(TL(t=this.remoteUserMap).call(t)).find(t=>t._videoSSRC===e.ssrc);i&&this.store.firstVideoFrameDecoded(i.uid,{firstReceivedEncodedFrame:Date.now(),frameType:e.type,rtpTimestamp:e.rtpTimestamp,framePayloadType:e.payloadType,frameDataLength:e.length,mimeType:e.mimeType})}}
1):o==yc.AUDIO&&await t(s.receiver,{enableTopn:!!TR("ENABLE_AUDIO_TOPN"),enableMetadata:!!TR("ENABLE_AUDIO_METADATA"),enablePts:!!TR("ENABLE_AUDIO_PTS"),onMetadata:e=>{this.safeEmit(y_.AudioMetadata,e)},onPts:e=>{this.safeEmit(y_.AudioPts,e)}})}if(o===yc.AUDIO?(n._audioTrack?n._audioTrack._updateOriginMediaStreamTrack(t):(n._audioTrack=new CV(t,n.uid,n._uintid,this.store),TY.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(n._audioTrack.getTrackId()))),s&&n._audioTrack._updateRtpTransceiver(s),this.bindRemoteTrackEvents(n,n._audioTrack)):(n._videoTrack?n._videoTrack._updateOriginMediaStreamTrack(t):(n._videoTrack=new Cx(t,n.uid,n._uintid,this.store,c),TY.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(n._videoTrack.getTrackId()))),s&&n._videoTrack._updateRtpTransceiver(s),this.bindRemoteTrackEvents(n,n._videoTrack)),TR("ENABLE_VIDEO_SEI")&&s){let{interceptRemoteVideoFrame:e,interceptRemoteAudioFrame:t}=IB();o==yc.VIDEO?await e(s.receiver,{onSei:e=>{var t;null==(t=n._videoTrack)||t._onSei(e)},onFirstFrame:e=>{var t;let i=Array.from(TL(t=this.remoteUserMap).call(t)).find(t=>t._videoSSRC===e.ssrc);i&&this.store.firstVideoFrameDecoded(i.uid,{firstReceivedEncodedFrame:Date.now(),frameType:e.type,rtpTimestamp:e.rtpTimestamp,framePayloadType:e.payloadType,frameDataLength:e.length,mimeType:e.mimeType})}}):o==yc.AUDIO&&await t(s.receiver)}let d=this.remoteUserMap.get(n);d?d.set(o,r):this.remoteUserMap.set(n,new Map([[o,r]])),this.statsCollector.addRemoteStats(n.uid),this.statsUploader.startUploadInboundStats();let l=this.pendingRemoteTracks.findIndex(e=>{let{user:t,kind:i}=e;return t.uid===n.uid&&o===i});-1!==l&&(this.pendingRemoteTracks.splice(l,1),this.emit(y_.MediaReconnectEnd,n.uid))}}async unsubscribe(e,t,i){let r=this.pendingRemoteTracks.filter(i=>{let{user:r,kind:n}=i;return void 0!==t?r.uid===e.uid&&t===n:r.uid===e.uid});if(r.forEach(e=>{let t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)}),this.connection&&this.state===yp.Connected||i||r.forEach(t=>{var i,r;let{kind:n}=t;n===yc.AUDIO?(null==(i=e._audioTrack)||i._destroy(),e._audioTrack=void 0):n===yc.VIDEO&&(null==(r=e._videoTrack)||r._destroy(),e._videoTrack=void 0)}),!this.connection||this.state!==yp.Connected)return;let n=this.filterTobeUnSubscribedTracks(e,t);if(0===n.length)return;await this.connection.stopReceiving(n.map(e=>{let[,{id:t}]=e;return t}));let o=this.createUnsubscribeMessage(n);return this.withdrawRemoteTracks(n),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),n.forEac
1h(e=>{var t,r,n;let[o,{kind:a}]=e;a===yc.VIDEO&&o._videoSSRC&&(null==(t=this.connection)||t.setStatsRemoteVideoIsReady(o._videoSSRC,!1)),a===yc.VIDEO?(this.unbindRemoteTrackEvents(o._videoTrack),i||(null==(r=o._videoTrack)||r._destroy(),o._videoTrack=void 0)):a===yc.AUDIO&&(this.unbindRemoteTrackEvents(o._audioTrack),i||(null==(n=o._audioTrack)||n._destroy(),o._audioTrack=void 0))}),o}async unsubscribeDataChannel(e,t){if(t.forEach(e=>{let t=this.pendingRemoteDataChannels.findIndex(t=>t.id===e.id);-1!==t&&this.pendingRemoteDataChannels.splice(t,1)}),!this.connection)return;let i=this.filterTobeUnSubscribedDataChannels(e,t);if(0===i.length)return;t.forEach(e=>{e._close()});let r=this.remoteDataChannelMap.get(e);return i.forEach(e=>{r&&r.delete(e.id)}),r&&0===r.size&&(this.remoteDataChannelMap.delete(e),await this.connection.stopDataChannels(e.uid)),i.map(e=>e.id)}async massUnsubscribe(e){return this.massUnsubscribeNoLock(e)}async massUnsubscribeNoLock(e){let t=[];for(let{user:i,mediaType:r}of e){let e=this.pendingRemoteTracks.filter(e=>{let{user:t,kind:n}=e;return void 0!==r?t.uid===i.uid&&r===n:t.uid===i.uid});e.forEach(e=>{let t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)}),t=t.concat(e)}if(!this.connection||this.state!==yp.Connected)return void t.forEach(e=>{var t,i;let{user:r,kind:n}=e;n===yc.AUDIO?(null==(t=r._audioTrack)||t._destroy(),r._audioTrack=void 0):n===yc.VIDEO&&(null==(i=r._videoTrack)||i._destroy(),r._videoTrack=void 0)});let i=as(e).call(e,(e,t)=>{let{user:i,mediaType:r}=t,n=this.filterTobeUnSubscribedTracks(i,r);return e.concat(n)},[]);if(0===i.length)return;await this.connection.stopReceiving(i.map(e=>{let[,{id:t}]=e;return t}));let r=this.createUnsubscribeAllMessage(i);return this.withdrawRemoteTracks(i),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),i.forEach(e=>{var t,i,r;let[n,{kind:o}]=e;o===yc.VIDEO&&n._videoSSRC&&(null==(t=this.connection)||t.setStatsRemoteVideoIsReady(n._videoSSRC,!1)),o===yc.VIDEO?(this.unbindRemoteTrackEvents(n._videoTrack),null==(i=n._videoTrack)||i._destroy(),n._videoTrack=void 0):o===yc.AUDIO&&(this.unbindRemoteTrackEvents(n._audioTrack),null==(r=n._audioTrack)||r._destroy(),n._audioTrack=void 0)}),r}isPreSubScribe(e){return!!this.connection&&this.state===yp.Connected&&!!this.connection.getPreMedia(e)}async muteRemote(e,t){if(!this.connection)return;let i=this.remoteUserMap.get(e);if(!i)return void TY.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid,"."));if(!i.get(t))return void TY.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));let r=t===yc.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==r&&this.connection.setStatsRemoteVideoIsReady(r,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.connection)return;let i=this.remoteUserMap.get(e);if(!i)return void TY.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid,"."));i.get(t)||TY.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."))}addAudioMetadata(e){let t=this.localTrackMap.get(yu.LocalAudioTrack),i=t&&t.track;i&&i.metadata.push(e)}getAllTracks(e){let t=this.localTrackMap.get(yu.LocalAudioTrack);if((null==t?void 0:t.track)instanceof CI){let i=t.track;return Array.from(this.localTrackMap.entries()).filter(e=>{let[t]=e;return t!==yu.LocalAudioTrack}).filter(t=>{let[i]=t;return!(e&&i===yu.LocalVideoLowTrack)}).map(e=>{let[,{track:t}]=e;return t}).concat(i.trackList)}return Array.from(this.localTrackMap.entries()).filter(t=>{let[i]=t;return!(e&&i===yu.LocalVideoLowTrack)}).map(e=>{let[,{track:t}]=e;return t})}getAllDataChannels(){return this.localDataChannels}reportPublishEvent(e,t,i,r,n){if(e){let i=this.localTrackMap.get(yu.LocalAudioTrack),o=r?this.localTrackMap.get(yu.LocalVideoLowTrack):this.localTrackMap.get(yu.LocalVideoTrack);T$.publish(this.store.sessionId,{eventElapse:AT.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==i?void 0:i.track.getTrackLabel(),videoName:null==o?void 0:o.track.getTrackLabel(),screenshare:-1!==(null==o?void 0:o.track._hints.indexOf(RE.SCREEN_TRACK)),audio:!!i,video:!!o,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:n})}else{var o;i||(i=[]);let a=i.find(e=>e instanceof CC),s=r?null==(o=this.localTrackMap.get(yu.LocalVideoTrack))?void 0:o.track:i.find(e=>e instanceof CP);T$.publish(this.store.sessionId,{eventElapse:AT.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==a?void 0:a.getTrackLabel(),videoName:null==s?void 0:s.getTrackLabel(),screenshare:-1!==(null==s?void 0:s._hints.indexOf(RE.SCREEN_TRACK)),audio:!!a,video:!!s,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:n})}}reportSubscribeEvent(e,t,i,r){let n=r===yc.VIDEO?i._videoSSRC:i._audioSSRC;n&&T$.subscribe(this.store.sessionId,{succ:e,ec:t,video:r===yc.VIDEO,audio:r===yc.AU
1DIO,peerid:i.uid,subscribeRequestid:n,p2pid:this.store.p2pId,eventElapse:AT.measureFromSubscribeStart(this.store.clientId,n),preSsrc:this.isPreSubScribe(n)})}reset(){TY.debug("[".concat(this.store.clientId,"] P2PChannel.reset")),this.mutex=new gG("P2PChannel-mutex",this.store.clientId),this.connection&&(this.resetConnection(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=AY(this.store),this.emit(y_.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection)),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.statsUploader.stopUploadBaseStats(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();let e=this.localTrackMap.get(yu.LocalAudioTrack);if((null==e?void 0:e.track)instanceof CI){if(e.track.trackList.length>0){let t=e.track;e.track.trackList.forEach(e=>{t.removeAudioTrack(e)})}e.track.close()}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.iceFailedCount=0,this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.localDataChannels=[],this.remoteDataChannelMap.clear(),this.pendingLocalDataChannels=[],this.pendingRemoteDataChannels=[],this.state=yp.Disconnected}getStats(){var e;return null==(e=this.connection)?void 0:e.getStats()}getRemoteVideoIsReady(e){var t;return(null==(t=this.connection)?void 0:t.getRemoteVideoIsReady(e))||!1}getLocalAudioVolume(){let e=this.localTrackMap.get(yu.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){let e=this.localTrackMap.get(yu.LocalVideoTrack);if(e)return{width:e.track.videoWidth||0,height:e.track.videoHeight||0}}getEncoderConfig(e){let t=this.localTrackMap.get(e);return t&&t.track instanceof CP||t&&t.track instanceof CC?t.track._encoderConfig:void 0}getLocalMedia(e){return this.localTrackMap.get(e)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;let i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;let i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}getRemoteMedia(e){var t;let i=Array.from(TL(t=this.remoteUserMap).call(t)).find(t=>t.uid===e);return i?{audioTrack:i.audioTrack,audioSSRC:i._audioSSRC,videoTrack:i.videoTrack,videoSSRC:i._videoSSRC}:{}}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map(e=>{let[t]=e;return{uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0}}),t=this.localTrackMap.get(yu.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=ll(e).call(e,(e,t)=>e.level-t.level)}async disconnectForReconnect(){this.connection&&(TY.debug("[".concat(this.store.clientId,"] P2PChannel.disconnectForReconnect closing P2PConnection")),this.state=yp.Reconnecting,TR("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach(e=>{var t;let[i]=e;i._videoTrack&&i._videoTrack._player&&(null==(t=i._videoTrack._player.getVideoElement())||t.pause(),i._videoTrack._player.isKeepLastFrame=!0,i._videoTrack._originMediaStreamTrack.stop())}),this.resetConnection(this.connection),this.connection=void 0,this.shouldForwardP2PCreation&&(this.connection=AY(this.store),this.emit(y_.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection)),0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach(e=>{var t;let[i,{track:r}]=e;switch(i){case yu.LocalVideoTrack:o5(t=r._hints).call(t,RE.LOW_STREAM)?r.close():this.pendingLocalTracks.push(r);break;case yu.LocalAudioTrack:r instanceof CI?this.pendingLocalTracks=this.pendingLocalTracks.concat(r.trackList):this.pendingLocalTracks.push(r);case yu.LocalVideoLowTrack:}}),this.emit(y_.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEac
1h(e=>{let[t,i]=e;Array.from(TL(i).call(i)).forEach(e=>{this.setPendingRemoteMedia(t,e)}),this.emit(y_.MediaReconnectStart,t.uid)}),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),0!==this.localDataChannels.length&&(this.localDataChannels.forEach(e=>{this.pendingLocalDataChannels.push(e)}),this.localDataChannels.length=0),0!==this.remoteDataChannelMap.size&&(Array.from(this.remoteDataChannelMap.entries()).forEach(e=>{let[t,i]=e;Array.from(TL(i).call(i)).forEach(e=>{this.setPendingRemoteDataChannel(t,e)})}),this.remoteDataChannelMap.clear()),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),TY.debug("[".concat(this.store.clientId,"] P2PChannel disconnected, waiting to reconnect.")))}hasPendingRemoteDataChannel(e,t){for(let i of this.pendingRemoteDataChannels){let{user:r,id:n}=i;if((e instanceof AA?e.uid:e)===r.uid&&n===t)return!0}return!1}setPendingRemoteDataChannel(e,t){this.hasPendingRemoteDataChannel(e,t)||this.pendingRemoteDataChannels.push({user:e,id:t})}hasPendingRemoteMedia(e,t){for(let i of this.pendingRemoteTracks){let{user:r,kind:n}=i;if((e instanceof AA?e.uid:e)===r.uid&&t===n)return!0}return!1}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t})}restartICE(e){var t=this;return fT(function*(){let i;if(!t.connection||t.state!==yp.Connected)return;let r=yield fC(t.mutex.lock("From P2PChannel.restartICE"));try{i=yield fC(t.connection.restartICE(e));let r=yield fC(i.next());if(r.done)return;let n=r.value,o=yield n;switch(Az(t.connection)&&t.reportPCStats(Date.now(),!1,t._pcStatsUploadType),e){case yd.UDP_TCP_RELAY:t._pcStatsUploadType=yl.UDP_TCP_RESTART;break;case yd.TCP_RELAY:t._pcStatsUploadType=yl.TCP_RESTART;break;case yd.RELAY:t._pcStatsUploadType=yl.RELAY_RESTART;break;default:t._pcStatsUploadType=yl.OLD_RESTART}t._isTryConnecting=!0,i.next(o)}catch(e){var n;null==(n=i)||n.throw(e)}finally{r()}})()}getUplinkNetworkQuality(){if(!this.connection)return 0;let e=this.connection.getStats(),t=this.localTrackMap.get(yu.LocalVideoTrack),i=this.localTrackMap.get(yu.LocalAudioTrack),r=e.videoSend.find(e=>e.ssrc===(null==t?void 0:t.ssrcs[0].ssrcId)),n=e.audioSend.find(e=>e.ssrc===(null==i?void 0:i.ssrcs[0].ssrcId));if(!r||!n)return 1;let o=gd(this,y_.NeedSignalRTT),a=r?r.rttMs:void 0,s=n?n.rttMs:void 0,c=a&&s?(a+s)/2:a||s,d=100*e.sendPacketLossRate*.7/50+.3*((c&&o?(c+o)/2:c||o)||0)/1500,l=d<.17?1:d<.36?2:d<.59?3:d<.1?4:5,h=null==t?void 0:t.track;if(h&&h._encoderConfig&&-1===h._hints.indexOf(RE.SCREEN_TRACK)){let t=h._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){let e=(1e3*t-i)/(1e3*t);return vh[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][l]}}return l}getDownlinkNetworkQuality(){if(!this.connection)return 0;let e=this.connection.getStats(),t=0;return Array.from(this.remoteUserMap.entries()).forEach(i=>{let[r]=i,n=r._audioSSRC,o=r._videoSSRC,a=e.audioRecv.find(e=>e.ssrc===n),s=e.videoRecv.find(e=>e.ssrc===o);if(!a&&!s)return void(t+=1);let c=gd(this,y_.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,h=a?a.jitterMs:void 0,u=e.recvPacketLossRate,p=.7*u*100/50+.3*l/1500;h&&(p=.6*u*100/50+.2*l/1500+.2*h/400),t+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5}),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t}async muteLocalTrack(e){return new dQ((t,i)=>{this.handleMuteLocalTrack(e,t,i)})}async replaceTrack(e,t){var i;if(TY.debug("[".concat(this.store.clientId,"] P2PChannel replaceTrack from [").concat(e.getTrackId(),"] to [").concat(t.getTrackId(),"]")),!this.connection||this.state!==yp.Connected)return;let r=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i});if(!r)return;let n=r[0];if(e!==t&&(this.unbindLocalTrackEvents([{track:e,type:n}]),this.bindLocalTrackEvents([{track:t,type:n}]),r[1].track=t),await (null==(i=this.connection)?void 0:i.replaceTrack(t,r[1].id)),this.isPlanB){let e=r[1];e.id=t._mediaStreamTrack.id,this.localTrackMap.set(n,e)}if(n===yu.LocalVideoTrack&&!TR("DISABLE_DUAL_STREAM_USE_ENCODING")&&T1.supportDualStreamEncoding){let t=this.localTrackMap.get(yu.LocalVideoLowTrack);if(t){let i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new dQ((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)})}}}filterTobePublishedTracks(e,t,i){let r=[],n=this.getAllTracks();e=gm(e=e.filter(e=>-1===n.indexOf(e)));let o,a=!1,s=this.localTrackMap.get(yu.LocalAudioTrack);for(let n of e){if(n instanceof CP&&(this.localTrackMap.has(yu.LocalVideoTrack)||a?new Sx(SU.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(r.push({track:n,type:yu.LocalVideoTrack}),a=!0),t)){let e=this.getLowVideoTrack(n,i);r.push({track:e,type:yu.LocalVideoLowTrack})}if(n instanceof CC)if(s){let e=s.track;if(e instanceof CI)AW([n]),e.addAudioTrack(n),this.bindLocalAudioTrackEvents(n,!0);else{let t=AH([e,n]);TY.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(t.getTrackId(),"]")),this.replaceTrack(e,t)}}else o instanceof CI?(AW([n]),o.addAudioTrack(n)):o=o||!n._useAudioElement&&T1.webAudioMediaStreamDest&&!n._bypassWebAudio?AH(o?[n,o]:[n]):n}return o&&(TY.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will send audioTrack [").concat(o.getTrackId(),"]")),r.push({track:o,type:yu.LocalAudioTrack})),r}filterTobeUnpublishedTracks(e){let t=[],i=this.getAllTracks();for(let r of e=gm(e=e.filter(e=>-1!==i.indexOf(e)))){if(r instanceof CC){let e=this.localTrackMap.get(yu.LocalAudioTrack);if(!e)continue;e.track instanceof CI?(e.track.removeAudioTrack(r),this.unbindLocalAudioTrackEvents(r),
10===e.track.trackList.length&&(t.push([yu.LocalAudioTrack,e]),e.track.close())):t.push([yu.LocalAudioTrack,e])}if(r instanceof CP){let e=this.localTrackMap.get(yu.LocalVideoTrack);if(!e)continue;t.push([yu.LocalVideoTrack,e]);let i=this.localTrackMap.get(yu.LocalVideoLowTrack);i&&t.push([yu.LocalVideoLowTrack,i])}}return t}filterTobePublishedDataChannels(e){return e=(e=gm(e)).filter(e=>-1===this.localDataChannels.findIndex(t=>t.id===e.id))}filterTobeUnpublishedDataChannels(e){return e=(e=(e=gm(e)).filter(e=>-1!==this.localDataChannels.indexOf(e))).filter(e=>e._originDataChannel)}bindLocalTrackEvents(e){e.forEach(e=>{let{track:t,type:i}=e;switch(i){case yu.LocalVideoTrack:t.addListener(R_.GET_STATS,this.handleGetLocalVideoStats),t.addListener(R_.GET_RTC_STATS,this.handleGetRTCStats),t.addListener(R_.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(R_.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(R_.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(R_.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.addListener(R_.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(R_.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(R_.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case yu.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case yu.LocalVideoLowTrack:}})}bindLocalAudioTrackEvents(e,t){e instanceof CI?e.trackList.forEach(e=>{e.addListener(R_.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(R_.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(R_.GET_STATS,this.handleGetLocalAudioStats),e.addListener(R_.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(R_.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)}):(e.addListener(R_.GET_STATS,this.handleGetLocalAudioStats),e.addListener(R_.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(R_.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(R_.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(R_.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||(e.addListener(R_.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.addListener(R_.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack)))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map(e=>{let[t,{track:i}]=e;return{track:i,type:t}})),e.forEach(e=>{let{track:t,type:i}=e;switch(i){case yu.LocalVideoTrack:t.off(R_.GET_STATS,this.handleGetLocalVideoStats),t.off(R_.GET_RTC_STATS,this.handleGetRTCStats),t.off(R_.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(R_.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(R_.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(R_.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.off(R_.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(R_.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(R_.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case yu.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case yu.LocalVideoLowTrack:}})}unbindLocalAudioTrackEvents(e){e instanceof CI?e.trackList.forEach(e=>{e.off(R_.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(R_.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(R_.GET_STATS,this.handleGetLocalAudioStats),e.off(R_.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(R_.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)}):(e.off(R_.GET_STATS,this.handleGetLocalAudioStats),e.off(R_.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(R_.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(R_.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(R_.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack),e.off(R_.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(R_.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof Cx&&t.addListener(R_.GET_STATS,t=>{t(this.handleGetRemoteVideoStats(e))}),t instanceof CV&&t.addListener(R_.GET_STATS,t=>{t(this.handleGetRemoteAudioStats(e))})}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(R_.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t,i]=e;i.has(yc.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(yc.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack)})}createGatewayPublishMessage(e,t){return e.map((e,i)=>{var r;let n,o,{track:a,type:s}=e;switch(s){case yu.LocalAudioTrack:n=v6.Audio,o={dtx:a instanceof Cv&&a._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case yu.LocalVideoTrack:n=o5(r=a._hints).call(r,RE.SCREEN_TRACK)?v6.Screen:v6.High,o=bc(bc({},y1(a)),{},{codec:this.store.codec,svc_mode:y7()});break;case yu.LocalVideoLowTrack:n=v6.Low,o=bc(bc({},y1(a)),{},{codec:this.store.codec,svc_mode:y7()})}
1return{stream_type:n,attributes:o,ssrcs:t[i]}})}createGatewayUnpublishMessage(e){return e.map(e=>{var t;let i,[r,{track:n,ssrcs:o,id:a}]=e;switch(r){case yu.LocalVideoTrack:i=o5(t=n._hints).call(t,RE.SCREEN_TRACK)?v6.Screen:v6.High;break;case yu.LocalAudioTrack:i=v6.Audio;break;case yu.LocalVideoLowTrack:i=v6.Low}return{stream_type:i,ssrcs:o,mid:a}})}assignLocalTracks(e,t){e.forEach((e,i)=>{let{track:r,type:n}=e;this.localTrackMap.set(n,{track:r,id:t[i].id,ssrcs:t[i].localSSRC})})}withdrawLocalTracks(e){e.forEach(e=>{let[t]=e;this.localTrackMap.delete(t)})}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{if(TY.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onConnectionStateChange(").concat(t,")")),this.emit(y_.PeerConnectionStateChange,t),"connecting"===t&&e instanceof AQ&&!Sl()&&TR("FIRST_TCP_CANDIDATE")&&window.setTimeout(()=>{"connecting"===t&&e.extendCandidate()},TR("FIRST_TCP_CANDIDATE_INTERVAL")),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),"connected"===t&&(this._restartTimer&&(window.clearTimeout(this._restartTimer),this._restartTimer=void 0),e instanceof AQ&&ba(e,!0),this._isTryConnecting&&this.reportPCStats(Date.now(),!0,this._pcStatsUploadType),this._isTryConnecting=!1,this._isStartRestartIce=!1,this._pcStatsUploadType=yl.DISCONNECTED_OR_FAILED,"CONNECTED"===gd(this,y_.QueryClientConnectionState)&&this._isWaitPcToRePub)){let e=this.pendingLocalTracks.map(e=>e.getTrackId()),t=this.pendingLocalDataChannels.map(e=>"dc_".concat(e.id));T$.reportApiInvoke(this.store.sessionId,{name:S3.REPUB_AFTER_PC_CONNECTED,options:e.concat(t),tag:S5.TRACER}).onSuccess(),this.republish()}if(TR("NEW_ICE_RESTART")&&e instanceof AQ&&!Sl()&&!this._forceTurn&&!this.store.useDcSignal){if(o5(yh).call(yh,t)){if(this._isStartRestartIce)return;this._isStartRestartIce=!0;let t=t=>{Az(e)&&(TY.debug("[".concat(this.store.clientId,"] [P2PChannel] try to restartICE, type is ").concat(t)),"CONNECTED"===gd(this,y_.QueryClientConnectionState)&&this.emit(y_.RequestRestartICE,t))},i=()=>{Az(e)&&(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),TY.debug("[".concat(this.store.clientId,"] P2PConnection disconnected timeout, force reconnect")),setTimeout(()=>
1this.emit(y_.P2PLost),0),this.iceFailedCount+=1,this.requestReconnect())};return void(this._restartTimer=window.setTimeout(()=>{!function e(t,i,r){if(0===bi.size&&0===br.size&&(Array.isArray(TR("RESTART_SEQUENCE"))&&TR("RESTART_SEQUENCE").length>0&&!function(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1){let r=e[i];if(e.filter(e=>e===r).length!==t.filter(e=>e===r).length)return!1}return!0}(bn,TR("RESTART_SEQUENCE"))&&(bn=TR("RESTART_SEQUENCE").filter(e=>{var t;if(o5(t=Object.values(yd)).call(t,e))return!0}),TY.debug("use reconnection policy from config distribution, queues: ".concat(bn.join(" => ")))),bo=TR("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&T1.supportPCSetConfiguration),0===bn.length)return void r();let n,{index:o=0,type:a}=br.get(t.id)||{};if(bo&&a===yd.RELAY)return void r();let s=a&&o>=bn.length-1;if(bo)a=yd.RELAY;else{if(s)return void r();a?a=bn[++o]:(a=bn[0],o=0)}TY.debug("[".concat(t.id,"] choose ICE restart policy: ").concat(a,", index: ").concat(o)),i(a),br.set(t.id,{index:o,type:a}),n=window.setTimeout(()=>e(t,i,r),bt),bi.set(t.id,n)}(e,t,i)},800))}}else{if("disconnected"===t&&"disconnected"===e.iceConnectionState)return setTimeout(()=>{"disconnected"===e.iceConnectionState&&TR("ICE_RESTART")&&"CONNECTED"===gd(this,y_.QueryClientConnectionState)&&this.emit(y_.RequestRestartICE)},800),void setTimeout(()=>{"disconnected"===e.peerConnectionState&&(TY.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection disconnected timeout 4000ms, force reconnect")),this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),this._isTryConnecting=!1,setTimeout(()=>
1this.emit(y_.P2PLost),0),this.iceFailedCount+=1,this.requestReconnect())},4e3);"failed"===t&&(TY.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection state failed, force reconnect")),this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),setTimeout(()=>this.emit(y_.P2PLost),0),this.iceFailedCount+=1,await this.requestReconnect())}},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),TY.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),T$.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:S5.TRACER}).onSuccess(),this.emit(y_.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{TY.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{TY.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{TY.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},e.onFirstAudioDecoded=e=>{var t,i;let r=Array.from(TL(t=this.remoteUserMap).call(t)).find(t=>t._audioSSRC===e);r&&(this.store.subscribe(r.uid,"audio",void 0,void 0,void 0,Date.now()),null==(i=r.audioTrack)||i.emit(RR.FIRST_FRAME_DECODED),T$.firstRemoteFrame(this.store.sessionId,TX.FIRST_AUDIO_DECODE,TJ.FIRST_AUDIO_DECODE,{peer:r._uintid,subscribeElapse:AT.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;let i=Array.from(TL(t=this.remoteUserMap).call(t)).find(t=>t._audioSSRC===e);i&&T$.firstRemoteFrame(this.store.sessionId,TX.FIRST_AUDIO_RECEIVED,TJ.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:AT.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,i)=>{var r;let n=Array.from(TL(r=this.remoteUserMap).call(r)).find(t=>t._videoSSRC===e);n&&this.store.firstVideoFrameDecoded(n.uid,{firstDecoded:Date.now()}),this.reportVideoFirstFrameDecoded(e,t,i)},e.onFirstVideoRender=e=>{var t;let i=Array.from(TL(t=this.remoteUserMap).call(t)).find(t=>t._videoSSRC===e);i&&(this.store.firstVideoFrameDecoded(i.uid,{firstPreRender:Date.now()}),this.reportVideoFirstFrameRender(i),this.emit(y_.FirstVideoPreRender,i.uid,e))},e.onFirstVideoReceived=e=>{var t;let i=Array.from(TL(t=this.remoteUserMap).call(t)).find(t=>t._videoSSRC===e);i&&(this.store.firstVideoFrameDecoded(i.uid,{firstReceived:Date.now()}),T$.firstRemoteFrame(this.store.sessionId,TX.FIRST_VIDEO_RECEIVED,TJ.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:AT.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstVideoBufferReady=e=>{var t;let i=Array.from(TL(t=this.remoteUserMap).call(t)).find(t=>t._videoSSRC===e);i&&this.emit(y_.FirstVideoBufferReady,i.uid,e)},e.onSelectedLocalCandidateChanged=(e,t)=>{let i="relay"===e.candidateType,r="relay"===t.candidateType;"unknown"!==t.candidateType&&i===r||this.emit(y_.ConnectionTypeChange,i),TY.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(y6(t))," -> ").concat(JSON.stringify(y6(e)),")"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{TY.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(y6(t))," -> ").concat(JSON.stringify(y6(e)),")"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},e.getLocalVideoStats=()=>{let e=this.statsCollector.getLocalVideoTrackStats(),t=this.statsCollector.getRTCStats();return bc(bc({},e),t)},e.onICECandidateError=e=>{this._iceError=e}}fallbackConnection(){TY.debug("[".concat(this.store.clientId,"] [P2PChannel] try to fallback connection")),this.state===yp.Connected?(TY.debug("[".concat(this.store.clientId,"] [P2PChannel] fallback to websocket but P2PChannel state still connected, disconnect first")),this.disconnectForReconnect()):(this.connection&&this.resetConnection(this.connection),this.shouldForwardP2PCreation&&(this.connection=AY(this.store),this.emit
1(y_.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection)))}resetConnection(e){e instanceof AQ&&(br.delete(e.id),ba(e)),e.close(),this.emit(y_.PeerConnectionStateChange,"closed"),e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0,e.getLocalVideoStats=void 0,this._isWaitPcToRePub=!1}filterTobeMutedTracks(e){let t=[];if(-1===this.getAllTracks().indexOf(e))return t;let i=this.localTrackMap.get(yu.LocalAudioTrack);if(e instanceof CC&&(null==i?void 0:i.track)instanceof CI)return i.track.isActive||t.push([yu.LocalAudioTrack,i]),t;let r=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i});if(r&&(t.push(r),r[0]===yu.LocalVideoTrack)){let e=this.localTrackMap.get(yu.LocalVideoLowTrack);e&&t.push([yu.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){let t=[],i=this.localTrackMap.get(yu.LocalAudioTrack);if(e instanceof CC&&(null==i?void 0:i.track)instanceof CI)return i.track.isActive&&t.push([yu.LocalAudioTrack,i]),t;let r=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i});if(r)if(r[0]===yu.LocalVideoTrack){t.push(r);let e=this.localTrackMap.get(yu.LocalVideoLowTrack);e&&t.push([yu.LocalVideoLowTrack,e])}else t.push(r);return t}createMuteMessage(e){return e.map(e=>{var t;let i,[r,{track:n,ssrcs:o,id:a}]=e;switch(r){case yu.LocalAudioTrack:i=v6.Audio;break;case yu.LocalVideoTrack:i=o5(t=n._hints).call(t,RE.SCREEN_TRACK)?v6.Screen:v6.High;break;case yu.LocalVideoLowTrack:i=v6.Low}return{stream_type:i,ssrcs:o,mid:a}})}createUnmuteMessage(e){return e.map(e=>{var t;let i,[r,{track:n,ssrcs:o,id:a}]=e;switch(r){case yu.LocalAudioTrack:i=v6.Audio;break;case yu.LocalVideoTrack:i=o5(t=n._hints).call(t,RE.SCREEN_TRACK)?v6.Screen:v6.High;break;case yu.LocalVideoLowTrack:i=v6.Low}return{stream_type:i,ssrcs:o,mid:a}})}filterTobeUnSubscribedTracks(e,t){let i=[],r=this.remoteUserMap.get(e);if(!r)return i;if(t){let n=r.get(t);if(!n)return i;i.push([e,{kind:t,id:n}])}else Array.from(r.entries()).forEach(t=>{let[r,n]=t;i.push([e,{kind:r,id:n}])});return i}filterTobeUnSubscribedDataChannels(e,t){let i=[];return t.forEach(t=>{var r;null!=(r=this.remoteDataChannelMap.get(e))&&r.has(t.id)&&i.push(t)}),i}createUnsubscribeMessage(e){let t=[];return e.forEach(e=>{let[i,{kind:r,id:n}]=e;switch(r){case yc.VIDEO:return void(i._videoSSRC&&t.push({stream_type:yc.VIDEO,ssrcId:i._videoSSRC}));case yc.AUDIO:return void(i._audioSSRC&&t.push({stream_type:yc.AUDIO,ssrcId:i._audioSSRC}))}}),t}createUnsubscribeAllMessage(e){let t=new Map;return e.forEach(e=>{let[i,{kind:r}]=e;if(t.has(i)){let e=t.get(i);r===yc.VIDEO?e|=v7.Video:e|=v7.Audio,t.set(i,e)}else r===yc.VIDEO?t.set(i,v7.Video):t.set(i,v7.Audio)}),{users:Array.from(t.entries()).map(e=>{let[t,i]=e;return{stream_id:t.uid,stream_type:i}})}}withdrawRemoteTracks(e){e.forEach(e=>{let[t,{kind:i}]=e,r=this.remoteUserMap.get(t);r&&(r.delete(i),0===Array.from(r.entries()).length&&this.remoteUserMap.delete(t))})}async updateBitrateLimit(e){let t=this.localTrackMap.get(yu.LocalVideoTrack),i=this.localTrackMap.get(yu.LocalVideoLowTrack);t&&(await t.track.setBitrateLimit(e.uplink),await new dQ((e,i)=>{this.handleUpdateVideoEncoder(t.track,e,i,!0)})),i&&e.low_stream_uplink&&(await i.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0}),await new dQ((e,t)=>{this.handleUpdateVideoEncoder(i.track,e,t,!0)}))}isP2PDisconnected(){return!this.connection||"connected"!==this.connection.peerConnectionState}isPreallocation(){return!(!this.connection||!("name"in this.connection)||"DataChannelConnection"!==this.connection.name||"closed"===this.connection.peerConnectionState)||this.connection instanceof AQ&&this.connection.isPreallocation}isPreSub(){return(this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name&&"closed"!==this.connection.peerConnectionState||this.connection instanceof AQ)&&this.connection.isPreSub()}isPreRender(){return this.connection instanceof AQ&&this.connection.isPreRen
1der}mapPubResToRemoteConfig(e,t,i){return e.map((e,r)=>{var n;let{stream_type:o}=e,a=null==(n=t.find(e=>{let{stream_type:t}=e;return o===t}))?void 0:n.attributes;if(a&&TR("DISABLE_SCREEN_SHARE_REMB")){let e=i[r]._hints;(o5(e).call(e,RE.SCREEN_TRACK)||o5(e).call(e,RE.SCREEN_LOW_TRACK))&&(a.remb=!1,TY.debug("disable remb for screen share, hints:",e))}return a})}async tryToUnmuteAudio(e){for(let i=0;i<e.length;i++)if(e[i]instanceof CC){var t;let r=this.filterTobeUnmutedTracks(e[i]);if(0===r.length)continue;await (null==(t=this.connection)?void 0:t.unmuteLocal(r.map(e=>{let[,{id:t}]=e;return t})));let n=this.createUnmuteMessage(r);return void await gc(this,y_.RequestUnmuteLocal,n)}}bindStatsUploaderEvents(){this.statsUploader.requestStats=()=>this.getStats(),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return!(null==(t=this.connection)||!t.getRemoteVideoIsReady(e))},this.statsUploader.requestUpload=(e,t)=>this.emit(y_.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(y_.RequestUploadStats,e),this.statsUploader.requestAllTracks=()=>this.getAllTracks(),this.statsUploader.requestTransportStats=()=>{var e;return{connectState:(null==(e=this.connection)?void 0:e.peerConnectionState)||"closed"}}}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0}async requestReconnect(){this.dtlsFailedCount+=1,await gO(gK(this.dtlsFailedCount,gH)),this.emit(y_.RequestReconnect)}async reconnectP2P(){let e=Array.from(this.localTrackMap.entries()),t=this.createGatewayUnpublishMessage(e);Array.from(this.remoteUserMap.entries()),t.length>0&&await gs(this,y_.RequestUnpublishForReconnectPC,t),this.disconnectForReconnect(),this.emit(y_.RequestReconnectPC)}canPublishLowStream(){return this.localTrackMap.has(yu.LocalVideoTrack)||this.pendingLocalTracks.some(e=>e instanceof CP)}throwIfTrackTypeNotMatch(e){if(e.filter(e=>e instanceof CP).length>1)throw new Sx(SU.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter(e=>e instanceof CC).length>1&&(e.some(e=>e instanceof CC&&e._bypassWebAudio)||!T1.webAudioMediaStreamDest))throw new Sx(SU.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(let t of e){if(t instanceof CP&&this.pendingLocalTracks.some(e=>e instanceof CP))throw new Sx(SU.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof CC&&this.pendingLocalTracks.some(e=>e instanceof CC)&&(!T1.webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some(e=>e instanceof CC&&e._bypassWebAudio)))throw new Sx(SU.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(e,t){var i;let r,n=!TR("DISABLE_DUAL_STREAM_USE_ENCODING")&&T1.supportDualStreamEncoding,o=bc(bc({},{width:160,height:120,framerate:15,bitrate:50}),t);r=n?e._mediaStreamTrack.clone():A$(e,o);let a=gw(8,"track-low-"),s=new CP(r,bc(bc({},n&&{scaleResolutionDownBy:y4(o,e)}),{},{frameRate:o.framerate,bitrateMax:o.bitrate,bitrateMin:o.bitrate}),void 0,void 0,a);return s.on(Rg.TRANSCEIVER_UPDATED,t=>{e._updateRtpTransceiver(t,Rm.LOW_STREAM)}),s._hints.push(RE.LOW_STREAM),o5(i=e._hints).call(i,RE.SCREEN_TRACK)&&s._hints.push(RE.SCREEN_LOW_TRACK),e.on("sei-to-send",e=>{s.emit("sei-to-send",e)}),e.addListener(R_.NEED_CLOSE,()=>{s.close()}),s}async globalLock(){return this.mutex.lock("From P2PChannel.globalLock")}async reportPCStats(e,t,i){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;if(this.connection&&this.connection instanceof AQ){var n,o,a,s;let c=this.store.keyMetrics.descriptionStart||0,{iceConnectionState:d,dtlsTransportState:l,peerConnectionState:h}=this.connection,{local:u,remote:p}=await this.connection.getSelectedCandidatePair();T$.pcStats(this.store.sessionId,{startTime:c,eventElapse:e-c||0,iceconnectionsate:d,dtlsstate:l,connectionstate:h,intSucc:t?1:2,error:this._iceError||r||"",selectedLocalCandidateProtocol:null!=(n=null==u?void 0:u.protocol)?n:"",selectedLocalCandidateType:null!=(o=u.candidateType)?o:"",selectedLocalCandidateAddress:"".concat(u.address,":").concat(u.port),selectedRemoteCandidateProtocol:null!=(a=p.protocol)?a:"",selectedRemoteCandidateType:null!=(s=p.candidateType)?s:"",selectedRemoteCandidateAddress:"".concat(p.address,":").concat(p.port),restartCnt:i,preallocation:this.connection.isPreallocation}),this._iceError=null}}reportVideoFirstFrameRender(e){let t=this.store.keyMetrics,i=t.firstVideoFrameDecoded.find(t=>t.userId===e.uid);if(!i)return;let{isInternalUpload:r,isExternalUpload:n}=i;
1if(r&&n)return;let{subscribeEnd:o,firstPreRender:a,peerPublishDuration:s,peerPubStatusMs:c}=i,{firstRender:d=0}=i;if(o&&(d||a)&&s&&c){i.isInternalUpload=!0;let{playEnd:r}=i;r&&(i.isExternalUpload=!0);let{firstPreRender:n=0}=i;d=n||d;let a=e.videoTrack,l={peer:e._uintid,width:(null==a?void 0:a._videoWidth)||0,height:(null==a?void 0:a._videoHeight)||0,ssrc:e._videoSSRC||0,p2pid:this.store.p2pId,peerPublishDuration:s,peerPubStatusMs:c,joinChannelStart:t.joinStart||0,preloadStart:t.preloadStart||0,preloadEnd:t.preloadEnd||0,apStart:t.requestAPStart||0,apEnd:t.requestAPEnd||0,suaEnd:t.requestSUAEnd||0,beforeConnect:t.beforeConnect||0,peerReceiver:t.peerReceiver||0,ice:t.iceConnectionEnd||0,pc:t.peerConnectionEnd||0,signalConnected:t.signalConnected||0,joinReq:t.joinReq||0,joinRes:t.joinRep||0,userJoinNotify:i.userJoinNotify||0,videoAddNotify:i.videoAddNotify||0,subscribeStart:i.subscribeStart||0,subscribeEnd:i.subscribeEnd||0,firstReceived:i.firstReceived||0,firstDecoded:i.firstDecoded||0,firstPreRender:n||0,firstRender:r?Math.max(d,r):Math.max(d,o),playStart:i.playStart||0,playEnd:i.playEnd||0,isPreSub:!(!e._videoSSRC||!this.isPreSubScribe(e._videoSSRC)),isPrePc:this.isPreallocation(),isPreInstantVideo:T4(this.store),firstReceivedEncodedFrame:i.firstReceivedEncodedFrame||0,frameType:i.frameType||"",rtpTimestamp:i.rtpTimestamp||0,framePayloadType:i.framePayloadType||0,frameDataLength:i.frameDataLength||0,mimeType:i.mimeType||""};T$.firstXLAPeerFirstVideoFrame(this.store.sessionId,l)}}reportVideoFirstFrameDecoded(e,t,i,r){var n;let o=Array.from(TL(n=this.remoteUserMap).call(n)).find(t=>t._videoSSRC===e);if(o){r||this.store.subscribe(o.uid,"video",void 0,void 0,void 0,void 0,Date.now());let n=this.store.keyMetrics,a=n.subscribe.find(e=>e.userId===o.uid&&"video"===e.type);T$.firstRemoteVideoDecode(this.store.sessionId,TX.FIRST_VIDEO_DECODE,TJ.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:i,subscribeElapse:AT.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:n.requestAPEnd||0,apStart:n.requestAPStart||0,joinGwEnd:n.joinGatewayEnd||0,joinGwStart:n.joinGatewayStart||0,pcEnd:n.peerConnectionEnd||0,pcStart:n.peerConnectionStart||0,subscriberEnd:(null==a?void 0:a.subscribeEnd)||0,subscriberStart:(null==a?void 0:a.subscribeStart)||0,videoAddNotify:(null==a?void 0:a.streamAdded)||0,state:+!!r,firstFrame:(null==a?void 0:a.firstFrame)||0})}}async remoteMediaSsrcChanged(e,t,i){if(!this.connection)return!1;let r=this.remoteUserMap.get(e);if(!r)return!1;let n=r.get(t);if(!n)return!1;let o=await this.connection.getRemoteSSRC(n);return void 0!==o&&o!==i}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach(e=>{let[t,{track:i}]=e;t===yu.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,Rm.LOW_STREAM):i._updateRtpTransceiver(void 0)})}constructor(e,t){super(),mb(this,"isPlanB",void 0),mb(this,"store",void 0),mb(this,"statsUploader",void 0),mb(this,"connection",void 0),mb(this,"localTrackMap",new Map),mb(this,"remoteUserMap",new Map),mb(this,"localDataChannels",[]),mb(this,"remoteDataChannelMap",new Map),mb(this,"pendingLocalTracks",[]),mb(this,"pendingRemoteTracks",[]),mb(this,"pendingLocalDataChannels",[]),mb(this,"pendingRemoteDataChannels",[]),mb(this,"statsCollector",void 0),mb(this,"shouldForwardP2PCreation",void 0),mb(this,"iceFailedCount",0),mb(this,"dtlsFailedCount",0),mb(this,"mutex",void 0),mb(this,"_state",yp.Disconnected),mb(this,"_pcStatsUploadType",TR("NEW_ICE_RESTART")?yl.FIRST_CONNECTION:yl.OLD_FIRST_CONNECTION),mb(this,"_isStartRestartIce",!1),mb(this,"_restartTimer",void 0),mb(this,"_isTryConnecting",!1),mb(this,"_iceError",null),mb(this,"_forceTurn",!1),mb(this,"_isWaitPcToRePub",!1),mb(this,"handleMuteLocalTrack",async(e,t,i)=>{let r=await this.mutex.lock("Locking from P2PChannel.handleMuteLocalTrack");try{if(!this.connection||this.state!==yp.Connected)return void i(new Sx(SU.INVALID_OPERATION,"Cannot call P2PChannel.handleMuteLocalTrack before connection established."));let r=this.filterTobeMutedTracks(e);if(0===r.length)return void t();let n=r.find(e=>"videoLowTrack"===e[0]);if(n){let e=n[1];this.store.enableInstantMuteRestore?(e.track._originMediaStreamTrack.enabled=!1,TY.info("[".concat(this.store.clientId,"] P2PChannel muteLocalLowTrack without close sender be
1cause enableInstantMuteRestore is true"))):e.track._originMediaStreamTrack.stop()}this.store.enableInstantMuteRestore?TY.info("[".concat(this.store.clientId,"] P2PChannel muteLocalTrack without close sender because enableInstantMuteRestore is true")):await this.connection.muteLocal(r.map(e=>{let[,{id:t}]=e;return t}));let o=this.createMuteMessage(r);await gc(this,y_.RequestMuteLocal,o),t()}catch(e){i(e)}finally{r()}}),mb(this,"handleUnmuteLocalTrack",async(e,t,i)=>{let r=await this.mutex.lock("Locking from P2PChannel.handleUnmuteLocalTrack");try{if(!this.connection||this.state!==yp.Connected)return void i(new Sx(SU.INVALID_OPERATION,"Cannot call P2PChannel.handleUnmuteLocalTrack before connection established."));let r=this.filterTobeUnmutedTracks(e);if(0===r.length)return void t();let n=r.find(e=>"videoLowTrack"===e[0]);if(n){let t=n[1];if(this.store.enableInstantMuteRestore)t.track._originMediaStreamTrack.enabled=!0,TY.info("[".concat(this.store.clientId,"] P2PChannel unmuteLocalLowTrack without close sender because enableInstantMuteRestore is true"));else{if(t.track._originMediaStreamTrack.stop(),!TR("DISABLE_DUAL_STREAM_USE_ENCODING")&&T1.supportDualStreamEncoding){let i=e._mediaStreamTrack.clone();t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}else{let i=A$(e,gl(this,y_.RequestLowStreamParameter));t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}await new dQ((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)})}}this.store.enableInstantMuteRestore?TY.info("[".concat(this.store.clientId,"] P2PChannel unmuteLocalTrack without close sender because enableInstantMuteRestore is true")):await this.connection.unmuteLocal(r.map(e=>{let[,{id:t}]=e;return t}));let o=this.createUnmuteMessage(r);await gc(this,y_.RequestUnmuteLocal,o),t()}catch(e){i(e)}finally{r()}}),mb(this,"handleUpdateVideoEncoder",async(e,t,i,r)=>{let n;r||(n=await this.mutex.lock("Locking from P2PChannel.handleUpdateVideoEncoder"));try{let i=this.localTrackMap.get(yu.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==yp.Connected)return void t();let{id:r,track:n}=i;await this.connection.updateSendParameters(r,n),await this.connection.updateEncoderConfig(r,n),this.emit(y_.UpdateVideoEncoder,n),t()}catch(e){i(e)}finally{var o;null==(o=n)||o()}}),mb(this,"handleUpdateVideoSendParameters",async(e,t,i)=>{let r=await this.mutex.lock("Locking from P2PChannel.handleUpdateVideoSendParameters");try{let i=this.localTrackMap.get(yu.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==yp.Connected)return void t();let{id:r,track:n}=i;await this.connection.updateSendParameters(r,n),t()}catch(e){i(e)}finally{r()}}),mb(this,"handleReplaceMixingTrack",async(e,t,i,r)=>{let n;if(!this.connection||this.state!==yp.Connected)return void t();let o=AH([e]);TY.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(o.getTrackId(),"]")),"boolean"==typeof r&&r||(n=await this.mutex.lock("From P2PChannel.handleReplaceMixingTrack"));try{await this.replaceTrack(e,o),t()}catch(e){i(e)}finally{var a;null==(a=n)||a()}}),mb(this,"handleReplaceTrack",async(e,t,i,r)=>{var n,o;let a;TY.debug("[".concat(this.store.clientId,"] P2PChannel handleReplaceTrack for [track-id-").concat(e.getTrackId(),"]")),"boolean"==typeof r&&r||(a=await this.mutex.lock("From P2PChannel.handleReplaceTrack"));try{let i=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i});if(!this.connection||!i||this.state!==yp.Connected)return void t();if(await (null==(n=this.connection)?void 0:n.replaceTrack(e,i[1].id)),this.isPlanB){let t=i[1];t.id=e._mediaStreamTrack.id,this.localTrackMap.set(i[0],t)}if(i[0]===yu.LocalVideoTrack&&!TR("DISABLE_DUAL_STREAM_USE_ENCODING")&&T1.supportDualStreamEncoding){let t=this.localTrackMap.get(yu.LocalVideoLowTrack);if(t){let i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new dQ((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)})}}t()}catch(e){i(e)}finally{null==(o=a)||o()}}),mb(this,"handleGetRTCStats",e=>{e(this.statsCollector.getRTCStats())}),mb(this,"handleGetLocalVideoStats",e=>{e(this.statsCollector.getLocalVideoTrackStats())}),mb(this,"handleGetLocalAudioStats",e=>{e(this.statsCollector.getLocalAudioTrackStats())}),mb(this,"handleGetRemoteVideoStats",e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid]),mb(this,"handleGetRemoteAudioStats",e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid]),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new be(this.store),this.bindStatsUploaderEvents(),this.mutex=new gG("P2PChannel-mutex",this.store.clientId),this.isPlanB=!T1.supportUnifiedPlan||TR("CHROME_FORCE_PLAN_B")&&SN(),this.shouldForwardP2PCreation=TR("FORWARD_P2P_CREATION")&&T1.supportPCSetConfiguration&&Sw(),this.shouldForwardP2PCreation&&(this.connection=AY(this.store),this.emit
1(y_.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection))}}).prototype,"startP2PConnection",[bu],Object.getOwnPropertyDescriptor(iH.prototype,"startP2PConnection"),iH.prototype),vP(iH.prototype,"connect",[bu],Object.getOwnPropertyDescriptor(iH.prototype,"connect"),iH.prototype),vP(iH.prototype,"updateRemoteRTPCapabilities",[bu],Object.getOwnPropertyDescriptor(iH.prototype,"updateRemoteRTPCapabilities"),iH.prototype),vP(iH.prototype,"publishDataChannel",[bu],Object.getOwnPropertyDescriptor(iH.prototype,"publishDataChannel"),iH.prototype),vP(iH.prototype,"unpublish",[bu],Object.getOwnPropertyDescriptor(iH.prototype,"unpublish"),iH.prototype),vP(iH.prototype,"unpublishDataChannel",[bu],Object.getOwnPropertyDescriptor(iH.prototype,"unpublishDataChannel"),iH.prototype),vP(iH.prototype,"unpublishLowStream",[bu],Object.getOwnPropertyDescriptor(iH.prototype,"unpublishLowStream"),iH.prototype),vP(iH.prototype,"subscribeDataChannel",[bu],Object.getOwnPropertyDescriptor(iH.prototype,"subscribeDataChannel"),iH.prototype),vP(iH.prototype,"subscribe",[bu],Object.getOwnPropertyDescriptor(iH.prototype,"subscribe"),iH.prototype),vP(iH.prototype,"massSubscribe",[bu],Object.getOwnPropertyDescriptor(iH.prototype,"massSubscribe"),iH.prototype),vP(iH.prototype,"unsubscribe",[bu],Object.getOwnPropertyDescriptor(iH.prototype,"unsubscribe"),iH.prototype),vP(iH.prototype,"unsubscribeDataChannel",[bu],Object.getOwnPropertyDescriptor(iH.prototype,"unsubscribeDataChannel"),iH.prototype),vP(iH.prototype,"massUnsubscribe",[bu],Object.getOwnPropertyDescriptor(iH.prototype,"massUnsubscribe"),iH.prototype),vP(iH.prototype,"muteRemote",[bu],Object.getOwnPropertyDescriptor(iH.prototype,"muteRemote"),iH.prototype),vP(iH.prototype,"unmuteRemote",[bu],Object.getOwnPropertyDescriptor(iH.prototype,"unmuteRemote"),iH.prototype),vP(iH.prototype,"hasRemoteMediaWithLock",[bu],Object.getOwnPropertyDescriptor(iH.prototype,"hasRemoteMediaWithLock"),iH.prototype),vP(iH.prototype,"disconnectForReconnect",[bu],Object.getOwnPropertyDescriptor(iH.prototype,"disconnectForReconnect"),iH.prototype),vP(iH.prototype,"updateBitrateLimit",[bu],Object.getOwnPropertyDescriptor(iH.prototype,"updateBitrateLimit"),iH.prototype),vP(iH.prototype,"remoteMediaSsrcChanged",[bu],Object.getOwnPropertyDescriptor(iH.prototype,"remoteMediaSsrcChanged"),iH.prototype),iH);function bu(e,t,i){let r=e[t];if("function"!=typeof r)throw Error("Cannot use mutex on object property.");return i.value=async function(){let e=this.mutex,i=await e.lock("From P2PChannel.".concat(t));try{for(var n=arguments.length,o=Array(n),a=0;a<n;a++)o[a]=arguments[a];return await r.apply(this,o)}finally{i()}},i}function bp(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function b_(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?bp(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):bp(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let bE=Date.now(),bm=new Map,bf=new Map;async function bS(e){let t=bm.get(e),i=Array.isArray(t)&&t[t.length-1],r=bf.get(e);if(!i)return void(r.isSyncing=!1);let n={uid:i.uid,payload:i.payload};0===r.firstRecvTs&&(r.firstRecvTs=i.recvTs,r.firstSendTs=i.sendTs);let o=i.sendTs-r.firstSendTs,a=o-(Date.now()-r.firstRecvTs);a>0&&(r.firstRecvTs=Date.now()-o);let s=i.mediaDelay+a;s<=0?(t.pop(),bg(i.context,n),s=0):s=Math.min(s,20),setTimeout(()=>t.length&&bS(e),s)}function bg(e,t){e.safeEmit(gi.STREAM_MESSAGE,t.uid,t.payload),e.onStreamMessage&&e.onStreamMessage(t)}let bT=St().name;function bR(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function bC(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
1t%2?bR(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):bR(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let bv="websdk_ng_cache_parameter",by=TR("MAX_PRELOAD_ASYNC_LENGTH"),bI=new Map,bA=[],bb=null,bO=0,bw=0,bN=new Map,bD=new Uint8Array([241,141,127,212,103,139,200,225,251,157,127,139,143,2,22,163]),bP=function(e,t){let i=[],r=0,n=async()=>{let e=i.shift();e&&await e(),i.length>0&&r<t?n():r--};return async function(){for(var o=arguments.length,a=Array(o),s=0;s<o;s++)a[s]=arguments[s];return new dQ(async(o,s)=>{i.push(async()=>{try{let t=await e(...a);o(t)}catch(e){s(e)}}),r<t&&(r++,n())})}}(bM,by),bL=f0.CancelToken.source();class bk{createMuteAudioTrack(){this._audioContext=new AudioContext;let e=this._audioContext.sampleRate,t=this._audioContext.createBuffer(2,10*e,e),i=this._audioContext.createBufferSource();i.buffer=t;let r=this._audioContext.createMediaStreamDestination();return i.connect(r),i.start(),r.stream.getAudioTracks()[0]}close(){this._audioContext&&(this._audioContext.close(),this._audioContext=null)}constructor(){mb(this,"_audioContext",null)}}async function bM(e,t,i,r,n,o,a){try{let s,c;if(!TR("ENABLE_PRELOAD"))return;if(!T1.supportWebCrypto)return void gR(()=>{TY.warn("Your browser does not support preloading, this feature be run in a secure environment")},"preload_webcrypto_not_supported");if(!i&&null!==i)throw new Sx(SU.INVALID_PARAMS,"Invalid token: ".concat(i,". If you don not use token, set it to null"));i&&SG(i,"token",1,2047),SG(e,"appid",1,2047),vK(t),r&&vY(r);let d=gN();TY.debug("preload channel ".concat(t,", uid is ").concat(r));let l={appId:e,cname:t,token:i||e,uid:"string"!=typeof r?r:null,sid:d,proxyServer:n,role:a};"string"==typeof r?(l.stringUid=r,[c,s]=await dQ.all([Ad(r,{sid:d,appId:e},bL.token),Ah(bC(bC({},l),{},{token:i||e,uid:0}),bL.token)]),l.uid=c.uid,s.gatewayInfo.uid=l.uid,s.gatewayInfo.res.uid=l.uid):(o&&(l.stringUid=o),s=await Ah(l,bL.token));let h={sid:d,appId:e,cname:t,token:i||e,uid:l.stringUid||r,intUid:l.uid||s.gatewayInfo.uid,stringUid:l.stringUid,ts:Date.now(),sua:c,ap:s};await bV(h),bO++}catch(e){throw bw++,function(e){bb||(bb=window.setTimeout(()=>{let t="";bN.forEach((e,i)=>{t+="".concat(i,": ").concat(e," ;")}),T$.reportApiInvoke(null,{name:S3.PRELOAD,options:{success:bO,failed:bw,err:t}}).onError(e),bO=0,bw=0,bN.clear(),bb=null},1e4));let t=bN.get(e.code)||0;bN.set(e.code,t+1)}(e),e}}async function bU(e){try{if(TR("AP_REQUEST_DETAIL")||TR("ENABLE_ROLE_SELECT_EDGE"))return;let t=bx(e);if(!t||"disabled"!==e.cloudProxyServer)return;let i=await async function(e,t){try{let i=await window.crypto.subtle.importKey("raw",gy(t),"AES-GCM",!1,["decrypt"]),r=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:bD},i,gC(e));return JSON.parse(window.atob(gv(new Uint8Array(r))))}catch(e){return}}(t,e.token||e.appId);if(!i||i.cname!==e.cname||i.appId!==e.appId||i.token!==e.token||(e.stringUid?i.stringUid!==e.stringUid:"number"==typeof e.uid?i.uid!==e.uid:i.uid!=e.uid))return;if(i&&Date.now()-i.ts<TR("AP_CACHE_LIFETIME"))return i}catch(e){TY.warn("Error get preloadInfo",e.message)}}function bx(e){let t;try{if(!(t=bG(bv)))return;let i=JSON.parse(t),r=bH(e),n=function(e,t){for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return -1}(i,e=>r in e);if(-1===n)return;let o=i.splice(n,1)[0];return bW(bv,JSON.stringify(i)),o[r]}catch(e){TY.warn("Error delete preload info: ".concat(t),e.message),bW(bv,"")}}async function bV(e){let t;try{e.uid&&bx({appId:e.appId,cname:e.cname,token:e.token,uid:e.uid,stringUid:e.stringUid});let i=bH(e),r=await async function(e,t){try{let i=await window.crypto.subtle.importKey("raw",gy(t),"AES-GCM",!1,["encrypt"]),r=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:bD},i,gC(window.btoa(JSON.stringify(e))));return gv(new Uint8Array(r))}catch(e){return}}(e,e.token||e.appId);if(!r)return;let n=(t=bG(bv))?JSON.parse(t):[];n.push({[i]:r}),n.length>TR("AP_CACHE_NUM")&&n.shift(),bW(bv,JSON.stringify(n))}catch(e){TY.warn("Error caching server parameters:",e.message),bW(bv,"")}}function bF(e){if(e){let t=bI.get(e);t&&(window.clearTimeout(t),t=null,bI.delete(e)),o5(bA).call(bA,e)||"disabled"!==e.cloudProxyServer||bA.push(e)}if(bI.size<TR("AP_CACHE_NUM")&&bA.length>0){let e=bA.shift();bI.set(e,window.setTimeout(async()=>{let{appId:t,cname:i,token:r,stringUid:n,uid:o,proxyServer:a,role:s}=e;try{await bP(t,i,r,o,a,n,s),bI.has(e)&&bF(e)}catch(t){TY.warn("update preload failed",t.message),bB(e)}},TR("AP_UPDATE_INTERVAL")))}}function bB(e){let t=bA.indexOf(e);-1!==t&&bA.splice(t,1);let i=bI.get(e);i&&(window.clearTimeout(i),i=null,bI.delete(e),bF())}function bj(e,t){let i=e.sua,r=e.ap;t&&i&&T$.reqUserAccount(e.sid,{lts:i.requestTime,elapse:i.elapse,success:!0,serverAddr:i.url,stringUid:t,uid:e.intUid,errorCode:null,extend:i.req}),T$.reportResourceTiming(e.ap.url,e.sid),T$.joinWebProxyAP(e.sid,{lts:r.requestTime,elapse:r.elapse,sucess:1,apServerAddr:r.url,turnServerAddrList:r.proxyInfo.addresses.map(e=>e.ip).join(","),eventType:"disabled",unilbsServerIds:[yz.CHOOSE_SERVER,yz.CLOUD_PROXY_FALLBACK].toString()}),T$.joinChooseServer(e.sid,{lts:r.requestTime,elapse:r.elapse,succ:!0,csAddr:r.url,opid:r.opid,serverList:r.gatewayInfo.gatewayAddrs.map(e=>e.address),ec:null,cid:r.gatewayInfo.cid.toString(),uid:r.gatewayInfo.uid.toString(),csIp:r.gatewayInfo.csIp,unilbsServerIds:[yz.CHOOSE_SERVER].toString(),isHttp3:r.isHttp3})}function bG(e){return window.atob(window.localStorage.getItem(e)||"")}function bW(e,t){window.localStorage.setItem(e,window.btoa(t))}function bH(e){let t="".concat(e.appId,"_").concat(e.cname);return"string"==typeof e.uid&&(t+="_s_".concat(e.uid)),"number"==typeof e.uid&&(t+="_".concat(e.uid)),e.token&&(t+="_".concat(e.token)),gF(t)}function bK(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let bY=[];function bz(e,t){if(e.offset+t>e.limit)throw Error("Skip past limit");e.offset+=t}function bq(e,t){let i=e.bytes,r=e.offset,n=e.limit,o=r+t;if(o>i.length){let t=new Uint8Array(2*o);t.set(i),e.bytes=t}return e.offset=o,o>n&&(e.limit=o),r}function bX(e,t){let i=e.offset;if(i+t>e.limit)throw Error("Read past limit");return e.offset+=t,i}function bJ(e,t){let i=bq(e,t.length);e.bytes.set(t,i)}function bQ(e,t){let i=bX(e,t),r=String.fromCharCode,n=e.bytes,o="";for(let e=0;e<t;
1e++){let a,s,c,d,l=n[e+i];0==(128&l)?o+=r(l):192==(224&l)?e+1>=t||128!=(192&(a=n[e+i+1]))||(d=(31&l)<<6|63&a)<128?o+="�":(o+=r(d),e++):224==(240&l)?e+2>=t||32896!=(49344&((a=n[e+i+1])|(s=n[e+i+2])<<8))||(d=(15&l)<<12|(63&a)<<6|63&s)<2048||d>=55296&&d<=57343?o+="�":(o+=r(d),e+=2):240==(248&l)?e+3>=t?o+="�":(a=n[e+i+1],8421504!=(0xc0c0c0&(a|(s=n[e+i+2])<<8|(c=n[e+i+3])<<16))||(d=(7&l)<<18|(63&a)<<12|(63&s)<<6|63&c)<65536||d>1114111?o+="�":(d-=65536,o+=r(55296+(d>>10),56320+(1023&d)),e+=3)):o+="�"}return o}function bZ(e,t){let i=t.length,r=0;for(let e=0;e<i;e++){let n=t.charCodeAt(e);n>=55296&&n<=56319&&e+1<i&&(n=(n<<10)+t.charCodeAt(++e)-0x35fdc00),r+=n<128?1:n<2048?2:n<65536?3:4}b2(e,r);let n=bq(e,r),o=e.bytes;for(let e=0;e<i;e++){let r=t.charCodeAt(e);r>=55296&&r<=56319&&e+1<i&&(r=(r<<10)+t.charCodeAt(++e)-0x35fdc00),r<128?o[n++]=r:(r<2048?o[n++]=r>>6&31|192:(r<65536?o[n++]=r>>12&15|224:(o[n++]=r>>18&7|240,o[n++]=r>>12&63|128),o[n++]=r>>6&63|128),o[n++]=63&r|128)}}function b$(e){return e.bytes[bX(e,1)]}function b0(e,t){let i=bq(e,1);e.bytes[i]=t}function b1(e){let t,i=0,r=0;do t=b$(e),i<32&&(r|=(127&t)<<i),i+=7;while(128&t);return r}function b2(e,t){for(t>>>=0;t>=128;)b0(e,127&t|128),t>>>=7;b0(e,t)}function b3(e,t){let i=t.low>>>0,r=(t.low>>>28|t.high<<4)>>>0,n=t.high>>>24,o=0===n?0===r?i<16384?i<128?1:2:i<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10,a=bq(e,o),s=e.bytes;switch(o){case 10:s[a+9]=n>>>7&1;case 9:s[a+8]=9!==o?128|n:127&n;case 8:s[a+7]=8!==o?r>>>21|128:r>>>21&127;case 7:s[a+6]=7!==o?r>>>14|128:r>>>14&127;case 6:s[a+5]=6!==o?r>>>7|128:r>>>7&127;
1case 5:s[a+4]=5!==o?128|r:127&r;case 4:s[a+3]=4!==o?i>>>21|128:i>>>21&127;case 3:s[a+2]=3!==o?i>>>14|128:i>>>14&127;case 2:s[a+1]=2!==o?i>>>7|128:i>>>7&127;case 1:s[a]=1!==o?128|i:127&i}}let b5={},b4={},b6=0xffffffffffffffff/2,b8=Oi(0,!0),b9=Oi(0),b7=Or(0,-0x80000000,!1),Oe=Or(-1,0x7fffffff,!1),Ot=Or(-1,-1,!0);function Oi(e,t){let i,r,n;return t?(n=0<=(e>>>=0)&&e<256)&&(r=b4[e])?r:(i=Or(e,0,!0),n&&(b4[e]=i),i):(n=-128<=(e|=0)&&e<128)&&(r=b5[e])?r:(i=Or(e,e<0?-1:0,!1),n&&(b5[e]=i),i)}function Or(e,t,i){return{low:0|e,high:0|t,unsigned:!!i}}function On(e,t){if(isNaN(e))return t?b8:b9;if(t){if(e<0)return b8;if(e>=0xffffffffffffffff)return Ot}else{if(e<=-b6)return b7;if(e+1>=b6)return Oe}return e<0?t?b8:b9:Or(e%0x100000000|0,e/0x100000000|0,t)}function Oo(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}class Oa extends S0{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;let t=this._connectionState;this._connectionState=e,this.emit(yC.CONNECTION_STATE_CHANGE,e,t)}get quality(){return this._quality}set quality(e){this._quality=e>1?1:e<.1?.1:e,this._qualityTimer&&(window.clearTimeout(this._qualityTimer),this._qualityTimer=null),this._quality>=1||(this._qualityTimer=window.setTimeout(()=>{this.quality=this._quality/this._qualityRatio},6e4))}async init(e,t){this.emit(yC.STATE_CHANGE,yv.CONNECT_AP),this._connectInfo=e;let i=this._cancelTokenSource.token;return this._retryConfig=t,new dQ((r,n)=>{this.on(yC.CONNECTION_STATE_CHANGE,(e,t)=>{e===yR.CONNECTED&&r()}),this.requestAP(e,i,t).then(e=>{this.connectWorker(e)}).catch(e=>{n(e)})})}updateConfig(e){var t;this._moderationInterval=null!=(t=e.interval)?t:1e3,e.extraInfo&&(this._extraInfo=this._encoder.encode(e.extraInfo)),e.vendor&&(this._vendor=e.vendor),TY.debug("[".concat(this._moderationId,"] updateConfig: ").concat(JSON.stringify(e))),this.connectionState===yR.CONNECTED&&this.inspectImage()}async requestAP(e,t,i){let r=TR("WEBCS_DOMAIN").map(e=>"https://".concat(e,"/api/v1")),n=await function(e,t,i,r){let{appId:n,areaCode:o,cname:a,sid:s,token:c,uid:d}=t,l="moderation_plugin",h={service_name:l,json_body:JSON.stringify({appId:n,areaCode:o,cname:a,command:"allocateEdge",requestId:++At,seq:At,sid:s,appToken:c,ts:Date.now(),uid:d+""})},u,p,_=e[0];return gY(async()=>{u=Date.now();let e=await Iz(_,{data:h,cancelToken:i,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(p=Date.now()-u,0!==e.code){let t=new T0(SU.UNEXPECTED_RESPONSE,"moderation plugin ap error, code"+e.code,{retry:!0,responseTime:p});throw TY.error(t.toString()),t}let t=JSON.parse(e.json_body);if(200!==t.code){let e=new T0(SU.UNEXPECTED_RESPONSE,"moderation plugin ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw TY.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){let e=new T0(SU.UNEXPECTED_RESPONSE,"moderation plugin ap empty server",{code:t.code,responseTime:p});throw TY.error(e.toString()),e}if(!t.servers.some(e=>!!e.wss)){let e=new T0(SU.UNEXPECTED_RESPONSE,"moderation plugin ap empty port",{code:t.code,responseTime:p});throw TY.error(e.toString()),e}let r=TR("IMAGE_MODERATION_WORKER_WSS");if(r)return{addressList:[r],workerToken:t.workerToken,vid:t.vid,responseTime:p};let n=TR("IMAGE_MODERATION_WORKER_HOST");return{addressList:t.servers.map(e=>{let{address:t,wss:i}=e;if(t&&i)return"wss://".concat(t.replace(/\./g,"-"),".").concat(n,":").concat(i,"/moderation")}).filter(e=>!!e),workerToken:t.workerToken,vid:t.vid,ticket:t.appTicket,responseTime:p}},(t,i)=>(T$.apworkerEvent(s,{success:!0,sc:200,serviceName:l,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===i,responseTime:p,serverIp:e[i%e.length]}),!1),(t,i)=>(T$.apworkerEvent(s,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[i%e.length]}),!!(t.code!==SU.OPERATION_ABORTED&&t.code!==SU.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(i+1)%e.length],!0)),r)}(r,e,t,i);
1this.emit(yC.STATE_CHANGE,yv.AP_CONNECTED);let{addressList:o,ticket:a}=n;return this._ticket=a,o}async connectWorker(e){this.emit(yC.STATE_CHANGE,yv.CONNECT_WORKER),await this._workerConnection.init(e,1e4)}handleWorkerEvents(){this._workerConnection.on(vH.CONNECTED,async()=>{this.emit(yC.STATE_CHANGE,yv.WORKER_CONNECTED,this._workerConnection.url),this.connectionState=yR.CONNECTED}),this._workerConnection.on(vH.CLOSED,()=>{this.connectionState=yR.CLOSED}),this._workerConnection.on(vH.FAILED,()=>{this.connectionState=yR.CLOSED}),this._workerConnection.on(vH.RECONNECTING,()=>{this.connectionState=this.connectionState===yR.CONNECTED?yR.RECONNECTING:yR.CONNECTING}),this._workerConnection.on(vH.ON_MESSAGE,async e=>{if(e.data instanceof ArrayBuffer){let t=function(e){var t,i={bytes:e,offset:0,limit:e.length};let r={};e:{for(;!((t=i).offset>=t.limit);){let e=b1(i);switch(e>>>3){case 0:break e;case 1:r.code=b1(i);break;case 2:r.msg=bQ(i,b1(i));break;case 3:r.requestId=bQ(i,b1(i));break;case 4:r.timestamp=function(e,t){let i,r=0,n=0,o=0;return r=127&(i=b$(e)),128&i&&(r|=(127&(i=b$(e)))<<7,128&i&&(r|=(127&(i=b$(e)))<<14,128&i&&(r|=(127&(i=b$(e)))<<21,128&i&&(n=127&(i=b$(e)),128&i&&(n|=(127&(i=b$(e)))<<7,128&i&&(n|=(127&(i=b$(e)))<<14,128&i&&(n|=(127&(i=b$(e)))<<21,128&i&&(o=127&(i=b$(e)),128&i&&(o|=(127&(i=b$(e)))<<7))))))))),{low:r|n<<28,high:n>>>4|o<<24,unsigned:t}}(i,!1);break;default:var n=i,o=7&e;switch(o){case 0:for(;128&b$(n););break;case 2:bz(n,b1(n));break;case 5:bz(n,4);break;case 1:bz(n,8);break;default:throw Error("Unimplemented type: "+o)}}}}return r}(new Uint8Array(e.data));TR("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&TY.debug("[".concat(this._moderationId,"] Response message for worker of image moderation "),JSON.stringify(t)),this._uploadNum++,void 0===t.code||0===t.code||(this._uploadFailedNum++,TY.error("[".concat(this._moderationId,"] Error response from worke, code is ").concat(t.code,", msg is ").concat(t.msg)),this._uploadTimer||(this._uploadTimer=window.setTimeout(()=>{T$.reportApiInvoke(this._connectInfo.sid||null,{name:S3.IMAGE_MODERATION_UPLOAD,options:[this._uploadFailedNum,this._uploadNum,t.code],tag:S5.TRACER}).onError(new T0(SU.IMAGE_MODERATION_UPLOAD_FAILED,t.msg)),this._uploadTimer=null},TR("IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL"))))}else TY.error("[".concat(this._moderationId,"] Unexpected message type from worker"))}),this._workerConnection.on(vH.WILL_RECONNECT,(e,t,i)=>{"recover"===e&&i(e),i("tryNext")}),this._workerConnection.on(vH.REQUEST_NEW_URLS,(e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)})}static intToLong(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}async requestToInspectImage(){let e=gd(this,yC.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void(TR("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&TY.debug("Only the track being played can be inspected"));this._sequence++;let i=await this.generateRequestData(e,t);this._workerConnection.sendMessage(i,!0,!0)}else TR("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&TY.debug("Only the track being published can be inspected")}async generateRequestData(e,t){let i,r,n,o,a,s,c,d,l,h,u,p,_,E,m,f,S,g,T,R,C,v,y,I,A,{appId:b,cname:O,cid:w,vid:N,sid:D,uid:P}=t,L=Date.now(),k=await e.getCurrentFrameImage("image/jpeg",this.quality),M=await Cg(k,b,O),U=this._sequence+"-"+w+"-"+P+"-"+L+"-"+gw(12,""),x={appId:b,cid:w,cname:O,deviceId:"",elapse:Oa.intToLong(Number(L-this._moderationStartTime)),fileSize:k.buffer.byteLength,height:k.height,width:k.width,jpg:M,networkType:6,osType:7,requestId:U,sdkVersion:"4.24.2",sequence:this._sequence,sid:D,timestamp:On(L),uid:P,vid:N,service:this._moderationMode,ticket:this._ticket,callbackData:this._extraInfo,vendorConfigs:this._vendor};void 0===this._extraInfo&&delete x.callbackData;let V=(i=function(){let e=bY.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}
1(),void 0!==(r=x.appId)&&(b2(i,10),bZ(i,r)),void 0!==(n=x.cid)&&(b2(i,16),b2(i,n)),void 0!==(o=x.cname)&&(b2(i,26),bZ(i,o)),void 0!==(a=x.deviceId)&&(b2(i,34),bZ(i,a)),void 0!==(s=x.elapse)&&(b2(i,40),b3(i,s)),void 0!==(c=x.fileSize)&&(b2(i,48),b3(i,bK(c))),void 0!==(d=x.height)&&(b2(i,56),b3(i,bK(d))),void 0!==(l=x.jpg)&&(b2(i,66),b2(i,l.length),bJ(i,l)),void 0!==(h=x.networkType)&&(b2(i,72),b3(i,bK(h))),void 0!==(u=x.osType)&&(b2(i,80),b3(i,bK(u))),void 0!==(p=x.requestId)&&(b2(i,90),bZ(i,p)),void 0!==(_=x.sdkVersion)&&(b2(i,98),bZ(i,_)),void 0!==(E=x.sequence)&&(b2(i,104),b3(i,bK(E))),void 0!==(m=x.sid)&&(b2(i,114),bZ(i,m)),void 0!==(f=x.timestamp)&&(b2(i,120),b3(i,f)),void 0!==(S=x.uid)&&(b2(i,128),b2(i,S)),void 0!==(g=x.vid)&&(b2(i,136),b2(i,g)),void 0!==(T=x.width)&&(b2(i,144),b3(i,bK(T))),void 0!==(R=x.service)&&(b2(i,152),b2(i,R)),void 0!==(C=x.callbackData)&&(b2(i,162),b2(i,C.length),bJ(i,C)),void 0!==(v=x.ticket)&&(b2(i,170),bZ(i,v)),void 0!==(y=x.vendorConfigs)&&(b2(i,178),bZ(i,y)),I=i.bytes,A=i.limit,I.length===A?I:I.subarray(0,A));if(V.byteLength<this._workerMessageLengthLimit){if(TR("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")){let e=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Oo(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Oo(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}({},x);delete e.jpg,TY.debug("[".concat(this._moderationId,"] Request message for worker of image moderation service: "),JSON.stringify(e))}return V}
1{let t=this.quality*this._qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:b,cname:O,cid:w,vid:N,sid:D,uid:P})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=f0.CancelToken.source(),this._workerConnection&&this._workerConnection.close(),this._moderationTimer&&window.clearInterval(this._moderationTimer),this._moderationTimer=null,this._uploadTimer&&window.clearTimeout(this._uploadTimer),this._uploadTimer=null,this.connectionState=yR.CLOSED,this.emit(yC.STATE_CHANGE,yv.CLOSED)}constructor(e){var t;super(),mb(this,"name","AgoraRTCImageModeration"),mb(this,"_connectionState",yR.CONNECTING),mb(this,"_sequence",0),mb(this,"_moderationStartTime",void 0),mb(this,"_workerConnection",void 0),mb(this,"_workerMessageLengthLimit",void 0),mb(this,"_qualityRatio",void 0),mb(this,"_connectInfo",void 0),mb(this,"_cancelTokenSource",f0.CancelToken.source()),mb(this,"_retryConfig",void 0),mb(this,"_moderationInterval",void 0),mb(this,"_moderationTimer",null),mb(this,"_moderationMode",1),mb(this,"_quality",1),mb(this,"_qualityTimer",null),mb(this,"_ticket",void 0),mb(this,"_moderationIntervalMinimum",void 0),mb(this,"_uploadFailedNum",0),mb(this,"_uploadNum",0),mb(this,"_uploadTimer",null),mb(this,"_extraInfo",void 0),mb(this,"_vendor",""),mb(this,"_encoder",new TextEncoder),mb(this,"_moderationId",void 0),mb(this,"inspectImage",()=>{if(this.connectionState!==yR.CONNECTED)throw new T0(SU.OPERATION_ABORTED,"image moderation service connection status is ".concat(this.connectionState));this._moderationTimer&&(window.clearInterval(this._moderationTimer),this._moderationTimer=null),this._moderationTimer=window.setInterval(()=>{this.connectionState===yR.CONNECTED?this.requestToInspectImage():TY.debug("[".concat(this._moderationId,"] Moderation State is not connected , "),this.connectionState)},this._moderationInterval<this._moderationIntervalMinimum?this._moderationIntervalMinimum:this._moderationInterval),this.requestToInspectImage()}),this._moderationId=gw(5,"image-moderation-"),this._workerMessageLengthLimit=TR("IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT"),this._moderationIntervalMinimum=TR("IMAGE_MODERATION_INTERVAL_MINIMUM"),this._moderationInterval=null!=(t=e.interval)?t:1e3,e.extraInfo&&(this._extraInfo=this._encoder.encode(e.extraInfo)),e.vendor&&(this._vendor=e.vendor),this._qualityRatio=TR("IMAGE_MODERATION_QUALITY_RATIO"),this._moderationStartTime=Number(Date.now()),this._workerConnection=new yH("worker-"+this._moderationId,gH),this.on(yC.STATE_CHANGE,(e,t)=>{TY.debug("[".concat(this._moderationId,"] Moderation operation :").concat(yv[e]," ").concat(t||""))}),this.handleWorkerEvents()}}function Os(e){if(SB(e.interval,"interval",1e3,1/0),e&&e.extraInfo&&e.extraInfo.length>1024)throw new T0(SU.INVALID_PARAMS,"config.extraInfo length cannot exceed 1024 bytes");if(e&&e.vendor&&e.vendor.length>1024)throw new T0(SU.INVALID_PARAMS,"config.vendor length cannot exceed 1024 bytes")}function Oc(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function Od(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Oc(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Oc(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}gG.setLogger(TY);let Ol=(iK=TZ(),iY=TZ({argsMap:(e,t)=>{if(!Array.isArray(t)){if(!(t instanceof RG))return[t];t=[t]}return t.map(e=>e?Object(e).toString():"null")}}),iz=TZ({argsMap:(e,t)=>(t||(t=[]),Array.isArray(t)||t.trackMediaType!==RC.DATA?(Array.isArray(t)||(t=[t]),t.map(e=>e.getTrackId())):[t.getChannelId()])}),iq=TZ({argsMap:(e,t,i,r)=>["object"==typeof t?t.uid:t,i,r]}),iX=TZ({argsMap:(e,t,i)=>[t,i]}),iJ=TZ({argsMap:(e,t)=>t.map(e=>{let{user:t,mediaType:i}=e;return[null==t?void 0:t.uid,i]})}),iQ=TZ({argsMap:(e,t,i,r)=>["object"==typeof t?t.uid:t,i,r]}),iZ=TZ({argsMap:(e,t)=>t.map(e=>{let{user:t,mediaType:i}=e;return{uid:null==t?void 0:t.uid,mediaType:i}})}),i$=TZ(),i0=TZ(),i1=TZ(),i2=TZ(),i3=TZ(),i5=TZ(),i4=TZ(),i6=TZ(),i8=TZ(),i9=TZ(),i7=TZ(),re=TZ(),rt=TZ(),ri=TZ(),rr=TZ(),rn=TZ(),ro=TZ({argsMap:(e,t)=>[t]}),ra=TZ(),rs=TZ(),rc=TZ(),rd=TZ(),rl=TZ(),rh=TZ(),ru=TZ(),rp=TZ(),r_=TZ({argsMap:(e,t)=>(Array.isArray(t)||(t=[t]),[JSON.stringify(t)])}),rE=TZ(),rm=TZ(),rf=TZ(),rS=TZ(),rg=TZ(),rT=TZ(),rR=TZ({reportResult:!0}),rC=TZ(),vP((rv=class extends S0{get connectionState(){return this._gateway.state}get remoteUsers(){return this._users}get localTracks(){return this._p2pChannel.getAllTracks(!0)}get uid(){return this._uid}get channelName(){return this._channelName}get localDataChannels(){return this._p2pChannel.getAllDataChannels()}get mode(){return this._config.mode}get role(){var e;return(null==(e=this._config)?void 0:e.role)||"audience"}get codec(){return this._config.codec}get audioCodec(){return this._config.audioCodec||"opus"}get isStringUID(){return!!this._joinInfo&&!!this._joinInfo.stringUid}get __className__(){return"Client"}async joinMeta(e,t,i,r,n){let o=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],a=arguments.length>6&&void 0!==arguments[6]&&arguments[6];TT("JOIN_GATEWAY_USE_443PORT_ONLY",o),TT("JOIN_GATEWAY_USE_DUAL_DOMAIN",a);let s=this._gateway.signal.websocket;return s instanceof yW&&(s.use443PortOnly=o,s.tryDoubleDomain=a),async function(e,t,i){f3.get(e)||f3.set(e,[]),f5.get(e)||f5.set(e,t),f4.get(e)||f4.set(e,0);let r=f3.get(e),n=f5.get(e);if(!r||!n)throw Error("concurrent: deferQueue or maxConcurrency is null");if(f4.get(e)===n){let e=f2();r.push(e),await e.promise}f4.set(e,f4.get(e)+1);for(var o=arguments.length,a=Array(o>3?o-3:0),s=3;s<o;s++)a[s-3]=arguments[s];let c=await i(...a);return f4.set(e,f4.get(e)-1),f4.get(e)===n-1&&r.length>0&&(r[0].resolve(),r.shift()),0===f4.get(e)&&(f3.set(e,[]),f5.set(e,0),f4.set(e,0)),c}("client.join",TR("JOIN_MAX_CONCURRENCY"),this.join.bind(this),e,t,i,r,n)}async join(e,t,i,r,n){var o;let a,s=++this._numberOfJoinCount;this.store.joinStart(),r&&(this.store.uid=r);let c="HTTPS"===(gz||gz||(gz=(window.location.protocol.split(":")[0]||"").toUpperCase())),d=void 0!==window.isSecureContext?window.isSecureContext:"Browser Not Support";(void 0!==window.isSecureContext||c)&&window.isSecureContext||TY.warning("The website must be running in a secure context (About secure context: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts ), otherwise the media collection will be restricted by the browser"),T$.setAppId(e);try{if(!i&&null!==i)throw new T0(SU.INVALID_PARAMS,"Invalid token: ".concat(i,". If you don not use token, set it to null"));if(i&&SG(i,"token",1,2047),SG(e,"appid",1,2047),vK(t),r&&vY(r),n)if("string"==typeof n)SG(n,"optionalInfo",1,256),a=n;else{if("object"!=typeof n)throw new T0(SU.INVALID_PARAMS,"Invalid options: options is not a string or object");{let{autoSubscribe:e,enableInstantMuteRestore:t,networkQualityProbe:i}=n;e&&(SV(e,"autoSubscribe"),TY.info("[".concat(this._clientId,"] join: autoSubscribe: ").concat(e)),this.store.autoSubscribe=e),t&&(SV(t,"enableInstantMuteRestore"),TY.info("[".concat(this._clientId,"] join: enableInstantMuteRestore: ").concat(t)),this.store.enableInstantMuteRestore=t),i&&(SV(i,"networkQualityProbe"),TY.info("[".concat(this._clientId,"] join: networkQualityProbe: ").concat(i)),this.store.networkQualityProbe=i)}}}catch(n){throw T$.reportApiInvoke(gN(),{name:S3.JOIN,options:[e,t,i,r],states:{isHttps:c,isSecureContext:d},tag:S5.TRACER}).onError(n),n}if(this._leaveMutex.isLocked&&(TY.debug("[".concat(this._clientId,"] join: waiting leave operation")),(await this._leaveMutex.lock())(),TY.debug("[".concat(this._clientId,"] join: continue"))),this._joinAndNotLeaveYet=!0,"DISCONNECTED"!==this.connectionState){let n=new T0(SU.INVALID_OPERATION,"[".concat(this._clientId,"] Client already in connecting/connected state"));throw T$.reportApiInvoke(gN(),{name:S3.JOIN,options:[e,t,i,r],states:{isHttps:c,isSecureContext:d},tag:S5.TRACER}).onError(n),n}this._gateway.state="CONNECTING",this.store.preloadStart();let l=await bU({appId:e,cname:t,uid:r,stringUid:"string"==typeof r?r:void 0,token:i||e,cloudProxyServer:this._cloudProxyServerMode});if(this.store.preloadEnd(),!this._joinAndNotLeaveYet)throw new T0(SU.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));let h=(null==l?void 0:l.sid)||gN();TY.info("[".concat(this._clientId,"] start join channel ").concat(t,", join number: ").concat(s)),this._sessionId||
1(this._sessionId=h,this.store.sessionId=this._sessionId);let u=T$.reportApiInvoke(this._sessionId,{id:this._clientId,name:S3.JOIN,options:[e,t,i,r],states:{isHttps:c,isSecureContext:d},tag:S5.TRACER}),p=Od(Od(Od({},this._rtmConfig),{},{role:this.role,clientId:this._clientId,appId:e,sid:this._sessionId,cname:t,uid:"string"!=typeof r?r:null,turnServer:this._turnServer,proxyServer:this._proxyServer,token:i||e,cloudProxyServer:this._cloudProxyServerMode,optionalInfo:a,license:this._license,useLocalAccessPoint:this._useLocalAccessPoint,preload:!!l},void 0!==this._remoteDefaultVideoStreamType&&{defaultVideoStream:this._remoteDefaultVideoStreamType}),{},{apRequestDetail:TR("AP_REQUEST_DETAIL")||void 0});if(this._useLocalAccessPoint&&(p.setLocalAPVersion=this._setLocalAPVersion),"string"==typeof r&&(p.stringUid=r,this._uintUid?(p.uid=this._uintUid,this._uintUid=void 0):p.uid=0),"none"!==this._encryptionMode&&this._encryptionSecret){if(p.aesmode=this._encryptionMode,p.aespassword=await (async e=>{let t=function(e){let t=window.atob("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCMnXAHkKIGAM+x4N22gCI+Wyu\nSTM9ztkT3uYslTT2PuKmZfPzhH6kVdO7PTjGCOZnAsyb3oTtWat0KcxQ4jxvqQV+\nHvYl3iI1Yd4vl2c3qRMJPLtRDfNxa2Mcxgq7e9aEUibzdd0st+OJAy3tOj/Y0aVy\nxQiYDz3vqa6bP29adwIDAQAB"),i=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)i[e]=t.charCodeAt(e);return i}(),i=await window.crypto.subtle.importKey("spki",t,{name:"RSA-OAEP",hash:"SHA-256"},!0,["encrypt"]),r=SQ(e);var n=new Uint8Array(await window.crypto.subtle.encrypt({name:"RSA-OAEP"},i,r));let o="";for(let e=0;e<n.length;e+=1)o+=String.fromCharCode(n[e]);return window.btoa(o)})(this._encryptionSecret),!this._joinAndNotLeaveYet)throw new T0(SU.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this._encryptionSalt&&(p.aessalt=this._encryptionSalt)}if(this._encryptDataStream&&("aes-128-gcm2"===this._encryptionMode||"aes-256-gcm2"===this._encryptionMode))if(this._encryptionSalt&&this._encryptionSecret)if(window.crypto.subtle){let e=new TextEncoder,t=TR("USE_PURE_ENCRYPTION_MASTER_KEY")?e.encode(p.appId+this._encryptionSecret+this._encryptionSecret):e.encode(p.appId+p.cname+this._encryptionSecret);this._encryptDataStreamIv=await async function(e,t,i){let r=await window.crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits","deriveKey"]),n="aes-128-gcm2"===e?128:256;return new Uint8Array(await window.crypto.subtle.deriveBits({name:"PBKDF2",iterations:1e3,hash:"SHA-256",salt:i},r,n+96)).subarray(n/8)}(this._encryptionMode,t,gC(this._encryptionSalt)),this._encryptDataStreamKey=await async function(e,t,i){let r=await window.crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits","deriveKey"]);return await window.crypto.subtle.deriveKey({name:"PBKDF2",iterations:1e3,hash:"SHA-256",salt:i},r,{name:"AES-GCM",length:"aes-128-gcm2"===e?128:256},!0,["encrypt","decrypt"])}(this._encryptionMode,t,gC(this._encryptionSalt))}else d?TY.warning("[".concat(this._clientId,"] encrypt datastream must be running in a secure context, fallback to plain data stream")):TY.warning("[".concat(this._clientId,"] current browser do not support WebCrypto ,fallback to plain data stream")),this._encryptDataStream=!1;else this._encryptDataStream=!1,TY.debug("[".concat(this._clientId,"] no salt / secret, cannot support encrypt data stream, fallback to plain data stream"));this._startSession(this._sessionId,{channel:t,appId:e,stringUid:p.stringUid});let _=this._sessionId;setTimeout(()=>{"CONNECTING"===this.connectionState&&_===this._sessionId&&T$.joinChannelTimeout(this._sessionId,5)},5e3);try{let r,n=p.cloudProxyServer;if(o5(o=["proxy3","proxy4","proxy5"]).call(o,n)){let e=TR("PROXY_SERVER_TYPE3");Array.isArray(e)?p.proxyServer=e[0]:p.proxyServer=e}if(T$.setProxyServer(p.proxyServer),TY.setProxyServer(p.proxyServer),this.store.requestAPStart(),l){if(TY.debug("[".concat(this._clientId,"] get serverInfo Success from Preload Cache ").concat(p.stringUid?", ".concat(p.stringUid," => ").concat(l.intUid):""," ")),p.stringUid&&!p.uid&&(p.uid=l.intUid),r={gatewayInfo:l.ap.gatewayInfo},TR("JOIN_WITH_FALLBACK_MEDIA_PROXY")&&"auto"===p.turnServer.mode)if(0===l.ap.proxyInfo.addresses.length)TY.warning("no edge services in a
1p response of proxy fallback, will not set proxy in iceServers");else{let e=(await y5(l.ap.proxyInfo,l.ap.gatewayInfo.uid)).map(e=>({turnServerURL:e.address,tcpport:e.tcpport||T_.tcpport,udpport:e.udpport||T_.udpport,username:e.username||T_.username,password:e.password||T_.password,forceturn:!1,security:!0}));p.turnServer={mode:"manual",servers:e}}bj(l,p.stringUid)}else{if(p.stringUid&&!p.uid){let e;[e,r]=await dQ.all([Ac(p.stringUid,p,this._axiosCancelSource.token,this._config.httpRetryConfig||gH,this.store).finally(()=>{this.store.requestSUAEnd()}),As(p,this._axiosCancelSource.token,this._config.httpRetryConfig||gH,!0,this.store).finally(()=>{this.store.requestAPEnd()})]),TY.debug("[".concat(this._clientId,"] getUserAccount Success ").concat(p.stringUid," => ").concat(e)),p.uid=e,r.gatewayInfo.uid=e,r.gatewayInfo.res.uid=e}else r=await As(p,this._axiosCancelSource.token,this._config.httpRetryConfig||gH,!0,this.store);if(!this._joinAndNotLeaveYet)throw new T0(SU.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"))}this.store.requestAPEnd(),setTimeout(()=>{this._configDistribute.startGetConfigDistribute(p,this._axiosCancelSource.token),this._configDistribute.on(yn.UPDATE_BITRATE_LIMIT,e=>{this._p2pChannel.updateBitrateLimit(e)}),this._configDistribute.on(yn.UPDATE_CLIENT_ROLE_OPTIONS,e=>{this._setClientRoleOptions(e)}),this._configDistribute.on(yn.UPDATE_REMOTE_VIDEO_STREAM_TYPE,e=>{var t;o5(t=[0,1,4,5,6,7,8,9]).call(t,e)&&(this.remoteUsers.forEach(t=>{this._remoteStreamTypeCacheMap.get(t.uid)!==e&&this.setRemoteVideoStreamType(t.uid,e)}),this.setRemoteDefaultVideoStreamType(e))}),this._configDistribute.on(yn.FALLBACK_TO_HLS,e=>{e&&this.safeEmit(gi.FALLBACK_TO_HLS,gr.CONFIG)}),this._configDistribute.on(yn.UPDATE_VOS_CONFIGURE,e=>{this._gateway.setConfigure(e).catch(e=>{TY.debug("[".concat(this._clientId,"] auto set vos config failed"),e)})})},0),this._key=i||e;let a=r.gatewayInfo,s=p.uid?p.uid:a.uid;this._joinInfo=Od(Od({},p),{},{cid:a.cid,uid:s,vid:a.vid,apResponse:a.res,apGatewayAddress:a.apGatewayAddress,uni_lbs_ip:a.uni_lbs_ip,gatewayAddrs:a.gatewayAddrs}),this.store.intUid=s,this.store.cid=a.cid;let c=await this._joinGateway();if(!this._joinAndNotLeaveYet)throw new T0(SU.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));u.onSuccess(c),this._appId=e,this._channelName=p.cname,this._uid=c,this.store.uid=c,setTimeout(()=>{this._networkQualityInterval&&window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=window.setInterval(this._handleUpdateNetworkQuality,2e3),!Ss()&&this.store.useDcSignal?(window.addEventListener("beforeunload",this._handleBeforeUnload),window.addEventListener("pagehide",this._handleBeforeUnload)):window.addEventListener(Ss()?"beforeunload":"pagehide",this._handleBeforeUnload),this._statsCollector.startUpdateStats()},0);let d=p.stringUid?"string uid: ".concat(p.stringUid,",uid: ").concat(p.uid):"uid: ".concat(this._uid);return TY.info("[".concat(this._clientId,"] Joining channel success: channel: ").concat(t,",").concat(d)),setTimeout(()=>{TY.startUpload()},5e3),this.store.joinEnd(),o5(vu).call(vu,this)||vu.push(this),"disabled"===this._cloudProxyServerMode&&T1.supportWebCrypto&&TR("ENABLE_PRELOAD")&&bF(this._joinInfo),this._rteDetailInterval&&(window.clearInterval(this._rteDetailInterval),this._rteDetailInterval=void 0),this._sessionId&&T$.reportRteDetail(this._sessionId),this._rteDetailInterval=window.setInterval(()=>{this._sessionId&&T$.reportRteDetail(this._sessionId)},TR("RTE_DETAIL_REPORT_INTERVAL")||6e4),c}catch(t){let e=Array.isArray(t)?t[0]:t;throw e&&e.code===SU.OPERATION_ABORTED?TY.warning("[".concat(this._clientId,"] join number: ").concat(s,", Joining channel failed, rollback"),e):TY.error("[".concat(this._clientId,"] join number: ").concat(s,", Joining channel failed, rollback"),e),e.code!==SU.OPERATION_ABORTED&&this._numberOfJoinCount===s&&(this._gateway.state="DISCONNECTED",this._reset()),u.onError(e),e}}async _joinGateway(){if(!this._joinInfo||!this._key)throw new T0(SU.INVALID_OPERATION);try{return await this._gateway.join(this._joinInfo,this._key,!("disabled"!==this._joinInfo.cloudProxyServer||this._joinInfo.proxyServer||!TR("JOIN_WITH_FALLBACK_SIGNAL_PROXY")))}catch(e){if(e.code===SU.INIT_DATACHANNEL_TIMEOUT){if(this._gateway.leave(!0,S8.FALLBACK),TY.debug("[".concat(this._clientId,"] join by datachannel timeout, fallback to websocket")),!this._joinInfo||!this._key)throw new T0(SU.INVALID_OPERATION);return T$.reportApiInvoke(this._sessionId,{name:S3.DATACHANNEL_FAILBACK,options:[this.store.clientId],tag:S5.TRACER}).onSuccess(),await this._joinGateway()}throw e}}async leave(){TY.info("[".concat(this._clientId,"] Leaving channel"));let e=()=>{!Ss()&&this.store.useDcSignal?(window.addEventListener("beforeunload",this._handleBeforeUnload),window.addEventListener("pagehide",this._handleBeforeUnload)):window.addEventListener(Ss()?"beforeunload":"pagehide",this._handleBeforeUnload),this._reset(),function(e){let t=vu.indexOf(e);-1!==t&&vu.splice(t,1)}(this),this._statsCollector.stopUpdateStats()};this.store.useDcSignal||e();let t=await this._leaveMutex.lock();if("DISCONNECTED"===this.connectionState)return TY.info("[".concat(this._clientId,"] Leaving channel repeated, success")),void t();await this._gateway.leave("CONNECTED"!==this.connectionState,S8.LEAVE),TY.info("[".concat(this._clientId,"] Leaving channel success")),this._joinAndNotLeaveYet=!1,this.store.resetJoinChannelServiceRecords(),t(),this.store.useDcSignal&&e()}async publish(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!Array.isArray(e)){if(!(e instanceof RG))return this._publishDataChannel
1(e);e=[e]}if(0===e.length)throw new T0(SU.INVALID_PARAMS,"param list is empty");let i=e;if("audience"===this._gateway.role)throw new T0(SU.INVALID_OPERATION,"audience can not publish stream");for(let e of i){if(!(e instanceof RG))throw new T0(SU.INVALID_PARAMS,"parameter is not local track");if(!e._enabled&&t)throw new T0(SU.TRACK_IS_DISABLED,"can not publish a disabled track: ".concat(e.getTrackId()))}TY.info("[".concat(this._clientId,"] Publishing tracks, id ").concat(i.map(e=>"".concat(e.getTrackId()," "))));let r=await this._publishMutex.lock();await this._configDistribute.awaitConfigDistributeComplete(),t&&i.forEach(e=>{let t=this._configDistribute.getBitrateLimit();e instanceof CP&&t&&e.setBitrateLimit(t.uplink)});try{await this._publishHighStream(i),TY.info("[".concat(this._clientId,"] Publish success, id ").concat(i.map(e=>"".concat(e.getTrackId()," "))))}catch(e){throw TY.error("[".concat(this._clientId,"] publish error"),e.toString()),e}finally{r()}}async _publishDataChannel(e){if(null==e)throw new T0(SU.INVALID_PARAMS,"parameter is not local track or datachannel config, config is ".concat(JSON.stringify(e)));SB(e.id,"id",0,65535,!0),SV(e.ordered,"ordered"),SG(e.metadata,"metadata",0,512),TY.info("[".concat(this._clientId,"] Publishing datachannels, id ").concat(e.id));let t=await this._publishMutex.lock();try{if(-1!==this._p2pChannel.getAllDataChannels().findIndex(t=>t.id===e.id))throw new T0(SU.INVALID_PARAMS,"Invalid id: ".concat(e.id,". If you want to republish the datachannel, unpublish first"));if(!this._joinInfo||void 0===this._uid)throw new T0(SU.INVALID_OPERATION,"Can't publish datachannel, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new T0(SU.INVALID_OPERATION,"can not publish datachannel in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&TR("FORCE_TURN")&&!TR("TURN_ENABLE_TCP")&&!TR("TURN_ENABLE_UDP"))throw new T0(SU.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");let t=IF(e,!1),i=await this._p2pChannel.publishDataChannel([t]);if(i.length>0){if("number"!=typeof t._originDataChannelId)throw TY.error("[".concat(this._clientId,"] can not publish with mediaType datachannel, cannot get RTCDatachannel id")),new T0(SU.CREATE_DATACHANNEL_ERROR);try{await dQ.all(i.map(e=>this._uid&&this._gateway.publishDataChannel(this._uid,e,!0))),await t._waitTillOpen()}catch(e){if(e.code!==SU.DISCONNECT_P2P)throw e}}return TY.info("[".concat(this._clientId,"] Publish dataChannels success, id ").concat(t.id)),t}catch(e){throw TY.error("[".concat(this._clientId,"] publish datachannels error"),e.toString()),e}finally{t()}}async unpublish(e){if(!this._joinInfo||void 0===this._uid)throw new T0(SU.INVALID_OPERATION,"Can't unpublish stream, haven't joined yet!");let t=[];if(e)if(Array.isArray(e))t=e;else{if(!(e instanceof RG))return this._unpublishDataChannel([e]);t=[e]}else this.store.useP2P||await this._unpublishDataChannel(),t=this._p2pChannel.getAllTracks(!0);TY.info("[".concat(this._clientId,"] Unpublish tracks, tracks ").concat(t.map(e=>"".concat(e.getTrackId()," "))," "));let i=await this._publishMutex.lock();try{if(this.store.useP2P){let e=await this._p2pChannel.unpublish(t);e&&await this._gateway.sendExtensionMessage(yy.UNPUBLISH,{unpubMsg:e},!0)}else{let e=await this._p2pChannel.unpublish(t);e&&await this._gateway.unpublish(e,this._uid),TY.info("[".concat(this._clientId,"] Unpublish success,tracks ").concat(t.map(e=>"".concat(e.getTrackId()))))}}catch(e){throw TY.error("[".concat(this._clientId,"] unpublish error"),e.toString()),e}finally{i&&i()}}async _unpublishDataChannel(e){void 0!==e&&0!==e.length||(e=this._p2pChannel.getAllDataChannels()),TY.info("[".concat(this._clientId,"] Unpublish datachannels, datachannels ").concat(e.map(e=>"".concat(e.id," "))," "));let t=await this._publishMutex.lock();try{let t=await this._p2pChannel.unpublishDataChannel(e);t&&await this._gateway.unpublishDataChannel(t),TY.info("[".concat(this._clientId,"] Unpublish dataChannel success,dataChannel ").concat(e.map(e=>"".concat(e.id))))}catch(e){throw TY.error("[".concat(this._clientId,"] unpublish dataChannel error"),e.toString()),e}finally{t&&t()}}async subscribe(e,t,i){if(!(e instanceof AA)){let t=this.remoteUsers.find(t=>t.uid===e);if(!t)throw new T0(SU.INVALID_REMOTE_USER,"user is not in the channel");e=t}
1return"datachannel"===t?this._subscribeDataChannel(e,i):this._subscribe(e,t)}async presubscribe(e,t){if(SF(t,"mediaType",["audio","video"]),this.store.useP2P)throw new T0(SU.INVALID_OPERATION,"can't presub at p2p mode");if(!this._joinInfo)throw new T0(SU.INVALID_OPERATION,"can't presub when not join");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new T0(SU.INVALID_OPERATION,"can't presub in ".concat(this.connectionState," state"));let i=t===yc.AUDIO,r=t===yc.VIDEO,n=await this._subscribeMutex.lock();try{let{ssrcId:n,ortc:o,rtxSsrcId:a,cname:s,uint_id:c}=await this._gateway.presubscribe(e,t,!0);if(null==n)throw new T0(SU.UNEXPECTED_RESPONSE,"no ssrc id");let d=this._users.find(t=>t.uid===e);d||((d=new AA(e,c||e))._is_pre_created=!0,this._users.push(d)),s&&(d._cname=s),d._uintid||(d._uintid=c||e),i&&(d._audioSSRC=n,d._audio_pre_subscribed=!0,o&&(d._audioOrtc=o)),r&&(d._videoSSRC=n,d._video_pre_subscribed=!0,o&&(d._videoOrtc=o),null!=a&&(d._rtxSsrcId=a)),TY.info("[".concat(this._clientId,"] presub succeed ssrc: ").concat(n)),await this._p2pChannel.subscribe(d,t,n,a,o);let l=i?d._audioTrack:d._videoTrack;if(!l)throw new T0(SU.UNEXPECTED_ERROR,"can not find remote track in user");return i&&(d._trust_audio_stream_added_state_=!0,d._audio_added_=!0),r&&(d._trust_video_stream_added_state_=!0,d._video_added_=!0),l}catch(t){throw TY.error("[".concat(this._clientId,"] presub user ").concat(e," error"),t),t}finally{n()}}async _subscribeDataChannel(e,t){var i,r;if(SB(t,"channelId",0,65535,!0),!this._joinInfo)throw new T0(SU.INVALID_OPERATION,"Can't subscribe datachannel, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new T0(SU.INVALID_OPERATION,"Can't subscribe datachannel in ".concat(this.connectionState," state"));if(!this._users.find(t=>t===e))throw TY.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),new T0(SU.INVALID_REMOTE_USER,"user is not in the channel");if(!e.hasAudio&&!e.hasVideo&&0===e._dataChannels.length)throw TY.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),new T0(SU.INVALID_REMOTE_USER,"user is not published");let n=null==(i=e._dataChannels)?void 0:i.find(e=>e.id===t);if(!n)throw TY.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, remote datachannel is not published")),new T0(SU.REMOTE_USER_IS_NOT_PUBLISHED);let o=await this._subscribeMutex.lock();TY.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: datachannel"));try{let t=await this._p2pChannel.subscribeDataChannel(e,[n]);if(t&&o5(t).call(t,n.id))try{if("number"!=typeof n._originDataChannelId)throw TY.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, cannot get RTCDatachannel")),new T0(SU.CREATE_DATACHANNEL_ERROR);let t={id:n.id,datachannelId:n._originDataChannelId,ordered:n.ordered,maxRetransmits:n.maxRetransmits,metadata:null!=(r=n.metadata)?r:""};await this._gateway.subscribeDataChannel(e.uid,t,!0),await n._waitTillOpen()}catch(t){if((null==t?void 0:t.code)!==SU.WS_ABORT)throw await this._p2pChannel.unsubscribeDataChannel(e,[n]),t;await this._p2pChannel.unsubscribeDataChannel(e,[n]),this._p2pChannel.setPendingRemoteDataChannel(e,n.id)}return TY.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: datachannel")),n}finally{o()}}async _p2pSubscribe(e,t,i){if(SF(t,"mediaType",["audio","video"]),!this._joinInfo)throw new T0(SU.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new T0(SU.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));if(!this._users.find(t=>t===e)){let t=new T0(SU.INVALID_REMOTE_USER,"user is not in the channel");throw TY.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),t}if(!e.hasAudio&&!e.hasVideo){let t=new T0(SU.INVALID_REMOTE_USER,"user is not published");throw TY.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),t}if(!i&&("audio"===t&&!e.hasAudio||"video"===t&&!e.hasVideo)){let i=new T0(SU.REMOTE_USER_IS_NOT_PUBLISHED);throw TY.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),i}let r=await this._subscribeMutex.lock();TY.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: ").concat(t));try{if(await this._p2pChannel.hasRemoteMediaWithLock(e,t))await this._p2pChannel.unmuteRemote(e,t);else try{let i="audio"===t?e._audioSSRC:e._videoSSRC,r="audio"===t?e._audioMid:e._videoMid;this.store.subscribe(e.uid,t,Date.now()),this.store.useP2P&&await this._p2pChannel.subscribe(e,t,i,r)}catch(e){throw e}TY.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),void 0!==this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch(e=>{TY.warning("[".concat(this._clientId,"] auto set fallback failed"),e)});let i="audio"===t?e._audioTrack:e._videoTrack;if(!i)throw new T0(SU.UNEXPECTED_ERROR,"can not find remote track in user object");return i}catch(t){throw TY.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{r()}}async _subscribe(e,t,i){if(this.store.useP2P)return this._p2pSubscribe(e,t);if(SF(t,"mediaType",["audio","video"]),!this._joinInfo)throw new T0(SU.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new T0(SU.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));if(!this._users.find(t=>t===e)){let t=new T0(SU.INVALID_REMOTE_USER,"user is not in the channel");throw TY.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),t}if(!e.hasAudio&&!e.hasVideo){let t=new T0(SU.INVALID_REMOTE_USER,"user is not published");throw TY.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),t}if(!(i||("audio"!==t||e.hasAudio&&void 0!==e._audioSSRC)&&("video"!==t||e.hasVideo&&void 0!==e._videoSSRC))){let i=new T0(SU.REMOTE_USER_IS_NOT_PUBLISHED);throw TY.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),i}let r="audio"===t?e._audioSSRC:e._videoSSRC,n="audio"===t?e._audioOrtc:e._videoOrtc,o="video"===t?e._rtxSsrcId:void 0,a={stream_type:"audio"===t?yc.AUDIO:yc.VIDEO,ssrcId:r};"video"===t&&this.store.firstVideoFrameDecoded(e.uid,{subscribeStart:Date.now()});let s=await this._subscribeMutex.lock();TY.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: ").concat(t));try{if(await this._p2pChannel.hasRemoteMediaWithLock(e,t))await this._p2pChannel.unmuteRemote(e,t);else try{let i="audio"===t?e._audioSSRC:e._videoSSRC;void 0!==i&&i!==r&&(r=i,n="audio"===t?e._audioOrtc:e._videoOrtc,o="video"===t?e._rtxSsrcId:void 0,a={stream_type:"audio"===t?yc.AUDIO:yc.VIDEO,ssrcId:r}),AT.markSubscribeStart(this.store.clientId,r),this.store.subscribe(e.uid,t,Date.now()),await this._p2pChannel.subscribe(e,t,r,o,n);try{this._p2pChannel.isPreSubScribe(r)||await this._gateway.subscribe(e.uid,a,!0)}catch(i){if((null==i?void 0:i.code)!==SU.WS_ABORT)throw await this._p2pChannel.unsubscribe(e,t),i;await this._p2pChannel.unsubscribe(e,t,!0),this._p2pChannel.setPendingRemoteMedia(e,t)}this.store.subscribe(e.uid,t,void 0,Date.now()),this._p2pChannel.reportSubscribeEvent(!0,null,e,t)}catch(i){throw this._p2pChannel.reportSubscribeEvent(!1,null==i?void 0:i.code,e,t),i}TY.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),void 0!==this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch(e=>{TY.warning("[".concat(this._clientId,"] auto set fallback failed"),e)});let i="audio"===t?e._audioTrack:e._videoTrack;if(!i)throw new T0(SU.UNEXPECTED_ERROR,"can not find remote track in user object");return"video"===t&&(this.store.firstVideoFrameDecoded(e.uid,{subscribeEnd:Date.now()}),this._p2pChannel.reportVideoFirstFrameRender(e)),i}catch(t){throw TY.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{s()}}async massSubscribe(e){if(SW(e,"subscribeList"),!this._joinInfo)throw new T0(SU.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new T0(SU.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));let t=Date.now(),i=new Map,r=await this._subscribeMutex.lock();TY.info("[".concat(this._clientId,"]start massSubscribe user ").concat(e.map(e=>{let{user:t,mediaType:i}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i)}).join("; ")));let n=(e=[...e]).map(e=>{let{user:t,mediaType:i}=e;return{user:t,mediaType:i}}),o=await this._p2pChannel.globalLock();try{var a;for(let t=e.length-1;t>=0;t--){let{user:r,mediaType:o}=e[t];if(SF(o,"mediaType",["audio","video"]),!r){let e=new T0(SU.INVALID_PARAMS,"user property does not exist in subscribeList item");throw TY.error("[".concat(this._clientId,"] user property does not exist in subscribeList item")),e}if(!this._users.find(e=>e===r)){let i=new T0(SU.INVALID_REMOTE_USER,"user is not in the channel");TY.error("[".concat(this._clientId,"] can not massSubscribe ").concat(r.uid,", this user is not in the channel")),n[t].error=i,e.splice(t,1);continue}if("audio"===o&&(!r.hasAudio||void 0===r._audioSSRC)||"video"===o&&(!r.hasVideo||void 0===r._videoSSRC)){let i=new T0(SU.REMOTE_USER_IS_NOT_PUBLISHED);TY.error("[".concat(this._clientId,"] can not subscribe ").concat(r.uid," with mediaType ").concat(o,", remote user is not published")),n[t].error=i,e.splice(t,1);continue}let a=v7.Video|v7.LwoVideo,s=i.get(r);if(s){if("video"===o?s&a:s&v7.Audio){e.splice(t,1),TY.warning("[".concat(this._clientId,"] repeat massSubscribe user:").concat(r.uid,", mediaType:").concat(o," twice"));continue}i.set(r,s|("video"===o?a:v7.Audio))}else i.set(r,"video"===o?a:v7.Audio)}for(let t=e.length-1;t>=0;t--){let{user:r,mediaType:n}=e[t],o=v7.Video|v7.LwoVideo;if(this._p2pChannel.hasRemoteMedia(r,n)){await this._p2pChannel.unmuteRemoteNoLock(r,n);let a=i.get(r);i.set(r,"video"===n?a^o:a^v7.Audio),e.splice(t,1)}}this.store.massSubscribe(e.map(e=>({userId:e.user.uid,type:e.mediaType})),t);let r=as(a=Array.from(i.entries())).call(a,(e,t)=>{let[i,r]=t;if(0===r)return e;let n={stream_id:i.uid,stream_type:r};return r&v7.Audio&&(n.audio_ssrc=i._audioSSRC),r&v7.Video&&(n.video_ssrc=i._videoSSRC),e.push(n),e},[]);try{e.length>0&&await this._p2pChannel.massSubscribeNoLock(e.map(e=>{let{user:t,mediaType:i}=e;return{user:t,mediaType:i,ssrcId:i===yc.VIDEO?t._videoSSRC:t._audioSSRC,rtxSsrcId:i===yc.VIDEO?t._rtxSsrcId:void 0}}));let i=new Map;if((r=r.filter(e=>e.video_ssrc&&!this._p2pChannel.isPreSubScribe(e.video_ssrc)||e.audio_ssrc&&!this._p2pChannel.isPreSubScribe(e.audio_ssrc)||!e.video_ssrc&&!e.audio_ssrc)).length>0){let e=await this._gateway.subscribeAll(r,!0);
1((null==e?void 0:e.users)||[]).forEach(e=>{let{stream_id:t,video_error_code:r,audio_error_code:n,error_code:o}=e;(r||n||o)&&i.set(t,{video_error_code:r,audio_error_code:n,error_code:o})})}if(Array.from(i.entries()).length>0){let e=[];Array.from(i.entries()).forEach(t=>{let[i,r]=t,n=this.remoteUsers.find(e=>e.uid===i);if(n){let t;r.error_code||r.video_error_code&&r.audio_error_code?t=void 0:r.video_error_code?t=yc.VIDEO:r.audio_error_code&&(t=yc.AUDIO),e.push({user:n,mediaType:t})}}),e.length>0&&await this._p2pChannel.massUnsubscribeNoLock(e)}for(let e of n){let t=i.get(e.user.uid);if(t){let i=t.error_code||"audio"===e.mediaType&&t.audio_error_code||"video"===e.mediaType&&t.video_error_code;if(i){let t=yD(i);TY.error("user:".concat(e.user.uid," mediaType:").concat(e.mediaType," has massSubscribe error ").concat(t.desc)),e.error=new T0(SU.SUBSCRIBE_FAILED,"code ".concat(i,": ").concat(t.desc))}}e.error||("video"===e.mediaType?e.track=e.user.videoTrack:e.track=e.user.audioTrack)}return this.store.massSubscribe(n.filter(e=>!e.error).map(e=>({userId:e.user.uid,type:e.mediaType})),void 0,Date.now()),n.forEach(e=>{var i;T$.subscribe(this.store.sessionId,{succ:!!e.error,ec:(null==(i=e.error)?void 0:i.code)||null,video:e.mediaType===yc.VIDEO,audio:e.mediaType===yc.AU
1DIO,peerid:e.user.uid,subscribeRequestid:e.mediaType===yc.VIDEO?e.user._videoSSRC:e.user._audioSSRC,p2pid:this.store.p2pId,eventElapse:Math.floor(performance.now()-t),preSsrc:this._p2pChannel.isPreSubScribe(e.user._videoSSRC)},!0)}),TY.info("[".concat(this._clientId,"] massSubscribe success ").concat(e.map(e=>{let{user:t,mediaType:i}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i)}).join("; "))),n}catch(t){throw await this._p2pChannel.massUnsubscribeNoLock(e),t}}finally{o(),r()}}async unsubscribe(e,t,i){if(!(e instanceof AA)){let t=this.remoteUsers.find(t=>t.uid===e);if(!t)throw new T0(SU.INVALID_REMOTE_USER,"user is not in the channel");e=t}if(t||this.store.useP2P){if("datachannel"===t)return this._unsubscribeDataChannel(e,i)}else await this._unsubscribeDataChannel(e,i);if(t&&SF(t,"mediaType",["audio","video"]),!this._joinInfo)throw new T0(SU.INVALID_OPERATION,"Can't unsubscribe stream, haven't joined yet!");if(!this._users.find(t=>t===e)){let t=new T0(SU.INVALID_REMOTE_USER,"user is not in the channel");throw TY.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}TY.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: ").concat(t));let r=await this._subscribeMutex.lock();try{if(this.store.useP2P)await this._p2pChannel.unsubscribe(e,t);else{let i=await this._p2pChannel.unsubscribe(e,t);i&&await this._gateway.unsubscribe(i,e.uid),t&&"audio"!==t||(e._audio_pre_subscribed=!1),t&&"video"!==t||(e._video_pre_subscribed=!1),e._is_pre_created&&gE(this._users,e),TY.info("[".concat(this._clientId,"] unsubscribe success uid: ").concat(e.uid,", mediaType: ").concat(t))}}catch(t){if(t.code===SU.DISCONNECT_P2P)return void TY.warning("disconnecting p2p, abort unsubscribe request.");throw TY.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}finally{r()}}async _unsubscribeDataChannel(e,t){let i;if(t&&SB(t,"id",0,65535,!0),!this._joinInfo)throw new T0(SU.INVALID_OPERATION,"Can't unsubscribe datachannel, haven't joined yet!");if(!this._users.find(t=>t===e)){let t=new T0(SU.INVALID_REMOTE_USER,"user is not in the channel");throw TY.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}if("number"==typeof t){let r=e._dataChannels.find(e=>e.id===t);r&&(i=[r])}else i=e._dataChannels;if(void 0===i){let i=new T0(SU.REMOTE_USER_IS_NOT_PUBLISHED);throw TY.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid," with channelId ").concat(t,", remote datachannel is not published")),i}TY.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(i.map(e=>e.id)));try{let t=await this._p2pChannel.unsubscribeDataChannel(e,i);t&&await this._gateway.unsubscribeDataChannel(t,e.uid),TY.info("[".concat(this._clientId,"] unsubscribe datachannel success uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(t))}catch(t){if(t.code===SU.DISCONNECT_P2P)return void TY.warning("disconnecting p2p, abort unsubscribe request.");throw TY.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}}async massUnsubscribe(e){if(SW(e,"unsubscribeList"),!this._joinInfo)throw new T0(SU.INVALID_OPERATION,"Can't unsubscribeAll stream, haven't joined yet!");TY.info("[".concat(this._clientId,"] start massUnsubscribe ").concat(e.map(e=>{let{user:t,mediaType:i}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i,";")}).join())),e=[...e];let t=new Map;for(let i=e.length-1;i>=0;i--){let{user:r,mediaType:n}=e[i];if(!r){let e=new T0(SU.INVALID_PARAMS,"user property does not exist in unsubscribeList item");throw TY.error("[".concat(this._clientId,"] user property does not exist in unsubscribeList item")),e}if(SF(n,"mediaType",["video","audio",void 0]),!this._users.find(e=>e===r)){TY.warning("[".concat(this._clientId,"] can not unsubscribe ").concat(r.uid,", user is not in the channel")),e.splice(i,1);continue}let o=v7.Video|v7.LwoVideo;if(t.has(r)){let a,s=t.get(r);switch(n){case"video":a=s&o;break;case"audio":a=s&v7.Audio;break;default:a=s&(v7.Audio|o)}if(a){TY.warning("[".concat(this._clientId,"] repeat massUnsubscribe user:").concat(r.uid,",mediaType:").concat(n," twice.")),e.splice(i,1);continue}n?"audio"===n?t.set(r,s|v7.Audio):"video"===n&&t.set(r,s|o):t.set(r,s|v7.Audio|o)}else n?"audio"===n?t.set(r,v7.Audio):"video"===n&&t.set(r,o):t.set(r,v7.Audio|o)}try{let t=await this._p2pChannel.massUnsubscribe(e);t&&await this._gateway.massUnsubscribe(t),TY.info("[".concat(this._clientId,"] massUnsubscribe success ").concat(e.map(e=>{let{user:t,mediaType:i}=e;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(i,";")}).join()))}catch(e){if(e.code===SU.DISCONNECT_P2P)return void TY.warning("[".concat(this._clientId,"] disconnecting p2p, abort unsubscribe request."));throw TY.error("[".concat(this._clientId,"] massUnsubscribe error"),e.toString()),e}}async setLowStreamParameter(e){!function(e){if(!e)throw new Sx(SU.INVALID_PARAMS);SH(e.width)||Sj(e.width,"streamParameter.width"),SH(e.height)||Sj(e.height,"streamParameter.height"),SH(e.framerate)||Sj(e.framerate,"streamParameter.framerate"),SH(e.bitrate)||SB(e.bitrate,"streamParameter.bitrate")}(e),(!e.width&&e.height||e.width&&!e.height)&&TY.warning("[".concat(this._clientId,"] The width and height parameters take effect only when both are set")),TY.info("[".concat(this._clientId,"] set low stream parameter to"),JSON.stringify(e));let t=this._configDistribute.getLowStreamConfigDistribute();if(t&&t.bitrate&&e.bitrate&&t.bitrate<e.bitrate&&(e.bitrate=t.bitrate),this._lowStreamParameter=e,this._isDualStreamEnabled)return this._p2pChannel.updateVideoStreamParameter(e,yu.LocalVideoLowTrack)}async setDualStreamMode(e,t){SF(e,"mode",[0,1,-1]);try{switch(t&&await this.setLowStreamParameter(t),this._dualStreamMode=e,this._joinInfo?this._gateway.setDualStreamMode(e).catch(e=>{TY.warning("[".concat(this._clientId,"] set dual stream mode failed"),e.toString())}):TY.debug("[".concat(this._clientId,"] haven't joined yet, cache dual stream mode ").concat(e)),e){case ge.AUTO_SIMULCAST_STREAM:TY.info("[".concat(this._clientId,"] set dual stream mode to ").concat(e));break;case ge.DISABLE_SIMULCAST_STREM:return this.disableDualStream();case ge.ENABLE_SIMULCAST_STREAM:return this.enableDualStream()}}catch(e){throw TY.error("[".concat(this._clientId,"] set dual stream mode error"),e.toString()),e}}async enableDualStream(){if(!T1.supportDualStream)throw T$.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),new T0(SU.NOT_SUPPORTED,"Your browser is not support dual stream");if(this._isDualStreamEnabled)throw new T0(SU.INVALID_OPERATION,"Dual stream is already enabled");if(this._p2pChannel.canPublishLowStream())try{await this._publishLowStream()}catch(e){throw T$.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),e}this._isDualStreamEnabled=!0,this._dualStreamMode=ge.ENABLE_SIMULCAST_STREAM,this._joinInfo&&this._gateway.setDualStreamMode(this._dualStreamMode,!0,!0).catch(e=>{TY.debug("[".concat(this._clientId,"] try to inform gateway to set dual stream mode to ").concat(this._dualStreamMode," ,but failed"),e.toString())}),T$.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!0}),TY.info("[".concat(this._clientId,"] enable dual stream"))}async disableDualStream(){if(this._isDualStreamEnabled){if(!this._joinInfo)return this._isDualStreamEnabled=!1,void TY.info("[".concat(this._clientId,"] disable dual stream before join"));if(this._p2pChannel.getLocalMedia(yu.LocalVideoLowTrack))try{let e=await this._p2pChannel.unpublishLowStream();e&&await this._gateway.unpublish(e,this._joinInfo.stringUid||this._joinInfo.uid)}catch(e){throw T$.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!1}),e}this._isDualStreamEnabled=!1,this._dualStreamMode=ge.DISABLE_SIMULCAST_STREM,this._joinInfo&&this._gateway.setDualStreamMode(this._dualStreamMode,!0,!0).catch(e=>{TY.debug("[".concat(this._clientId,"] try to inform gateway to set dual stream mode to ").concat(this._dualStreamMode," ,but failed"),e.toString())}),T$.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!0}),TY.info("[".concat(this._clientId,"] disable dual stream"))}}
1async setClientRole(e,t){if(SF(e,"role",["audience","host"]),t&>(t),"rtc"===this.mode||"p2p"===this.mode)throw TY.warning("[".concat(this._clientId,"]").concat(this.mode," mode can not use setClientRole")),new T0(SU.INVALID_OPERATION,"".concat(this.mode," mode can not use setClientRole"));if(t&&t.level&&"host"===e)throw new T0(SU.INVALID_OPERATION,"host mode can not set audience latency level");if("audience"===e&&this._p2pChannel.hasLocalMedia())throw new T0(SU.INVALID_OPERATION,"can not set client role to audience when publishing stream");let i=this._config.role;if(this._joinInfo&&(this._joinInfo.role=e),e!==i&&TR("ENABLE_ROLE_SELECT_EDGE")?(this._gateway.updateClientRole(e,t),this._config.role=e,this._gateway.reconnect("recover",gn.REGIONAL_DISTRIBUTION)):(await this._gateway.setClientRole(e,t),this._config.role=e),TY.info("[".concat(this._clientId,"] set client role to ").concat(e,", level: ").concat(t&&t.level)),"audience"===i&&"audience"!==e&&this._pendingRtpCapabilityChange&&this._p2pChannel instanceof bh){let{video_codec:e}=this._pendingRtpCapabilityChange;this._p2pChannel.updateRemoteRTPCapabilities(e.map(e=>e.toLowerCase()).filter(e=>{var t;return o5(t=Object.keys(TI)).call(t,e)}))}}async _setClientRoleOptions(e){if("rtc"===this.mode||"p2p"===this.mode||"audience"!==this._config.role||this._p2pChannel.hasLocalMedia())return;let t=!1;try{e&>(e),await this._gateway.setClientRole(this._config.role,e),t=!0}catch(e){}finally{TY.info("[".concat(this._clientId,"] set client role options ").concat(t?"succeed":"failed",", options is ").concat(e))}}getRemoteInboundOffset(){var e;let t=null==(e=this._p2pChannel.getStats())?void 0:e.audioSend[0];if(!t||!t.timestamp)return 0;let i=t.timestamp-Date.now();return Math.abs(i)>1e3+t.rttMs+100?this.ntpAlignErrorCount+=1:this.ntpAlignErrorCount=0,this.ntpAlignErrorCount>=3?i:0}getNtpWallTimeInMs(){return"visible"===document.visibilityState&&(this.remoteInboundOffset=this.getRemoteInboundOffset()),this.remoteInboundOffset+Date.now()+this._gateway.ntpOffset}setProxyServer(e,t){if(SG(e,"proxyServer"),!t){if("DISCONNECTED"!==this.connectionState)throw new T0(SU.INVALID_OPERATION,"Set proxy server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new T0(SU.INVALID_OPERATION,"You have already set the proxy")}this._proxyServer=e,T$.setProxyServer(this._proxyServer),TY.setProxyServer(this._proxyServer),TY.info("[".concat(this._clientId,"] Set proxy server ").concat(t?"by initialize call":""," success."))}setTurnServer(e,t){if(Array.isArray(e)||(e=[e]),!t){if("DISCONNECTED"!==this.connectionState)throw new T0(SU.INVALID_OPERATION,"Set turn server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new T0(SU.INVALID_OPERATION,"You have already set the proxy")}if(S9(e))return this._turnServer={servers:e,mode:"original-manual"},void TY.info("[".concat(this._clientId,"] Set original turnserver ").concat(t?"by initialize call":""," success: ").concat(e.map(e=>e.urls).join(","),"."));e.forEach(e=>S7(e)),this._turnServer={servers:e,mode:"manual"},TY.info("[".concat(this._clientId,"] Set turnserver ").concat(t?"by initialize call":""," success."))}setLicense(e){if("DISCONNECTED"!==this.connectionState)throw new T0(SU.INVALID_OPERATION,"you should set license before join channel");if(SG(e,"license",32,32),!/^[A-Za-z\d]+$/.test(e))throw new T0(SU.INVALID_PARAMS,"license should only contains characters from A-Z a-z 0-9");this._license=e,TY.info("[".concat(this._clientId,"] set license success"),e)}startProxyServer(e){let t;if("DISCONNECTED"!==this.connectionState)throw new T0(SU.INVALID_OPERATION,"Start proxy server before join channel");if(this._proxyServer||"manual"===this._turnServer.mode||this._useLocalAccessPoint)throw new T0(SU.INVALID_OPERATION,"You have already set the proxy");switch(void 0===e&&(e=3),e){case 1:case 2:throw new T0(SU.NOT_SUPPORTED,"proxy mode 1/2 has been deprecated and not supported.");case 3:t="proxy3";break;case 4:t="proxy4";break;case 5:t="proxy5";break;default:throw new T0(SU.INVALID_PARAMS,"proxy server mode must be ".concat("3|4|5"))}this._cloudProxyServerMode=t,this.store.cloudProxyServerMode=t,TY.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode)}stopProxyServer(){if("DISCONNECTED"!==this.connectionState)throw new T0(SU.INVALID_OPERATION,"Stop proxy server after leave channel");T$.setProxyServer(),TY.setProxyServer(),this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled",TY.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode),this._proxyServer=void 0,this._turnServer={mode:"auto",servers:[]}}setLocalAccessPointsV2(e){if(!e.accessPoints)throw new T0(SU.INVALID_PARAMS,"accessPoints is required.");SW(e.accessPoints.serverList,"accessPoints.serverList"),SG(e.accessPoints.domain,"accessPoints.domain");let t=(e,t)=>{SB(e,t,0,65535,!0)},i=443;if(e.accessPoints.port&&(t(e.accessPoints.port,"accessPoints.port"),i=e.accessPoints.port),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new T0(SU.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");TR("CLOSE_AFB_FOR_LOCAL_AP")&&(TT("JOIN_WITH_FALLBACK_SIGNAL_PROXY",!1),TT("JOIN_WITH_FALLBACK_MEDIA_PROXY",!1));let r=/^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/,n=e.accessPoints.domain,o=e.accessPoints.serverList.map(e=>r.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(n):e),a=o.map(e=>"".concat(e,":").concat(i));this._useLocalAccessPoint=!0,this._setLocalAPVersion=2,TT("WEBCS_DOMAIN",a),TT("WEBCS_DOMAIN_BACKUP_LIST",a),TT("GATEWAY_DOMAINS",[n]),e.report&&e.report.hostname&&Array.isArray(e.report.hostname)&&e.report.hostname.length?(SW(e.report.hostname,"report.hostname"),TT("EVENT_REPORT_DOMAIN",e.report.hostname[0]),TT("EVENT_REPORT_BACKUP_DOMAIN",e.report.hostname[1]||e.report.hostname[0])
1):(TT("EVENT_REPORT_DOMAIN",o[0]),TT("EVENT_REPORT_BACKUP_DOMAIN",o[1]||o[0]));let s=6443;e.report&&e.report.port&&(t(e.report.port,"report.port"),s=e.report.port),TT("STATS_COLLECTOR_PORT",s),e.report?TT("ENABLE_EVENT_REPORT",!0):TT("ENABLE_EVENT_REPORT",!1);let c="";e.log&&e.log.hostname&&Array.isArray(e.log.hostname)&&e.log.hostname.length?(SW(e.log.hostname,"log.hostname"),c=e.log.hostname[0]):c=o[0];let d=6444;e.log&&e.log.port&&(t(e.log.port,"log.port"),d=e.log.port),TT("LOG_UPLOAD_SERVER","".concat(c,":").concat(d));let l=[];e.cds&&e.cds.hostname&&Array.isArray(e.cds.hostname)&&e.cds.hostname.length?(SW(e.cds.hostname,"cds.hostname"),l=e.cds.hostname):l=o;let h=443;e.cds&&e.cds.port&&(t(e.cds.port,"cds.port"),h=e.cds.port),TT("CDS_AP",l.map(e=>"".concat(e,":").concat(h))),e.cds?TT("ENABLE_CONFIG_DISTRIBUTE",!0):TT("ENABLE_CONFIG_DISTRIBUTE",!1),TY.info("set local access point v2 success")}setLocalAccessPoints(e,t){if(SW(e,"serverList"),SG(t,"domain"),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new T0(SU.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");let i=/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;e=e.map(e=>i.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(t):e),this._useLocalAccessPoint=!0,this._setLocalAPVersion=1,TT("WEBCS_DOMAIN",e),TT("WEBCS_DOMAIN_BACKUP_LIST",e),TT("GATEWAY_DOMAINS",[t]),TT("EVENT_REPORT_DOMAIN",e[0]),TT("EVENT_REPORT_BACKUP_DOMAIN",e[1]||e[0]),TT("LOG_UPLOAD_SERVER","".concat(e[0],":6444")),TY.info("[".concat(this._clientId,"] set local access point success"))}async setRemoteDefaultVideoStreamType(e){if(SF(e,"streamType",[0,1,4,5,6,7,8,9]),this._remoteDefaultVideoStreamType=e,this._joinInfo)try{await this._gateway.setDefaultRemoteVideoStreamType(e),this._joinInfo.defaultVideoStream=this._remoteDefaultVideoStreamType}catch(e){throw TY.error("[".concat(this._clientId,"] set default remote video stream type error"),e.toString()),e}else TY.debug("[".concat(this._clientId,"] haven't joined yet, cache remoteDefaultVideoStreamType ").concat(e))}async setRemoteVideoStreamType(e,t){SF(t,"streamType",[0,1,4,5,6,7,8,9]);try{await this._gateway.setRemoteVideoStreamType(e,t),setTimeout(()=>{let t=this._users.find(t=>t.uid===e);t&&t.videoTrack&&t.videoTrack.updateMediaStreamTrackResolution()},2e3)}catch(e){throw TY.error("[".concat(this._clientId,"] set remote video stream type error"),e.toString()),e}TY.info("[".concat(this._clientId,"] set remote ").concat(e," video stream type to ").concat(t)),this._remoteStreamTypeCacheMap.set(e,t)}async setStreamFallbackOption(e,t){SF(t,"fallbackType",[0,1,2,3,4,5,6,7,8]);try{await this._gateway.setStreamFallbackOption(e,t)}catch(e){throw TY.error("[".concat(this._clientId,"] set stream fallback option"),e.toString()),e}TY.info("[".concat(this._clientId,"] set remote ").concat(e," stream fallback type to ").concat(t)),this._streamFallbackTypeCacheMap.set(e,t)}setEncryptionConfig(e,t,i,r){SF(e,"encryptionMode",["aes-128-xts","aes-256-xts","aes-128-ecb","sm4-128-ecb","aes-128-gcm","aes-256-gcm","aes-128-gcm2","aes-256-gcm2","none"]),SG(t,"secret");let n=["aes-128-gcm2","aes-256-gcm2"];if(o5(n).call(n,e)){if(!i||!(i instanceof Uint8Array&&32===i.length))throw new T0(SU.INVALID_PARAMS,"salt must be an Uint8Array and exactly equal to 32 bytes")}else if(i)throw new T0(SU.INVALID_PARAMS,"current encrypt mode does not need salt");if(r){if(SV(r,"encryptDataStream"),!o5(n).call(n,e))throw new T0(SU.INVALID_PARAMS,"current encrypt mode does not support data stream");this._encryptDataStream=!0}RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*,.<>?/:;'\"|{}\\[\\]])(?=.{8,})").test(t)||TY.warning("The secret is not strong:\n The secret must contain at least 1 lowercase alphabetical character,\n The secret must contain at least 1 uppercase alphabetical character,\n The secret must contain at least 1 numeric character,\n The secret must contain at least one special character,\n The secret must be eight characters or longer.\n "),this._encryptionMode=e,this._encryptionSecret=t,i&&(this._encryptionSalt=gv(i))}async renewToken(e){if(SG(e,"token",1,2047),!this._key||!this._joinInfo)throw new T0(SU.INVALID_OPERATION,"renewToken should not be called before user join");let t=this._key;this._key=e,this._joinInfo&&(this._joinInfo.token=e);let i=await this._renewTokenMutex.lock();try{if(TR("USE_NEW_TOKEN")){TY.debug("[".concat(this._clientId,"] start renew token with ticket from unilbs"));let t=await A_(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||gH);TY.debug("[".concat(this._clientId,"] get ticket from unilbs success")),await this._gateway.renewToken({token:e,ticket:t})}else TY.debug("[".concat(this._clientId,"] start renew token without ticket")),await this._gateway.renewToken({token:e});TY.debug("[".concat(this._clientId,"] renewToken success"))}catch(e){throw this._key=t,this._joinInfo.token=t,TY.error("[".concat(this._clientId,"] renewToken failed"),e.toString()),e}finally{i()}}enableAudioVolumeIndicator(){this._audioVolumeIndicationInterval?TY.warning("you have already enabled audio volume indicator!"):this._audioVolumeIndicationInterval=window.setInterval(()=>{let e=this._p2pChannel.getAudioLevels();this.safeEmit(gi.VOLUME_INDICATOR,e)},TR("AUDIO_VOLUME_INDICATION_INTERVAL")||2e3)}getRTCStats(){let e=this._statsCollector.getRTCStats();return e.Duration=Math.round(this._gateway.getInChannelInfo().duration/1e3),e}async startLiveStreaming(e,t){if(!t){if("h264"!==this.codec)throw new T0(SU.LIVE_STREAMING_INVALID_RAW_STREAM,"raw streaming is only support h264");if(!this._p2pChannel.hasLocalMedia())throw new T0(SU.LIVE_STREAMING_INVALID_RAW_STREAM,"can not find stream to raw streaming")}if(this._liveRawStreamingClient&&this._liveRawStreamingClient.hasUrl(e)||this._liveTranscodeStreamingClient&&this._liveTranscodeStreamingClient.hasUrl(e))throw new T0(SU.LIVE_STREAMING_TASK_CONFLICT);let i=t?vz.TRANSCODE:vz.RAW;return this._createLiveStreamingClient(i).startLiveStreamingTask(e,i)}setLiveTranscoding(e){return this._createLiveStreamingClient(vz.TRANSCODE).setTranscodingConfig(e)}async stopLiveStreaming(e){let t=[this._liveRawStreamingClient,this._liveTranscodeStreamingClient].filter(t=>t&&t.hasUrl(e));if(!t.length)throw new T0(SU.INVALID_PARAMS,"can not find live streaming url to stop");await dQ.all(t.map(t=>t&&t.stopLiveStreamingTask(e)))}async startChannelMediaRelay(e){AI(e);let t=this._createChannelMediaRelayClient();await t.startChannelMediaRelay(e)}async updateChannelMediaRelay(e){AI(e);let t=this._createChannelMediaRelayClient();await t.updateChannelMediaRelay(e)}async stopChannelMediaRelay(){let e=this._createChannelMediaRelayClient();await e.stopChannelMediaRelay(),this._statsCollector.onStatsChanged&&(this._statsCollector.onStatsChanged=void 0)}sendAudioMetadata(e){this._p2pChannel instanceof bh&&this._p2pChannel.addAudioMetadata(e)}async sendStreamMessage(e){var t;let i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!this._joinInfo)throw new T0(SU.INVALID_OPERATION,"can not send data stream, not joined");if(("string"==typeof e||e instanceof Uint8Array)&&(e={payload:e}),"string"==typeof e.payload){let t=new TextEncoder;e.payload=t.encode(e.payload)}let r=!1;if(this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&o5(t=["aes-128-gcm2","aes-256-gcm2"]).call(t,this._encryptionMode)&&(r=!0,e.payload=await async function(e,t,i){var r;let n=as(r=Array.from(i)).call(r,(e,t)=>e+t,0),o={serverTs:0,seq:TA++,length:i.length,checkSum:n},a=new Uint8Array(gM(n,2)),s=new ArrayBuffer(10),c=new DataView(s);c.setUint32(0,o.serverTs),c.setUint16(4,o.seq),c.setUint16(6,o.length),c.setUint16(8,o.checkSum);let d=16-i.length%16;i=gI(i,new Uint8Array(d));let l=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:e,tagLength:128,additionalData:a},t,i);return gI(new Uint8Array(s),new Uint8Array(l))}(this._encryptDataStreamIv,this._encryptDataStreamKey,e.payload)),new Blob([e.payload]).size>1024)throw new T0(SU.INVALID_PARAMS,r?"encrypted stream message out of range.":"stream message out of range.");return this._gateway.signal.request(vB.DATA_STREAM,{payload:gv(e.payload),syncWithAudio:e.syncWithAudio,sendTs:Date.now()-bE},!i)}sendMetadata(e){if(!this._joinInfo)throw new T0(SU.INVALID_OPERATION,"can not send metadata, not joined");if(new Blob([e]).size>1024)throw new T0(SU.METADATA_OUT_OF_RANGE);return this._gateway.signal.request(vB.SEND_METADATA,{session_id:this._joinInfo.sid,metadata:gv(e)})}async sendCustomReportMessage(e){if(Array.isArray(e)||(e=[e]),e.forEach(Tz),!this._joinInfo)throw new T0(SU.INVALID_OPERATION,"can not send custom report, not joined");await T$.sendCustomReportMessage(this._joinInfo.sid,e)}getLocalAudioStats(){return this._statsCollector.getLocalAudioTrackStats()}getRemoteAudioStats(){return this._statsCollector.getRemoteAudioTrackStats()}getLocalVideoStats(){return this._statsCollector.getLocalVideoTrackStats()}getRemoteVideoStats(){return this._statsCollector.getRemoteVideoTrackStats()}getRemoteNetworkQuality(){let e=this._statsCollector.getRemoteNetworkQualityStats();if(TR("DELETE_NEQ_AFTER_USER_LEAVE")){let t=this._users.map(e=>e.uid+"");Object.keys(e).forEach(i=>
1{o5(t).call(t,i)||delete e[i]})}return e}getNetworkQuality(){return this._statsCollector.getNetworkQuality()}async pickSVCLayer(e,t){SF(t.spatialLayer,"spatialLayer",[0,1,2,3]),SF(t.temporalLayer,"temporalLayer",[0,1,2,3]);try{await this._gateway.pickSVCLayer(e,t)}catch(e){throw TY.error("[".concat(this._clientId,"] pick SVC layer failed"),e.toString()),e}}async setRTMConfig(e){let{apRTM:t=!1,rtmFlag:i}=e;if(SV(t,"apRTM"),SB(i,"rtmFlag",0),this._rtmConfig.apRTM=t,this._rtmConfig.rtmFlag=i,TY.debug("[".concat(this._clientId,"] setRTMconfig ").concat(JSON.stringify(e)," in ").concat(this.connectionState," state")),("CONNECTED"===this.connectionState||"RECONNECTING"===this.connectionState)&&this._joinInfo)return this._joinInfo.apRTM=t,this._joinInfo.rtmFlag=i,this._gateway.setRTM2Flag(i)}_reset(){if(TY.debug("[".concat(this._clientId,"] reset client")),function(e){let t=vp.indexOf(e);-1!==t&&vp.splice(t,1)}(this._clientId),this.store.hasStartJoinChannel=!1,this.store.isABTestSuccess=!1,this.store.autoSubscribe=!1,this._pendingRtpCapabilityChange=void 0,this._axiosCancelSource.cancel(),this._axiosCancelSource=f0.CancelToken.source(),this._streamFallbackTypeCacheMap=new Map,this._remoteStreamTypeCacheMap=new Map,this._configDistribute.stopGetConfigDistribute(),this._joinInfo&&bB(this._joinInfo),this._rteDetailInterval&&(window.clearInterval(this._rteDetailInterval),this._rteDetailInterval=void 0,this._sessionId&&T$.reportRteDetail(this._sessionId)),this._fallbackServerInfo=void 0,this._joinInfo=void 0,this._proxyServer=void 0,this._defaultStreamFallbackType=void 0,this._sessionId&&T$.removeSid(this._sessionId),this._sessionId=null,this.store.sessionId=null,this.store.resetFirstVideoFrameDecoded(),this._statsCollector.reset(),this._key=void 0,this._appId=void 0,this._uid=void 0,this.store.uid=void 0,this._channelName=void 0,this._encryptionMode="none",this._encryptionSecret=null,this._encryptionSalt=null,this._encryptDataStreamKey=null,this._encryptDataStreamIv=null,this._pendingPublishedUsers=[],this._users.forEach(e=>{e._audioTrack&&e._audioTrack._destroy(),e._videoTrack&&e._videoTrack._destroy(),e._dataChannels&&(e._dataChannels.forEach(e=>e._close()),e._dataChannels.length=0)}),this._users=[],this._audioVolumeIndicationInterval&&(window.clearInterval(this._audioVolumeIndicationInterval),this._audioVolumeIndicationInterval=void 0),"fallback"===this._cloudProxyServerMode&&(this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled"),this._p2pChannel.reset(),this._publishMutex=new gG("client-publish",this._clientId),this._subscribeMutex=new gG("client-subscribe",this._clientId),this._networkQualityInterval&&(window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=void 0),this._liveRawStreamingClient&&(this._liveRawStreamingClient.terminate(),this._liveRawStreamingClient.removeAllListeners(),this._liveRawStreamingClient=void 0),this._liveTranscodeStreamingClient&&(this._liveTranscodeStreamingClient.terminate(),this._liveTranscodeStreamingClient.removeAllListeners(),this._liveTranscodeStreamingClient=void 0),this._channelMediaRelayClient&&(this._channelMediaRelayClient.dispose(),this._channelMediaRelayClient=void 0),this._inspect)try{this._inspect.close(),this._inspect=void 0}catch(e){}if(this._moderation)try{this.setImageModeration(!1)}catch(e){}}_startSession(e,t){var i;let r=e||gN();e?TY.debug("[".concat(this._clientId,"] new Session ").concat(r)):TY.debug("[".concat(this._clientId,"] renewSession ").concat(this._sessionId," => ").concat(r));let n=e?"":this._sessionId||"";this._sessionId=r,this.store.sessionId=r,T$.addSid(r);let o={lts:(new Date).getTime(),mode:this.mode,buildFormat:1,stringUid:(null==t?void 0:t.stringUid)||(null==(i=this._joinInfo)?void 0:i.stringUid),channelProfile:+("live"===this.mode),channelMode:0,isABTestSuccess:Number(this._configDistribute.isSuccess),lsid:n,clientRole:"audience"===this.role?2:1,rteUrl:this.store.rteUrl,rteSid:this.store.rteSid};T$.sessionInit(this._sessionId,Od({cname:t.channel,appid:t.appId},o)),this._joinInfo&&(this._joinInfo.sid=r),this._gateway.joinInfo&&(this._gateway.joinInfo.sid=r)}async _publishHighStream(e){if(!this._joinInfo||void 0===this._uid)throw new T0(SU.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new T0(SU.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&TR("FORCE_TURN")&&!TR("TURN_ENABLE_TCP")&&!TR("TURN_ENABLE_UDP"))throw new T0(SU.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");TY.debug("[".concat(this._clientId,"] publish high stream"));try{let i=await this._p2pChannel.publish(e,this._isDualStreamEnabled,this._lowStreamParameter);if(this.store.useP2P){let e=(await i.next()).value;if(e){try{await this._gateway.sendExtensionMessage(yy.PUBLISH,e,!0)}catch(e){throw i.throw(e),e}await i.next()}this._p2pChannel.reportPublishEvent(!0,null)}else{let r=(await i.next()).value;if(r){var t;let e;try{e=await this._gateway.publish(this._uid,r,!0)}catch(e){if(e.code!==SU.DISCONNECT_P2P)throw i.throw(e),e}await i.next((null==(t=e)?void 0:t.ortc)||[])}for(let t of(this._p2pChannel.reportPublishEvent(!0,null),e))t instanceof CP&&t._encoderConfig&&this._gateway.setVideoProfile(t._encoderConfig).catch(e=>{TY.debug("[".concat(this._clientId,"] stop setVideoProfile, because websocket is closed"))}),!t.muted&&t.enabled||await this._p2pChannel.muteLocalTrack(t)}}catch(t){if(this._p2pChannel.reportPublishEvent(!1,null==t?void 0:t.code,e),(null==t?void 0:t.code)===SU.WS_ABORT)return;throw t}}async _publishLowStream(){if(!this._joinInfo||void 0===this._uid)throw new T0(SU.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new T0(SU.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));TY.debug("[".concat(this._clientId,"] publish low stream"));let e=this._configDistribute.getLowStreamConfigDistribute();e&&e.bitrate&&(this._lowStreamParameter||(this._lowStreamParameter={width:160,height:120,framerate:15,bitrate:50}),this._lowStreamParameter&&this._lowStreamParameter.bitrate&&e.bitrate<this._lowStreamParameter.bitrate&&(this._lowStreamParameter.bitrate=e.bitrate));try{let e=await this._p2pChannel.publishLowStream(this._lowStreamParameter),i=(await e.next()).value;if(i){var t;let r;try{r=await this._gateway.publish(this._uid,i,!0)}catch(t){if(t.code!==SU.DISCONNECT_P2P)throw e.throw(t),t}e.next((null==(t=r)?void 0:t.ortc)||[]),this._p2pChannel.reportPublishEvent(!0,null,void 0,!0)}}catch(e){if(this._p2pChannel.reportPublishEvent(!1,null==e?void 0:e.code,void 0,!0),(null==e?void 0:e.code)===SU.WS_ABORT)return;throw e}}_createLiveStreamingClient(e){let t=()=>{var e;if(!this._joinInfo||!this._appId)return new T0(SU.INVALID_OPERATION,"can not create live streaming client, please join channel first").throw();
1let t=(e={joinInfo:this._joinInfo,appId:this._appId,websocketRetryConfig:this._config.websocketRetryConfig,httpRetryConfig:this._config.httpRetryConfig},IV("LiveStreaming").create(e));return t.onLiveStreamError=(e,t)=>{T$.reportApiInvoke(this._sessionId,{name:S3.ON_LIVE_STREAM_ERROR,options:[e,t],tag:S5.TRACER}).onSuccess(),this.safeEmit(gi.LIVE_STREAMING_ERROR,e,t)},t.onLiveStreamWarning=(e,t)=>{T$.reportApiInvoke(this._sessionId,{name:S3.ON_LIVE_STREAM_WARNING,options:[e,t],tag:S5.TRACER}).onSuccess(),this.safeEmit(gi.LIVE_STREAMING_WARNING,e,t)},t.on(v$.REQUEST_WORKER_MANAGER_LIST,(e,t,i)=>{if(!this._joinInfo)return i(new T0(SU.INVALID_OPERATION,"can not find join info to get worker manager"));(async function(e,t,i,r){let n=TR("UAP_AP").slice(0,TR("AJAX_REQUEST_CONCURRENT")).map(e=>t.proxyServer?"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1?action=uap"):"https://".concat(e,"/api/v1?action=uap"));return await function(e,t,i,r,n){I5+=1;let o={service_name:t,json_body:JSON.stringify({sid:i.sid,command:"convergeAllocateEdge",uid:"666",appId:i.appId,ts:Math.floor(Date.now()/1e3),seq:I5,requestId:I5,version:Th,cname:i.cname})},a,s,c=e[0];return gY(async()=>{a=Date.now();let e=await Iz(c,{data:o,cancelToken:r,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"}});if(s=Date.now()-a,0!==e.code){let t=new T0(SU.UNEXPECTED_RESPONSE,"live streaming ap error, code"+e.code,{retry:!0,responseTime:s});throw TY.error(t.toString()),t}let i=JSON.parse(e.json_body);if(200!==i.code){let e=new T0(SU.UNEXPECTED_RESPONSE,"live streaming app center error, code: ".concat(i.code,", reason: ").concat(i.reason),{code:i.code,responseTime:s});throw TY.error(e.toString()),e}if(!i.servers||0===i.servers.length){let e=new T0(SU.UNEXPECTED_RESPONSE,"live streaming app center empty server",{code:i.code,responseTime:s});throw TY.error(e.toString()),e}let n={addressList:i.servers.map(e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(TR("WORKER_DOMAIN"),":").concat(e.wss,"?serviceName=").concat(encodeURIComponent(t))),workerToken:i.workerToken,vid:i.vid};return TR("LIVE_STREAMING_ADDRESS")&&(n.addressList=TR("LIVE_STREAMING_ADDRESS")instanceof Array?TR("LIVE_STREAMING_ADDRESS"):[TR("LIVE_STREAMING_ADDRESS")]),I3(I3({},n),{},{responseTime:s})},(r,n)=>(T$.apworkerEvent(i.sid,{success:!0,sc:200,serviceName:t,responseDetail:JSON.stringify(r.addressList),firstSuccess:0===n,responseTime:s,serverIp:e[n%e.length]}),!1),(r,n)=>(T$.apworkerEvent(i.sid,{success:!1,sc:r.data&&r.data.code||200,serviceName:t,responseTime:s,serverIp:e[n%e.length]}),!!(r.code!==SU.OPERATION_ABORTED&&r.code!==SU.UNEXPECTED_RESPONSE||r.data&&r.data.retry)&&(c=e[(n+1)%e.length],!0)),n)}(n,e,t,i,r)})(e,this._joinInfo,this._axiosCancelSource.token,gH).then(t).catch(i)}),t};return e===vz.RAW?(this._liveRawStreamingClient=this._liveRawStreamingClient||t(),this._liveRawStreamingClient):(this._liveTranscodeStreamingClient=this._liveTranscodeStreamingClient||t(),this._liveTranscodeStreamingClient)}_createChannelMediaRelayClient(){var e;if(!this._joinInfo)return new T0(SU.INVALID_OPERATION,"can not create channel media relay client, please join channel first").throw();if(!this._channelMediaRelayClient){let{sendResolutionWidth:t,sendResolutionHeight:i}=this.getLocalVideoStats(),r=(e={joinInfo:this._joinInfo,clientId:this._clientId,websocketRetryConfig:this._config.websocketRetryConfig,httpRetryConfig:this._config.httpRetryConfig,resolution:{width:t,height:i}},IV("ChannelMediaRelay").create(e));r.on("state",e=>{e===v5.RELAY_STATE_FAILURE&&r&&r.dispose(),this.safeEmit(gi.CHANNEL_MEDIA_RELAY_STATE,e)}),r.on("event",e=>{this.safeEmit(gi.CHANNEL_MEDIA_RELAY_EVENT,e)}),this._channelMediaRelayClient=r,this._statsCollector.onStatsChanged=(e,t)=>{var i;"resolution"===e&&(null==(i=this._channelMediaRelayClient)||i.setVideoProfile(t))}}return this._channelMediaRelayClient}_handleUpdateDataChannel(e,t){let{added:i,deleted:r}=e,n=[];if(t){let e=[];this._users.forEach(t=>{t._dataChannels.forEach(r=>{i.every(e=>e.uid!==t._uintid||e.stream_id!==r.id)&&e.push({uid:t._uintid,stream_id:r.id,ordered:r.ordered,max_retrans_times:r.maxRetransmits,metadata:r.metadata})})}),e.length>
10&&this._handleUpdateDataChannel({added:[],deleted:e})}Array.isArray(i)&&i.length>0&&i.forEach(e=>{let{uid:i,stream_id:r,ordered:o,max_retrans_times:a,metadata:s}=e,c=this._users.find(e=>e._uintid===i);if(!c)return void TY.error("[".concat(this._clientId,"] can not find target user!(on_add_data_channel)"));if(TY.debug("[".concat(this._clientId,"] data_channel added with uid ").concat(i)),o5(n).call(n,c)||n.push(c),c._uintid||(c._uintid=i),-1===c._dataChannels.findIndex(t=>t.id===e.stream_id)){let e={id:r,ordered:!!o,maxRetransmits:a,metadata:s},i=IF(e,!0);c._dataChannels.push(i),TY.info("[".concat(this._clientId,"] remote user ").concat(c.uid," published datachannel")),t||this.safeEmit(gi.USER_PUBLISHED,c,"datachannel",e)}this._p2pChannel.hasPendingRemoteDataChannel(c,e.stream_id)&&(TY.debug("[".concat(this._clientId,"] resubscribe datachannel for user ").concat(c.uid," after reconnect.")),this._subscribeDataChannel(c,e.stream_id).catch(e=>{TY.error("[".concat(this._clientId,"] resubscribe datachannel error"),e.toString())}))}),t&&(this.safeEmit(gi.PUBLISHED_USER_LIST,this._pendingPublishedUsers),this._pendingPublishedUsers=[]),Array.isArray(r)&&r.length>0&&r.forEach(e=>{let{uid:t,stream_id:i}=e,r=this._users.find(e=>e._uintid===t);if(!r)return void TY.error("[".concat(this._clientId,"] can not find target user!(on_delete_data_channel)"));let n=r._dataChannels.find(t=>t.id===e.stream_id);n&&(TY.debug("[".concat(this._clientId,"] data_stream delete with uid ").concat(t)),this._p2pChannel.unsubscribeDataChannel(r,[n]).then(e=>{if(r._dataChannels=r._dataChannels.filter(e=>e!==n),e)return this._gateway.unsubscribeDataChannel(e,r.uid)}),TY.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished datachannel ,id:").concat(n.id)),this.safeEmit(gi.USER_UNPUBLISHED,r,"datachannel",n._config))})}_getEncodingName(e){var t,i,r,n;if(!this._joinResponse)return;let o=null==(t=this._joinResponse.ortc.rtpCapabilities.sendrecv)?void 0:t.videoCodecs;if(!o)return;for(let t of o)if(t.payloadType===e)return null==t||null==(r=t.rtpMap)?void 0:r.encodingName;let a=null==(i=this._joinResponse.ortc.rtpCapabilities.recv)?void 0:i.videoCodecs;if(a){for(let t of a)if(t.payloadType===e)return null==t||null==(n=t.rtpMap)?void 0:n.encodingName}return 0===e?"unknown":void 0}_handleRemoveDataChannels(e){let t=this._users.find(t=>t.uid===e.uid);if(t){if(void 0!==t._dataChannels&&t._dataChannels.length>0){TY.debug("[".concat(this._clientId,"] datachannel removed with uid ").concat(e.uid));let i=()=>{TY.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished datachannel")),t._dataChannels.forEach(e=>{this.safeEmit(gi.USER_UNPUBLISHED,t,"datachannel",e._config)})};this._p2pChannel.unsubscribeDataChannel(t,t._dataChannels).then(e=>{if(e)return this._gateway.unsubscribeDataChannel(e,t.uid)}),i()}}else TY.warning("[".concat(this._clientId,"] can not find target user!(on_remove_datachannel)"))}_handleGatewayEvents(){this._gateway.on(v8.UPDATE_GATEWAY_CONFIG,()=>{!function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void TY.error("Error loading sdk config",e.message)}if(e)try{let t=JSON.parse(window.atob(e)),i=Date.now();Object.keys(t).forEach(e=>{let{value:r,type:n,expires:o}=t[e];o&&o<=i||n||vE()||!Object.prototype.hasOwnProperty.call(TE,e)||(Tv[e]=r,Tg[e]=r,TY.debug("Update gateway parameters from config distribute",e,r))})}catch(e){TY.error("Error update config from local cache",e.message)}}()}),this._gateway.on(v8.DISCONNECT_P2P,async()=>{await this._p2pChannel.disconnectForReconnect()}),this._gateway.on(v8.CONNECTION_STATE_CHANGE,(e,t,i)=>{var r,n;if(i===S8.FALLBACK)return;let o=()=>{this.safeEmit(gi.CONNECTION_STATE_CHANGE,e,t,i)};if(T$.reportApiInvoke(this._sessionId||(null==(r=this._gateway.joinInfo)?void 0:r.sid)||null,{name:S3.CONNECTION_STATE_CHANGE,options:[e,t,i],tag:S5.TRACER}).onSuccess(JSON.stringify({cur:e,prev:t,reason:i})),TY.info("[".concat(this._clientId,"] signal connection state change: ").concat(t," -> ").concat(e)),"DISCONNECTED"===e)return this._reset(),void o();
1"RECONNECTING"===e?(this._users.forEach(e=>{e._trust_in_room_=!1,e._trust_audio_enabled_state_=!1,e._trust_video_enabled_state_=!1,e._trust_audio_mute_state_=!1,e._trust_video_mute_state_=!1,e._trust_audio_stream_added_state_=!1,e._trust_video_stream_added_state_=!1,e._is_pre_created||(e._audio_pre_subscribed||(e._audioSSRC=void 0,e._audioOrtc=void 0),e._video_pre_subscribed||(e._videoSSRC=void 0,e._videoOrtc=void 0,e._rtxSsrcId=void 0),e._cname=void 0)}),this._userOfflineTimeout&&window.clearTimeout(this._userOfflineTimeout),this._streamRemovedTimeout&&window.clearTimeout(this._streamRemovedTimeout),this._userOfflineTimeout=void 0,this._streamRemovedTimeout=void 0):"CONNECTED"===e&&(this._streamFallbackTypeCacheMap.forEach((e,t)=>{this._gateway.setStreamFallbackOption(t,e).catch(e=>{TY.warning("[".concat(this._clientId,"] auto set stream fallback option failed"),e)})}),this._remoteStreamTypeCacheMap.forEach((e,t)=>{this._gateway.setRemoteVideoStreamType(t,e).catch(e=>{TY.warning("[".concat(this._clientId,"] auto set remote stream type failed"),e)})}),TR("VOS_CONFIGURE")&&Array.isArray(TR("VOS_CONFIGURE"))&&TR("VOS_CONFIGURE").length>0&&(this._gateway.setConfigure(TR("VOS_CONFIGURE")).catch(e=>{TY.debug("[".concat(this._clientId,"] auto set vos config failed"),e)}),TY.debug("[".concat(this._clientId,"] ws connected auto set vos config"))),void 0!==this._remoteDefaultVideoStreamType&&void 0===(null==(n=this._joinInfo)?void 0:n.defaultVideoStream)&&this.setRemoteDefaultVideoStreamType(this._remoteDefaultVideoStreamType).then(()=>{TY.debug("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway connected"))}).catch(e=>{TY.error("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway failed, ").concat(e))}),this._dualStreamMode&&this._gateway.setDualStreamMode(this._dualStreamMode).catch(e=>{TY.warning("[".concat(this._clientId,"] auto set dual stream mode failed"),e)}),this.store.useP2P||(this._p2pChannel.republish(),this._userOfflineTimeout=window.setTimeout(()=>{"CONNECTED"===this.connectionState&&(this._userOfflineTimeout=void 0,this._users.filter(e=>!e._trust_in_room_).forEach(e=>{TY.debug("[".concat(this._clientId,"] user offline timeout, emit user offline ").concat(e.uid)),this._handleUserOffline({uid:e.uid})}))},3e3),this._streamRemovedTimeout=window.setTimeout(()=>{"CONNECTED"===this.connectionState&&(this._streamRemovedTimeout=void 0,this._users.forEach(e=>{e._trust_audio_mute_state_||(TY.debug("[".concat(this._clientId,"] auto dispatch audio unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,yc.AUDIO,!1)),e._trust_video_mute_state_||(TY.debug("[".concat(this._clientId,"] auto dispatch video unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,yc.VIDEO,!1)),e._trust_audio_enabled_state_||(TY.debug("[".concat(this._clientId,"] auto dispatch enable local audio ").concat(e.uid)),this._handleSetStreamLocalEnable("audio",e.uid,!0)),e._trust_video_enabled_state_||(TY.debug("[".concat(this._clientId,"] auto dispatch enable local video ").concat(e.uid)),this._handleSetStreamLocalEnable("video",e.uid,!0)),e._trust_video_stream_added_state_||(TY.debug("[".concat(this._clientId,"] auto dispatch reset video stream added ").concat(e.uid)),this._handleResetAddStream(e,"video")),e._trust_audio_stream_added_state_||(TY.debug("[".concat(this._clientId,"] auto dispatch reset audio stream added ").concat(e.uid)),this._handleResetAddStream(e,"audio")),e._video_added_||e._audio_added_||(TY.debug("[".concat(this._clientId,"] auto dispatch stream remove ").concat(e.uid)),this._handleRemoveStream({uid:e.uid,uint_id:e._uintid}))}))},1e3))),o()}),this._gateway.on(v8.REQUEST_NEW_GATEWAY_LIST,async(e,t)=>{if(!this._joinInfo)return t(new T0(SU.UNEXPECTED_ERROR,"can not recover, no join info"));try{let t;if(this._fallbackServerInfo)t=this._fallbackServerInfo,this._fallbackServerInfo=void 0,this._joinInfo.preload=!1,T$.reportApiInvoke(this._sessionId,{name:S3.VOS_FALLBACK_CN,options:{cur:t.gatewayInfo.gatewayAddrs,prev:this._joinInfo.gatewayAddrs,is_done:!0},tag:S5.TRACER}).onSuccess(),TY.info("[".concat(this._clientId,"] use fallback cn server info"));else{let e=await bU(Od(Od({},this._joinInfo),{},{uid:this._joinInfo.uid,stringUid:void 0}));e?(t=e.ap,bj(e),this._joinInfo.preload=!0):(t=await Aa(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||gH,this.store),this._joinInfo.preload=!1)}this._joinInfo&&(this._joinInfo.apResponse=t.gatewayInfo.res,this._joinInfo.gatewayAddrs=t.gatewayInfo.gatewayAddrs,this._joinInfo.uni_lbs_ip=t.gatewayInfo.uni_lbs_ip);let i=[];
1t.gatewayInfo.gatewayAddrs.forEach(e=>{let{address:t}=e,[r,n]=t.split(":");this._joinInfo&&this._joinInfo.proxyServer?i.push({proxy:this._joinInfo.proxyServer,host:r,port:n}):i.push({host:r,port:n})}),e(i)}catch(e){t(e)}}),this._gateway.on(v8.NETWORK_QUALITY,e=>{"normal"===this._networkQualitySensitivity&&this.safeEmit(gi.NETWORK_QUALITY,e)}),this._gateway.on(v8.STREAM_TYPE_CHANGE,(e,t)=>{this.safeEmit(gi.STREAM_TYPE_CHANGED,e,t),T$.reportApiInvoke(this._sessionId,{name:S3.STREAM_TYPE_CHANGE,options:[e,t],tag:S5.TRACER}).onSuccess(JSON.stringify({uid:e,streamType:t}))}),this._gateway.isPreSub=()=>"isPreSub"in this._p2pChannel&&this._p2pChannel.isPreSub(),this._gateway.isPreallocation=()=>"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation(),this._gateway.on(v8.IS_P2P_DISCONNECTED,e=>{e(!!this._p2pChannel.isP2PDisconnected()||!(this._p2pChannel.hasLocalMedia()||this._p2pChannel.hasRemoteMedia()))}),this._gateway.on(v8.REQUEST_P2P_CONNECTION_PARAMS,async(e,t,i)=>{try{let i=await this._p2pChannel.getEstablishParams();i&&"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation()||(i=await this._p2pChannel.startP2PConnection(e)),t(i)}catch(e){i(e)}}),this._gateway.on(v8.JOIN_RESPONSE,(e,t)=>{let i;if(this.store.useP2P)return;this._joinResponse=e,e.attributes?i=e.attributes.userAttributes.preSubSsrcs:TY.debug("no attributes in joinResponse");let r=Iu(e.ortc,t,i);this._p2pChannel.connect(r)}),this._gateway.on(v8.PRE_CONNECT_PC,async(e,t,i)=>{let{candidates:r,fingerprint:n,turnServer:o}=e;if(this._joinInfo&&r.length>0&&!this._p2pChannel.isPlanB){let{cert:e,cid:s}=this._joinInfo.apResponse,c="".concat(s,"_").concat(e);if(c.length<4||c.length>256)return void TY.debug("[".concat(this._clientId,"] ufrag length is not valid, length: ").concat(c.length));await this._p2pChannel.startP2PConnection({turnServer:o,cloudProxyServer:this._joinInfo.cloudProxyServer,isPreallocation:!0});try{var a;t(await this._p2pChannel.connect({iceParameters:{iceUfrag:"".concat(s,"_").concat(e),icePwd:"".concat(s,"_").concat(e)},dtlsParameters:{fingerprints:[{hashFunction:"sha-256",fingerprint:null!=(a=TR("FINGERPRINT"))?a:n}]},candidates:r,rtpCapabilities:{send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},setup:"active",cname:"o/i14u9pJrxRKAsu",preallocation:!0}))}catch(e){e.code&&e.code===SU.EXCHANGE_SDP_FAILED&&await this._p2pChannel.startP2PConnection({turnServer:o,cloudProxyServer:this._joinInfo.cloudProxyServer},!0),i(e)}}}),this._gateway.on(v8.VOS_FALLBACK,e=>{"fallback_hls"===e&&this.safeEmit(gi.FALLBACK_TO_HLS,gr.VOSERROR)}),this._gateway.on(v8.RESET_SIGNAL,()=>{this._p2pChannel instanceof bh&&this._p2pChannel.fallbackConnection(),this._handleGatewaySignalEvents()}),this._gateway.on(v8.DATACHANNEL_FAILBACK,()=>{T$.reportApiInvoke(this._sessionId,{name:S3.DATACHANNEL_FAILBACK,options:{},tag:S5.TRACER}).onSuccess(),this._joinGateway()})}_handleGatewaySignalEvents(){this._gateway.signal.on(vG.ON_USER_ONLINE,this._handleUserOnline),this._gateway.signal.on(vG.ON_USER_OFFLINE,this._handleUserOffline),this._gateway.signal.on(vG.ON_ADD_AUDIO_STREAM,e=>this._handleAddAudioOrVideoStream("audio",e.uid,e.ssrcId,e.cname,e.pt,e.uint_id,e.ortc)),this._gateway.signal.on(vG.ON_ADD_VIDEO_STREAM,e=>this._handleAddAudioOrVideoStream("video",e.uid,e.ssrcId,e.cname,e.pt,e.uint_id,e.ortc,e.rtxSsrcId)),this._gateway.signal.on(vG.ON_REMOTE_DATASTREAM_UPDATE,e=>{this._handleUpdateDataChannel(e)}),this._gateway.signal.on(vG.ON_REMOTE_FULL_DATASTREAM_INFO,e=>{this._handleUpdateDataChannel({added:e.datastreams||[],deleted:[]},!0)}),this._gateway.signal.on(vG.ON_REMOVE_STREAM,this._handleRemoveStream),this._gateway.signal.on(vG.ON_P2P_LOST,this._handleP2PLost),this._gateway.signal.on(vG.MUTE_AUDIO,e=>this._handleMuteStream(e.uid,yc.AUDIO,!0)),this._gateway.signal.on(vG.UNMUTE_AUDIO,e=>this._handleMuteStream(e.uid,yc.AUDIO,!1)),this._gateway.signal.on(vG.MUTE_VIDEO,e=>this._handleMuteStream(e.uid,yc.VIDEO,!0)),this._gateway.signal.on(vG.UNMUTE_VIDEO,e=>this._handleMuteStream(e.uid,yc.VIDEO,!1)),this._gateway.signal.on(vG.RECEIVE_METADATA,e=>{let t=gC(e.metadata);this.safeEmit(gi.RECEIVE_METADATA,e.uid,t)}),this._gateway.signal.on(vG.ON_DATA_STREAM,async e=>{var t;if(!e)return;let i=gC(e.payload);if(this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&o5(t=["aes-128-gcm2","aes-256-gcm2"]).call(t,this._encryptionMode)){if(e.payload.length<10)throw new T0(SU.UNEXPECTED_RESPONSE,"payload length ".concat(e.payload.length," is less than header length ").concat(10));i=await async function(e,t,i){let r=i.subarray(0,10),n=r.slice(8,10),o=(n[0]<<8)+n[1],a=(r[6]<<8)+r[7],s=await window.crypto.subtle.decrypt({
1name:"AES-GCM",iv:e,tagLength:128,additionalData:new Uint8Array(gM(o,2))},t,i.subarray(10));return new Uint8Array(s).subarray(0,a)}(this._encryptDataStreamIv,this._encryptDataStreamKey,i)}let r=0;if(e.ordered||e.syncWithAudio){let t=this._p2pChannel.getStats(),i=this.remoteUsers.find(t=>t.uid===e.uid),n=null==t?void 0:t.audioRecv.find(e=>e.ssrc===(null==i?void 0:i._audioSSRC));r=null==n?void 0:n.jitterBufferMs}(null==r||Number.isNaN(r))&&(r=0),function(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2?arguments[2]:void 0;if(!e.syncWithAudio)return bg(r,{uid:e.uid,payload:e.payload});let n="".concat(r.id,"-").concat(e.uid),o=bm.get(n)||[],a=o.findIndex(t=>e.sendTs>=t.sendTs),s=b_(b_({},e),{},{context:r,mediaDelay:i,recvTs:Date.now()});-1===a?o.push(s):o.splice(a,0,s),bm.set(n,o);let c=!1;bf.has(n)?c=!(null==(t=bf.get(n))||!t.isSyncing):bf.set(n,{isSyncing:c,firstRecvTs:0,firstSendTs:0}),c||bS(n)}(Od(Od({},e),{},{payload:i}),r,{id:this._clientId,onStreamMessage:"function"==typeof this.onStreamMessage?this.onStreamMessage.bind(this):void 0,safeEmit:this.safeEmit.bind(this)})}),this._gateway.signal.on(vG.ON_CRYPT_ERROR,()=>{gR(()=>{TY.warning("[".concat(this._clientId,"] on crypt error")),this.safeEmit(gi.CRYPT_ERROR)},this._sessionId)}),this._gateway.signal.on(vG.ON_TOKEN_PRIVILEGE_WILL_EXPIRE,this._handleTokenWillExpire),this._gateway.signal.on(vG.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{TY.warning("[".concat(this._clientId,"] received message onTokenPrivilegeDidExpire, please get new token and join again")),this._gateway.leave(!0,S8.TOKEN_EXPIRE),this.safeEmit(gi.ON_TOKEN_PRIVILEGE_DID_EXPIRE),this._reset()}),this._gateway.signal.on(vG.ON_STREAM_FALLBACK_UPDATE,e=>{TY.debug("[".concat(this._clientId,"] stream fallback peerId: ").concat(e.stream_id,", attr: ").concat(e.stream_type)),this.safeEmit(gi.STREAM_FALLBACK,e.stream_id,1===e.stream_type?"fallback":"recover")}),this._gateway.signal.on(vG.ENABLE_MULTI_STREAM,e=>{this._dualStreamMode===ge.AUTO_SIMULCAST_STREAM&&this.enableDualStream().catch(e=>{TY.debug("[".concat(this._clientId,"] set dual stream mode error"),e.toString())})}),this._gateway.signal.on(vG.ON_PUBLISH_STREAM,e=>{this.uid===this._uid&&(this._p2pChannel.reportPublishEvent(!0,null,void 0,!1,JSON.stringify({proxy:e.proxy})),TY.info("[".concat(this._clientId,"] on publish stream, ").concat(JSON.stringify(e))))}),this._gateway.signal.on(vG.ENABLE_LOCAL_VIDEO,e=>{this._handleSetStreamLocalEnable("video",e.uid,!0)}),this._gateway.signal.on(vG.DISABLE_LOCAL_VIDEO,e=>{this._handleSetStreamLocalEnable("video",e.uid,!1)}),this._gateway.signal.on(vF.REQUEST_TIMEOUT,(e,t)=>{if(this._joinInfo)switch(e){case vB.PUBLISH:{if(!t)return;let e=t.ortc;if(e){var i,r;let n=e.some(e=>{let{stream_type:t}=e;return t===v6.Audio}),o=e.some(e=>{let{stream_type:t}=e;return t!==v6.Audio}),a=e.some(e=>{let{stream_type:t}=e;return t===v6.Screen||t===v6.ScreenLow});"offer"===t.state&&T$.publish(this._joinInfo.sid,{eventElapse:AT.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:!1,ec:SU.TIMEOUT,audio:n,video:o,p2pid:t.p2p_id,publishRequestid:this.store.pubId,screenshare:a,audioName:n?null==(i=e.find(e=>{let{stream_type:t}=e;return t===v6.Audio}))||null==(i=i.ssrcs[0])?void 0:i.ssrcId.toString():void 0,videoName:o?null==(r=e.find(e=>{let{stream_type:t}=e;return t!==v6.Audio}))||null==(r=r.ssrcs[0])?void 0:r.ssrcId.toString():void 0})}break}case vB.SUBSCRIBE:t&&T$.subscribe(this._joinInfo.sid,{succ:!1,ec:SU.TIMEOUT,audio:t.stream_type===yc.AU
1DIO,video:t.stream_type===yc.VIDEO,peerid:t.stream_id,subscribeRequestid:t.ssrcId,p2pid:this.store.p2pId,eventElapse:AT.measureFromSubscribeStart(this.store.clientId,t.ssrcId),preSsrc:this._p2pChannel.isPreSubScribe(t.ssrcId)})}}),this._gateway.signal.on(vG.ON_P2P_OK,e=>{this.uid,this._uid}),this._gateway.signal.on(vG.ON_PUBLISHED_USER_LIST,e=>{if(null==e||!e.users)return;TR("BLOCK_LOCAL_CLIENT")&&(e.users=e.users.filter(e=>!v_(e.string_id||e.stream_id,this.channelName)));let t=[],i=[];for(let r of e.users){let e=this._users.find(e=>e._uintid===r.stream_id);e?e._trust_in_room_=!0:(e=new AA(r.string_id||r.stream_id,r.stream_id),this._users.push(e),this.store.firstVideoFrameDecoded(e.uid,{userJoinNotify:Date.now()}),0===this.getListeners(gi.PUBLISHED_USER_LIST).length&&(TY.debug("[".concat(this._clientId,"] user online"),r.stream_id),this.safeEmit(gi.USER_JOINED,e)));let n=v7.Audio&r.stream_type,o=(v7.Video|v7.LwoVideo)&r.stream_type,a=0!=(65280&r.stream_type),s=n&&e.hasAudio,c=o&&e.hasVideo;o&&(e._trust_video_stream_added_state_=!0,e._video_added_=!0,e._videoSSRC=r.video_ssrc,e._rtxSsrcId=r.video_rtx),n&&(e._trust_audio_stream_added_state_=!0,e._audio_added_=!0,e._audioSSRC=r.audio_ssrc),n&&!s&&0===this.getListeners(gi.PUBLISHED_USER_LIST).length&&(TY.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published audio")),this.safeEmit(gi.USER_PUBLISHED,e,"audio")),o&&!c&&0===this.getListeners(gi.PUBLISHED_USER_LIST).length&&(TY.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published video")),this.safeEmit(gi.USER_PUBLISHED,e,"video")),(n&&!s||o&&!c||a)&&t.push(e),o&&this._p2pChannel.hasPendingRemoteMedia(e,"video")&&i.push({user:e,mediaType:"video"}),n&&this._p2pChannel.hasPendingRemoteMedia(e,"audio")&&i.push({user:e,mediaType:"audio"})}i.length>0&&(TY.debug("[".concat(this._clientId,"] RE massSubscribe after reconnect ").concat(i.map(e=>"user: ".concat(e.user.uid,", mediaType: ").concat(e.mediaType)).join("; ")," ")),this.massSubscribe(i).catch(e=>{TY.error("[".concat(this._clientId,"] mass resubscribe error"),e.toString())})),this.getListeners(gi.PUBLISHED_USER_LIST).length>0?TR("ENABLE_DATASTREAM_2")?this._pendingPublishedUsers=t:(TY.info("[".concat(this._clientId,"] client emit user-list event, users: ").concat(t.map(e=>e.uid).join(", "))),this.safeEmit(gi.PUBLISHED_USER_LIST,t)):TY.info("[".concat(this._clientId,"] client not emit user-list event case there is no user-list listener, users: ").concat(t.map(e=>e.uid).join(", ")))}),this._gateway.signal.on(vG.ON_RTP_CAPABILITY_CHANGE,e=>{let{video_codec:t}=e;if(this._p2pChannel instanceof bh){if("audience"===this.role&&TR("UPDATE_RTP_CAP_IN_HOST"))return this._pendingRtpCapabilityChange=e,void TY.debug("[".concat(this._clientId,"] no need to change rtp capability because of audience, params: ").concat(JSON.stringify(e)));this._p2pChannel.updateRemoteRTPCapabilities(t.map(e=>e.toLowerCase()).filter(e=>{var t;return o5(t=Object.keys(TI)).call(t,e)}))}}),this._gateway.signal.on(vF.VOS_FALLBACK_PROMISE,async(e,t,i)=>{if("FALLBACKCN"===e&&TR("ENABLE_QUALITY_FALLBACK")){if(!this._joinInfo)return i(new T0(SU.UNEXPECTED_ERROR,"can not recover, no join info"));TY.info("[".concat(this._clientId,"] try fallback to cn, start request new server info"));let n=this._joinInfo.apRequestDetail;try{this._joinInfo.apRequestDetail=e;let r=await Aa(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||gH,this.store);if(TR("QUALITY_FALLBACK_REHEARSAL"))return T$.reportApiInvoke(this._sessionId,{name:S3.VOS_FALLBACK_CN,options:{cur:r.gatewayInfo.gatewayAddrs,prev:this._joinInfo.gatewayAddrs,is_done:!1},tag:S5.TRACER}).onSuccess(),this._joinInfo.apRequestDetail=n,void i();this._fallbackServerInfo=r,t()}catch(t){var r;let e=null==t||null==(r=t.data)?void 0:r.desc;TR("QUALITY_FALLBACK_REHEARSAL")?(T$.reportApiInvoke(this._sessionId,{name:S3.VOS_FALLBACK_CN,options:{cur:"failed, errorReason: "+e,prev:this._joinInfo.gatewayAddrs,is_done:!1},tag:S5.TRACER}).onSuccess(),this._joinInfo.apRequestDetail=n):Array.isArray(e)&&o5(e).call(e,"request downgrade fallback")&&this.safeEmit(gi.FALLBACK_TO_HLS,gr.AP_ERROR),i(t)}}else i()})}_handleP2PEvents(){this._gateway.signal.on(vG.ON_USER_OFFLINE,()=>{this._p2pChannel.disconnectForReconnect()}),this._gateway.signal.on(yy.PUBLISH,(e,t,i)=>{let{uid:r}=e;
1e.forEach(e=>{let{kind:n,ssrcs:o,mid:a,isMuted:s}=e;this._handleP2PAddAudioOrVideoStream(n,r,o[0].ssrcId,a);let c=this._users.find(e=>e.uid===r);return c&&this.store.useP2P?this._p2pChannel.mockSubscribe(c,n,o[0].ssrcId,a).then(()=>{t()}).catch(i):t(),this._handleMuteStream(r,n,!!s)})}),this._gateway.signal.on(yy.CALL,async(e,t,i)=>{if(this.store.useP2P)try{var r;t(await this._p2pChannel.startP2P({turnServer:null==(r=this._joinInfo)?void 0:r.turnServer},e))}catch(e){i(e)}}),this._gateway.signal.on(vF.P2P_CONNECTION,async e=>{this.store.useP2P&&(await this._p2pChannel).p2pConnect(e)}),this._gateway.signal.on(yy.UNPUBLISH,async(e,t,i)=>{if(this.store.useP2P){let{unpubMsg:r,uid:n}=e,o=this._users.find(e=>e.uid===n);if(!o)return TY.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(n)),void t();try{r.forEach(async e=>{let{stream_type:t}=e,i=t===v6.Audio?yc.AUDIO:yc.VIDEO;await this._p2pChannel.unsubscribe(o,i),this._handleMuteStream(n,i,!0)}),t()}catch(e){i(e)}}}),this._gateway.signal.on(yy.CONTROL,async(e,t)=>{let{action:i}=e;switch(i){case yA.MUTE_LOCAL_VIDEO:this._handleMuteStream(t,yc.VIDEO,!0);break;case yA.MUTE_LOCAL_AUDIO:this._handleMuteStream(t,yc.AUDIO,!0);break;case yA.UNMUTE_LOCAL_VIDEO:this._handleP2PAddAudioOrVideoStream("video",t),this._handleMuteStream(t,yc.VIDEO,!1);break;case yA.UNMUTE_LOCAL_AUDIO:this._handleP2PAddAudioOrVideoStream("audio",t),this._handleMuteStream(t,yc.AUDIO,!1)}}),this._gateway.signal.on(yy.RESTART_ICE,async(e,t,i)=>{if(this.store.useP2P)try{let{direction:i,iceParameter:r}=e;i!==vW.SEND_ONLY||r?t(await this._p2pChannel.restartICE(i,r)):(this._p2pChannel.handleDisconnect(i),t())}catch(e){i(e)}}),this._gateway.signal.on(yy.CANDIDATE,e=>{if(this.store.useP2P){let{candidate:t,direction:i}=e;this._p2pChannel.addRemoteCandidate(t,i)}}),this._p2pChannel.on(y_.RequestP2PRestartICE,async(e,t,i)=>{try{let{direction:i}=e;t(await this._gateway.sendExtensionMessage(yy.RESTART_ICE,e,i===vW.SEND_ONLY))}catch(e){i(e)}}),this._p2pChannel.on(y_.LocalCandidate,e=>{this._gateway.sendExtensionMessage(yy.CANDIDATE,JSON.stringify(e),!0)}),this._p2pChannel.on(y_.RequestP2PMuteLocal,async(e,t,i)=>{try{await this._gateway.sendExtensionMessage(yy.CONTROL,e,!0),t()}catch(e){i(e)}}),this._p2pChannel.on(y_.RequestP2PUnmuteRemote,async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.unmuteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===SU.DISCONNECT_P2P?t():i(e)}else t()}),this._p2pChannel.on(y_.RequestP2PMuteRemote,async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.muteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===SU.DISCONNECT_P2P?t():i(e)}else t()}),this._p2pChannel.on(y_.StateChange,(e,t)=>{t===yp.Connected&&this._p2pChannel.republish()})}_handleP2PChannelEvents(){this._p2pChannel.on(y_.PeerConnectionStateChange,e=>{let t=this._peerConnectionState;e!==t&&(this.safeEmit(gi.PEERCONNECTION_STATE_CHANGE,e,t),this._peerConnectionState=e)}),this._p2pChannel.on(y_.RequestMuteLocal,async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.muteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===SU.DISCONNECT_P2P?t():i(e)}else t()}),this._p2pChannel.on(y_.RequestUnmuteLocal,async(e,t,i)=>{if(this._joinInfo)try{await this._gateway.unmuteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===SU.DISCONNECT_P2P?t():i(e)}else t()}),this._p2pChannel.on(y_.RequestRePublish,(e,t,i)=>{this.publish(e,!1).then(t).catch(i)}),this._p2pChannel.on(y_.RequestRePublishDataChannel,(e,t,i)=>{dQ.all(e.map(async e=>{let t=await this._p2pChannel.publishDataChannel([e]);try{t.forEach(e=>{this._uid&&this._gateway.publishDataChannel(this._uid,e,!0)})}catch(e){if(e.code!==SU.DISCONNECT_P2P)throw e}})).then(t).catch(i)}),this._p2pChannel.on(y_.RequestReSubscribe,async(e,t,i)=>{try{for(let{user:t,kind:i}of e)i===yc.VIDEO?await this.subscribe(t,"video"):await this.subscribe(t,"audio");t()}catch(e){i(e)}}),this._p2pChannel.on(y_.RequestUpload,(e,t)=>{this._gateway.upload(e,t)}),this._p2pChannel.on(y_.RequestUploadStats,e=>{this._gateway.uploadWRTCStats(e)}),this._p2pChannel.on(y_.MediaReconnectStart,e=>{this.safeEmit(gi.MEDIA_RECONNECT_START,e)}),this._p2pChannel.on(y_.MediaReconnectEnd,e=>{this.safeEmit(gi.MEDIA_RECONNECT_END,e)}),this._p2pChannel.on(y_.NeedSignalRTT,e=>{e(this._gateway.getSignalRTT())}),this._p2pChannel.on(y_.RequestRestartICE,async e=>{let t;if(this.store.useP2P)return;let i=await this._p2pChannel.restartICE(e),r=await i.next();if(r.done)return;let n=r.value;try{t=await this._gateway.restartICE({iceParameters:n})}catch(e){return void i.throw(e)}let{iceParameters:o}=function(e){let t=e.iceParameters;
1return{iceParameters:{iceUfrag:t.iceUfrag,icePwd:t.icePwd}}}(t);await i.next({remoteIceParameters:o})}),this._p2pChannel.on(y_.RequestReconnect,async()=>{this._gateway.reconnect()}),this._p2pChannel.on(y_.RequestReconnectPC,async()=>{var e;let{iceParameters:t,dtlsParameters:i,rtpCapabilities:r}=await this._p2pChannel.startP2PConnection({turnServer:null==(e=this._joinInfo)?void 0:e.turnServer}),{gatewayEstablishParams:n,gatewayAddress:o}=await this._gateway.reconnectPC({iceParameters:t,dtlsParameters:i,rtpCapabilities:r}),a=Iu(n,o);await this._p2pChannel.connect(a),await this._p2pChannel.republish(),await this._p2pChannel.reSubscribe()}),this._p2pChannel.on(y_.RequestUnpublishForReconnectPC,async(e,t,i)=>{this._joinInfo&&void 0!==this._uid?(await this._gateway.unpublish(e,this._uid),t()):i()}),this._p2pChannel.on(y_.P2PLost,()=>{this.safeEmit(gi.P2P_LOST,this.store.uid)}),this._p2pChannel.on(y_.UpdateVideoEncoder,e=>{e._encoderConfig&&this._gateway.setVideoProfile(e._encoderConfig)}),this._p2pChannel.on(y_.ConnectionTypeChange,e=>{this.safeEmit(gi.IS_USING_CLOUD_PROXY,e),this._gateway.setUsingProxy(e)}),this._p2pChannel.on(y_.FirstVideoBufferReady,(e,t)=>{this.safeEmit(gi.FIRST_VIDEO_BUFFER_READY,e,t)}),this._p2pChannel.on(y_.FirstVideoPreRender,(e,t)=>{this.safeEmit(gi.FIRST_VIDEO_PRE_RENDER,e,t)}),this._p2pChannel.on(y_.RequestLowStreamParameter,e=>{e(this._lowStreamParameter||{width:160,height:120,framerate:15,bitrate:50})}),this._p2pChannel.on(y_.QueryClientConnectionState,e=>{e(this.connectionState)}),this._p2pChannel.on(y_.AudioMetadata,e=>{this.safeEmit(gi.AUDIO_METADATA,e)}),this._p2pChannel.on(y_.AudioPts,e=>{this.safeEmit(gi.AUDIO_PTS,Number(e))})}getKeyMetrics(){return this.store.keyMetrics}async enableContentInspect(e){var t;if(!this._joinInfo||"CONNECTED"!==this.connectionState)throw new T0(SU.INVALID_OPERATION,"[".concat(this._clientId,"] can not create content inspect, please join channel first"));if(this._inspect)throw new T0(SU.INVALID_OPERATION,"[".concat(this._clientId,"] Inspect content service already in connecting/connected state"));try{let i=(t={config:e},IV("ContentInspect").create(t));this._inspect=i,this.handleVideoInspectEvents(i);let{appId:r,cname:n,sid:o,token:a,uid:s,cid:c,vid:d}=this._joinInfo;await i.init({appId:r,areaCode:"",cname:n,sid:o,token:a,uid:s,cid:c,vid:d?Number(d):0},gH)}catch(e){throw Array.isArray(e)?e[0]:e}}handleVideoInspectEvents(e){e.on(yf.CONNECTION_STATE_CHANGE,(t,i)=>{if(this.safeEmit(gi.CONTENT_INSPECT_CONNECTION_STATE_CHANGE,t,i),i===yE.CONNECTED){if("CONNECTED"!==this.connectionState)return void this.safeEmit(gi.CONTENT_INSPECT_ERROR,new T0(SU.OPERATION_ABORTED,"Content inspect was cancelled because it left the channel"));e.inspectImage()}}),e.on(yf.INSPECT_RESULT,(e,t)=>{var i;if((null==t?void 0:t.code)===SU.INVALID_OPERATION&&"DISCONNECTED"===this.connectionState)return TY.debug("Stop inspect content because that has left channel"),null==this||null==(i=this._inspect)||i.close(),void(this._inspect=void 0);this.safeEmit(gi.CONTENT_INSPECT_RESULT,e,t)}),e.on(yf.CLIENT_LOCAL_VIDEO_TRACK,e=>{e(this.localTracks.filter(e=>"video"===e.trackMediaType)[0])})}async disableContentInspect(){if(!this._inspect)throw new T0(SU.INVALID_OPERATION,"[".concat(this._clientId,"] inspectVideoContent not started"));try{this._inspect.close(),this._inspect=void 0}catch(e){throw Array.isArray(e)?e[0]:e}}async setImageModeration(e,t){if(SV(e,"enabled"),e){if(!t)throw new T0(SU.INVALID_PARAMS,"config is required");if(Os(t),!this._joinInfo)throw new T0(SU.INVALID_OPERATION,"can not create image moderation, please join channel first");try{if(this._moderation)this._moderation.updateConfig(t);else{let e=(i={config:t},IV("ImageModeration").create(i));this._moderation=e,this.handleImageModerationEvents(e);let{appId:r,cname:n,sid:o,token:a,uid:s,cid:c,vid:d}=this._joinInfo;await e.init({appId:r,areaCode:"",cname:n,sid:o,token:a,uid:s,cid:c,vid:d?Number(d):0},gH)}}catch(e){throw Array.isArray(e)?e[0]:e}}else{var i;if(!this._moderation)throw new T0(SU.INVALID_OPERATION,"[".concat(this._clientId,"] image moderation not started"));try{this._moderation.close(),this._moderation.removeAllListeners(),this._moderation=void 0}catch(e){throw Array.isArray(e)?e[0]:e}}}handleImageModerationEvents(e){e.on(yC.CONNECTION_STATE_CHANGE,(t,i)=>{if(this.safeEmit(gi.IMAGE_MODERATION_CONNECTION_STATE_CHANGE,t,i),t===yR.CONNECTED){if("CONNECTED"!==this.connectionState)throw this.setImageModeration(!1),new T0(SU.OPERATION_ABORTED,"Image moderation was cancelled because it left the channel");e.inspectImage()}}),e.on(yC.CLIENT_LOCAL_VIDEO_TRACK,e=>{e(this.localTracks.filter(e=>"video"===e.trackMediaType)[0])})}setP2PTransport(e){if(SF(e,"transport",["default","auto","relay","sd-rtn"]),"p2p"!==this.mode)throw new T0(SU.INVALID_OPERATION,"only p2p mode can set p2pTransport");this.store.p2pTransport=e,TY.info("[".concat(this._clientId,"] set client p2pTransport to ").concat(e))}getJoinChannelServiceRecords(){return TY.debug("getJoinChannelServiceRecords"),this.store.joinChannelServiceRecords}async setPublishAudioFilterEnabled(e){SV(e,"enabled"),TT("ENABLE_PUBLISH_AUDIO_FILTER",e),this._joinInfo&&await this._gateway.setPublishAudioFilterEnabled(e)}_setRteInfo(e,t){this.store.rteUrl=e,this.store.rteSid=t}
vendor: 1,840 bytes, line 1
1_isPreRender(){return"isPreRender"in this._p2pChannel&&this._p2pChannel.isPreRender()}_handleResetAddStream(e,t){switch(t){case"audio":e._audio_added_=!1,e._trust_audio_stream_added_state_=!0;break;case"video":e._video_added_=!1,e._trust_video_stream_added_state_=!0}}constructor(e,t){var i;let r;if(super(),mb(this,"store",void 0),mb(this,"_uid",void 0),mb(this,"_channelName",void 0),mb(this,"_uintUid",void 0),mb(this,"_users",[]),mb(this,"_config",void 0),mb(this,"_clientId",void 0),mb(this,"_appId",void 0),mb(this,"_sessionId",null),mb(this,"_key",void 0),mb(this,"_rtmConfig",{}),mb(this,"_joinInfo",void 0),mb(this,"_gateway",void 0),mb(this,"_statsCollector",void 0),mb(this,"_configDistribute",void 0),mb(this,"_leaveMutex",void 0),mb(this,"_publishMutex",void 0),mb(this,"_renewTokenMutex",void 0),mb(this,"_subscribeMutex",void 0),mb(this,"_encryptionMode","none"),mb(this,"_encryptionSecret",null),mb(this,"_encryptionSalt",null),mb(this,"_encryptDataStream",!1),mb(this,"_encryptDataStreamKey",null),mb(this,"_encryptDataStreamIv",null),mb(this,"_proxyServer",void 0),mb(this,"_turnServer",{servers:[],mode:"auto"}),mb(this,"_cloudProxyServerMode","disabled"),mb(this,"_isDualStreamEnabled",!1),mb(this,"_defaultStreamFallbackType",void 0),mb(this,"_lowStreamParameter",void 0),mb(this,"_streamFallbackTypeCacheMap",new Map),mb(this,"_remoteStreamTypeCacheMap",new Map),mb(this,"_axiosCancelSource",f0.CancelToken.source()),mb(this,"_audioVolumeIndicationInterval",void 0),mb(this,"_networkQualityInterval",void 0),mb(this,"_userOfflineTimeout",void 0),mb(this,"_streamRemovedTimeout",void 0),mb(this,"_rteDetailInterval",void 0),mb(this,"_liveTranscodeStreamingClient",void 0),mb(this,"_liveRawStreamingClient",void 0),mb(this,"_channelMediaRelayClient",void 0),mb(this,"_networkQualitySensitivity","normal"),mb(this,"_p2pCh
1annel",void 0),mb(this,"_useLocalAccessPoint",!1),mb(this,"_setLocalAPVersion",void 0),mb(this,"_joinAndNotLeaveYet",!1),mb(this,"_numberOfJoinCount",0),mb(this,"_joinResponse",null),mb(this,"_remoteDefaultVideoStreamType",void 0),mb(this,"_inspect",void 0),mb(this,"_moderation",void 0),mb(this,"_license",void 0),mb(this,"_pendingPublishedUsers",[]),mb(this,"ntpAlignErrorCount",0),mb(this,"remoteInboundOffset",0),mb(this,"_peerConnectionState",void 0),mb(this,"_pendingRtpCapabilityChange",void 0),mb(this,"_fallbackServerInfo",void 0),mb(this,"_dualStreamMode",void 0),mb(this,"_handleLocalTrackEnable",(e,t,i)=>{this.publish(e,!1).then(t).catch(i)}),mb(this,"_handleLocalTrackDisable",(e,t,i)=>{this.unpublish(e).then(t).catch(i)}),mb(this,"_handleUserOnline",e=>{if(TR("BLOCK_LOCAL_CLIENT")&&v_(e.uid,this.channelName))return void TY.debug("[".concat(e.uid,"] will be ignored in local"));this.isStringUID&&"string"!=typeof e.uid&&TY.error("[".concat(this._clientId,"] StringUID is Mixed with UintUID"));let t=this._users.find(t=>t.uid===e.uid);if(t)t._trust_in_room_=!0,t._is_pre_created&&(t._is_pre_created=!1,this.safeEmit(gi.USER_JOINED,t));else{let t=new AA(e.uid,e.uint_id||e.uid);this._users.push(t),TY.debug("[".concat(this._clientId,"] user online"),e.uid),this.store.firstVideoFrameDecoded(t.uid,{userJoinNotify:Date.now()}),this.safeEmit(gi.USER_JOINED,t)}}),mb(this,"_handleUserOffline",e=>{if(TR("BLOCK_LOCAL_CLIENT")&&v_(e.uid,this.channelName))return;let t=this._users.find(t=>t.uid===e.uid);t&&(this._handleRemoveStream(e),this._handleRemoveDataChannels(e),t._audio_pre_subscribed||t._video_pre_subscribed?t._is_pre_created=!0:gE(this._users,t),this._remoteStreamTypeCacheMap.delete(t.uid),this._streamFallbackTypeCacheMap.delete(t.uid),TY.debug("[".concat(this._clientId,"] user offline"),e.uid,"reason:",e.reason),this.safeEmit(gi.USER_LEAVED,t,e.reason))}),mb(this,"_handleAddAudioOrVideoStream",(e,t,i,r,n,o,a,s)=>{if(TR("BLOCK_LOCAL_CLIENT")&&v_(t,this.channelName))return;let c=this._users.find(e=>e.uid===t);if(!c)return void TY.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));TY.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(c.uid,e,void 0,void 0,void 0,Date.now()),"video"===e&&this.store.firstVideoFrameDecoded(c.uid,{videoAddNotify:Date.now()});let d="audio"===e?c.hasAudio:c.hasVideo;c._uintid||(c._uintid=o||t),"audio"===e?c._trust_audio_stream_added_state_=!0:c._trust_video_stream_added_state_=!0,"audio"===e?(c._audio_added_=!0,void 0!==i&&(c._audioSSRC=i),void 0!==r&&(c._cname=r),a&&(c._audioOrtc=a)):(c._video_added_=!0,void 0!==i&&(c._videoSSRC=i),void 0!==r&&(c._cname=r),void 0!==s&&(c._rtxSsrcId=s),a&&(c._videoOrtc=a)),("audio"===e?c.hasAudio:c.hasVideo)&&!d&&(TY.info("[".concat(this._clientId,"] remote user ").concat(c.uid," published ").concat(e)),this.safeEmit(gi.USER_PUBLISHED,c,e)),"video"===e?T$.onGatewayStream(this._sessionId,TX.ON_ADD_VIDEO_STREAM,TJ.ON_ADD_VIDEO_STREAM,{peer:o||t,ssrc:c._videoSSRC}):T$.onGatewayStream(this._sessionId,TX.ON_ADD_AUDIO_STREAM,TJ.ON_ADD_AUDIO_STREAM,{peer:o||t,ssrc:c._audioSSRC}),this._p2pChannel.remoteMediaSsrcChanged(c,e,i).then(t=>{if(t&&(TY.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(c.uid," after rejoin because SSRC id changed.")),this._p2pChannel instanceof bh))return this._p2pChannel.unsubscribe(c,e,!0).then(()=>this._subscribe(c,e,!0).catch(e=>{TY.error("[".concat(this._clientId,"] resubscribe error"),e.toString())}))}),this._p2pChannel.hasPendingRemoteMedia(c,e)&&(TY.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(c.uid," after reconnect.")),this._subscribe(c,e,!0).catch(e=>{TY.error("[".concat(this._clientId,"] resubscribe error"),e.toString())}));let l=this._getEncodingName(n);"video"===e&&("unknown"===l?this.safeEmit(gi.AV1_DECODABLE_RESULT,!1):Ss()||Sh()||(null==l?void 0:l.toLocaleLowerCase())!==TI.av1||Ao().then(e=>{TR("FLS_ENABLE_AV1_DECODE_DETECT")&&this.safeEmit(gi.AV1_DECODABLE_RESULT,e),e||this._gateway.downgradeCodec(l)}))}),mb(this,"_handleRemoveStream",e=>{if(TR("BLOCK_LOCAL_CLIENT")&&v_(e.uid,this.channelName))return;let t=this._users.find(t=>t.uid===e.uid);if(!t)return void TY.warning("[".concat(this._clientId,"] can not find target user!(on_remove_stream)"));TY.debug("[".concat(this._clientId,"] stream removed with uid ").concat(e.uid));let i=()=>{};t.hasAudio&&t.hasVideo?i=()=>{TY.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(gi.USER_UNPUBLISHED,t,"audio"),TY.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(gi.USER_UNPUBLISHED,t,"video")}:t.hasVideo?i=()=>{TY.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(gi.USER_UNPUBLISHED,t,"video")}:t.hasAudio&&(i=()=>{TY.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(gi.USER_UNPUBLISHED,t,"audio")}),t._video_pre_subscribed||t._audio_pre_subscribed||(t._trust_audio_stream_added_state_=!0,t._trust_video_stream_added_state_=!0,t._audio_added_=!1,t._video_added_=!1,this._p2pChannel instanceof bh&&this._p2pChannel.unsubscribe(t).then(e=>{if(e)return this._gateway.unsubscribe(e,t.uid)}),t._audioSSRC=void 0,t._videoSSRC=void 0,t._audioOrtc=void 0,t._videoOrtc=void 0,t._rtxSsrcId=void 0),T$.onGatewayStream(this._sessionId,TX.ON_REMOVE_STREAM,TJ.ON_REMOVE_STREAM,{peer:e.uint_id||e.uid}),i()}),mb(this,"_handleSetStreamLocalEnable",(e,t,i)=>{if(TR("BLOCK_LOCAL_CLIENT")&&v_(t,this.channelName))return;let r=this._users.find(e=>e.uid===t);if(!r)return void TY.error("[".concat(this._clientId,"] can not find target user!(disable_local)"));TY.debug("[".concat(this._clientId,"] local ").concat(e," ").concat(i?"enabled":"disabled"," with uid ").concat(t));let n="audio"===e?r.hasAudio:r.hasVideo;if("audio"===e){r._trust_audio_enabled_state_=!0;let e=r._audio_enabled_;if(r._audio_enabled_=i,r._audio_enabled_===e)return;{let e=r._audio_enabled_?"enable-local-audio":"disable-local-audio";TY.debug("[".concat(this._clientId,"] user-info-updated, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(gi.USER_INFO_UPDATED,t,e)}}else{r._trust_video_enabled_state_=!0;let e=r._video_enabled_;if(r._video_enabled_=i,r._video_enabled_===e)return;{let e=r._video_enabled_?"enable-local-video":"disable-local-video";TY.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(gi.USER_INFO_UPDATED,t,e)}}let o="audio"===e?r.hasAudio:r.hasVideo;return n!==o?!n&&o?(TY.info("[".concat(this._clientId,"] remote user ").concat(t," published ").concat(e)),void this.safeEmit(gi.USER_PUBLISHED,r,e)):("video"===e&&r._videoTrack&&r._videoTrack._destroy(),"audio"===e&&r._audioTrack,this._p2pChannel.muteRemote(r,e),TY.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished ").concat(e)),void this.safeEmit(gi.USER_UNPUBLISHED,r,e)):void 0}),mb(this,"_handleMuteStream",(e,t,i)=>{if(TR("BLOCK_LOCAL_CLIENT")&&v_(e,this.channelName))return;TY.debug("[".concat(this._clientId,"] receive mute message"),e,t,i);let r=this._users.find(t=>t.uid===e);if(!r)return void TY.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(e));let n="audio"===t?r.hasAudio:r.hasVideo;if("audio"===t){r._trust_audio_mute_state_=!0;let t=r._audio_muted_;if(r._audio_muted_=i,r._audio_muted_===t)return;{let t=r._audio_muted_?"mute-audio":"unmute-audio";TY.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(gi.USER_INFO_UPDATED,e,t)}}else{r._trust_video_mute_state_=!0;let t=r._video_muted_;if(r._video_muted_=i,r._video_muted_===t)return;{let t=r._video_muted_?"mute-video":"unmute-video";TY.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(gi.USER_INFO_UPDATED,e,t)}}let o="audio"===t?r.hasAudio:r.hasVideo;if(n!==o){if(!n&&o)return("audio"===t?r._audioSSRC:r._videoSSRC)?(TY.info("[".concat(this._clientId,"] remote user ").concat(e," published ").concat(t)),void this.safeEmit(gi.USER_PUBLISHED,r,t)):void TY.warning("[".concat(this._clientId,"] remote user ").concat(e," receive ").
1concat(t," unmute message before add stream message, ").concat(t," SSRC doesn't exist yet."));"video"===t&&r._videoTrack&&!r._video_pre_subscribed&&r._videoTrack._destroy(),"audio"===t&&r._audioTrack,this._p2pChannel.muteRemote(r,t),TY.info("[".concat(this._clientId,"] remote user ").concat(e," unpublished ").concat(t)),this.safeEmit(gi.USER_UNPUBLISHED,r,t)}}),mb(this,"_handleP2PLost",async e=>{TY.debug("[".concat(this._clientId,"] receive p2p lost"),e),parseInt(e.p2pid,10)===this.store.p2pId?await this._p2pChannel.requestReconnect():TY.warning("[".concat(this._clientId,"] P2PLost stream not found"),e)}),mb(this,"_handleTokenWillExpire",()=>{TY.debug("[".concat(this._clientId,"] received message onTokenPrivilegeWillExpire")),this.safeEmit(gi.ON_TOKEN_PRIVILEGE_WILL_EXPIRE)}),mb(this,"_handleBeforeUnload",e=>{"beforeunload"===e.type&&void 0!==e.returnValue&&""!==e.returnValue||(this.leave(),TY.info("[".concat(this._clientId,"] auto leave onbeforeunload or pagehide")))}),mb(this,"_handleUpdateNetworkQuality",()=>{if("normal"===this._networkQualitySensitivity)return;if(navigator&&void 0!==navigator.onLine&&!navigator.onLine)return void this.safeEmit(gi.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6});let e={downlinkNetworkQuality:0,uplinkNetworkQuality:0};e.uplinkNetworkQuality=this._p2pChannel.getUplinkNetworkQuality(),e.downlinkNetworkQuality=this._p2pChannel.getDownlinkNetworkQuality(),this.safeEmit(gi.NETWORK_QUALITY,e)}),mb(this,"_handleP2PAddAudioOrVideoStream",(e,t,i,r)=>{let n=this._users.find(e=>e.uid===t);if(!n)return void TY.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));TY.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(n.uid,e,void 0,void 0,void 0,Date.now());let o="audio"===e?n.hasAudio:n.hasVideo;"audio"===e?n._trust_audio_stream_added_state_=!0:n._trust_video_stream_added_state_=!0,"audio"===e?(n._audio_added_=!0,void 0!==i&&(n._audioSSRC=i),void 0!==r&&(n._audioMid=r)):(n._video_added_=!0,void 0!==i&&(n._videoSSRC=i),void 0!==r&&(n._videoMid=r)),("audio"===e?n.hasAudio:n.hasVideo)&&!o&&(TY.info("[".concat(this._clientId,"] remote user ").concat(n.uid," published ").concat(e)),this.safeEmit(gi.USER_PUBLISHED,n,e)),this._p2pChannel.hasPendingRemoteMedia(n,e)&&(TY.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(n.uid," after reconnect.")),this._subscribe(n,e,!0).catch(e=>{TY.error("[".concat(this._clientId,"] resubscribe error"),e.toString())}))}),this._config=e,this._clientId=t||gw(5,"client-"),this.store=new class{dispatch(e){this.state=function(e,t){switch(t.type){case Ty.SET_SESSION_ID:return SM(SM({},e),{},{sessionId:t.sessionId});case Ty.SET_P2P_ID:return SM(SM({},e),{},{p2pId:t.p2pId});case Ty.SET_UID:return SM(SM({},e),{},{uid:t.uid});case Ty.SET_INT_UID:return SM(SM({},e),{},{intUid:t.intUid});case Ty.SET_PUB_ID:return SM(SM({},e),{},{pubId:t.pubId});case Ty.KEY_METRIC_CLIENT_CREATED:return SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{clientCreated:t.metric})});case Ty.KEY_METRIC_JOIN_START:return SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{joinStart:t.metric})});case Ty.KEY_METRIC_PRELOAD_START:return SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{preloadStart:t.metric})});case Ty.KEY_METRIC_PRELOAD_END:return SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{preloadEnd:t.metric})});case Ty.KEY_METRIC_JOIN_END:return SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{joinEnd:t.metric})});case Ty.KEY_METRIC_REQUEST_AP_START:return SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{requestAPStart:t.metric})});case Ty.KEY_METRIC_REQUEST_AP_END:return SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{requestAPEnd:t.metric})});case Ty.KEY_METRIC_REQUEST_SUA_END:return SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{requestSUAEnd:t.metric})});case Ty.KEY_METRIC_BEFORE_CONNECT:return SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{beforeConnect:t.metric})});case Ty.KEY_METRIC_PEER_RECEIVER:return SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{peerReceiver:t.metric})});case Ty.KEY_METRIC_SIGNAL_CONNECTED:return SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{signalConnected:t.metric})});case Ty.KEY_METRIC_JOIN_REQ:return SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{joinReq:t.metric})});case Ty.KEY_METRIC_JOIN_REP:return SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{joinRep:t.metric})});case Ty.KEY_METRIC_JOIN_GATEWAY_START:return SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{joinGatewayStart:t.metric})});case Ty.KEY_METRIC_JOIN_GATEWAY_END:return SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{joinGatewayEnd:t.metric})});case Ty.KEY_METRIC_PEER_CONNECTION_START:return SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{peerConnectionStart:t.metric})});case Ty.KEY_METRIC_PEER_CONNECTION_END:return SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{peerConnectionEnd:t.metric})});case Ty.KEY_METRIC_DESCRIPTION_START:return SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{descriptionStart:t.metric})});case Ty.KEY_METRIC_SIGNAL_CHANNEL_OPEN:return SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{signalChannelOpen:t.metric})});case Ty.KEY_METRIC_ICE_CONNECTION_END:return SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{iceConnectionEnd:t.metric})});case Ty.KEY_METRIC_PUBLISH:{let i=e.keyMetrics.publish,r=i.findIndex(e=>e.trackId===t.metric.trackId);return -1!==r?(i[r]=SM(SM({},i[r]),t.metric),SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{publish:[...i]})})):SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{publish:[...e.keyMetrics.publish,t.metric]})})}case Ty.KEY_METRIC_SUBSCRIBE:{let i=e.keyMetrics.subscribe,r=i.findIndex(e=>e.userId===t.metric.userId&&e.type===t.metric.type);return -1!==r?(i[r]=SM(SM({},i[r]),t.metric),SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{subscribe:[...i]})})):SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{subscribe:[...e.keyMetrics.subscribe,t.metric]})})}case Ty.KEY_METRIC_FIRST_VIDEO_FRAME_DECODED:{let i=e.keyMetrics.first
vendor: 4,240 bytes, line 1
1VideoFrameDecoded,r=i.findIndex(e=>e.userId===t.metric.userId);return -1!==r?(i[r]=SM(SM({},i[r]),t.metric),SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{firstVideoFrameDecoded:[...i]})})):SM(SM({},e),{},{keyMetrics:SM(SM({},e.keyMetrics),{},{firstVideoFrameDecoded:[...e.keyMetrics.firstVideoFrameDecoded,t.metric]})})}case Ty.RESET_FIRST_VIDEO_FRAME_DECODED:return e.keyMetrics.firstVideoFrameDecoded=[],e;case Ty.SET_CLOUD_PROXY_SERVER_MODE:return e.cloudProxyServerMode=t.mode,e;case Ty.RECORD_JOIN_CHANNEL_SERVICE:return"number"!=typeof t.index?e.joinChannelServiceRecords=[...e.joinChannelServiceRecords,t.record]:(e.joinChannelServiceRecords[t.index]=SM(SM({},e.joinChannelServiceRecords[t.index]),t.record),e.joinChannelServiceRecords=[...e.joinChannelServiceRecords]),e;case Ty.RESET_JOIN_CHANNEL_SERVICE_RECORDS:return e.joinChannelServiceRecords=[],e;case Ty.RESET_KEY_METRICS:return e.keyMetrics={publish:[],subscribe:[],firstVideoFrameDecoded:[]},e;case Ty.SET_USE_P2P:return SM(SM({},e),{},{useP2P:t.val});case Ty.SET_TRANSPORT_TYPE:return SM(SM({},e),{},{p2pTransport:t.val});case Ty.SET_RTE_URL:return SM(SM({},e),{},{rteUrl:t.rteUrl});case Ty.SET_RTE_SID:return SM(SM({},e),{},{rteSid:t.rteSid});default:return e}}(this.state,e)}get useDcSignal(){return this.state.useDcSignal}set useDcSignal(e){this.state.useDcSignal=e}set autoSubscribe(e){this.state.autoSubscribe=e}get autoSubscribe(){return this.state.autoSubscribe}set enableInstantMuteRestore(e){this.state.enableInstantMuteRestore=e}get enableInstantMuteRestore(){return this.state.enableInstantMuteRestore}set networkQualityProbe(e){this.state.networkQualityProbe=e}get networkQualityProbe(){return this.state.networkQualityProbe}set sessionId(e){this.dispatch({type:Ty.SET_SESSION_ID,sessionId:e})}get sessionId(){return this.state.sessionId}set rteUrl(e){this.dispatch({type:Ty.SET_RTE_URL,rteUrl:e})}get rteUrl(){return this.state.rteUrl}set rteSid(e){this.dispatch({type:Ty.SET_RTE_SID,rteSid:e})}get rteSid(){return this.state.rteSid}set cid(e){this.state.cid=e}get cid(){return this.state.cid}set codec(e){this.state.codec=e}get codec(){return this.state.codec}get mode(){return this.state.mode}get audioCodec(){return this.state.audioCodec}get clientId(){return this.state.clientId}set p2pId(e){this.dispatch({type:Ty.SET_P2P_ID,p2pId:e})}get p2pId(){return this.state.p2pId}set dcId(e){this.dispatch({type:Ty.SET_DC_ID,dcId:e})}get dcId(){return this.state.dcId}set uid(e){this.dispatch({type:Ty.SET_UID,uid:e})}get uid(){return this.state.uid}set intUid(e){this.dispatch({type:Ty.SET_INT_UID,intUid:e})}get intUid(){return this.state.intUid}set pubId(e){this.dispatch({type:Ty.SET_PUB_ID,pubId:e})}get pubId(){return this.state.pubId}set cloudProxyServerMode(e){this.dispatch({type:Ty.SET_CLOUD_PROXY_SERVER_MODE,mode:e})}get cloudProxyServerMode(){return this.state.cloudProxyServerMode}set useP2P(e){this.dispatch({type:Ty.SET_USE_P2P,val:e})}get useP2P(){return this.state.useP2P}set p2pTransport(e){this.dispatch({type:Ty.SET_TRANSPORT_TYPE,val:e})}get p2pTransport(){return this.state.p2pTransport}set hasStartJoinChannel(e){this.state.hasStartJoinChannel=e}get hasStartJoinChannel(){return this.state.hasStartJoinChannel}set isABTestSuccess(e){this.state.isABTestSuccess=e}get isABTestSuccess(){return this.state.isABTestSuccess}clientCreated(){this.dispatch({type:Ty.KEY_METRIC_CLIENT_CREATED,metric:Date.now()})}joinStart(){this.dispatch({type:Ty.KEY_METRIC_JOIN_START,metric:Date.now()})}preloadStart(){this.dispatch({type:Ty.KEY_METRIC_PRELOAD_START,metric:Date.now()})}preloadEnd(){this.dispatch({type:Ty.KEY_METRIC_PRELOAD_END,metric:Date.now()})}joinEnd(){this.dispatch({type:Ty.KEY_METRIC_JOIN_END,metric:Date.now()})}requestAPStart(){this.dispatch({type:Ty.KEY_METRIC_REQUEST_AP_START,metric:Date.now()})}requestAPEnd(){this.dispatch({type:Ty.KEY_METRIC_REQUEST_AP_END,metric:Date.now()})}requestSUAEnd(){this.dispatch({type:Ty.KEY_METRIC_REQUEST_SUA_END,metric:Date.now()})}beforeConnect(){this.dispatch({type:Ty.KEY_METRIC_BEFORE_CONNECT,metric:Date.now()})}peerReceiver(){this.dispatch({type:Ty.KEY_METRIC_PEER_RECEIVER,metric:Date.now()})}signalConnected(){this.dispatch({type:Ty.KEY_METRIC_SIGNAL_CONNECTED,metric:Date.now()})}
1joinReq(){this.dispatch({type:Ty.KEY_METRIC_JOIN_REQ,metric:Date.now()})}joinRep(){this.dispatch({type:Ty.KEY_METRIC_JOIN_REP,metric:Date.now()})}joinGatewayStart(){this.dispatch({type:Ty.KEY_METRIC_JOIN_GATEWAY_START,metric:Date.now()})}joinGatewayEnd(){this.dispatch({type:Ty.KEY_METRIC_JOIN_GATEWAY_END,metric:Date.now()})}peerConnectionStart(){this.dispatch({type:Ty.KEY_METRIC_PEER_CONNECTION_START,metric:Date.now()})}peerConnectionEnd(){this.dispatch({type:Ty.KEY_METRIC_PEER_CONNECTION_END,metric:Date.now()})}firstVideoFrameDecoded(e,t){this.dispatch({type:Ty.KEY_METRIC_FIRST_VIDEO_FRAME_DECODED,metric:SM({userId:e},t)})}descriptionStart(){this.dispatch({type:Ty.KEY_METRIC_DESCRIPTION_START,metric:Date.now()})}signalChannelOpen(){this.dispatch({type:Ty.KEY_METRIC_SIGNAL_CHANNEL_OPEN,metric:Date.now()})}iceConnectionEnd(){this.dispatch({type:Ty.KEY_METRIC_ICE_CONNECTION_END,metric:Date.now()})}publish(e,t,i,r){this.dispatch({type:Ty.KEY_METRIC_PUBLISH,metric:SM(SM({trackId:e,type:t},i&&{publishStart:i}),r&&{publishEnd:r})})}subscribe(e,t,i,r,n,o,a){this.dispatch({type:Ty.KEY_METRIC_SUBSCRIBE,metric:SM(SM(SM(SM(SM({userId:e,type:t},i&&{subscribeStart:i}),r&&{subscribeEnd:r}),n&&{firstFrame:n}),o&&{streamAdded:o}),a&&{firstDecoded:a})})}massSubscribe(e,t,i,r){e.forEach(e=>{this.dispatch({type:Ty.KEY_METRIC_SUBSCRIBE,metric:SM(SM(SM({userId:e.userId,type:e.type},t&&{subscribeStart:t}),i&&{subscribeEnd:i}),r&&{firstFrame:r})})})}get keyMetrics(){return this.state.keyMetrics}recordJoinChannelService(e,t){"gateway"===e.service&&Array.isArray(e.urls)&&(e.urls=e.urls.map(e=>e.replace(/(\d+)-\d+-\d+-(\d+)/,"$1-*-*-$2")));try{return"number"!=typeof t?(this.dispatch({type:Ty.RECORD_JOIN_CHANNEL_SERVICE,record:SM(SM({},e),{},{sessionId:this.sessionId,cloudProxyMode:this.cloudProxyServerMode,uid:this.uid})}),this.state.joinChannelServiceRecords.length-1):(t<0||t>=this.state.joinChannelServiceRecords.length||this.dispatch({type:Ty.RECORD_JOIN_CHANNEL_SERVICE,record:e,index:t}),t)}catch(e){return 0}}resetJoinChannelServiceRecords(){this.dispatch({type:Ty.RESET_JOIN_CHANNEL_SERVICE_RECORDS})}resetKeyMetrics(){this.dispatch({type:Ty.RESET_KEY_METRICS})}resetFirstVideoFrameDecoded(){this.dispatch({type:Ty.RESET_FIRST_VIDEO_FRAME_DECODED})}get joinChannelServiceRecords(){try{return this.state.joinChannelServiceRecords}catch(e){return[]}}constructor(e,t,i,r,n){SL(this,"state",void 0),this.state={codec:e,audioCodec:t,mode:i,clientId:r,sessionId:null,p2pId:0,dcId:0,pubId:0,subId:0,keyMetrics:{publish:[],subscribe:[],firstVideoFrameDecoded:[]},joinChannelServiceRecords:[],cloudProxyServerMode:"disabled",useP2P:!1,p2pTransport:Tp.Default,hasStartJoinChannel:!1,isABTestSuccess:!1,rteUrl:void 0,rteSid:void 0,autoSubscribe:!1,enableInstantMuteRestore:!1,networkQualityProbe:!1,useDcSignal:!!n}}}(e.codec,e.audioCodec,e.mode,this._clientId,1===TR("SIGNAL_CHANNEL")),this._leaveMutex=new gG("client-leave",this._clientId),this._publishMutex=new gG("client-publish",this._clientId),this._renewTokenMutex=new gG("client-renewtoken",this._clientId),this._subscribeMutex=new gG("client-subscribe",this._clientId),this.store.clientCreated(),e.proxyServer&&this.setProxyServer(e.proxyServer,!0),e.turnServer&&this.setTurnServer(e.turnServer,!0),TY.info("[".concat(this._clientId,"] Initializing AgoraRTC client v").concat(Th," build: ").concat(Tf,", mode: ").concat(this.mode,", codec: ").concat(this.codec)),e.clientRoleOptions)try{gt(e.clientRoleOptions),r=Object.assign({},e.clientRoleOptions)}catch(e){TY.warning("[".concat(this._clientId,"] ").concat(e.toString()))}this._statsCollector=new Av(this.store),this._statsCollector.onStatsException=(e,t,i)=>{TY.warn("[".concat(this._clientId,"] receive exception msg, code: ").concat(e,", msg: ").concat(t,", uid: ").concat(i)),e===Ag.VIDEO_ENCODE_FAILED&&this.localTracks.forEach(e=>{e instanceof CL&&TR("ENABLE_ENCODE_EXCEPTION")&&e.findClosestProfile()}),this.safeEmit(gi.EXCEPTION,{code:e,msg:t,uid:i})},this._statsCollector.onUploadPublishDuration=(e,t,i,r)=>{let n=this._users.find(t=>t.uid===e);n&&(this.store.keyMetrics&&(this.store.firstVideoFrameDecoded(n.uid,{peerPublishDuration:i,peerPubStatusMs:Date.now()}),this._p2pChannel.reportVideoFirstFrameRender(n)),T$.peerPublishStatus(this._sessionId,{subscribeElapse:r,audioPublishDuration:t,videoPublishDuration:i,peer:n._uintid}))},this._statsCollector.onVideoCodecChanged=e=>{if(TR("VIDEO_STANDARD_BITRATE_VERSION")&&("av1"===e||"h265"===e||"h264"===e)){let t=this.localTracks.find(e=>e instanceof CP);t&&1!==t._saveEncodeBitrateRatio&&t.setSaveEncodeBitrateRatio("h264"===e?TR("BASELINE_MORE_H264_BITRATE_RATIO"):void 0)}},this.store.useP2P="p2p"===e.mode,this._gateway=new IH(this.store,{clientId:this._clientId,mode:this.mode,codec:this.codec,websocketRetryConfig:e.websocketRetryConfig||gH,httpRetryConfig:e.httpRetryConfig||gH,forceWaitGatewayResponse:void 0===e.forceWaitGatewayResponse||e.forceWaitGatewayResponse,statsCollector:this._statsCollector,role:e.role,clientRoleOptions:r}),this._configDistribute=new Af(this._clientId,this.store),this.store.useP2P?(this._p2pChannel=(i={store:this.store,statsCollector:this._statsCollector},IV("P2PChannel").create(i)),this._handleP2PEvents()):this._p2pChannel=new bh(this.store,this._statsCollector),this._handleP2PChannelEvents(),this._handleGatewayEvents(),this._handleGatewaySignalEvents()}}).prototype,"leave",[iK],Object.getOwnPropertyDescriptor(rv.prototype,"leave"),rv.prototype),vP(rv.prototype,"publish",[iY],Object.getOwnPropertyDescriptor(rv.prototype,"publish"),rv.prototype),vP(rv.prototype,"unpublish",[iz],Object.getOwnPropertyDescriptor(rv.prototype,"unpublish"),rv.prototype),vP(rv.prototype,"subscribe",[iq],Object.getOwnPropertyDescriptor(rv.prototype,"subscribe"),rv.prototype),vP(rv.prototype,"presubscribe",[iX],Object.getOwnPropertyDescriptor(rv.prototype,"presubscribe"),rv.prototype),vP(rv.prototype,"massSubscribe",[iJ],Object.getOwnPropertyDescriptor(rv.prototype,"massSubscribe"),rv.prototype),vP(rv.prototype,"unsubscribe",[iQ],Object.getOwnPropertyDescriptor(rv.prototype,"unsubscribe"),rv.prototype),vP(rv.prototype,"massUnsubscribe",[iZ],Object.getOwnPropertyDescriptor(rv.prototype,"massUnsubscribe"),rv.prototype),vP(rv.prototype,"setLowStreamParameter",[i$],Object.getOwnPropertyDescriptor(rv.prototype,"setLowStreamParameter"),rv.prototype),vP(rv.prototype,"setDualStreamMode",[i0],Object.getOwnPropertyDescriptor(rv.prototype,"setDualStreamMode"),rv.prototype),vP(rv.prototype,"enableDualStream",[i1],Object.getOwnPropertyDescriptor(rv.prototype,"enableDualStream"),rv.prototype),vP(rv.prototype,"disableDualStream",[i2],Object.getOwnPropertyDescriptor(rv.prototype,"disableDualStream"),rv.prototype),vP(rv.prototype,"setClientRole",[i3],Object.getOwnPropertyDescriptor(rv.prototype,"setClientRole"),rv.prototype),vP(rv.prototype,"_setClientRoleOptions",[i5],Ob
1ject.getOwnPropertyDescriptor(rv.prototype,"_setClientRoleOptions"),rv.prototype),vP(rv.prototype,"setProxyServer",[i4],Object.getOwnPropertyDescriptor(rv.prototype,"setProxyServer"),rv.prototype),vP(rv.prototype,"setTurnServer",[i6],Object.getOwnPropertyDescriptor(rv.prototype,"setTurnServer"),rv.prototype),vP(rv.prototype,"setLicense",[i8],Object.getOwnPropertyDescriptor(rv.prototype,"setLicense"),rv.prototype),vP(rv.prototype,"startProxyServer",[i9],Object.getOwnPropertyDescriptor(rv.prototype,"startProxyServer"),rv.prototype),vP(rv.prototype,"stopProxyServer",[i7],Object.getOwnPropertyDescriptor(rv.prototype,"stopProxyServer"),rv.prototype),vP(rv.prototype,"setLocalAccessPointsV2",[re],Object.getOwnPropertyDescriptor(rv.prototype,"setLocalAccessPointsV2"),rv.prototype),vP(rv.prototype,"setLocalAccessPoints",[rt],Object.getOwnPropertyDescriptor(rv.prototype,"setLocalAccessPoints"),rv.prototype),vP(rv.prototype,"setRemoteDefaultVideoStreamType",[ri],Object.getOwnPropertyDescriptor(rv.prototype,"setRemoteDefaultVideoStreamType"),rv.prototype),vP(rv.prototype,"setRemoteVideoStreamType",[rr],Object.getOwnPropertyDescriptor(rv.prototype,"setRemoteVideoStreamType"),rv.prototype),vP(rv.prototype,"setStreamFallbackOption",[rn],Object.getOwnPropertyDescriptor(rv.prototype,"setStreamFallbackOption"),rv.prototype),vP(rv.prototype,"setEncryptionConfig",[ro],Object.getOwnPropertyDescriptor(rv.prototype,"setEncryptionConfig"),rv.prototype),vP(rv.prototype,"renewToken",[ra],Object.getOwnPropertyDescriptor(rv.prototype,"renewToken"),rv.prototype),vP(rv.prototype,"enableAudioVolumeIndicator",[rs],Object.getOwnPropertyDescriptor(rv.prototype,"enableAudioVolumeIndicator"),rv.prototype),vP(rv.prototype,"startLiveStreaming",[rc],Object.getOwnPropertyDescriptor(rv.prototype,"startLiveStreaming"),rv.prototype),vP(rv.prototype,"setLiveTranscoding",[rd],Object.getOwnPropertyDescriptor(rv.prototype,"setLiveTranscoding"),rv.prototype),vP(rv.prototype,"stopLiveStreaming",[rl],Object.getOwnPropertyDescriptor(rv.prototype,"stopLiveStreaming"),rv.prototype),vP(rv.prototype,"startChannelMediaRelay",[rh],Object.getOwnPropertyDescriptor(rv.prototype,"startChannelMediaRelay"),rv.prototype),vP(rv.prototype,"updateChannelMediaRelay",[ru],Object.getOwnPropertyDescriptor(rv.prototype,"updateChannelMediaRelay"),rv.prototype),vP(rv.prototype,"stopChannelMediaRelay",[rp],Object.getOwnPropertyDescriptor(rv.prototype,"stopChannelMediaRelay"),rv.prototype),vP(rv.prototype,"sendCustomReportMessage",[r_],Object.getOwnPropertyDescriptor(rv.prototype,"sendCustomReportMessage"),rv.prototype),vP(rv.prototype,"pickSVCLayer",[rE],Object.getOwnPropertyDescriptor(rv.prototype,"pickSVCLayer"),rv.prototype),vP(rv.prototype,"setRTMConfig",[rm],Object.getOwnPropertyDescriptor(rv.prototype,"setRTMConfig"),rv.prototype),vP(rv.prototype,"enableContentInspect",[rf],Object.getOwnPropertyDescriptor(rv.prototype,"enableContentInspect"),rv.prototype),vP(rv.prototype,"disableContentInspect",[rS],Object.getOwnPropertyDescriptor(rv.prototype,"disableContentInspect"),rv.prototype),vP(rv.prototype,"setImageModeration",[rg],Object.getOwnPropertyDescriptor(rv.prototype,"setImageModeration"),rv.prototype),vP(rv.prototype,"setP2PTransport",[rT],Object.getOwnPropertyDescriptor(rv.prototype,"setP2PTransport"),rv.prototype),vP(rv.prototype,"getJoinChannelServiceRecords",[rR],Object.getOwnPropertyDescriptor(rv.prototype,"getJoinChannelServiceRecords"),rv.prototype),vP(rv.prototype,"setPublishAudioFilterEnabled",[rC],Object.getOwnPropertyDescriptor(rv.prototype,"setPublishAudioFilterEnabled"),rv.prototype),rv);function Oh(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{codec:"vp8",audioCodec:"opus",mode:"rtc"},i=gw(5,"client-"),r=T$.reportApiInvoke(null,{id:i,name:S3.CREATE_CLIENT,options:[t],tag:S5.TRACER});try{SF(t.codec,"config.codec",["vp8","vp9","av1","h264","h265"]),SF(t.mode,"config.mode",["rtc","live","p2p"]),void 0!==t.audioCodec&&SF(t.audioCodec,"config.audioCodec",["opus","pcmu","pcma","g722"]),void 0!==t.proxyServer&&SG(t.proxyServer,"config.proxyServer",1,1e4),void 0!==t.turnServer&&S7(t.turnServer),void 0!==t.httpRetryConfig&&S4(t.httpRetryConfig),void 0!==t.websocketRetryConfig&&S4(t.websocketRetryConfig)}
1catch(e){throw r.onError(e),e}return(Sg(16,0,!0)||ST(16,0,!0))&&("vp9"===t.codec&&(t.codec="vp8",TY.debug("browser not support vp9, force use vp8")),TT("UNSUPPORTED_VIDEO_CODEC",["vp9"])),void 0===t.audioCodec&&(t.audioCodec="opus"),r.onSuccess(),new Ol(Od(Od({forceWaitGatewayResponse:!0},t),{},{role:o5(e=["rtc","p2p"]).call(e,t.mode)?"host":t.role||"audience"}),i)}class Ou{initPeers(){this.peerPair=[new RTCPeerConnection,new RTCPeerConnection],this.peerPair[1].ontrack=e=>{let t=document.createElement("audio");t.srcObject=new MediaStream([e.track]),t.play(),this.audioPlayerElement=t}}async switchSdp(){if(!this.peerPair)return;let e=async(e,t)=>{let i="offer"===t?await e.createOffer():await e.createAnswer();return await e.setLocalDescription(i),"complete"===e.iceGatheringState?e.localDescription:new dQ(t=>{e.onicegatheringstatechange=()=>{"complete"===e.iceGatheringState&&t(e.localDescription)}})},t=async(e,t)=>await e.setRemoteDescription(t);try{let i=await e(this.peerPair[0],"offer");await t(this.peerPair[1],i);let r=await e(this.peerPair[1],"answer");await t(this.peerPair[0],r)}catch(e){throw new T0(SU.LOCAL_AEC_ERROR,e.toString()).print()}}async getTracksFromMediaElement(e){let t;if(this.audioTrack)return this.audioTrack;try{e instanceof HTMLVideoElement&&(e.captureStream?e.captureStream():e.mozCaptureStream()),t=this.context.createMediaStreamDestination(),this.context.createMediaElementSource(e).connect(t)}catch(e){throw new T0(SU.LOCAL_AEC_ERROR,e.toString()).print()}if(!t)throw new T0(SU.LOCAL_AEC_ERROR,"no dest node when local aec").print();let i=t.stream.getAudioTracks()[0];return this.audioTrack=i,i}getElement(){return this.element}async startEchoCancellation(){this.context.resume(),this.peerPair&&this.close(),this.initPeers();let e=this.element,t=await this.getTracksFromMediaElement(e);this.peerPair&&this.peerPair[0].addTrack(t),await this.switchSdp()}close(){TY.debug("close echo cancellation unit, id is",this.id),this.audioPlayerElement&&this.audioPlayerElement.pause(),this.peerPair&&this.peerPair.forEach(e=>{e.close()}),this.peerPair=void 0,this.audioPlayerElement=void 0}constructor(e,t){mb(this,"id",0),mb(this,"element",void 0),mb(this,"peerPair",void 0),mb(this,"context",void 0),mb(this,"audioPlayerElement",void 0),mb(this,"audioTrack",void 0),Ou.count+=1,this.id=Ou.count,this.element=e,this.context=t}}mb(Ou,"count",0);let Op=window.AudioContext||window.webkitAudioContext,O_=new(ry=TZ({report:T$}),vP((rI=class{processExternalMediaAEC(e){if(!this._doesEnvironmentNeedAEC())return TY.debug("the system does not need to process local aec"),-1;this.context||(this.context=new Op);let t=this.units.find(t=>t&&t.getElement()===e);return t||(t=new Ou(e,this.context),this.units.push(t)),t.startEchoCancellation(),TY.debug("start processing local audio echo cancellation, id is",t.id),t.id}_doesEnvironmentNeedAEC(){return St().name!==f8.SAFARI}constructor(){mb(this,"units",[]),mb(this,"context",void 0)}}).prototype,"processExternalMediaAEC",[ry],Object.getOwnPropertyDescriptor(rI.prototype,"processExternalMediaAEC"),rI.prototype),rI);function OE(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function Om(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?OE(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):OE(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let Of=window||document;function OS(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!Of)return;let i=D$._cspEventHandlerPointer;if(i&&t)return void console.error(i,t);let r=e=>{if(!(e&&e.blockedURI&&(D$.onSecurityPolicyViolation||D$.getListeners(yT.SECURITY_POLICY_VIOLATION).length>0)))return;let t=e.blockedURI;TR("CSP_DETECTED_HOSTNAME_LIST").some(e=>o5(t).call(t,e))&&(D$.onSecurityPolicyViolation&&"function"==typeof D$.onSecurityPolicyViolation&&D$.onSecurityPolicyViolation(e),D$.getListeners(yT.SECURITY_POLICY_VIOLATION).length>0&&D$.safeEmit(yT.SECURITY_POLICY_VIOLATION,e))};i&&Of.removeEventListener("securitypolicyviolation",i),(t||e&&"function"==typeof e||D$.getListeners(yT.SECURITY_POLICY_VIOLATION).length>0)&&Of.addEventListener("securitypolicyviolation",r),D$._cspEventHandlerPointer=r}var Og=RegExp.prototype,OT=rW(function(e){return e===Og||rJ(Og,e)?pW(e):e.flags});function OR(e){let t=e.length;for(;--t>=0;)e[t]=0}let OC=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),Ov=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),Oy=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),OI=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),OA=Array(576);OR(OA);let Ob=Array(60);OR(Ob);let OO=Array(512);OR(OO);let Ow=Array(256);OR(Ow);let ON=Array(29);OR(ON);let OD=Array(30);function OP(e,t,i,r,n){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=r,this.max_length=n,this.has_stree=e&&e.length}function OL(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}OR(OD);let Ok=e=>e<256?OO[e]:OO[256+(e>>>7)],OM=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},OU=(e,t,i)=>{e.bi_valid>16-i?(e.bi_buf|=t<<e.bi_valid&65535,OM(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)},Ox=(e,t,i)=>{OU(e,i[2*t],i[2*t+1])},OV=(e,t)=>{let i=0;do i|=1&e,e>>>=1,i<<=1;while(--t>0);return i>>>1},OF=(e,t,i)=>{let r=Array(16),n,o,a=0;for(n=1;n<=15;n++)a=a+i[n-1]<<1,r[n]=a;for(o=0;o<=t;o++){let t=e[2*o+1];0!==t&&(e[2*o]=OV(r[t]++,t))}},OB=e=>{let t;for(t=0;t<286;t++)e.dyn_ltree[2*t]=0;for(t=0;t<30;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},Oj=e=>{e.bi_valid>8?OM(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},OG=(e,t,i,r)=>{let n=2*t,o=2*i;return e[n]<e[o]||e[n]===e[o]&&r[t]<=r[i]},OW=(e,t,i)=>{let r=e.heap[i],n=i<<1;for(;
1n<=e.heap_len&&(n<e.heap_len&&OG(t,e.heap[n+1],e.heap[n],e.depth)&&n++,!OG(t,r,e.heap[n],e.depth));)e.heap[i]=e.heap[n],i=n,n<<=1;e.heap[i]=r},OH=(e,t,i)=>{let r,n,o,a,s=0;if(0!==e.sym_next)do r=(255&e.pending_buf[e.sym_buf+s++])+((255&e.pending_buf[e.sym_buf+s++])<<8),n=e.pending_buf[e.sym_buf+s++],0===r?Ox(e,n,t):(Ox(e,(o=Ow[n])+256+1,t),0!==(a=OC[o])&&OU(e,n-=ON[o],a),Ox(e,o=Ok(--r),i),0!==(a=Ov[o])&&OU(e,r-=OD[o],a));while(s<e.sym_next);Ox(e,256,t)},OK=(e,t)=>{let i=t.dyn_tree,r=t.stat_desc.static_tree,n=t.stat_desc.has_stree,o=t.stat_desc.elems,a,s,c,d=-1;for(e.heap_len=0,e.heap_max=573,a=0;a<o;a++)0!==i[2*a]?(e.heap[++e.heap_len]=d=a,e.depth[a]=0):i[2*a+1]=0;for(;e.heap_len<2;)i[2*(c=e.heap[++e.heap_len]=d<2?++d:0)]=1,e.depth[c]=0,e.opt_len--,n&&(e.static_len-=r[2*c+1]);for(t.max_code=d,a=e.heap_len>>1;a>=1;a--)OW(e,i,a);c=o;do a=e.heap[1],e.heap[1]=e.heap[e.heap_len--],OW(e,i,1),s=e.heap[1],e.heap[--e.heap_max]=a,e.heap[--e.heap_max]=s,i[2*c]=i[2*a]+i[2*s],e.depth[c]=(e.depth[a]>=e.depth[s]?e.depth[a]:e.depth[s])+1,i[2*a+1]=i[2*s+1]=c,e.heap[1]=c++,OW(e,i,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{let i=t.dyn_tree,r=t.max_code,n=t.stat_desc.static_tree,o=t.stat_desc.has_stree,a=t.stat_desc.extra_bits,s=t.stat_desc.extra_base,c=t.stat_desc.max_length,d,l,h,u,p,_,E=0;for(u=0;u<=15;u++)e.bl_count[u]=0;for(i[2*e.heap[e.heap_max]+1]=0,d=e.heap_max+1;d<573;d++)(u=i[2*i[2*(l=e.heap[d])+1]+1]+1)>c&&(u=c,E++),i[2*l+1]=u,l>r||(e.bl_count[u]++,p=0,l>=s&&(p=a[l-s]),_=i[2*l],e.opt_len+=_*(u+p),o&&(e.static_len+=_*(n[2*l+1]+p)));if(0!==E){do{for(u=c-1;0===e.bl_count[u];)u--;e.bl_count[u]--,e.bl_count[u+1]+=2,e.bl_count[c]--,E-=2}while(E>0);for(u=c;0!==u;u--)for(l=e.bl_count[u];0!==l;)(h=e.heap[--d])>r||(i[2*h+1]!==u&&(e.opt_len+=(u-i[2*h+1])*i[2*h],i[2*h+1]=u),l--)}})(e,t),OF(i,d,e.bl_count)},OY=(e,t,i)=>{let r,n,o=-1,a=t[1],s=0,c=7,d=4;for(0===a&&(c=138,d=3),t[2*(i+1)+1]=65535,r=0;r<=i;r++)n=a,a=t[2*(r+1)+1],++s<c&&n===a||(s<d?e.bl_tree[2*n]+=s:0!==n?(n!==o&&e.bl_tree[2*n]++,e.bl_tree[32]++):s<=10?e.bl_tree[34]++:e.bl_tree[36]++,s=0,o=n,0===a?(c=138,d=3):n===a?(c=6,d=3):(c=7,d=4))},Oz=(e,t,i)=>{let r,n,o=-1,a=t[1],s=0,c=7,d=4;for(0===a&&(c=138,d=3),r=0;r<=i;r++)if(n=a,a=t[2*(r+1)+1],!(++s<c&&n===a)){if(s<d)do Ox(e,n,e.bl_tree);while(0!=--s);else 0!==n?(n!==o&&(Ox(e,n,e.bl_tree),s--),Ox(e,16,e.bl_tree),OU(e,s-3,2)):s<=10?(Ox(e,17,e.bl_tree),OU(e,s-3,3)):(Ox(e,18,e.bl_tree),OU(e,s-11,7));s=0,o=n,0===a?(c=138,d=3):n===a?(c=6,d=3):(c=7,d=4)}},Oq=!1,OX=(e,t,i,r)=>{OU(e,0+ +!!r,3),Oj(e),OM(e,i),OM(e,~i),i&&e.pending_buf.set(e.window.subarray(t,t+i),e.pending),e.pending+=i};var OJ={_tr_init:e=>{Oq||((()=>{let e,t,i,r,n,c=Array(16);for(i=0,r=0;r<28;r++)for(ON[r]=i,e=0;e<1<<OC[r];e++)Ow[i++]=r;for(Ow[i-1]=r,n=0,r=0;r<16;r++)for(OD[r]=n,e=0;e<1<<Ov[r];e++)OO[n++]=r;for(n>>=7;r<30;r++)for(OD[r]=n<<7,e=0;e<1<<Ov[r]-7;e++)OO[256+n++]=r;for(t=0;t<=15;t++)c[t]=0;for(e=0;e<=143;)OA[2*e+1]=8,e++,c[8]++;for(;e<=255;)OA[2*e+1]=9,e++,c[9]++;for(;e<=279;)OA[2*e+1]=7,e++,c[7]++;for(;e<=287;)OA[2*e+1]=8,e++,c[8]++;for(OF(OA,287,c),e=0;e<30;e++)Ob[2*e+1]=5,Ob[2*e]=OV(e,5);o=new OP(OA,OC,257,286,15),a=new OP(Ob,Ov,0,30,15),s=new OP([],Oy,0,19,7)})(),Oq=!0),e.l_desc=new OL(e.dyn_ltree,o),e.d_desc=new OL(e.dyn_dtree,a),e.bl_desc=new OL(e.bl_tree,s),e.bi_buf=0,e.bi_valid=0,OB(e)},_tr_stored_block:OX,_tr_flush_block:(e,t,i,r)=>{let n,o,a=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,i=0xf3ffc07f;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<256;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0})(e)),OK(e,e.l_desc),OK(e,e.d_desc),a=(e=>{let t;for(OY(e,e.dyn_ltree,e.l_desc.max_code),OY(e,e.dyn_dtree,e.d_desc.max_code),OK(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*OI[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t})(e),n=e.opt_len+3+7>>>3,(o=e.static_len+3+7>>>3)<=n&&(n=o)):n=o=i+5,i+4<=n&&-1!==t?OX(e,t,i,r):4===e.strategy||o===n?(OU(e,2+ +!!r,3),OH(e,OA,Ob)):(OU(e,4+ +!!r,3),((e,t,i,r)=>{let n;for(OU(e,t-257,5),OU(e,i-1,5),OU(e,r-4,4),n=0;n<r;n++)OU(e,e.bl_tree[2*OI[n]+1],3);Oz(e,e.dyn_ltree,t-1),Oz(e,e.dyn_dtree,i-1)})(e,e.l_desc.max_code+1,e.d_desc.max_code+1,a+1),OH(e,e.dyn_ltree,e.dyn_dtree)),OB(e),r&&Oj(e)},_tr_tally:(e,t,i)=>(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>
18,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(Ow[i]+256+1)]++,e.dyn_dtree[2*Ok(t)]++),e.sym_next===e.sym_end),_tr_align:e=>{OU(e,2,3),Ox(e,256,OA),16===e.bi_valid?(OM(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}},OQ=(e,t,i,r)=>{let n=65535&e,o=e>>>16&65535,a=0;for(;0!==i;){a=i>2e3?2e3:i,i-=a;do o=o+(n=n+t[r++]|0)|0;while(--a);n%=65521,o%=65521}return n|o<<16};let OZ=new Uint32Array((()=>{let e,t=[];for(var i=0;i<256;i++){e=i;for(var r=0;r<8;r++)e=1&e?0xedb88320^e>>>1:e>>>1;t[i]=e}return t})());var O$=(e,t,i,r)=>{let n=r+i;e^=-1;for(let i=r;i<n;i++)e=e>>>8^OZ[255&(e^t[i])];return -1^e},O0={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},O1={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};let{_tr_init:O2,_tr_stored_block:O3,_tr_flush_block:O5,_tr_tally:O4,_tr_align:O6}=OJ,{Z_NO_FLUSH:O8,Z_PARTIAL_FLUSH:O9,Z_FULL_FLUSH:O7,Z_FINISH:we,Z_BLOCK:wt,Z_OK:wi,Z_STREAM_END:wr,Z_STREAM_ERROR:wn,Z_DATA_ERROR:wo,Z_BUF_ERROR:wa,Z_DEFAULT_COMPRESSION:ws,Z_FILTERED:wc,Z_HUFFMAN_ONLY:wd,Z_RLE:wl,Z_FIXED:wh,Z_DEFAULT_STRATEGY:wu,Z_UNKNOWN:wp,Z_DEFLATED:w_}=O1,wE=(e,t)=>(e.msg=O0[t],t),wm=e=>2*e-9*(e>4),wf=e=>{let t=e.length;for(;--t>=0;)e[t]=0},wS=e=>{let t,i,r,n=e.w_size;r=t=e.hash_size;do i=e.head[--r],e.head[r]=i>=n?i-n:0;while(--t);r=t=n;do i=e.prev[--r],e.prev[r]=i>=n?i-n:0;while(--t)},wg=(e,t,i)=>(t<<e.hash_shift^i)&e.hash_mask,wT=e=>{let t=e.state,i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+i),e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))},wR=(e,t)=>{O5(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,wT(e.strm)},wC=(e,t)=>{e.pending_buf[e.pending++]=t},wv=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},wy=(e,t,i,r)=>{let n=e.avail_in;return n>r&&(n=r),0===n?0:(e.avail_in-=n,t.set(e.input.subarray(e.next_in,e.next_in+n),i),1===e.state.wrap?e.adler=OQ(e.adler,t,n,i):2===e.state.wrap&&(e.adler=O$(e.adler,t,n,i)),e.next_in+=n,e.total_in+=n,n)},wI=(e,t)=>{let i,r,n=e.max_chain_length,o=e.strstart,a=e.prev_length,s=e.nice_match,c=e.strstart>e.w_size-262?e.strstart-(e.w_size-262):0,d=e.window,l=e.w_mask,h=e.prev,u=e.strstart+258,p=d[o+a-1],_=d[o+a];e.prev_length>=e.good_match&&(n>>=2),s>e.lookahead&&(s=e.lookahead);do if(d[(i=t)+a]===_&&d[i+a-1]===p&&d[i]===d[o]&&d[++i]===d[o+1]){o+=2,i++;do;while(d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&o<u);if(r=258-(u-o),o=u-258,r>a){if(e.match_start=t,a=r,r>=s)break;p=d[o+a-1],_=d[o+a]}}while((t=h[t&l])>c&&0!=--n);return a<=e.lookahead?a:e.lookahead},wA=e=>{let t,i,r,n=e.w_size;do{if(i=e.window_size-e.lookahead-e.strstart,e.strstart>=n+(n-262)&&(e.window.set(e.window.subarray(n,n+n-i),0),e.match_start-=n,e.strstart-=n,e.block_start-=n,e.insert>e.strstart&&(e.insert=e.strstart),wS(e),i+=n),0===e.strm.avail_in)break;if(t=wy(e.strm,e.window,e.strstart+e.lookahead,i),e.lookahead+=t,e.lookahead+e.insert>=3)for(r=e.strstart-e.insert,e.ins_h=e.window[r],e.ins_h=wg(e,e.ins_h,e.window[r+1]);e.insert&&(e.ins_h=wg(e,e.ins_h,e.window[r+3-1]),e.prev[r&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=r,r++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<262&&0!==e.strm.avail_in)},wb=(e,t)=>{let i,r,n,o=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,a=0,s=e.strm.avail_in;do{if(i=65535,n=e.bi_valid+42>>3,e.strm.avail_out<n||(n=e.strm.avail_out-n,i>(r=e.strstart-e.block_start)+e.strm.avail_in&&(i=r+e.strm.avail_in),i>n&&(i=n),i<o&&(0===i&&t!==we||t===O8||i!==r+e.strm.avail_in)))break;a=+(t===we&&i===r+e.strm.avail_in),O3(e,0,0,a),e.pending_buf[e.pending-4]=i,e.pending_buf[e.pending-3]=i>>
18,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,wT(e.strm),r&&(r>i&&(r=i),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+r),e.strm.next_out),e.strm.next_out+=r,e.strm.avail_out-=r,e.strm.total_out+=r,e.block_start+=r,i-=r),i&&(wy(e.strm,e.strm.output,e.strm.next_out,i),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i)}while(0===a);return(s-=e.strm.avail_in)&&(s>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=s&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-s,e.strm.next_in),e.strstart),e.strstart+=s,e.insert+=s>e.w_size-e.insert?e.w_size-e.insert:s),e.block_start=e.strstart),e.high_water<e.strstart&&(e.high_water=e.strstart),a?4:t!==O8&&t!==we&&0===e.strm.avail_in&&e.strstart===e.block_start?2:(n=e.window_size-e.strstart,e.strm.avail_in>n&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,n+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),n>e.strm.avail_in&&(n=e.strm.avail_in),n&&(wy(e.strm,e.window,e.strstart,n),e.strstart+=n,e.insert+=n>e.w_size-e.insert?e.w_size-e.insert:n),e.high_water<e.strstart&&(e.high_water=e.strstart),n=e.bi_valid+42>>3,o=(n=e.pending_buf_size-n>65535?65535:e.pending_buf_size-n)>e.w_size?e.w_size:n,((r=e.strstart-e.block_start)>=o||(r||t===we)&&t!==O8&&0===e.strm.avail_in&&r<=n)&&(i=r>n?n:r,a=+(t===we&&0===e.strm.avail_in&&i===r),O3(e,e.block_start,i,a),e.block_start+=i,wT(e.strm)),a?3:1)},wO=(e,t)=>{let i,r;for(;;){if(e.lookahead<262){if(wA(e),e.lookahead<262&&t===O8)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=wg(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-262&&(e.match_length=wI(e,i)),e.match_length>=3)if(r=O4(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do e.strstart++,e.ins_h=wg(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart;while(0!=--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=wg(e,e.ins_h,e.window[e.strstart+1]);else r=O4(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(r&&(wR(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===we?(wR(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(wR(e,!1),0===e.strm.avail_out)?1:2},ww=(e,t)=>{let i,r,n;for(;;){if(e.lookahead<262){if(wA(e),e.lookahead<262&&t===O8)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=wg(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-262&&(e.match_length=wI(e,i),e.match_length<=5&&(e.strategy===wc||3===e.match_length&&e.strstart-e.match_start>4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){n=e.strstart+e.lookahead-3,r=O4(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do++e.strstart<=n&&(e.ins_h=wg(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart);while(0!=--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,r&&(wR(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if((r=O4(e,0,e.window[e.strstart-1]))&&wR(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(r=O4(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===we?(wR(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(wR(e,!1),0===e.strm.avail_out)?1:2};function wN(e,t,i,r,n){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=r,this.func=n}let wD=[new wN(0,0,0,0,wb),new wN(4,4,8,4,wO),new wN(4,5,16,8,wO),new wN(4,6,32,32,wO),new wN(4,4,16,16,ww),new wN(8,16,32,32,ww),new wN(8,16,128,128,ww),new wN(8,32,128,256,ww),new wN(32,128,258,1024,ww),new wN(32,258,258,4096,ww)];function wP(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=w_,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),wf(this.dyn_ltree),wf(this.dyn_dtree),wf(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),wf(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),wf(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}let wL=e=>{if(!e)return 1;let t=e.state;return t&&t.strm===e&&(42===t.status||57===t.status||69===t.status||73===t.status||91===t.status||103===t.status||113===t.status||666===t.status)?0:1};var wk=(e,t)=>{if(wL(e)||t>wt||t<0)return e?wE(e,wn):wn;let i=e.state;if(!e.output||0!==e.avail_in&&!e.input||666===i.status&&t!==we)return wE(e,0===e.avail_out?wa:wn);let r=i.last_flush;if(i.last_flush=t,0!==i.pending){if(wT(e),0===e.avail_out)return i.last_flush=-1,wi}else if(0===e.avail_in&&wm(t)<=wm(r)&&t!==we)return wE(e,wa);if(666===i.status&&0!==e.avail_in)return wE(e,wa);if(42===i.status&&0===i.wrap&&(i.status=113),42===i.status){let t=w_+(i.w_b
1its-8<<4)<<8;if(t|=(i.strategy>=wd||i.level<2?0:i.level<6?1:6===i.level?2:3)<<6,0!==i.strstart&&(t|=32),wv(i,t+=31-t%31),0!==i.strstart&&(wv(i,e.adler>>>16),wv(i,65535&e.adler)),e.adler=1,i.status=113,wT(e),0!==i.pending)return i.last_flush=-1,wi}if(57===i.status){if(e.adler=0,wC(i,31),wC(i,139),wC(i,8),i.gzhead)wC(i,+!!i.gzhead.text+2*!!i.gzhead.hcrc+4*!!i.gzhead.extra+8*!!i.gzhead.name+16*!!i.gzhead.comment),wC(i,255&i.gzhead.time),wC(i,i.gzhead.time>>8&255),wC(i,i.gzhead.time>>16&255),wC(i,i.gzhead.time>>24&255),wC(i,9===i.level?2:4*(i.strategy>=wd||i.level<2)),wC(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(wC(i,255&i.gzhead.extra.length),wC(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=O$(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(wC(i,0),wC(i,0),wC(i,0),wC(i,0),wC(i,0),wC(i,9===i.level?2:4*(i.strategy>=wd||i.level<2)),wC(i,3),i.status=113,wT(e),0!==i.pending)return i.last_flush=-1,wi}if(69===i.status){if(i.gzhead.extra){let t=i.pending,r=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+r>i.pending_buf_size;){let n=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+n),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>t&&(e.adler=O$(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex+=n,wT(e),0!==i.pending)return i.last_flush=-1,wi;t=0,r-=n}let n=new Uint8Array(i.gzhead.extra);i.pending_buf.set(n.subarray(i.gzindex,i.gzindex+r),i.pending),i.pending+=r,i.gzhead.hcrc&&i.pending>t&&(e.adler=O$(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let t,r=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>r&&(e.adler=O$(e.adler,i.pending_buf,i.pending-r,r)),wT(e),0!==i.pending)return i.last_flush=-1,wi;r=0}t=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,wC(i,t)}while(0!==t);i.gzhead.hcrc&&i.pending>r&&(e.adler=O$(e.adler,i.pending_buf,i.pending-r,r)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let t,r=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>r&&(e.adler=O$(e.adler,i.pending_buf,i.pending-r,r)),wT(e),0!==i.pending)return i.last_flush=-1,wi;r=0}t=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,wC(i,t)}while(0!==t);i.gzhead.hcrc&&i.pending>r&&(e.adler=O$(e.adler,i.pending_buf,i.pending-r,r))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(wT(e),0!==i.pending))return i.last_flush=-1,wi;wC(i,255&e.adler),wC(i,e.adler>>8&255),e.adler=0}if(i.status=113,wT(e),0!==i.pending)return i.last_flush=-1,wi}if(0!==e.avail_in||0!==i.lookahead||t!==O8&&666!==i.status){let r=0===i.level?wb(i,t):i.strategy===wd?((e,t)=>{let i;for(;;){if(0===e.lookahead&&(wA(e),0===e.lookahead)){if(t===O8)return 1;break}if(e.match_length=0,i=O4(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(wR(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===we?(wR(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(wR(e,!1),0===e.strm.avail_out)?1:2})(i,t):i.strategy===wl?((e,t)=>{let i,r,n,o,a=e.window;for(;;){if(e.lookahead<=258){if(wA(e),e.lookahead<=258&&t===O8)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(r=a[n=e.strstart-1])===a[++n]&&r===a[++n]&&r===a[++n]){o=e.strstart+258;do;while(r===a[++n]&&r===a[++n]&&r===a[++n]&&r===a[++n]&&r===a[++n]&&r===a[++n]&&r===a[++n]&&r===a[++n]&&n<o);e.match_length=258-(o-n),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=O4(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=O4(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(wR(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===we?(wR(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(wR(e,!1),0===e.strm.avail_out)?1:2})(i,t):wD[i.level].func(i,t);if(3!==r&&4!==r||(i.status=666),1===r||3===r)return 0===e.avail_out&&(i.last_flush=-1),wi;if(2===r&&(t===O9?O6(i):t!==wt&&(O3(i,0,0,!1),t===O7&&(wf(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),wT(e),0===e.avail_out))return i.last_flush=-1,wi}return t!==we?wi:i.wrap<=0?wr:(2===i.wrap?(wC(i,255&e.adler),wC(i,e.adler>>8&255),wC(i,e.adler>>16&255),wC(i,e.adler>>24&255),wC(i,255&e.total_in),wC(i,e.total_in>>8&255),wC(i,e.total_in>>16&255),wC(i,e.total_in>>24&255)):(wv(i,e.adler>>>16),wv(i,65535&e.adler)),wT(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?wi:wr)},wM=e=>{if(wL(e))return wn;let t=e.state.status;return e.state=null,113===t?wE(e,wo):wi};let wU=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);
1var wx=function(e){let t=Array.prototype.slice.call(arguments,1);for(;t.length;){let i=t.shift();if(i){if("object"!=typeof i)throw TypeError(i+"must be non-object");for(let t in i)wU(i,t)&&(e[t]=i[t])}}return e},wV=e=>{let t=0;for(let i=0,r=e.length;i<r;i++)t+=e[i].length;let i=new Uint8Array(t);for(let t=0,r=0,n=e.length;t<n;t++){let n=e[t];i.set(n,r),r+=n.length}return i};let wF=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){wF=!1}let wB=new Uint8Array(256);for(let e=0;e<256;e++)wB[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;wB[254]=wB[254]=1;var wj=e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,i,r,n,o,a=e.length,s=0;for(n=0;n<a;n++)55296==(64512&(i=e.charCodeAt(n)))&&n+1<a&&56320==(64512&(r=e.charCodeAt(n+1)))&&(i=65536+(i-55296<<10)+(r-56320),n++),s+=i<128?1:i<2048?2:i<65536?3:4;for(t=new Uint8Array(s),o=0,n=0;o<s;n++)55296==(64512&(i=e.charCodeAt(n)))&&n+1<a&&56320==(64512&(r=e.charCodeAt(n+1)))&&(i=65536+(i-55296<<10)+(r-56320),n++),i<128?t[o++]=i:(i<2048?t[o++]=192|i>>>6:(i<65536?t[o++]=224|i>>>12:(t[o++]=240|i>>>18,t[o++]=128|i>>>12&63),t[o++]=128|i>>>6&63),t[o++]=128|63&i);return t},wG=(e,t)=>{let i,r,n=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));let o=Array(2*n);for(r=0,i=0;i<n;){let t=e[i++];if(t<128){o[r++]=t;continue}let a=wB[t];if(a>4)o[r++]=65533,i+=a-1;else{for(t&=2===a?31:3===a?15:7;a>1&&i<n;)t=t<<6|63&e[i++],a--;a>1?o[r++]=65533:t<65536?o[r++]=t:(t-=65536,o[r++]=55296|t>>10&1023,o[r++]=56320|1023&t)}}var a=r;if(a<65534&&o.subarray&&wF)return String.fromCharCode.apply(null,o.length===a?o:o.subarray(0,a));let s="";for(let e=0;e<a;e++)s+=String.fromCharCode(o[e]);return s},wW=(e,t)=>{(t=t||e.length)>e.length&&(t=e.length);let i=t-1;for(;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+wB[e[i]]>t?i:t},wH=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};let wK=Object.prototype.toString,{Z_NO_FLUSH:wY,Z_SYNC_FLUSH:wz,Z_FULL_FLUSH:wq,Z_FINISH:wX,Z_OK:wJ,Z_STREAM_END:wQ,Z_DEFAULT_COMPRESSION:wZ,Z_DEFAULT_STRATEGY:w$,Z_DEFLATED:w0}=O1;function w1(e){let t,i;this.options=wx({level:wZ,method:w0,chunkSize:16384,windowBits:15,memLevel:8,strategy:w$},e||{});let r=this.options;r.raw&&r.windowBits>0?r.windowBits=-r.windowBits:r.gzip&&r.windowBits>0&&r.windowBits<16&&(r.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new wH,this.strm.avail_out=0;let n=((e,t,i,r,n,o)=>{if(!e)return wn;let a=1;if(t===ws&&(t=6),r<0?(a=0,r=-r):r>15&&(a=2,r-=16),n<1||n>9||i!==w_||r<8||r>15||t<0||t>9||o<0||o>wh||8===r&&1!==a)return wE(e,wn);8===r&&(r=9);let s=new wP;return e.state=s,s.strm=e,s.status=42,s.wrap=a,s.gzhead=null,s.w_bits=r,s.w_size=1<<s.w_bits,s.w_mask=s.w_size-1,s.hash_bits=n+7,s.hash_size=1<<s.hash_bits,s.hash_mask=s.hash_size-1,s.hash_shift=~~((s.hash_bits+3-1)/3),s.window=new Uint8Array(2*s.w_size),s.head=new Uint16Array(s.hash_size),s.prev=new Uint16Array(s.w_size),s.lit_bufsize=1<<n+6,s.pending_buf_size=4*s.lit_bufsize,s.pending_buf=new Uint8Array(s.pending_buf_size),s.sym_buf=s.lit_bufsize,s.sym_end=3*(s.lit_bufsize-1),s.level=t,s.strategy=o,s.method=i,(e=>{var t;let i=(e=>{if(wL(e))return wE(e,wn);e.total_in=e.total_out=0,e.data_type=wp;let t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?42:113,e.adler=+(2!==t.wrap),t.last_flush=-2,O2(t),wi})(e);return i===wi&&((t=e.state).window_size=2*t.w_size,wf(t.head),t.max_lazy_match=wD[t.level].max_lazy,t.good_match=wD[t.level].good_length,t.nice_match=wD[t.level].nice_length,t.max_chain_length=wD[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=2,t.match_available=0,t.ins_h=0),i})(e)})(this.strm,r.level,r.method,r.windowBits,r.memLevel,r.strategy);if(n!==wJ)throw Error(O0[n]);if(r.header&&(t=this.strm,i=r.header,wL(t)||2!==t.state.wrap||(t.state.gzhead=i)),r.dictionary){let e;if(e="string"==typeof r.dictionary?wj(r.dictionary):"[object ArrayBuffer]"===wK.call(r.dictionary)?new Uint8Array(r.dictionary):r.dictionary,(n=((e,t)=>{let i=t.length;if(wL(e))return wn;let r=e.state,n=r.wrap;if(2===n||1===n&&42!==r.status||r.lookahead)return wn;if(1===n&&(e.adler=OQ(e.adler,t,i,0)),r.wrap=0,i>=r.w_size){0===n&&(wf(r.head),r.strstart=0,r.block_start=0,r.insert=0);let e=new Uint8Array(r.w_size);e.set(t.subarray(i-r.w_size,i),0),t=e,i=r.w_size}let o=e.avail_in,a=e.next_in,s=e.input;for(e.avail_in=i,e.next_in=0,e.input=t,wA(r);r.lookahead>=3;){let e=r.strstart,t=r.lookahead-2;do r.ins_h=wg(r,r.ins_h,r.window[e+3-1]),r.prev[e&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=e,e++;while(--t);r.strstart=e,r.lookahead=2,wA(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=2,r.match_available=0,e.next_in=a,e.input=s,e.avail_in=o,r.wrap=n,wi})(this.strm,e))!==wJ)throw Error(O0[n]);this._dict_set=!0}}function w2(e,t){let i=new w1(t);if(i.push(e,!0),i.err)throw i.msg||O0[i.err];return i.result}w1.prototype.push=function(e,t){let i,r,n=this.strm,o=this.options.chunkSize;if(this.ended)return!1;for(r=t===~~t?t:!0===t?wX:wY,"string"==typeof e?n.input=wj(e):"[object ArrayBuffer]"===wK.call(e)?n.input=new
1Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;;)if(0===n.avail_out&&(n.output=new Uint8Array(o),n.next_out=0,n.avail_out=o),(r===wz||r===wq)&&n.avail_out<=6)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else{if((i=wk(n,r))===wQ)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),i=wM(this.strm),this.onEnd(i),this.ended=!0,i===wJ;if(0!==n.avail_out){if(r>0&&n.next_out>0)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else if(0===n.avail_in)break}else this.onData(n.output)}return!0},w1.prototype.onData=function(e){this.chunks.push(e)},w1.prototype.onEnd=function(e){e===wJ&&(this.result=wV(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var w3=function(e,t){let i,r,n,o,a,s,c,d,l,h,u,p,_,E,m,f,S,g,T,R,C,v,y,I,A=e.state;i=e.next_in,y=e.input,r=i+(e.avail_in-5),n=e.next_out,I=e.output,o=n-(t-e.avail_out),a=n+(e.avail_out-257),s=A.dmax,c=A.wsize,d=A.whave,l=A.wnext,h=A.window,u=A.hold,p=A.bits,_=A.lencode,E=A.distcode,m=(1<<A.lenbits)-1,f=(1<<A.distbits)-1;e:do for(p<15&&(u+=y[i++]<<p,p+=8,u+=y[i++]<<p,p+=8),S=_[u&m];;){if(u>>>=g=S>>>24,p-=g,0==(g=S>>>16&255))I[n++]=65535&S;else{if(!(16&g)){if(0==(64&g)){S=_[(65535&S)+(u&(1<<g)-1)];continue}if(32&g){A.mode=16191;break e}e.msg="invalid literal/length code",A.mode=16209;break e}for(T=65535&S,(g&=15)&&(p<g&&(u+=y[i++]<<p,p+=8),T+=u&(1<<g)-1,u>>>=g,p-=g),p<15&&(u+=y[i++]<<p,p+=8,u+=y[i++]<<p,p+=8),S=E[u&f];;){if(u>>>=g=S>>>24,p-=g,!(16&(g=S>>>16&255))){if(0==(64&g)){S=E[(65535&S)+(u&(1<<g)-1)];continue}e.msg="invalid distance code",A.mode=16209;break e}if(R=65535&S,p<(g&=15)&&(u+=y[i++]<<p,(p+=8)<g&&(u+=y[i++]<<p,p+=8)),(R+=u&(1<<g)-1)>s){e.msg="invalid distance too far back",A.mode=16209;break e}if(u>>>=g,p-=g,R>(g=n-o)){if((g=R-g)>d&&A.sane){e.msg="invalid distance too far back",A.mode=16209;break e}if(C=0,v=h,0===l){if(C+=c-g,g<T){T-=g;do I[n++]=h[C++];while(--g);C=n-R,v=I}}else if(l<g){if(C+=c+l-g,(g-=l)<T){T-=g;do I[n++]=h[C++];while(--g);if(C=0,l<T){T-=g=l;do I[n++]=h[C++];while(--g);C=n-R,v=I}}}else if(C+=l-g,g<T){T-=g;do I[n++]=h[C++];while(--g);C=n-R,v=I}for(;T>2;)I[n++]=v[C++],I[n++]=v[C++],I[n++]=v[C++],T-=3;T&&(I[n++]=v[C++],T>1&&(I[n++]=v[C++]))}else{C=n-R;do I[n++]=I[C++],I[n++]=I[C++],I[n++]=I[C++],T-=3;while(T>2);T&&(I[n++]=I[C++],T>1&&(I[n++]=I[C++]))}break}}break}while(i<r&&n<a);i-=T=p>>3,p-=T<<3,u&=(1<<p)-1,e.next_in=i,e.next_out=n,e.avail_in=i<r?r-i+5:5-(i-r),e.avail_out=n<a?a-n+257:257-(n-a),A.hold=u,A.bits=p};let w5=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),w4=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),w6=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),w8=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);var w9=(e,t,i,r,n,o,a,s)=>{let c=s.bits,d,l,h,u,p,_,E=0,m=0,f=0,S=0,g=0,T=0,R=0,C=0,v=0,y=0,I=null,A=new Uint16Array(16),b=new Uint16Array(16),O,w,N,D=null;for(E=0;E<=15;E++)A[E]=0;for(m=0;m<r;m++)A[t[i+m]]++;for(g=c,S=15;S>=1&&0===A[S];S--);if(g>S&&(g=S),0===S)return n[o++]=0x1400000,n[o++]=0x1400000,s.bits=1,0;for(f=1;f<S&&0===A[f];f++);for(g<f&&(g=f),C=1,E=1;E<=15;E++)if(C<<=1,(C-=A[E])<0)return -1;if(C>0&&(0===e||1!==S))return -1;for(b[1]=0,E=1;E<15;E++)b[E+1]=b[E]+A[E];for(m=0;m<r;m++)0!==t[i+m]&&(a[b[t[i+m]]++]=m);if(0===e?(I=D=a,_=20):1===e?(I=w5,D=w4,_=257):(I=w6,D=w8,_=0),y=0,m=0,E=f,p=o,T=g,R=0,h=-1,u=(v=1<<g)-1,1===e&&v>852||2===e&&v>592)return 1;for(;;){O=E-R,a[m]+1<_?(w=0,N=a[m]):a[m]>=_?(w=D[a[m]-_],N=I[a[m]-_]):(w=96,N=0),d=1<<E-R,f=l=1<<T;do n[p+(y>>R)+(l-=d)]=O<<24|w<<16|N;while(0!==l);for(d=1<<E-1;y&d;)d>>=1;if(0!==d?(y&=d-1,y+=d):y=0,m++,0==--A[E]){if(E===S)break;E=t[i+a[m]]}if(E>g&&(y&u)!==h){for(0===R&&(R=g),p+=f,C=1<<(T=E-R);T+R<S&&!((C-=A[T+R])<=0);)T++,C<<=1;if(v+=1<<T,1===e&&v>852||2===e&&v>592)return 1;n[h=y&u]=g<<24|T<<16|p-o}}return 0!==y&&(n[p+y]=E-R<<24|4194304),s.bits=g,0};let{Z_FINISH:w7,Z_BLOCK:Ne,Z_TREES:Nt,Z_OK:Ni,Z_STREAM_END:Nr,Z_NEED_DICT:Nn,Z_STREAM_ERROR:No,Z_DATA_ERROR:Na,Z_MEM_ERROR:Ns,Z_BUF_ER
1ROR:Nc,Z_DEFLATED:Nd}=O1,Nl=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function Nh(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}let Nu=e=>{if(!e)return 1;let t=e.state;return+(!t||t.strm!==e||t.mode<16180||t.mode>16211)},Np=e=>{if(Nu(e))return No;let t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,(e=>{if(Nu(e))return No;let t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=16180,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,Ni})(e)},N_,NE,Nm=!0,Nf=e=>{if(Nm){N_=new Int32Array(512),NE=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(w9(1,e.lens,0,288,N_,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;w9(2,e.lens,0,32,NE,0,e.work,{bits:5}),Nm=!1}e.lencode=N_,e.lenbits=9,e.distcode=NE,e.distbits=5},NS=(e,t,i,r)=>{let n,o=e.state;return null===o.window&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new Uint8Array(o.wsize)),r>=o.wsize?(o.window.set(t.subarray(i-o.wsize,i),0),o.wnext=0,o.whave=o.wsize):((n=o.wsize-o.wnext)>r&&(n=r),o.window.set(t.subarray(i-r,i-r+n),o.wnext),(r-=n)?(o.window.set(t.subarray(i-r,i),0),o.wnext=r,o.whave=o.wsize):(o.wnext+=n,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=n))),0};var Ng=(e,t)=>{let i,r,n,o,a,s,c,d,l,h,u,p,_,E,m,f,S,g,T,R,C,v,y,I,A=0,b=new Uint8Array(4),O=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(Nu(e)||!e.output||!e.input&&0!==e.avail_in)return No;16191===(n=e.state).mode&&(n.mode=16192),c=e.next_out,a=e.output,l=e.avail_out,s=e.next_in,o=e.input,d=e.avail_in,h=n.hold,u=n.bits,p=d,_=l,I=Ni;e:for(;;)switch(n.mode){case 16180:if(0===n.wrap){n.mode=16192;break}for(;u<16;){if(0===d)break e;d--,h+=o[s++]<<u,u+=8}if(2&n.wrap&&35615===h){0===n.wbits&&(n.wbits=15),n.check=0,b[0]=255&h,b[1]=h>>>8&255,n.check=O$(n.check,b,2,0),h=0,u=0,n.mode=16181;break}if(n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&h)<<8)+(h>>8))%31){e.msg="incorrect header check",n.mode=16209;break}if((15&h)!==Nd){e.msg="unknown compression method",n.mode=16209;break}if(h>>>=4,u-=4,y=8+(15&h),0===n.wbits&&(n.wbits=y),y>15||y>n.wbits){e.msg="invalid window size",n.mode=16209;break}n.dmax=1<<n.wbits,n.flags=0,e.adler=n.check=1,n.mode=512&h?16189:16191,h=0,u=0;break;case 16181:for(;u<16;){if(0===d)break e;d--,h+=o[s++]<<u,u+=8}if(n.flags=h,(255&OT(n))!==Nd){e.msg="unknown compression method",n.mode=16209;break}if(57344&OT(n)){e.msg="unknown header flags set",n.mode=16209;break}n.head&&(n.head.text=h>>8&1),512&OT(n)&&4&n.wrap&&(b[0]=255&h,b[1]=h>>>8&255,n.check=O$(n.check,b,2,0)),h=0,u=0,n.mode=16182;case 16182:for(;u<32;){if(0===d)break e;d--,h+=o[s++]<<u,u+=8}n.head&&(n.head.time=h),512&OT(n)&&4&n.wrap&&(b[0]=255&h,b[1]=h>>>8&255,b[2]=h>>>16&255,b[3]=h>>>24&255,n.check=O$(n.check,b,4,0)),h=0,u=0,n.mode=16183;case 16183:for(;u<16;){if(0===d)break e;d--,h+=o[s++]<<u,u+=8}n.head&&(n.head.xflags=255&h,n.head.os=h>>8),512&OT(n)&&4&n.wrap&&(b[0]=255&h,b[1]=h>>>8&255,n.check=O$(n.check,b,2,0)),h=0,u=0,n.mode=16184;case 16184:if(1024&OT(n)){for(;u<16;){if(0===d)break e;d--,h+=o[s++]<<u,u+=8}n.length=h,n.head&&(n.head.extra_len=h),512&OT(n)&&4&n.wrap&&(b[0]=255&h,b[1]=h>>>8&255,n.check=O$(n.check,b,2,0)),h=0,u=0}else n.head&&(n.head.extra=null);n.mode=16185;case 16185:if(1024&OT(n)&&((E=n.length)>d&&(E=d),E&&(n.head&&(y=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Uint8Array(n.head.extra_len)),n.head.extra.set(o.subarray(s,s+E),y)),512&OT(n)&&4&n.wrap&&(n.check=O$(n.check,o,E,s)),d-=E,s+=E,n.length-=E),n.length))break e;n.length=0,n.mode=16186;
1case 16186:if(2048&OT(n)){if(0===d)break e;E=0;do y=o[s+E++],n.head&&y&&n.length<65536&&(n.head.name+=String.fromCharCode(y));while(y&&E<d);if(512&OT(n)&&4&n.wrap&&(n.check=O$(n.check,o,E,s)),d-=E,s+=E,y)break e}else n.head&&(n.head.name=null);n.length=0,n.mode=16187;case 16187:if(4096&OT(n)){if(0===d)break e;E=0;do y=o[s+E++],n.head&&y&&n.length<65536&&(n.head.comment+=String.fromCharCode(y));while(y&&E<d);if(512&OT(n)&&4&n.wrap&&(n.check=O$(n.check,o,E,s)),d-=E,s+=E,y)break e}else n.head&&(n.head.comment=null);n.mode=16188;case 16188:if(512&OT(n)){for(;u<16;){if(0===d)break e;d--,h+=o[s++]<<u,u+=8}if(4&n.wrap&&h!==(65535&n.check)){e.msg="header crc mismatch",n.mode=16209;break}h=0,u=0}n.head&&(n.head.hcrc=OT(n)>>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=16191;break;case 16189:for(;u<32;){if(0===d)break e;d--,h+=o[s++]<<u,u+=8}e.adler=n.check=Nl(h),h=0,u=0,n.mode=16190;case 16190:if(0===n.havedict)return e.next_out=c,e.avail_out=l,e.next_in=s,e.avail_in=d,n.hold=h,n.bits=u,Nn;e.adler=n.check=1,n.mode=16191;case 16191:if(t===Ne||t===Nt)break e;case 16192:if(n.last){h>>>=7&u,u-=7&u,n.mode=16206;break}for(;u<3;){if(0===d)break e;d--,h+=o[s++]<<u,u+=8}switch(n.last=1&h,u-=1,3&(h>>>=1)){case 0:n.mode=16193;break;case 1:if(Nf(n),n.mode=16199,t===Nt){h>>>=2,u-=2;break e}break;case 2:n.mode=16196;break;case 3:e.msg="invalid block type",n.mode=16209}h>>>=2,u-=2;break;case 16193:for(h>>>=7&u,u-=7&u;u<32;){if(0===d)break e;d--,h+=o[s++]<<u,u+=8}if((65535&h)!=(h>>>16^65535)){e.msg="invalid stored block lengths",n.mode=16209;break}if(n.length=65535&h,h=0,u=0,n.mode=16194,t===Nt)break e;case 16194:n.mode=16195;case 16195:if(E=n.length){if(E>d&&(E=d),E>l&&(E=l),0===E)break e;a.set(o.subarray(s,s+E),c),d-=E,s+=E,l-=E,c+=E,n.length-=E;break}n.mode=16191;break;case 16196:for(;u<14;){if(0===d)break e;d--,h+=o[s++]<<u,u+=8}if(n.nlen=257+(31&h),u-=5,n.ndist=1+(31&(h>>>=5)),u-=5,n.ncode=4+(15&(h>>>=5)),h>>>=4,u-=4,n.nlen>286||n.ndist>30){e.msg="too many length or distance symbols",n.mode=16209;break}n.have=0,n.mode=16197;case 16197:for(;n.have<n.ncode;){for(;u<3;){if(0===d)break e;d--,h+=o[s++]<<u,u+=8}n.lens[O[n.have++]]=7&h,h>>>=3,u-=3}for(;n.have<19;)n.lens[O[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,i={bits:n.lenbits},I=w9(0,n.lens,0,19,n.lencode,0,n.work,i),n.lenbits=i.bits,I){e.msg="invalid code lengths set",n.mode=16209;break}n.have=0,n.mode=16198;case 16198:for(;n.have<n.nlen+n.ndist;){for(;S=(A=n.lencode[h&(1<<n.lenbits)-1])>>>24,g=A>>>16&255,T=65535&A,!(S<=u);){if(0===d)break e;d--,h+=o[s++]<<u,u+=8}if(T<16)h>>>=S,u-=S,n.lens[n.have++]=T;else{if(16===T){for(r=S+2;u<r;){if(0===d)break e;d--,h+=o[s++]<<u,u+=8}if(h>>>=S,u-=S,0===n.have){e.msg="invalid bit length repeat",n.mode=16209;break}y=n.lens[n.have-1],E=3+(3&h),h>>>=2,u-=2}else if(17===T){for(r=S+3;u<r;){if(0===d)break e;d--,h+=o[s++]<<u,u+=8}h>>>=S,u-=S,y=0,E=3+(7&h),h>>>=3,u-=3}else{for(r=S+7;u<r;){if(0===d)break e;d--,h+=o[s++]<<u,u+=8}h>>>=S,u-=S,y=0,E=11+(127&h),h>>>=7,u-=7}if(n.have+E>n.nlen+n.ndist){e.msg="invalid bit length repeat",n.mode=16209;break}for(;E--;)n.lens[n.have++]=y}}if(16209===n.mode)break;if(0===n.lens[256]){e.msg="invalid code -- missing end-of-block",n.mode=16209;break}if(n.lenbits=9,i={bits:n.lenbits},I=w9(1,n.lens,0,n.nlen,n.lencode,0,n.work,i),n.lenbits=i.bits,I){e.msg="invalid literal/lengths set",n.mode=16209;break}if(n.distbits=6,n.distcode=n.distdyn,i={bits:n.distbits},I=w9(2,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,i),n.distbits=i.bits,I){e.msg="invalid distances set",n.mode=16209;break}if(n.mode=16199,t===Nt)break e;case 16199:n.mode=16200;case 16200:if(d>=6&&l>=258){e.next_out=c,e.avail_out=l,e.next_in=s,e.avail_in=d,n.hold=h,n.bits=u,w3(e,_),c=e.next_out,a=e.output,l=e.avail_out,s=e.next_in,o=e.input,d=e.avail_in,h=n.hold,u=n.bits,16191===n.mode&&(n.back=-1);break}for(n.back=0;S=(A=n.lencode[h&(1<<n.lenbits)-1])>>>24,g=A>>>16&255,T=65535&A,!(S<=u);){if(0===d)break e;d--,h+=o[s++]<<u,u+=8}if(g&&0==(240&g)){for(R=S,C=g,v=T;S=(A=n.lencode[v+((h&(1<<R+C)-1)>>R)])>>>24,g=A>>>16&255,T=65535&A,!(R+S<=u);){if(0===d)break e;d--,h+=o[s++]<<u,u+=8}h>>>=R,u-=R,n.back+=R}if(h>>>=S,u-=S,n.back+=S,n.length=T,0===g){n.mode=16205;break}if(32&g){n.back=-1,n.mode=16191;break}if(64&g){e.msg="invalid literal/length code",n.mode=16209;break}n.extra=15&g,n.mode=16201;case 16201:if(n.extra){for(r=n.extra;u<r;){if(0===d)break e;d--,h+=o[s++]<<u,u+=8}n.length+=h&(1<<n.extra)-1,h>>>=n.extra,u-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=16202;case 16202:for(;S=(A=n.distcode[h&(1<<n.distbits)-1])>>>24,g=A>>>16&255,T=65535&A,!(S<=u);){if(0===d)break e;d--,h+=o[s++]<<u,u+=8}if(0==(240&g)){for(R=S,C=g,v=T;S=(A=n.distcode[v+((h&(1<<R+C)-1)>>R)])>>>24,g=A>>>16&255,T=65535&A,!(R+S<=u);){if(0===d)break e;d--,h+=o[s++]<<u,u+=8}h>>>=R,u-=R,n.back+=R}if(h>>>=S,u-=S,n.back+=S,64&g){e.msg="invalid distance code",n.mode=16209;break}n.offset=T,n.extra=15&g,n.mode=16203;case 16203:if(n.extra){for(r=n.extra;u<r;){if(0===d)break e;d--,h+=o[s++]<<u,u+=8}n.offset+=h&(1<<n.extra)-1,h>>>=n.extra,u-=n.extra,n.back+=n.extra}if(n.offset>
1n.dmax){e.msg="invalid distance too far back",n.mode=16209;break}n.mode=16204;case 16204:if(0===l)break e;if(E=_-l,n.offset>E){if((E=n.offset-E)>n.whave&&n.sane){e.msg="invalid distance too far back",n.mode=16209;break}E>n.wnext?(E-=n.wnext,m=n.wsize-E):m=n.wnext-E,E>n.length&&(E=n.length),f=n.window}else f=a,m=c-n.offset,E=n.length;E>l&&(E=l),l-=E,n.length-=E;do a[c++]=f[m++];while(--E);0===n.length&&(n.mode=16200);break;case 16205:if(0===l)break e;a[c++]=n.length,l--,n.mode=16200;break;case 16206:if(n.wrap){for(;u<32;){if(0===d)break e;d--,h|=o[s++]<<u,u+=8}if(_-=l,e.total_out+=_,n.total+=_,4&n.wrap&&_&&(e.adler=n.check=OT(n)?O$(n.check,a,_,c-_):OQ(n.check,a,_,c-_)),_=l,4&n.wrap&&(OT(n)?h:Nl(h))!==n.check){e.msg="incorrect data check",n.mode=16209;break}h=0,u=0}n.mode=16207;case 16207:if(n.wrap&&OT(n)){for(;u<32;){if(0===d)break e;d--,h+=o[s++]<<u,u+=8}if(4&n.wrap&&h!==(0|n.total)){e.msg="incorrect length check",n.mode=16209;break}h=0,u=0}n.mode=16208;case 16208:I=Nr;break e;case 16209:I=Na;break e;case 16210:return Ns;default:return No}return e.next_out=c,e.avail_out=l,e.next_in=s,e.avail_in=d,n.hold=h,n.bits=u,(n.wsize||_!==e.avail_out&&n.mode<16209&&(n.mode<16206||t!==w7))&&NS(e,e.output,e.next_out,_-e.avail_out),p-=e.avail_in,_-=e.avail_out,e.total_in+=p,e.total_out+=_,n.total+=_,4&n.wrap&&_&&(e.adler=n.check=OT(n)?O$(n.check,a,_,e.next_out-_):OQ(n.check,a,_,e.next_out-_)),e.data_type=n.bits+64*!!n.last+128*(16191===n.mode)+256*(16199===n.mode||16194===n.mode),(0===p&&0===_||t===w7)&&I===Ni&&(I=Nc),I},NT=e=>{if(Nu(e))return No;let t=e.state;return t.window&&(t.window=null),e.state=null,Ni},NR=(e,t)=>{let i,r=t.length;return Nu(e)||0!==(i=e.state).wrap&&16190!==i.mode?No:16190===i.mode&&OQ(1,t,r,0)!==i.check?Na:NS(e,t,r,r)?(i.mode=16210,Ns):(i.havedict=1,Ni)},NC=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1};let Nv=Object.prototype.toString,{Z_NO_FLUSH:Ny,Z_FINISH:NI,Z_OK:NA,Z_STREAM_END:Nb,Z_NEED_DICT:NO,Z_STREAM_ERROR:Nw,Z_DATA_ERROR:NN,Z_MEM_ERROR:ND}=O1;function NP(e){this.options=wx({chunkSize:65536,windowBits:15,to:""},e||{});let t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new wH,this.strm.avail_out=0;let i=((e,t)=>{if(!e)return No;let i=new Nh;e.state=i,i.strm=e,i.window=null,i.mode=16180;let r=((e,t)=>{let i;if(Nu(e))return No;let r=e.state;return t<0?(i=0,t=-t):(i=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?No:(null!==r.window&&r.wbits!==t&&(r.window=null),r.wrap=i,r.wbits=t,Np(e))})(e,t);return r!==Ni&&(e.state=null),r})(this.strm,t.windowBits);if(i!==NA||(this.header=new NC,((e,t)=>{if(Nu(e))return;let i=e.state;return 0==(2&i.wrap)||(i.head=t,t.done=!1)})(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=wj(t.dictionary):"[object ArrayBuffer]"===Nv.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=NR(this.strm,t.dictionary))!==NA)))throw Error(O0[i])}function NL(e,t){let i=new NP(t);if(i.push(e),i.err)throw i.msg||O0[i.err];return i.result}NP.prototype.push=function(e,t){let i,r,n,o=this.strm,a=this.options.chunkSize,s=this.options.dictionary;if(this.ended)return!1;for(r=t===~~t?t:!0===t?NI:Ny,"[object ArrayBuffer]"===Nv.call(e)?o.input=new Uint8Array(e):o.input=e,o.next_in=0,o.avail_in=o.input.length;;){for(0===o.avail_out&&(o.output=new Uint8Array(a),o.next_out=0,o.avail_out=a),(i=Ng(o,r))===NO&&s&&((i=NR(o,s))===NA?i=Ng(o,r):i===NN&&(i=NO));o.avail_in>0&&i===Nb&&o.state.wrap>0&&0!==e[o.next_in];)Np(o),i=Ng(o,r);switch(i){case Nw:case NN:case NO:case ND:return this.onEnd(i),this.ended=!0,!1}if(n=o.avail_out,o.next_out&&(0===o.avail_out||i===Nb))if("string"===this.options.to){let e=wW(o.output,o.next_out),t=o.next_out-e,i=wG(o.output,e);o.next_out=t,o.avail_out=a-t,t&&o.output.set(o.output.subarray(e,e+t),0),this.onData(i)}else this.onData(o.output.length===o.next_out?o.output:o.output.subarray(0,o.next_out));if(i!==NA||0!==n){if(i===Nb)return i=NT(this.strm),this.onEnd(i),this.ended=!0,!0;if(0===o.avail_in)break}}return!0},NP.prototype.onData=function(e){this.chunks.push(e)},NP.prototype.onEnd=function(e){e===NA&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=wV(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};let{Deflate:Nk,deflate:NM,deflateRaw:NU,gzip:Nx}={Deflate:w1,deflate:w2,deflateRaw:function(e,t){return(t=t||{}).raw=!0,w2(e,t)},gzip:function(e,t){return(t=t||{}).gzip=!0,w2(e,t)},constants:O1},{Inflate:NV,inflate:NF,inflateRaw:NB,ungzip:Nj}={Inflate:NP,inflate:NL,inflateRaw:function(e,t){return(t=t||{}).raw=!0,NL(e,t)},ungzip:NL,constants:O1};var NG=((tn=NG||{})[tn.ONE_BYTE=0]="ONE_BYTE",tn[tn.TWO_BYTE=1]="TWO_BYTE",tn);class NW{get startTime(){let e=Date.now()-this._startTime;return e<65536?e:(this._startTime+=65536,this.startTime)}get sequence(){return this._sequence<0x100000000?this._sequence++:(this._sequence-=0x100000000,this.sequence)}serialize(e){let t={commonPacketHeader:{length:0,reserved:0,extension:0,sequence:this.sequence},commonStreamHeader:this.startTime,extension:void 0,payload:e};if(e.byteLength>128){let i=new Uint8Array(4);i.set([1,0,0,0]);let r={id:0,length:4,data:i.buffer},n={profile:+!this.isUseOneByte,length:this.isUseOneByte?5:6,datas:[r]};t.commonPacketHeader.extension=1,t.extension=n,t.payload=this.compress(e),t.commonPacketHeader.length=8+(t.extension.length+2)+t.payload.byteLength}else t.commonPacketHeader.length=8+t.payload.byteLength;TR("SHOW_DATASTREAM2_LOG")&&TY.debug("send data header: ".concat(JSON.stringify(t.commonPacketHeader)));
1let i=new ArrayBuffer(t.commonPacketHeader.length),r=new Uint8Array(i),n=new DataView(i),o=0;if(n.setUint16(o,t.commonPacketHeader.extension<<15|t.commonPacketHeader.reserved<<14|t.commonPacketHeader.length,!0),o+=2,n.setUint32(o,t.commonPacketHeader.sequence,!0),o+=4,n.setUint16(o,t.commonStreamHeader,!0),o+=2,t.extension){let e=this.serializeExtension(t.extension);r.set(new Uint8Array(e),o),o+=e.byteLength}if(r.set(new Uint8Array(t.payload),o),(o+=t.payload.byteLength)!==t.commonPacketHeader.length)throw Error("serialize error!");return i}deserialize(e){let t,i;if(e.byteLength<4)return new ArrayBuffer(0);let r=new DataView(e),n=0,o=r.getUint16(n,!0);n+=2;let a={length:16383&o,reserved:(16384&o)>>14,extension:(32768&o)>>15,sequence:r.getUint16(n+2,!0)<<16|r.getUint16(n,!0)};if(n+=4,TR("SHOW_DATASTREAM2_LOG")&&TY.debug("receive data header: ".concat(JSON.stringify(a))),r.getUint16(n,!0),n+=2,a.extension){i=this.deserializeExtension(e.slice(n)),n+=2+i.length,t=e.slice(n);let r=!1;if(i.datas.length>0){let e=i.datas.find(e=>0===e.id);e&&(r=1==(1&new DataView(e.data).getUint32(0,!0)))}t=r?this.decompress(t):t}else t=e.slice(8);return t}serializeExtension(e){let{profile:t,length:i,datas:r}=e,n=new ArrayBuffer(i+2),o=new Uint8Array(n),a=new DataView(n),s=0;if(a.setUint8(s++,t),a.setUint8(s++,i),r.forEach(e=>{t?(a.setUint8(s++,e.id),a.setUint8(s++,e.length)):a.setUint8(s++,e.id|e.length<<4),o.set(new Uint8Array(e.data),s),s+=e.data.byteLength}),s!==i+2)throw Error("serialize extension error, is ".concat(s,"!==").concat(i+2));return n}deserializeExtension(e){let t=new DataView(e),i=0,r=t.getUint8(i);i++;let n=t.getUint8(i);i++;let o=r===NG.TWO_BYTE,a=[],s=new DataView(e,2),c=0;for(;c<n;){let e=0,t=0,i=new ArrayBuffer(0);o?(e=s.getUint8(c),c++,t=s.getUint8(c)):(e=15&s.getUint8(c),t=s.getUint8(c)>>4),c++,t>0&&(i=s.buffer.slice(c+2,c+2+t),c+=i.byteLength),a.push({id:e,length:t,data:i})}if(c!==n)throw Error("parse error");return{profile:r,length:n,datas:a}}decompress(e){return NF(new Uint8Array(e))}compress(e){return NM(new Uint8Array(e))}constructor(){mb(this,"_sequence",0),mb(this,"_startTime",Date.now()),mb(this,"isUseOneByte",!0)}}class NH extends S0{isConnect(){return"connected"===this.ws.state}sendMessage(e){let t=this.requestId++;return e.requestId=t,e.seq=t,this.ws.sendMessage(e),t}waitStatus(e){return new dQ((t,i)=>{let r=window.setTimeout(()=>{i(new T0(SU.TIMEOUT,"wait status timeout, status: ".concat(e)))},5e3);this.once(e,n=>{window.clearTimeout(r),n.state&&0!==n.state?i(new T0(SU.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(e))):t(void 0)}),this.once("dispose",()=>{window.clearTimeout(r),i(new T0(SU.WS_ABORT))})})}async request(e){if("closed"===this.ws.state)throw new T0(SU.WS_DISCONNECT);let t=()=>new dQ((e,t)=>{this.ws.once(vH.CLOSED,()=>t(new T0(SU.WS_ABORT))),this.ws.once(vH.CONNECTED,e)});"connected"!==this.ws.state&&await t();let i=this.sendMessage(e),r=new dQ((e,t)=>{let r=()=>{t(new T0(SU.WS_ABORT))};this.ws.once(vH.RECONNECTING,r),this.ws.once(vH.CLOSED,r),this.once("req_".concat(i),e),gO(3e3).then(()=>{this.removeAllListeners("req_".concat(i)),this.ws.off(vH.RECONNECTING,r),this.ws.off(vH.CLOSED,r),t(new T0(SU.TIMEOUT,"cross channel ws request timeout"))})}),n=await r;if(!n||200!==n.code)throw new T0(SU.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(JSON.stringify(n)));return n}async connect(e){this.ws.removeAllListeners(vH.REQUEST_NEW_URLS),this.ws.on(vH.REQUEST_NEW_URLS,t=>{t(e)}),await this.ws.init(e)}dispose(){this.clearHeartBeatCheck(),this.emit("dispose"),this.removeAllListeners(),this.ws.close()}sendPing(e){let t=this.requestId++;return e.requestId=t,this.ws.sendMessage(e),t}startHeartBeatCheck(){this.heartBeatTimer&&window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=window.setInterval(()=>{this.sendPing({command:"ping",appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sid:this.joinInfo.sid,ts:+new Date,requestId:0})},3e3)}clearHeartBeatCheck(){window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=void 0}constructor(e,t,i){super(),mb(this,"ws",void 0),mb(this,"requestId",1),mb(this,"heartBeatTimer",void 0),mb(this,"joinInfo",void 0),mb(this,"clientId",void 0),mb(this,"onOpen",()=>
1{this.emit("open"),this.startHeartBeatCheck()}),mb(this,"onClose",e=>{this.emit("close"),this.dispose()}),mb(this,"onMessage",e=>{let t=JSON.parse(e.data);if(!t||"serverResponse"!==t.command||!t.requestId)return t&&"serverStatus"===t.command&&t.serverStatus&&t.serverStatus.command?(this.emit("status",t.serverStatus),void this.emit(t.serverStatus.command,t.serverStatus)):void 0;this.emit("req_".concat(t.requestId),t)}),this.joinInfo=e,this.clientId=t,this.ws=new yH("cross-channel-".concat(this.clientId),i),this.ws.on(vH.RECONNECTING,()=>{this.ws.reconnectMode="retry",this.emit("reconnecting")}),this.ws.on(vH.CONNECTED,this.onOpen),this.ws.on(vH.ON_MESSAGE,this.onMessage),this.ws.on(vH.CLOSED,this.onClose)}}class NK extends S0{set state(e){e!==this._state&&(e!==v5.RELAY_STATE_FAILURE&&(this.errorCode=v4.RELAY_OK),this.emit("state",e,this.errorCode),this._state=e)}get state(){return this._state}async startChannelMediaRelay(e){if(this.state!==v5.RELAY_STATE_IDLE)throw new T0(SU.INVALID_OPERATION);this.state=v5.RELAY_STATE_CONNECTING,await this.connect(),TY.debug("[".concat(this.clientId,"] startChannelMediaRelay: connect success"));try{await this.sendStartRelayMessage(e)}catch(e){if(e.data&&e.data.serverResponse&&"SetSourceChannel"===e.data.serverResponse.command)throw new T0(SU.CROSS_CHANNEL_FAILED_JOIN_SRC);if(e.data&&e.data.serverResponse&&"SetDestChannelStatus"===e.serverResponse.command)throw new T0(SU.CROSS_CHANNEL_FAILED_JOIN_DEST);if(e.data&&e.data.serverResponse&&"StartPacketTransfer"===e.serverResponse.command)throw new T0(SU.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST);throw e}this.prevChannelMediaConfig=e}async updateChannelMediaRelay(e){if(this.state!==v5.RELAY_STATE_RUNNING)throw new T0(SU.INVALID_OPERATION);await this.sendUpdateMessage(e),this.prevChannelMediaConfig=e}async setVideoProfile(e){if(this._resolution=e,this.state!==v5.RELAY_STATE_RUNNING)throw new T0(SU.INVALID_OPERATION);let t=this.genMessage(v2.SetVideoProfile);await this.signal.request(t),TY.debug("[".concat(this.clientId,"] startChannelMediaRelay: setVideoProfile success"))}async stopChannelMediaRelay(){await this.sendStopRelayMessage(),TY.debug("[".concat(this.clientId,"] stopChannelMediaRelay: send stop message success")),this.state=v5.RELAY_STATE_IDLE,this.dispose()}dispose(){TY.debug("[".concat(this.clientId,"] disposeChannelMediaRelay")),this.cancelToken.cancel(),this.cancelToken=f0.CancelToken.source(),this.state=v5.RELAY_STATE_IDLE,this.emit("dispose"),this.signal.dispose(),this.prevChannelMediaConfig=void 0}async connect(){let e=await Ap(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=e.workerToken,await this.signal.connect(e.addressList),this.emit("event",v3.NETWORK_CONNECTED),this.signal.on("status",this.onStatus),this.signal.on("reconnecting",this.onReconnect)}async sendStartRelayMessage(e){let t=this.genMessage(v2.SetSdkProfile,e);await this.signal.request(t),TY.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));let i=this.genMessage(v2.SetSourceChannel,e);await this.signal.request(i),await this.signal.waitStatus("SetSourceChannelStatus"),this.emit("event",v3.PACKET_JOINED_SRC_CHANNEL),TY.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));let r=this.genMessage(v2.SetSourceUserId,e);await this.signal.request(r),TY.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));let n=this.genMessage(v2.SetDestChannel,e);await this.signal.request(n),await this.signal.waitStatus("SetDestChannelStatus"),this.emit("event",v3.PACKET_JOINED_DEST_CHANNEL),TY.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetDestChannel success"));let o=this.genMessage(v2.StartPacketTransfer,e);await this.signal.request(o),this.emit("event",v3.PACKET_SENT_TO_DEST_CHANNEL),this.state=v5.RELAY_STATE_RUNNING,TY.debug("[".concat(this.clientId,"] startChannelMediaRelay: StartPacketTransfer success")),this.setVideoProfile(this._resolution)}async sendUpdateMessage(e){let t=this.genMessage(v2.UpdateDestChannel,e);
1await this.signal.request(t),this.emit("event",v3.PACKET_UPDATE_DEST_CHANNEL),TY.debug("[".concat(this.clientId,"] sendUpdateMessage: UpdateDestChannel success"))}async sendStopRelayMessage(){let e=this.genMessage(v2.StopPacketTransfer);await this.signal.request(e),TY.debug("[".concat(this.clientId,"] sendStopRelayMessage: StopPacketTransfer success"))}genMessage(e,t){let i=[],r=[],n=[];this.requestId+=1;let o={appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sdkVersion:Th,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};"4.24.2"===o.sdkVersion&&(o.sdkVersion="0.0.1");let a=null,s=null;switch(e){case v2.SetSdkProfile:return o.clientRequest={command:"SetSdkProfile",type:"multi_channel"},o;case v2.SetSourceChannel:if(!(s=t&&t.getSrcChannelMediaInfo()))throw new T0(SU.UNEXPECTED_ERROR,"can not find source config");return o.clientRequest={command:"SetSourceChannel",uid:"0",channelName:s.channelName,token:s.token||this.joinInfo.appId},o;case v2.SetSourceUserId:if(!(s=t&&t.getSrcChannelMediaInfo()))throw new T0(SU.UNEXPECTED_ERROR,"can not find source config");return o.clientRequest={command:"SetSourceUserId",uid:s.uid+""},o;case v2.SetDestChannel:if(!(a=t&&t.getDestChannelMediaInfo()))throw new T0(SU.UNEXPECTED_ERROR,"can not find dest config");return a.forEach(e=>{i.push(e.channelName),r.push(e.uid+""),n.push(e.token||this.joinInfo.appId)}),o.clientRequest={command:"SetDestChannel",channelName:i,uid:r,token:n},o;case v2.StartPacketTransfer:return o.clientRequest={command:"StartPacketTransfer"},o;case v2.Reconnect:return o.clientRequest={command:"Reconnect"},o;case v2.StopPacketTransfer:return o.clientRequest={command:"StopPacketTransfer"},o;
1case v2.UpdateDestChannel:if(!(a=t&&t.getDestChannelMediaInfo()))throw new T0(SU.UNEXPECTED_ERROR,"can not find dest config");return a.forEach(e=>{i.push(e.channelName),r.push(e.uid+""),n.push(e.token||this.joinInfo.appId)}),o.clientRequest={command:"UpdateDestChannel",channelName:i,uid:r,token:n},o;case v2.SetVideoProfile:o.clientRequest={command:"SetVideoProfile",width:this._resolution.width,height:this._resolution.height}}return o}constructor(e,t,i,r,n){super(),mb(this,"joinInfo",void 0),mb(this,"sid",void 0),mb(this,"clientId",void 0),mb(this,"cancelToken",f0.CancelToken.source()),mb(this,"workerToken",void 0),mb(this,"requestId",0),mb(this,"signal",void 0),mb(this,"prevChannelMediaConfig",void 0),mb(this,"httpRetryConfig",void 0),mb(this,"_resolution",void 0),mb(this,"_state",v5.RELAY_STATE_IDLE),mb(this,"errorCode",v4.RELAY_OK),mb(this,"onStatus",e=>{TY.debug("[".concat(this.clientId,"] ChannelMediaStatus: ").concat(JSON.stringify(e))),e&&e.command&&("onAudioPacketReceived"===e.command&&this.emit("event",v3.PACKET_RECEIVED_AUDIO_FROM_SRC),"onVideoPacketReceived"===e.command&&this.emit("event",v3.PACKET_RECEIVED_VIDEO_FROM_SRC),"onSrcTokenPrivilegeDidExpire"===e.command&&(this.errorCode=v4.SRC_TOKEN_EXPIRED,this.state=v5.RELAY_STATE_FAILURE),"onDestTokenPrivilegeDidExpire"===e.command&&(this.errorCode=v4.DEST_TOKEN_EXPIRED,this.state=v5.RELAY_STATE_FAILURE))}),mb(this,"onReconnect",async()=>{TY.debug("[".concat(this.clientId,"] ChannelMediaSocket disconnect, reconnecting")),this.emit("event",v3.NETWORK_DISCONNECTED),this.state=v5.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch(e=>{this.state!==v5.RELAY_STATE_IDLE&&(TY.error("auto restart channel media relay failed",e.toString()),this.errorCode=v4.SERVER_CONNECTION_LOST,this.state=v5.RELAY_STATE_FAILURE)})}),this.joinInfo=e,this.clientId=t,this.sid=gN(),this.signal=new NH(this.joinInfo,this.clientId,i),this.httpRetryConfig=r,this._resolution=n}}function NY(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function Nz(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?NY(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):NY(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}class Nq extends S0{init(e){return this.websocket.init(e)}async request(e,t,i,r){this.reqId+=1,"request"===e&&(this.commandReqId+=1);let n=this.commandReqId,o=this.reqId;if(!o||!this.websocket)throw new T0(SU.UNEXPECTED_ERROR);let a=Nz({command:e,sdkVersion:"4.24.2"===Th?"0.0.1":Th,seq:o,requestId:o,allocate:i,cname:this.spec.cname,appId:this.spec.appId,sid:this.spec.sid,uid:this.spec.uid.toString(),ts:Math.floor(Date.now()/1e3)},t);if("closed"===this.websocket.state)throw new T0(SU.WS_DISCONNECT);let s=()=>new dQ((e,t)=>{this.websocket.once(vH.CLOSED,()=>t(new T0(SU.WS_ABORT))),this.websocket.once(vH.CONNECTED,e)});"connected"!==this.websocket.state&&await s(),a.clientRequest&&(a.clientRequest.workerToken=this.token);let c=new dQ((e,t)=>{let i=()=>{t(new T0(SU.WS_ABORT))};this.websocket.once(vH.RECONNECTING,i),this.websocket.once(vH.CLOSED,i),this.once("@".concat(o,"-").concat(this.spec.sid),t=>{e(t)})});r&&T$.workerEvent(this.spec.sid,Nz(Nz({},r),{},{requestId:n,actionType:"request",payload:JSON.stringify(t.clientRequest),serverCode:0,code:0}));let d=Date.now();this.websocket.sendMessage(a);let l=null;try{l=await c}catch(r){if("closed"===this.websocket.state)throw r;return await s(),await this.request(e,t,i)}return r&&T$.workerEvent(this.spec.sid,Nz(Nz({},r),{},{requestId:n,actionType:"response",payload:JSON.stringify(l.serverResponse),serverCode:l.code,success:200===l.code,responseTime:Date.now()-d})),200!==l.code&&this.handleResponseError(l),l}tryNextAddress(){this.reconnectMode="tryNext",this.websocket.reconnect("tryNext")}close(){let e="4.24.2"===Th?"0.0.1":Th;this.reqId+=1,"connected"===this.websocket.state?(this.websocket.sendMessage({command:"request",appId:this.spec.appId,cname:this.spec.cname,uid:this.spec.uid.toString(),sdkVersion:e,sid:this.spec.sid,seq:this.reqId,ts:Math.floor(Date.now()/1e3),requestId:this.reqId,clientRequest:{command:"DestroyWorker"}}),this.websocket.close(!1,!0)):this.websocket.close(!1),this.pingpongTimer&&(window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0)}handleResponseError(e){switch(e.code){case v0.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void TY.warning("live stream response already exists stream");case v0.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case v0.LIVE_STREAM_RESPONSE_BAD_STREAM:case v0.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return new T0(SU.LIVE_STREAMING_INVALID_ARGUMENT,"",{code:e.code}).throw();case v0.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if("UnpublishStream"
1===e.serverResponse.command)return;throw new T0(SU.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case v0.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new T0(SU.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:e.code}).throw();case v0.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{let t=new T0(SU.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(vZ.WARNING,t,e.serverResponse.url)}case v0.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:{let t=new T0(SU.LIVE_STREAMING_WARN_FREQUENT_REQUEST);return this.emit(vZ.WARNING,t,e.serverResponse.url)}case v0.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new T0(SU.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case v0.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new T0(SU.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:e.code}).throw();case v0.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{let t=new T0(SU.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT);return this.emit(vZ.WARNING,t,e.serverResponse.url)}case v0.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return new T0(SU.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code}).throw();case v0.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new T0(SU.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream resource limit",{retry:!0,changeAddress:!0});case v0.LIVE_STREAM_RESPONSE_WORKER_LOST:case v0.LIVE_STREAM_RESPONSE_WORKER_QUIT:if("UnpublishStream"===e.serverResponse.command)return;throw new T0(SU.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case v0.ERROR_FAIL_SEND_MESSAGE:if("UnpublishStream"===e.serverResponse.command)return;if("UpdateTranscoding"===e.serverResponse.command||"ControlStream"===e.serverResponse.command)return new T0(SU.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:e.code}).throw();throw new T0(SU.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case v0.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case v0.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case v0.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case v0.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return new T0(SU.LIVE_STREAMING_CDN_ERROR,"",{code:e.code}).throw()}}startPingPong(){this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(()=>{"connected"===this.websocket.state&&this.request("ping",{}).catch(gD)},6e3)}constructor(e,t,i,r){super(),mb(this,"spec",void 0),mb(this,"token",void 0),mb(this,"websocket",void 0),mb(this,"pingpongTimer",void 0),mb(this,"reconnectMode","retry"),mb(this,"serviceMode",void 0),mb(this,"reqId",0),mb(this,"commandReqId",0),mb(this,"handleWebSocketOpen",()=>{this.reconnectMode="retry",this.startPingPong()}),mb(this,"handleWebSocketMessage",e=>{if(!e.data)return;let t=JSON.parse(e.data);t.requestId?this.emit("@".concat(t.requestId,"-").concat(t.sid),t):(T$.workerEvent(this.spec.sid,{actionType:"status",serverCode:t.code,workerType:this.serviceMode===vz.TRANSCODE?1:2}),this.emit(vZ.PUBLISH_STREAM_STATUS,t))}),this.spec=t,this.token=e,this.serviceMode=r,this.websocket=new yH("live-streaming",i),this.websocket.on(vH.CONNECTED,this.handleWebSocketOpen),this.websocket.on(vH.ON_MESSAGE,this.handleWebSocketMessage),this.websocket.on(vH.REQUEST_NEW_URLS,(e,t)=>{gs(this,vZ.REQUEST_NEW_ADDRESS).then(e).catch(t)}),this.websocket.on(vH.RECONNECTING,()=>{this.websocket.reconnectMode=this.reconnectMode})}}function NX(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function NJ(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?NX(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):NX(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}class NQ extends S0{async setTranscodingConfig(e){var t;let i=NJ(NJ({},vQ),e);66!==i.videoCodecProfile&&77!==i.videoCodecProfile&&100!==i.videoCodecProfile&&(TY.debug("[".concat(this.spec.clientId,"] set transcoding config, fix video codec profile: ").concat(i.videoCodecProfile," -> 100")),i.videoCodecProfile=100),i.transcodingUsers||(i.transcodingUsers=i.userConfigs),i.transcodingUsers&&(i.transcodingUsers=i.transcodingUsers.map(e=>NJ(NJ(NJ({},vq),e),{},{zOrder:e.zOrder?e.zOrder+1:1}))),SH(i.width)||SB(i.width,"config.width",0,1e4),SH(i.height)||SB(i.height,"config.height",0,1e4),SH(i.videoBitrate)||SB(i.videoBitrate,"config.videoBitrate",1,1e6),SH(i.videoFrameRate)||SB(i.videoFrameRate,"config.videoFrameRate"),SH(i.lowLatency)||SV(i.lowLatency,"config.lowLatency"),SH(i.audioSampleRate)||SF(i.audioSampleRate,"config.audioSampleRate",[32e3,44100,48e3]),SH(i.audioBitrate)||SB(i.audioBitrate,"config.audio
1Bitrate",1,128),SH(i.audioChannels)||SF(i.audioChannels,"config.audioChannels",[1,2,3,4,5]),SH(i.videoGop)||SB(i.videoGop,"config.videoGop"),SH(i.videoCodecProfile)||SF(i.videoCodecProfile,"config.videoCodecProfile",[66,77,100]),SH(i.userCount)||SB(i.userCount,"config.userCount",0,17),SH(i.backgroundColor)||SB(i.backgroundColor,"config.backgroundColor",0,0xffffff),SH(i.userConfigExtraInfo)||SG(i.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1),i.transcodingUsers&&!SH(i.transcodingUsers)&&(SW(i.transcodingUsers,"config.transcodingUsers"),i.transcodingUsers.forEach((e,t)=>{vY(e.uid),SH(e.x)||SB(e.x,"transcodingUser[".concat(t,"].x"),0,1e4),SH(e.y)||SB(e.y,"transcodingUser[".concat(t,"].y"),0,1e4),SH(e.width)||SB(e.width,"transcodingUser[".concat(t,"].width"),0,1e4),SH(e.height)||SB(e.height,"transcodingUser[".concat(t,"].height"),0,1e4),SH(e.zOrder)||SB(e.zOrder-1,"transcodingUser[".concat(t,"].zOrder"),0,100),SH(e.alpha)||SB(e.alpha,"transcodingUser[".concat(t,"].alpha"),0,1,!1)})),SH(i.watermark)||vJ(i.watermark,"watermark"),SH(i.backgroundImage)||vJ(i.backgroundImage,"backgroundImage"),i.images&&!SH(i.images)&&(SW(i.images,"config.images"),i.images.forEach((e,t)=>{vJ(e,"images[".concat(t,"]"))}));let r=[];i.images&&r.push(...i.images.map(e=>NJ(NJ(NJ({},vX),e),{},{zOrder:255}))),i.backgroundImage&&(r.push(NJ(NJ(NJ({},vX),i.backgroundImage),{},{zOrder:0})),delete i.backgroundImage),i.watermark&&(r.push(NJ(NJ(NJ({},vX),i.watermark),{},{zOrder:255})),delete i.watermark),i.images=r,i.transcodingUsers&&(i.userConfigs=i.transcodingUsers.map(e=>NJ({},e)),i.userCount=i.transcodingUsers.length,delete i.transcodingUsers);let n=(i.userConfigs||[]).map(e=>"number"==typeof e.uid?dQ.resolve(e.uid):Ac(e.uid,this.spec,this.cancelToken.token,this.httpRetryConfig));if((await dQ.all(n)).forEach((e,t)=>{i.userConfigs&&i.userConfigs[t]&&(i.userConfigs[t].uid=e)}),this.transcodingConfig=i,this.connection)try{let e=await this.connection.request("request",{clientRequest:{command:"UpdateTranscoding",transcodingConfig:this.transcodingConfig}},!1,{command:"UpdateTranscoding",workerType:1,requestByUser:!0,tid:Array.from(d1(t=this.streamingTasks).call(t)).map(e=>e.taskId).join("#")});TY.debug("[".concat(this.spec.clientId,"] update live transcoding config success, code: ").concat(e.code,", config:"),JSON.stringify(this.transcodingConfig))}catch(e){if(!e.data||!e.data.retry)throw e;e.data.changeAddress&&this.connection.tryNextAddress(),this.streamingTasks.forEach(t=>{TY.warning("[".concat(this.spec.clientId,"] live streaming receive error"),e.toString(),"try to republish",t.url),this.startLiveStreamingTask(t.url,t.mode,e).then(()=>{TY.debug("[".concat(this.spec.clientId,"] live streaming republish ").concat(t.url," success"))}).catch(e=>{TY.error("[".concat(this.spec.clientId,"] live streaming republish failed"),t.url,e.toString()),this.onLiveStreamError&&this.onLiveStreamError(t.url,e)})})}}async startLiveStreamingTask(e,t,i){if(!this.transcodingConfig&&t===vz.TRANSCODE)throw new T0(SU.INVALID_OPERATION,"[LiveStreaming] no transcoding config found, can not start transcoding streaming task");let r={command:"PublishStream",ts:Date.now(),url:e,uid:this.spec.uid.toString(),autoDestroyTime:100,acceptImageTimeout:!0};TY.debug("[".concat(this.spec.clientId,"] start live streaming ").concat(e,", mode: ").concat(t));let n=await this.taskMutex.lock();if(!this.connection&&i)return void n();if(this.streamingTasks.get(e)&&!i)return n(),new T0(SU.LIVE_STREAMING_TASK_CONFLICT).throw();try{this.connection||(this.connection=await this.connect(t))}catch(e){throw n(),e}switch(t){case vz.TRANSCODE:r.transcodingConfig=NJ({},this.transcodingConfig);case vz.RAW:}this.uapResponse&&this.uapResponse.vid&&(r.vid=this.uapResponse.vid),this.isStartingStreamingTask=!0;let o=this.lastTaskId++;try{let a=new dQ((t,r)=>{gO(this.retryTimeout).then(()=>{if(i)return r(i);let t=this.statusError.get(e);return t?(this.statusError.delete(e),r(t)):void 0})}),s=await dQ.race([this.connection.request("request",{clientRequest:r},!0,{url:e,command:"PublishStream",workerType:t===vz.TRANSCODE?1:2,requestByUser:!i,tid:o.toString()}),a]);this.isStartingStreamingTask=!1,TY.debug("[".concat(this.spec.clientId,"] live streaming started, code: ").concat(s.code)),this.streamingTasks.set(e,{clientRequest:r,mode:t,url:e,taskId:o}),n()}catch(r){if(n(),this.isStartingStreamingTask=!1,!r.data||!r.data.retry||i)throw r;return r.data.changeAddress&&this.connection.tryNextAddress(),await this.startLiveStreamingTask(e,t,r)}}stopLiveStreamingTask(e){return new dQ((t,i)=>{let r=this.streamingTasks.get(e);if(!r||!this.connection)return new T0(SU.UNEXPECTED_ERROR,"can not find streaming task to stop").throw();let n=r.mode;r.abortTask=()=>{TY.debug("[".concat(this.spec.clientId,"] stop live streaming success(worker exception)")),this.streamingTasks.delete(e),t()},this.connection.request("request",{clientRequest:{command:"UnpublishStream",url:r.url}},!1,{url:e,command:"UnPublishStream",workerType:n===vz.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then(i=>{TY.debug("[".concat(this.spec.clientId,"] stop live streaming success, code: ").concat(i.code)),this.streamingTasks.delete(e),0===this.streamingTasks.size&&(this.connection&&this.connection.close(),this.connection=void 0),t()}).catch(i)})}resetAllTask(){var e;let t=Array.from(d1(e=this.streamingTasks).call(e));for(let e of(this.terminate(),t))this.startLiveStreamingTask(e.url,e.mode).catch(t=>{this.onLiveStreamError&&this.onLiveStreamError(e.url,t)})}terminate(){this.cancelToken&&this.cancelToken.cancel(),this.streamingTasks=new Map,this.isStartingStreamingTask=!1,this.statusError=ne
1w Map,this.cancelToken=f0.CancelToken.source(),this.uapResponse=void 0,this.connection&&this.connection.close(),this.connection=void 0}async connect(e){if(this.connection)throw new T0(SU.UNEXPECTED_ERROR,"live streaming connection has already connected");let t=await gs(this,v$.REQUEST_WORKER_MANAGER_LIST,e);return this.uapResponse=t,this.connection=new Nq(t.workerToken,this.spec,this.wsRetryConfig,e),this.connection.on(vZ.WARNING,(e,t)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e)),this.connection.on(vZ.PUBLISH_STREAM_STATUS,e=>this.handlePublishStreamServer(e)),this.connection.on(vZ.REQUEST_NEW_ADDRESS,(t,i)=>{if(!this.connection)return i(new T0(SU.UNEXPECTED_ERROR,"can not get new live streaming address list"));gs(this,v$.REQUEST_WORKER_MANAGER_LIST,e).then(e=>{this.uapResponse=e,t(e.addressList)}).catch(i)}),await this.connection.init(t.addressList),this.connection}handlePublishStreamServer(e){let t=e.serverStatus&&e.serverStatus.url||"empty_url",i=this.streamingTasks.get(t),r=e.reason;switch(e.code){case v0.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case v0.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case v0.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case v0.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:{let r=new T0(SU.LIVE_STREAMING_CDN_ERROR,"",{code:e.code});if(i)return TY.error(r.toString()),this.onLiveStreamError&&this.onLiveStreamError(t,r);if(!this.isStartingStreamingTask)return;this.statusError.set(t,r)}case v0.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{let e=new T0(SU.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,r);return this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e)}case v0.LIVE_STREAM_RESPONSE_WORKER_LOST:case v0.LIVE_STREAM_RESPONSE_WORKER_QUIT:var n;if(!this.connection)return;for(let t of(this.connection.tryNextAddress(),Array.from(d1(n=this.streamingTasks).call(n))))t.abortTask?t.abortTask():(TY.warning("[".concat(this.spec.clientId,"] publish stream status code"),e.code,"try to republish",t.url),this.startLiveStreamingTask(t.url,t.mode,new T0(SU.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code})).then(()=>{TY.debug("[".concat(this.spec.clientId,"] republish live stream success"),t.url)}).catch(e=>{TY.error(e.toString()),this.onLiveStreamError&&this.onLiveStreamError(t.url,e)}));return}}hasUrl(e){return this.streamingTasks.has(e)}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:gH,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:gH;super(),mb(this,"onLiveStreamWarning",void 0),mb(this,"onLiveStreamError",void 0),mb(this,"spec",void 0),mb(this,"retryTimeout",1e4),mb(this,"connection",void 0),mb(this,"httpRetryConfig",void 0),mb(this,"wsRetryConfig",void 0),mb(this,"streamingTasks",new Map),mb(this,"isStartingStreamingTask",!1),mb(this,"taskMutex",new gG("live-streaming")),mb(this,"cancelToken",f0.CancelToken.source()),mb(this,"transcodingConfig",void 0),mb(this,"uapResponse",void 0),mb(this,"lastTaskId",1),mb(this,"statusError",new Map),this.spec=e,this.httpRetryConfig=i,this.wsRetryConfig=t}}function NZ(e,t){switch(t){case 0:for(;128&De(e););break;case 2:N5(e,Dn(e));break;case 5:N5(e,4);break;case 1:N5(e,8);break;default:throw Error("Unimplemented type: "+t)}}new Uint8Array(new Float32Array(1).buffer);let N$=new Float64Array(1),N0=new Uint8Array(N$.buffer);function N1(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let N2=[];function N3(){let e=N2.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function N5(e,t){if(e.offset+t>e.limit)throw Error("Skip past limit");e.offset+=t}function N4(e){return e.offset>=e.limit}function N6(e,t){let i=e.bytes,r=e.offset,n=e.limit,o=r+t;if(o>i.length){let t=new Uint8Array(2*o);t.set(i),e.bytes=t}return e.offset=o,o>n&&(e.limit=o),r}function N8(e,t){let i=e.offset;if(i+t>e.limit)throw Error("Read past limit");return e.offset+=t,i}function N9(e,t){let i=N8(e,t),r=String.fromCharCode,n=e.bytes,o="";for(let e=0;e<t;e++){let a,s,c,d,l=n[e+i];0==(128&l)?o+=r(l):192==(224&l)?e+1>=t||128!=(192&(a=n[e+i+1]))||(d=(31&l)<<6|63&a)<128?o+="�":(o+=r(d),e++):224==(240&l)?e+2>=t||32896!=(49344&((a=n[e+i+1])|(s=n[e+i+2])<<8))||(d=(15&l)<<12|(63&a)<<6|63&s)<2048||d>=55296&&d<=57343?o+="�":(o+=r(d),e+=2):240==(248&l)?e+3>=t?o+="�":(a=n[e+i+1],8421504!=(0xc0c0c0&(a|(s=n[e+i+2])<<8|(c=n[e+i+3])<<16))||
1(d=(7&l)<<18|(63&a)<<12|(63&s)<<6|63&c)<65536||d>1114111?o+="�":(d-=65536,o+=r(55296+(d>>10),56320+(1023&d)),e+=3)):o+="�"}return o}function N7(e,t){let i=t.length,r=0;for(let e=0;e<i;e++){let n=t.charCodeAt(e);n>=55296&&n<=56319&&e+1<i&&(n=(n<<10)+t.charCodeAt(++e)-0x35fdc00),r+=n<128?1:n<2048?2:n<65536?3:4}Do(e,r);let n=N6(e,r),o=e.bytes;for(let e=0;e<i;e++){let r=t.charCodeAt(e);r>=55296&&r<=56319&&e+1<i&&(r=(r<<10)+t.charCodeAt(++e)-0x35fdc00),r<128?o[n++]=r:(r<2048?o[n++]=r>>6&31|192:(r<65536?o[n++]=r>>12&15|224:(o[n++]=r>>18&7|240,o[n++]=r>>12&63|128),o[n++]=r>>6&63|128),o[n++]=63&r|128)}}function De(e){return e.bytes[N8(e,1)]}function Dt(e,t){let i=N6(e,1);e.bytes[i]=t}function Di(e){let t=N8(e,8),i=e.bytes;return N0[0]=i[t++],N0[1]=i[t++],N0[2]=i[t++],N0[3]=i[t++],N0[4]=i[t++],N0[5]=i[t++],N0[6]=i[t++],N0[7]=i[t++],N$[0]}function Dr(e,t){let i=N6(e,8),r=e.bytes;N$[0]=t,r[i++]=N0[0],r[i++]=N0[1],r[i++]=N0[2],r[i++]=N0[3],r[i++]=N0[4],r[i++]=N0[5],r[i++]=N0[6],r[i++]=N0[7]}function Dn(e){let t,i=0,r=0;do t=De(e),i<32&&(r|=(127&t)<<i),i+=7;while(128&t);return r}function Do(e,t){for(t>>>=0;t>=128;)Dt(e,127&t|128),t>>>=7;Dt(e,t)}function Da(e,t){let i=t.low>>>0,r=(t.low>>>28|t.high<<4)>>>0,n=t.high>>>24,o=0===n?0===r?i<16384?i<128?1:2:i<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10,a=N6(e,o),s=e.bytes;switch(o){case 10:s[a+9]=n>>>7&1;case 9:s[a+8]=9!==o?128|n:127&n;case 8:s[a+7]=8!==o?r>>>21|128:r>>>21&127;case 7:s[a+6]=7!==o?r>>>14|128:r>>>14&127;case 6:s[a+5]=6!==o?r>>>7|128:r>>>7&127;
1case 5:s[a+4]=5!==o?128|r:127&r;case 4:s[a+3]=4!==o?i>>>21|128:i>>>21&127;case 3:s[a+2]=3!==o?i>>>14|128:i>>>14&127;case 2:s[a+1]=2!==o?i>>>7|128:i>>>7&127;case 1:s[a]=1!==o?128|i:127&i}}function Ds(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}let Dc=new Map([["moderation",1],["supervise",2]]);class Dd extends S0{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;let t=this._connectionState;this._connectionState=e,this.emit(yf.CONNECTION_STATE_CHANGE,t,e)}get inspectType(){return this._inspectType}set inspectType(e){var t;this._inspectMode=as(t=e.map(e=>Dc.get(e)||0)).call(t,(e,t)=>e+t),this._inspectType=e}get quality(){return this._quality}set quality(e){this._quality=e>1?1:e<.1?.1:e,this.qualityTimer&&(window.clearTimeout(this.qualityTimer),this.qualityTimer=null),this._quality>=1||(this.qualityTimer=window.setTimeout(()=>
1{this.quality=this._quality/this.qualityRatio},6e4))}async init(e,t){this.emit(yf.STATE_CHANGE,ym.CONNECT_AP),this._connectInfo=e;let i=this._cancelTokenSource.token;return this._retryConfig=t,new dQ((r,n)=>{this.on(yf.CONNECTION_STATE_CHANGE,(e,t)=>{t===yE.CONNECTED&&r()}),this.requestAP(e,i,t).then(e=>{this.connectWorkerManager(e)}).catch(e=>{n(e)})})}async requestAP(e,t,i){let r=TR("WEBCS_DOMAIN").map(e=>"https://".concat(e,"/api/v1")),n=await function(e,t,i,r){let{appId:n,areaCode:o,cname:a,sid:s,token:c,uid:d}=t,l="image_moderation_api",h={service_name:l,json_body:JSON.stringify({appId:n,areaCode:o,cname:a,command:"allocateEdge",requestId:++At,seq:At,sid:s,token:c,ts:Date.now(),uid:d+""})},u,p,_=e[0];return gY(async()=>{u=Date.now();let e=await Iz(_,{data:h,cancelToken:i,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(p=Date.now()-u,0!==e.code){let t=new T0(SU.UNEXPECTED_RESPONSE,"image inspect ap error, code"+e.code,{retry:!0,responseTime:p});throw TY.error(t.toString()),t}let t=JSON.parse(e.json_body);if(200!==t.code){let e=new T0(SU.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw TY.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){let e=new T0(SU.UNEXPECTED_RESPONSE,"image inspect ap empty server",{code:t.code,responseTime:p});throw TY.error(e.toString()),e}let r=TR("VIDEO_INSPECT_WORKER_MANAGER_WSS");if(r)return{addressList:[r],workerToken:t.workerToken,vid:t.vid,responseTime:p};let n=TR("VIDEO_INSPECT_WORKER_MANAGER_HOST"),o=TR("VIDEO_INSPECT_WORKER_MANAGER_PORT");return{addressList:t.servers.map(e=>{let{address:t,wss:i}=e;if(t&&i)return"wss://".concat(t.replace(/\./g,"-"),".").concat(n,":").concat(o||i)}).filter(e=>!!e),workerToken:t.workerToken,vid:t.vid,responseTime:p}},(t,i)=>(T$.apworkerEvent(s,{success:!0,sc:200,serviceName:l,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===i,responseTime:p,serverIp:e[i%e.length]}),!1),(t,i)=>(T$.apworkerEvent(s,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[i%e.length]}),!!(t.code!==SU.OPERATION_ABORTED&&t.code!==SU.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(i+1)%e.length],!0)),r)}(r,e,t,i);this.emit(yf.STATE_CHANGE,ym.AP_CONNECTED);let{addressList:o}=n;return this.wmSequence++,o}async connectWorkerManager(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._needWorkUrlOnly=t,this.emit(yf.STATE_CHANGE,ym.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(e,1e4)}async connectWorker(e){await this.workerConnection.init([e])}handleWorkerManagerEvents(){this.workerManagerConnection.on(vH.CONNECTED,async()=>{this.emit(yf.STATE_CHANGE,ym.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.24.2",sid:this._connectInfo.sid,seq:this.wmSequence,ts:Number(Date.now()),requestId:Math.floor(1e12*Math.random()),allocate:!0,clientRequest:{command:"join"}},!0)}),this.workerManagerConnection.on(vH.CLOSED,()=>{this._innerConnectionState<ym.GET_WORKER_MANAGER_RESPONSE&&TY.debug("[".concat(this._inspectId,"] Inspect worker manager is closed before connecting worker"))}),this.workerManagerConnection.on(vH.FAILED,()=>{this._innerConnectionState<ym.GET_WORKER_MANAGER_RESPONSE&&TY.debug("[".concat(this._inspectId,"] Connecting inspect worker manager is failed before connecting worker"))}),this.workerManagerConnection.on(vH.RECONNECTING,()=>{this._innerConnectionState<ym.GET_WORKER_MANAGER_RESPONSE&&TY.debug("[".concat(this._inspectId,"] Inspect worker manager is reconnecting before connecting worker"))}),this.workerManagerConnection.on(vH.ON_MESSAGE,async e=>{this.emit(yf.STATE_CHANGE,ym.GET_WORKER_MANAGER_RESPONSE);let t=this.workerManagerConnection.url;this.workerManagerConnection.close();let i=JSON.parse(e.data);if(200!==i.code)throw TY.error("[".concat(this._inspectId,"] Unexpected code ").concat(i.code," from worker manager")),new T0(SU.UNEXPECTED_RESPONSE,"response code of worker is unexpected",i);if(!(i.serverResponse&&i.serverResponse.portWss&&t))throw TY.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(i))),new T0(SU.UNEXPECTED_RESPONSE,"response content of worker is unexpected",i);{let e=TR("VIDEO_INSPECT_WORKER_PORT")||i.serverResponse.portWss,r=t.replace(/:\d+\/?$/,":".concat(e));
1this.emit(yf.STATE_CHANGE,ym.CONNECT_WORKER,r),this._needWorkUrlOnly?this.emit(yf.REQUEST_NEW_WORKER_URL,r):await this.connectWorker(r)}}),this.workerManagerConnection.on(vH.WILL_RECONNECT,(e,t,i)=>{i(e)}),this.workerManagerConnection.on(vH.REQUEST_NEW_URLS,(e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)})}handleWorkerEvents(){this.workerConnection.on(vH.CONNECTED,async()=>{this.emit(yf.STATE_CHANGE,ym.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=yE.CONNECTED}),this.workerConnection.on(vH.ON_MESSAGE,async e=>{if(e.data instanceof ArrayBuffer){var t,i;let r=function(e){let t={};e:for(;!N4(e);){let i=Dn(e);switch(i>>>3){case 0:break e;case 1:t.code=Dn(e);break;case 2:t.msg=N9(e,Dn(e));break;case 3:{let i=function(e){let t=Dn(e),i=e.limit;return e.limit=e.offset+t,i}(e);t.data=function(e){let t={};e:for(;!N4(e);){let i=Dn(e);switch(i>>>3){case 0:break e;case 1:t.requestId=N9(e,Dn(e));break;case 2:t.requestType=Dn(e)>>>0;break;case 3:t.scorePorn=Di(e);break;case 4:t.scoreSexy=Di(e);break;case 5:t.scoreNeutral=Di(e);break;case 6:t.requestScene=Dn(e)>>>0;break;case 7:t.scene=Dn(e)>>>0;break;default:NZ(e,7&i)}}return t}(e),e.limit=i;break}default:NZ(e,7&i)}}return t}({bytes:t=new Uint8Array(e.data),offset:0,limit:t.length});if(TR("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")&&TY.debug("[".concat(this._inspectId,"] Response message for worker of inspect content "),JSON.stringify(r)),200===r.code){if(Array.isArray(this.inspectType)&&1===this.inspectType.length&&"supervise"===this.inspectType[0])return void this.emit(yf.INSPECT_RESULT,void 0,void 0);if(r.data&&r.data.scorePorn&&r.data.scoreSexy&&r.data.scoreNeutral){let e={porn:r.data.scorePorn,sexy:r.data.scoreSexy,neutral:r.data.scoreNeutral},t=as(i=Object.keys(e)).call(i,(t,i)=>e[t]>e[i]?t:i,"porn"),n=Object.keys(e).find(e=>e===t);this.emit(yf.INSPECT_RESULT,n)}else this.emit(yf.INSPECT_RESULT,void 0,new T0(SU.UNEXPECTED_RESPONSE,r.code+"","There is an unexpected data on message"))}else this.emit(yf.INSPECT_RESULT,void 0,new T0(SU.UNEXPECTED_RESPONSE,r.code+"",r.msg))}else TY.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit(yf.INSPECT_RESULT,void 0,new T0(SU.UNEXPECTED_RESPONSE,"invalid worker message type"))}),this.workerConnection.on(vH.CLOSED,()=>{this.connectionState=yE.CLOSED}),this.workerConnection.on(vH.FAILED,()=>{this.connectionState=yE.CLOSED}),this.workerConnection.on(vH.RECONNECTING,()=>{this.connectionState=this.connectionState===yE.CONNECTED?yE.RECONNECTING:yE.CONNECTING}),this.workerConnection.on(vH.WILL_RECONNECT,(e,t,i)=>{"recover"===e&&i(e),i("tryNext")}),this.workerConnection.on(vH.REQUEST_NEW_URLS,(e,t)=>{this.workerManagerConnection.close(),this.once(yf.REQUEST_NEW_WORKER_URL,t=>{e([t])}),this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e=>{this.connectWorkerManager(e,!0)}).catch(e=>{t(e)})})}async requestToInspectImage(){this.sequence++;let e=gd(this,yf.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void this.emit(yf.INSPECT_RESULT,void 0,new T0(SU.INVALID_OPERATION,"Only the track being played can be inspected"));let i=await this.generateRequestData(e,t);this.workerConnection.sendMessage(i,!0,!0)}else this.emit(yf.INSPECT_RESULT,void 0,new T0(SU.INVALID_OPERATION,"Only the track being published can be inspected"))}async generateRequestData(e,t){var i;let r,n,o,{appId:a,cname:s,cid:c,vid:d,sid:l,uid:h}=t,u=Date.now(),p=await e.getCurrentFrameImage("image/jpeg",this.quality),_=await Cg(p,a,s),E=this.sequence+"-"+c+"-"+h+"-"+u+"-"+gw(12,""),m={appId:a,cid:c,cname:s,deviceId:"",elapse:{low:i=0|Number(u-this.inspectStartTime),high:i>>31,unsigned:i>=0},fileSize:_.byteLength,jpgEncryption:2,height:p.height,width:p.width,jpg:_,networkType:6,osType:7,requestId:E,sdkVersion:"4.24.2",sequence:this.sequence,sid:l,timestamp:On(u),uid:h,vid:d,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};void 0===this.extraInfo&&delete m.callbackData,void 0===this.ossFilePrefix&&delete m.ossFilePrefix;let f=(function(e,t){let i,r=e.appId;void 0!==r&&(Do(t,10),N7(t,r));let n=e.cid;
1void 0!==n&&(Do(t,16),Do(t,n));let o=e.cname;void 0!==o&&(Do(t,26),N7(t,o));let a=e.deviceId;void 0!==a&&(Do(t,34),N7(t,a));let s=e.elapse;void 0!==s&&(Do(t,40),Da(t,s));let c=e.fileSize;void 0!==c&&(Do(t,48),Da(t,N1(c)));let d=e.height;void 0!==d&&(Do(t,56),Da(t,N1(d)));let l=e.jpg;void 0!==l&&(Do(t,66),Do(t,l.length),i=N6(t,l.length),t.bytes.set(l,i));let h=e.networkType;void 0!==h&&(Do(t,72),Da(t,N1(h)));let u=e.osType;void 0!==u&&(Do(t,80),Da(t,N1(u)));let p=e.requestId;void 0!==p&&(Do(t,90),N7(t,p));let _=e.sdkVersion;void 0!==_&&(Do(t,98),N7(t,_));let E=e.sequence;void 0!==E&&(Do(t,104),Da(t,N1(E)));let m=e.sid;void 0!==m&&(Do(t,114),N7(t,m));let f=e.timestamp;void 0!==f&&(Do(t,120),Da(t,f));let S=e.uid;void 0!==S&&(Do(t,128),Do(t,S));let g=e.vid;void 0!==g&&(Do(t,136),Do(t,g));let T=e.width;void 0!==T&&(Do(t,144),Da(t,N1(T)));let R=e.service;void 0!==R&&(Do(t,152),Do(t,R));let C=e.callbackData;void 0!==C&&(Do(t,162),N7(t,C));let v=e.jpgEncryption;void 0!==v&&(Do(t,168),Do(t,v));let y=e.requestType;void 0!==y&&(Do(t,176),Do(t,y));let I=e.scorePorn;void 0!==I&&(Do(t,185),Dr(t,I));let A=e.scoreSexy;void 0!==A&&(Do(t,193),Dr(t,A));let b=e.scoreNeutral;void 0!==b&&(Do(t,201),Dr(t,b));let O=e.scene;void 0!==O&&(Do(t,208),Do(t,O));let w=e.ossFilePrefix;void 0!==w&&(Do(t,218),N7(t,w));let N=e.serviceVendor;if(void 0!==N)for(let e of N){var D;Do(t,226);let i=N3();(function(e,t){let i=e.service;void 0!==i&&(Do(t,8),Do(t,i));let r=e.vendor;void 0!==r&&(Do(t,16),Do(t,r));let n=e.token;void 0!==n&&(Do(t,26),N7(t,n));let o=e.callbackUrl;void 0!==o&&(Do(t,34),N7(t,o))})(e,i),Do(t,i.limit),function(e,t){let i=N6(e,t.limit),r=e.bytes,n=t.bytes;for(let e=0,o=t.limit;e<o;e++)r[e+i]=n[e]}(t,i),D=i,N2.push(D)}}(m,r=N3()),n=r.bytes,o=r.limit,n.length===o?n:n.subarray(0,o));if(f.byteLength<this.workerMessageLengthLimit){if(TR("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")){let e=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Ds(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Ds(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}({},m);delete e.jpg,TY.debug("[".concat(this._inspectId,"] Request message for worker of inspect content "),JSON.stringify(e))}return f}
1{let t=this.quality*this.qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:a,cname:s,cid:c,vid:d,sid:l,uid:h})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=f0.CancelToken.source(),this.workerManagerConnection&&this.workerManagerConnection.close(),this.workerConnection&&this.workerConnection.close(),this.inspectTimer&&window.clearInterval(this.inspectTimer),this.inspectTimer=null,this.connectionState=yE.CLOSED,this.emit(yf.STATE_CHANGE,ym.CLOSED)}constructor(e){super(),mb(this,"name","AgoraRTCVideoContentInspect"),mb(this,"_connectionState",yE.CONNECTING),mb(this,"_innerConnectionState",void 0),mb(this,"sequence",0),mb(this,"inspectStartTime",void 0),mb(this,"workerManagerConnection",void 0),mb(this,"workerConnection",void 0),mb(this,"workerMessageLengthLimit",void 0),mb(this,"inspectIntervalMinimum",void 0),mb(this,"qualityRatio",void 0),mb(this,"_connectInfo",void 0),mb(this,"_cancelTokenSource",f0.CancelToken.source()),mb(this,"_retryConfig",void 0),mb(this,"wmSequence",0),mb(this,"inspectInterval",void 0),mb(this,"inspectTimer",null),mb(this,"ossFilePrefix",void 0),mb(this,"extraInfo",void 0),mb(this,"_inspectType",void 0),mb(this,"_inspectMode",void 0),mb(this,"_quality",1),mb(this,"qualityTimer",null),mb(this,"_inspectId",void 0),mb(this,"_needWorkUrlOnly",!1),mb(this,"inspectImage",()=>{if(this.connectionState!==yE.CONNECTED)throw new T0(SU.OPERATION_ABORTED,"content inspect service connection status is ".concat(this.connectionState));this.inspectTimer&&(window.clearInterval(this.inspectTimer),this.inspectTimer=null),this.inspectTimer=window.setInterval(()=>{this.connectionState===yE.CONNECTED?this.requestToInspectImage():TY.debug("[".concat(this._inspectId,"] Inspect State is not connected , "),this.connectionState)},this.inspectInterval<this.inspectIntervalMinimum?this.inspectIntervalMinimum:this.inspectInterval),this.requestToInspectImage()}),this._inspectId=gw(5,"inspect-"),this.workerMessageLengthLimit=TR("VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT"),this.inspectIntervalMinimum=TR("VIDEO_INSPECT_INTERVAL_MINIMUM"),this.qualityRatio=TR("VIDEO_INSPECT_QUALITY_RATIO"),this.inspectInterval=e.interval,this.ossFilePrefix=e.ossFilePrefix,this.extraInfo=e.extraInfo,this.inspectType=e.inspectType,this.inspectStartTime=Number(Date.now()),this.workerManagerConnection=new yH("worker-manager-"+this._inspectId,gH),this.on(yf.STATE_CHANGE,(e,t)=>{this._innerConnectionState=e,TY.debug("[".concat(this._inspectId,"] Inspect operation :").concat(ym[e]," ").concat(t||""))}),this.handleWorkerManagerEvents(),this.workerConnection=new yH("worker-"+this._inspectId,gH),this.handleWorkerEvents()}}var Dl=rW(nf.Object.getOwnPropertySymbols),Dh=ox.indexOf,Du=r6([].indexOf),Dp=!!Du&&1/Du([1],1,-0)<0;oI({target:"Array",proto:!0,forced:Dp||!o7("indexOf")},{indexOf:function(e){var t=arguments.length>1?arguments[1]:void 0;return Dp?Du(this,e,t)||0:Dh(this,e,t)}});var D_=oF("Array","indexOf"),DE=Array.prototype,Dm=rW(function(e){var t=e.indexOf;return e===DE||rJ(DE,e)&&t===DE.indexOf?D_:t});let Df=class{get localCapabilities(){return gS(this._localCapabilities)}get rtpCapabilities(){return gS(this._rtpCapabilities)}get candidates(){return gS(this._candidates)}get iceParameters(){return gS(this._iceParameters)}get dtlsParameters(){return gS(this._dtlsParameters)}toString(){return Tw(this.sessionDesc)}hasMid(e){return Array.isArray(e)?e.every(e=>this.hasMid(e)):this.sessionDesc.mediaDescriptions.some(t=>t.attributes.mid===e)}send(e,t,i,r,n){i=i.replace(/ /g,"-");let{ssrcs:o,ssrcGroups:a}=I_(t,this.cname,TR("SYNC_GROUP")?i:void 0),s=this.findPreloadMediaDesc(o);if(s){if(Sl()&&this.firefoxSsrcMidMap.set(o[0].ssrcId,s.attributes.mid),n&&(n.twcc||n.remb)){let e=this.sessionDesc.mediaDescriptions.indexOf(s);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(s,n),{mid:s.attributes.mid,needExchangeSDP:!0}}return{mid:s.attributes.mid,needExchangeSDP:!1}}{let t,i=this.findAvailableMediaIndex(e,o,r);return -1===i?(t=this.createOrRecycleSendMedia(e,o,a,"sendonly",r,n),this.updateBundleMids()):((t=gS(this.sessionDesc.mediaDescriptions[i])).attributes.direction="sendonly",t.attributes.ssrcs=o,t.attributes.ssrcGroups=a,this.sessionDesc.mediaDescriptions[i]=this.mungSendMediaDesc(t,n)),Sl()&&this.firefoxSsrcMidMap.set(o[0].ssrcId,t.attributes.mid),{needExchangeSDP:!0,mid:t.attributes.mid}}}stopSending(e){let t=this.sessionDesc.mediaDescriptions.filter(t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid));if(t.length!==e.length)throw Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");
1t.forEach(e=>{e.attributes.ssrcs=[]}),this.updateBundleMids()}receive(e,t,i){let r=[];return e.forEach(e=>{let n=e._mediaStreamTrack.kind,o=this.findAvailableRecvMediaIndex(n),a,s=!1;-1===o?(s=!0,a=this.createOrRecycleRecvMedia(e,[],"recvonly",t,i),this.updateBundleMids()):(a=gS(this.sessionDesc.mediaDescriptions[o])).attributes.direction="recvonly",r.push({mid:a.attributes.mid,needCreateTransceiver:s})}),r}stopReceiving(e){let t=this.sessionDesc.mediaDescriptions.filter(t=>-1!==e.indexOf(t.attributes.mid));if(t.length!==e.length)throw Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach(e=>{e.media.port="0",e.attributes.direction="inactive"}),this.updateBundleMids()}addRemoteCandidate(e){let{foundation:t,protocol:i,address:r,port:n,type:o,relatedAddress:a,relatedPort:s,priority:c}=new RTCIceCandidate(e),d={foundation:null!=t?t:"",componentId:"1",transport:null!=i?i:"",priority:c?c+"":"",connectionAddress:null!=r?r:"",port:n?n+"":"",type:o?o+"":"",relAddr:null!=a?a:"",relPort:s?s+"":"",extension:{}};this.candidates.some(e=>e.priority===d.priority&&e.connectionAddress===d.connectionAddress&&e.port===d.port)||(this._candidates.push(d),this.sessionDesc.mediaDescriptions.forEach(e=>{e.attributes.candidates=this.candidates}))}clearRemoteCandidate(){this._candidates=[],this.sessionDesc.mediaDescriptions[0].attributes.candidates=this._candidates}createOrRecycleRecvMedia(e,t,i,r,n){let o=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,s=Ib(o,a,this.localCapabilities.send,o===yc.AUDIO?n:r),c=o===yc.VIDEO?a.videoExtensions:a.audioExtensions,d="".concat(++this.currentMidIndex),l={media:{mediaType:o,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:s.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:[],extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:s,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(d)}};l=this.mungRecvMediaDsec(l,e);let h=this.findFirstClosedMedia(o);if(h){let e=this.sessionDesc.mediaDescriptions.indexOf(h);this.sessionDesc.mediaDescriptions[e]=l}else this.sessionDesc.mediaDescriptions.push(l);return l}muteRemote(e){let t=this.sessionDesc.mediaDescriptions.filter(t=>o5(e).call(e,t.attributes.mid||""));if(t.length!==e.length)throw Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(e=>{e.attributes.direction="inactive"})}unmuteRemote(e){let t=this.sessionDesc.mediaDescriptions.filter(t=>o5(e).call(e,t.attributes.mid||""));if(t.length!==e.length)throw Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(e=>{e.attributes.direction="recvonly"})}findAvailableMediaIndex(e,t,i){return this.sessionDesc.mediaDescriptions.findIndex(r=>{let n=r.media.mediaType===e&&"0"!==r.media.port&&("sendonly"===r.attributes.direction||"sendrecv"===r.attributes.direction)&&0===r.attributes.ssrcs.length;if(Sl()){if(n){let e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return!(e||"0"!==r.attributes.mid&&"1"!==r.attributes.mid)||!(!e||e!==r.attributes.mid)}return!1}return n&&r.attributes.mid===i})}findAvailableRecvMediaIndex(e){return this.sessionDesc.mediaDescriptions.findIndex(t=>{let i=t.media.mediaType===e&&"0"!==t.media.port&&("recvonly"===t.attributes.direction||"sendrecv"===t.attributes.direction);return"0"!==t.attributes.mid&&"1"!==t.attributes.mid&&i})}predictReceivingMids(e){let t=[];for(let i=0;i<e;i++)t.push((this.currentMidIndex+i+1).toString(10));return t}restartICE(e){e=gS(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach(t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd})}createOrRecycleSendMedia(e,t,i,r,n,o){let a=this.rtpCapabilities.send,s=e===yc.VIDEO?a.videoCodecs:a.audioCodecs,c=e===yc.VIDEO?a.videoExtensions:a.audioExtensions;Sl()&&(n="".concat(++this.currentMidIndex));let d={media:{mediaType:e,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:s.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:[],extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:i,rtcpFeedbackWildcards:[],payloads:s,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:r,rtcpMux:!0,rtcpRsize:!0,mid:n}};d=this.mungSendMediaDesc(d,o);let l=this.findFirstClosedMedia(e);if(l){let e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=d}else this.sessionDesc.mediaDescriptions.push(d);return d}mungRecvMediaDsec(e,t,i){let r=gS(e);return Im(r),IE(r,t),If(r,t),IS(r),Ig(r,i,this.localCapabilities.send),r}mungSendMediaDesc(e,t){let i=gS(e);return Ig(i,t,this.localCapabilities.recv),IA(i),i}updateRecvMedia(e,t){let i=this.sessionDesc.mediaDescriptions.findIndex(t=>t.attributes.mid===e);if(-1!==i){let e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter(e=>"0"!==e.media.port).map(e=>e.attributes.mid)}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find(t=>{var i;return(null==(i=t.attributes)||null==(i=i.ssrcs[0])?void 0:i.ssrcId)===e[0].ssrcId})}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find(t=>Sl()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port)}constructor(e){let t;mb(this,"sessionDesc",void 0),mb(this,"_localCapabilities",void 0),mb(this,"_rtpCapabilities",void 0),mb(this,"_candidates",void 0),mb(this,"_iceParameters",void 0),mb(this,"_dtlsParameters",void 0),mb(this,"setup",void 0),mb(this,"currentMidIndex",void 0),mb(this,"cname","o/i14u9pJrxRKAsu"),mb(this,"firefoxSsrcMidMap",new Map);let{remoteIceParameters:i,remoteDtlsParameters:r,candidates:n,remoteRTPCapabilities:o,localCapabilities:a,direction:s,setup:c,videoCodec:d,audioCodec:l}=e=gS(e);this.setup=c,t=s===vW.RECEIVE_ONLY?TO("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=extmap-allow-mixed\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n"):TO("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=extmap-allow-mixed\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=recvonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=recvonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n"),this._rtpCapabilities=o,this._candidates=n,this._iceParameters=i,this._dtlsParameters=r,this._localCapabilities=a;let h=s===vW.RECEIVE_ONLY?this.rtpCapabilities.send:this.rtpCapabilities.recv,u=s===vW.RECEIVE_ONLY?this._localCapabilities.recv:this._localCapabilities.send,p=s===vW.RECEIVE_ONLY?o.send.videoCodecs:Ib(yc.
1VIDEO,h,u,d),_=s===vW.RECEIVE_ONLY?o.send.audioCodecs:Ib(yc.AUDIO,h,u,l);for(let e of t.mediaDescriptions)e.attributes.iceUfrag=i.iceUfrag,e.attributes.icePwd=i.icePwd,e.attributes.fingerprints=r.fingerprints,e.attributes.candidates=n,e.attributes.setup=this.setup,"application"===e.media.mediaType&&(e.attributes.sctpPort="5000"),"video"===e.media.mediaType&&(e.media.fmts=p.map(e=>e.payloadType.toString(10)),e.attributes.payloads=p,e.attributes.extmaps=h.videoExtensions),"audio"===e.media.mediaType&&(e.media.fmts=_.map(e=>e.payloadType.toString(10)),e.attributes.payloads=_,e.attributes.extmaps=h.audioExtensions,IA(e));this.sessionDesc=t,this.currentMidIndex=t.mediaDescriptions.length-1}},DS=["sdp"];function Dg(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function DT(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Dg(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Dg(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let DR=(rA=class e extends ya{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get dtlsTransportState(){var e,t;return null!=(e=null==(t=this.peerConnection.getReceivers()[0])||null==(t=t.transport)?void 0:t.state)?e:null}get localCodecs(){return[]}set isInRestartIce(e){this._isInRestartIce=e}get isInRestartIce(){return this._isInRestartIce}async establish(e){try{let t=await IC();if(this.localCapabilities=II(t),e){let{sdp:t}=e,i=function(e,t){if(null==e)return{};var i,r,n=function(e,t){if(null==e)return{};var i={};for(var r in e)if(({}).hasOwnProperty.call(e,r)){if(-1!==Dm(t).call(t,r))continue;i[r]=e[r]}return i}(e,t);if(Dl){var o=Dl(e);for(r=0;r<o.length;r++)i=o[r],-1===Dm(t).call(t,i)&&({}).propertyIsEnumerable.call(e,i)&&(n[i]=e[i])}return n}(e,DS),r=function(){let e={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},t=Id(arguments.length>2?arguments[2]:void 0,arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},"sendonly"),i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(Iy(t,e,"videoExtensions",i,r,n),Iy(t,e,"videoCodecs",i,r,n),Iy(t,e,"audioExtensions",i,r,n),Iy(t,e,"audioCodecs",i,r,n),TR("RAISE_H264_BASELINE_PRIORITY")){let e=n.videoCodecs.findIndex(e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"===e.fmtp.parameters["profile-level-id"]);if(-1!==e){let t=n.videoCodecs.findIndex(e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase());if(t<e){TY.debug("raising H264 baseline profile priority");let i=n.videoCodecs[e];n.videoCodecs.splice(e,1),n.videoCodecs.splice(t,0,i)}-1!==t&&TR("FILTER_SEND_H264_BASELINE")&&(i.videoCodecs=i.videoCodecs.filter(e=>!(e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"!==e.fmtp.parameters["profile-level-id"])))}}return{send:i,recv:r,sendrecv:n}}({},{},t);this.remoteSDP=new Df({remoteIceParameters:i.iceParameters,remoteDtlsParameters:i.dtlsParameters,candidates:[],remoteRTPCapabilities:r,localCapabilities:this.localCapabilities,direction:this.direction,setup:"actpass",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),await this.setRemoteDescription({type:"offer",sdp:this.remoteSDP.toString()}),this.isReady=!0;let n=await this.peerConnection.createAnswer();if(!n.sdp)throw Error("Cannot get answer sdp when trying to establish PeerConnection.");let o=Il(n.sdp);await this.peerConnection.setLocalDescription(n);let a=await Iv({},{},n.sdp);this.localCapabilities=II(a);let s=this.peerConnection.getTransceivers()[0];return null!=s&&s.receiver&&s.receiver.transport&&this.tryBindTransportEvents(s.receiver.transport),DT(DT({},o),{},{sdp:n.sdp})}{this.peerConnection.addTransceiver("video",{direction:"sendonly"}),this.peerConnection.addTransceiver("audio",{direction:"sendonly"});let e=await this.peerConnection.createOffer();if(!e.sdp)throw Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");let t=Il(e.sdp);return this.initialOffer=e,DT(DT({},t),{},{sdp:e.sdp})}}catch(e){throw new Sx(SU.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e){try{if(!this.initialOffer)throw Error("Cannot establish P2PConnection without initial offer.");await this.peerConnection.setLocalDescription(this.initialOffer);let{sdp:t,iceParameters:i,dtlsParameters:r}=e,n=await Iv({},{},t);this.remoteSDP=new Df({remoteIceParameters:i,remoteDtlsParameters:r,candidates:[],remoteRTPCapabilities:n,localCapabilities:this.localCapabilities,direction:this.direction,setup:"active",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),await this.setRemoteDescription({type:"answer",sdp:this.remoteSDP.toString()});let o=this.peerConnection.getTransceivers()[0];null!=o&&o.sender&&o.sender.transport&&this.tryBindTransportEvents(o.sender.transport)}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}async addRemoteCandidate(e){try{e&&this.pendingCandidates.push(e),this.peerConnection.remoteDescription&&this.isReady&&(this.pendingCandidates.forEac
1h(e=>{this.peerConnection.addIceCandidate(e)}),this.pendingCandidates=[])}catch(e){throw new Sx(SU.ADD_CANDIDATE_FAILED,"P2PConnection.addRemoteCandidate failed; ".concat(e.toString()))}}send(e,t,i){var r=this;return fT(function*(){let n=yield fC(r.mutex.lock("From P2PConnection.send"));try{if(!r.remoteSDP)throw Error("Cannot call P2PConnection.send before remote SDP created");let n=[],o=r.remoteSDP.receive(e,t,i);e.forEach((e,t)=>{if(o[t].needCreateTransceiver){let t=r.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});n.push(t),e._updateRtpTransceiver(t)}else{let i=r.peerConnection.getTransceivers().find(e=>e.mid===o[t].mid);if(!i)throw Error("cannot find transceiver when sendPeerconnection send, mid is ".concat(o[t].mid));n.push(i),e._updateRtpTransceiver(i)}}),Sl()&&!0===TR("SIMULCAST")&&(yield fC(r.applySimulcastForFirefox(n,e)));let a=o.map(e=>e.mid),s=yield fC(r.peerConnection.createOffer()),c=r.mungSendOfferSDP(s.sdp,e,a),d=TO(c),l=a.map(e=>{let t=d.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw Error("Cannot extract ssrc from mediaDescription.");return Ih(t,TR("USE_PUB_RTX"))}),h=n.map((e,t)=>{let i=a[t];return{localSSRC:l[t],id:i}});yield fC(r.peerConnection.setLocalDescription({type:"offer",sdp:c}));try{yield h}catch(t){let e=r.remoteSDP.toString();throw yield fC(r.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield fC(r.peerConnection.setRemoteDescription({type:"answer",sdp:e})),yield fC(r.stopSending(a,!0)),t}yield fC(r.applySimulcastEncodings(n,e)),yield fC(r.applySendEncodings(n,e));let u=r.remoteSDP.toString(),p=r.logSDPExchange(c,"offer","local","send");return null==p||p(u),yield fC(r.setRemoteDescription({type:"answer",sdp:u})),n.map((e,t)=>{let i=a[t];return{localSSRC:l[t],id:i}})}catch(e){throw e instanceof Sx?e:new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{n()}})()}async stopSending(e,t){let i=t?void 0:await this.mutex.lock("From P2PConnection.stopSending");try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.stopSending before remote SDP created");let t=this.peerConnection.getTransceivers().filter(t=>-1!==e.indexOf(t.mid));if(t.length!==e.length)throw Error("Transceivers' length (".concat(t.length,") doesn't match mids' length (").concat(e.length,") when trying to call P2PConnection.stopSending."));t.map(e=>{var t;e.direction="inactive",null==(t=e.stop)||t.call(e)});let i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(i),this.remoteSDP.stopReceiving(e);let n=this.remoteSDP.toString();null==r||r(n),await this.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}finally{i&&i()}}async receive(e,t,i,r){try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));let{mid:n,needExchangeSDP:o}=this.remoteSDP.send(e,t,i,r);if(o){let t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","receive");await this.setRemoteDescription({type:"offer",sdp:t});let r=await this.peerConnection.createAnswer(),o=this.mungReceiveAnswerSDP(r.sdp,n,e);null==i||i(o||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:o}),TY.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."))}else TY.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."));let a=this.peerConnection.getTransceivers().find(e=>e.mid===n);if(!a||null===a.mid)throw Error("Cannot get transceiver after setLocalDescription.");return{track:a.receiver.track,mid:a.mid,transceiver:a}}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async mockReceive(e,t,i,r){try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));let{mid:n,needExchangeSDP:o}=this.remoteSDP.send(e,t,i,r);if(o){let t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","receive");await this.setRemoteDescription({type:"offer",sdp:t});let r=await this.peerConnection.createAnswer(),o=this.mungReceiveAnswerSDP(r.sdp,n,e);null==i||i(o||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:o}),TY.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").
1concat(e," by exchanging SDP."))}else TY.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."))}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);let t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.setRemoteDescription({type:"offer",sdp:t});let r=await this.peerConnection.createAnswer();null==i||i(r.sdp||""),await this.peerConnection.setLocalDescription(r)}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async restartICE(t){try{if(this.store.p2pTransport===Tp.Auto&&(this.store.p2pTransport=Tp.SdRtn,T1.supportPCSetConfiguration&&this.peerConnection.setConfiguration(e.resolvePCConfiguration(this.spec,this.store.p2pTransport))),this.restartCnt>3&&(this.restartCnt=0,T1.supportPCSetConfiguration&&this.peerConnection.setConfiguration(e.resolvePCConfiguration(this.spec,this.store.p2pTransport,++this.curTurnServerIndex))),!t){this.restartCnt++,this.isReady=!1;let e=await this.peerConnection.createOffer({iceRestart:!0});if(!e.sdp)throw Error("Cannot restartICE because restart offer SDP does not exist.");let{iceParameters:t}=Il(e.sdp);return this.store.descriptionStart(),this.direction===vW.SEND_ONLY&&await this.peerConnection.setLocalDescription(e),t}if(!this.remoteSDP)throw Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");if(this.remoteSDP.restartICE(t),this.store.descriptionStart(),this.direction===vW.RECEIVE_ONLY){this.restartCnt++,await this.setRemoteDescription({type:"offer",sdp:this.remoteSDP.toString()});let e=await this.peerConnection.createAnswer();if(!e.sdp)throw Error("Cannot get answer sdp when trying to iceRestart.");let{iceParameters:t}=Il(e.sdp);return await this.peerConnection.setLocalDescription(e),t}await this.setRemoteDescription({type:"answer",sdp:this.remoteSDP.toString()}),this.isReady=!0}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}close(){var e;this.peerConnection.close(),this.peerConnection.onicecandidate=null,null==(e=this.onConnectionStateChange)||e.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.transport=void 0,this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");let i=await this.peerConnection.createOffer(),r=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);let n=this.remoteSDP.toString(),o=this.logSDPExchange(r,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:r}),null==o||o(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){let i=this.peerConnection.getTransceivers().filter(t=>t.mid===e);1===i.length&&(this.isVP8Simulcast(t)?Sl()||await this.applySimulcastEncodings(i,[t]):await this.applySendEncodings(i,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){let i=this.peerConnection.getTransceivers().find(e=>e.mid===t);i&&await i.sender.replaceTrack(e._mediaStreamTrack)}async getSelectedCandidatePair(){let e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){let{local:t,remote:i}=e[0].transport.iceTransport.getSelectedCandidatePair();return{local:DT(DT({},g2),{},{candidateType:t.type,protocol:t.protocol,address:t.address,port:t.port}),remote:DT(DT({},g2),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e,t;o5(e=["connected","completed"]).call(e,this.peerConnection.iceConnectionState)&&(this.isReady=!1),null==(t=this.onICEConnectionStateChange)||t.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;"connected"===this.peerConnection.connectionState&&(this.restartCnt=0),null==(e=this.onConnectionStateChange)||e.call(this,this.peerConnection.connectionState)},this.startICECandidate()}startICECandidate(){this.peerConnection.onicecandidate||(this.localCandidateCount=0,this.peerConnection.onicecandidate=e=>{if(e.candidate){var t;e.candidate.candidate&&(null==(t=this.onLocalCandidate)||t.call(this,e.candidate.toJSON())),this.localCandidateCount+=1}else TY.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount)})}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t,i){var r;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o={iceServers:[]};return t.iceServers?o.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(S9(t.turnServer.servers)?o.iceServers=t.turnServer.servers:(o.iceServers&&o.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers,i,n)),TR("USE_TURN_SERVER_OF_GATEWAY")&&o.iceServers&&t.turnServer.serversFromGateway&&o.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway,i,n)),o5(r=[Tp.Relay,Tp.SdRtn]).call(r,i)&&(o.iceTransportPolicy="relay"),TR("FORCE_TURN_TCP")?o.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEac
1h(e=>{e.forceturn&&(o.iceTransportPolicy="relay")}))),TR("ENABLE_ENCODED_TRANSFORM")&&T1.supportWebRTCEncodedTransform&&(o.encodedInsertableStreams=!0),TY.debug("P2PConnection p2pTransport is ".concat(i)),o}static turnServerConfigToIceServers(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,r=[],n=e.filter(e=>e.tcpport);TY.debug("P2PConnection turnServers is ".concat(n,", current index is ").concat(i));let o=n.length>i?n[i]:n[0];switch(t){case Tp.SdRtn:let a=e.filter(e=>{var t;return o5(t=e.username).call(t,"glb:")&&e.turnServerURL==e.turnServerURL}),s=a.length>i?a[i]:a[0];s&&(r.push({username:s.username,credential:s.password,credentialType:"password",urls:"turn:".concat(yQ(s.turnServerURL),":").concat(s.tcpport,"?transport=udp")}),r.push({username:s.username,credential:s.password,credentialType:"password",urls:"turns:".concat(yQ(s.turnServerURL),":").concat(s.tcpport,"?transport=tcp")}));break;case Tp.Relay:o&&(r.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":").concat(o.tcpport,"?transport=udp")}),r.push({username:o.username,credential:o.password,credentialType:"password",urls:"turns:".concat(yQ(o.turnServerURL),":").concat(o.tcpport,"?transport=tcp")}));break;default:o&&(r.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":").concat(o.tcpport,"?transport=udp")}),r.push({username:o.username,credential:o.password,credentialType:"password",urls:"turns:".concat(yQ(o.turnServerURL),":").concat(o.tcpport,"?transport=tcp")}),r.push({username:o.username,credential:o.password,credentialType:"password",urls:"stun:".concat(o.turnServerURL,":").concat(o.tcpport)}))}return r}tryBindTransportEvents(e){if(e){this.transport=e,e.onstatechange=()=>{var t;null!=e&&e.state&&(null==(t=this.onDTLSTransportStateChange)||t.call(this,e.state))},e.onerror=e=>{var t;null==(t=this.onDTLSTransportError)||t.call(this,"error"in e?e.error:e)};let t=e.iceTransport;t&&(t.onstatechange=()=>{var t;let i=null==e?void 0:e.iceTransport.state;i&&(null==(t=this.onICETransportStateChange)||t.call(this,i))},t.getSelectedCandidatePair&&(t.onselectedcandidatepairchange=()=>{if(t.getSelectedCandidatePair()){let{local:e,remote:i}=t.getSelectedCandidatePair()||{};if(e&&i){let t=e.address+":"+e.port,r=i.address+":"+i.port;TY.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(y8(t)),", remote ").concat(JSON.stringify(y8(r))))}}}))}}tryUnbindTransportEvents(){this.transport&&(this.transport.onstatechange=null,this.transport.onerror=null,this.transport.iceTransport&&(this.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var i,r,n;if(t||(t=this.peerConnection.getSenders().find(t=>t.track===e._mediaStreamTrack)),!t)return TY.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return TY.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!T1.supportSetRtpSenderParameters)return TY.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");let o={},a={};switch(e._optimizationMode){case"motion":o.degradationPreference="maintain-framerate";break;case"detail":o.degradationPreference="maintain-resolution";break;default:o.degradationPreference="balanced"}if(e._encoderConfig){let{bitrateMax:t,frameRate:i,scaleResolutionDownBy:n}=e._encoderConfig;t&&(a.maxBitrate=1e3*t),o5(r=e._hints).call(r,RE.LOW_STREAM)&&(i&&(a.maxFramerate=y0(i)),n&&n>=1&&(a.scaleResolutionDownBy=n))}if(TR("DSCP_TYPE")&&SN()){let e=TR("DSCP_TYPE");o5(n=["very-low","low","medium","high"]).call(n,e)&&(a.networkPriority=e)}let s=t.getParameters(),c=null==(i=s.encodings)?void 0:i[0];Sl()&&!c&&(o.encodings=[a]),c&&Object.assign(c,a),Object.assign(s,o),TY.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(s.encodings))),await t.setParameters(s)}async applySendEncodings(e,t){try{if(!T1.supportSetRtpSenderParameters||e.length!==t.length)return;for(let i=0;i<e.length;i++){let r=e[i],n=t[i];n instanceof CP&&!this.isVP8Simulcast(n)&&await this.updateRtpSenderEncodings(n,r.sender)}}catch(e){TY.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,i){let r=TO(e);return t.forEach((e,t)=>{let n=i[t],o=r.mediaDescriptions.find(e=>e.attributes.mid===n);o&&(IE(o,e),IT(o,e,this.store.codec))}),Tw(r)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null==(t=this.onFirstAudioReceived)||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null==(t=this.onFirstVideoReceived)||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null==(t=this.onFirstAudioDecoded)||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var r;null==(r=this.onFirstVideoDecoded)||r.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null==(i=this.onSelectedLocalCandidateChanged)||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null==(i=this.onSelectedRemoteCandidateChanged)||i.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null==(t=this.onFirstVideoDecodedTimeout)||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let s=0;s<e.length;s++){var i,r,n,o,a;let c=e[s],d=t[s];if(d instanceof CP&&!o5(i=d._hints).call(i,RE.LOW_STREAM)&&null!=(r=d._encoderConfig)&&r.bitrateMax&&(null==(n=d._encoderConfig)?void 0:n.bitrateMax)>
1200&&null!=(o=d._scalabilityMode)&&o.numSpatialLayers&&(null==(a=d._scalabilityMode)?void 0:a.numSpatialLayers)>1&&"vp8"===this.store.codec){let e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];let i=c.sender.getParameters();await c.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!Sl()&&e.length===t.length)for(let i=0;i<e.length;i++){let r=t[i];if(r instanceof CP&&this.isVP8Simulcast(r)){let t=e[i],n={},o={high:1e3*(r._encoderConfig.bitrateMax-50),medium:5e4};n.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:o.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:o.medium,scaleResolutionDownBy:4}];let a=t.sender.getParameters();await t.sender.setParameters(Object.assign(a,n))}}}isVP8Simulcast(e){var t,i,r,n,o;return!!(e instanceof CP&&TR("SIMULCAST")&&"vp8"===this.store.codec&&!o5(t=e._hints).call(t,RE.LOW_STREAM)&&null!=(i=e._encoderConfig)&&i.bitrateMax&&(null==(r=e._encoderConfig)?void 0:r.bitrateMax)>200&&null!=(n=e._scalabilityMode)&&n.numSpatialLayers&&(null==(o=e._scalabilityMode)?void 0:o.numSpatialLayers)>1)}logSDPExchange(e,t,i,r){if(TR("SDP_LOGGING"))return TY.upload("[".concat(this.store.clientId,"] exchanging ").concat(i," ").concat(t," SDP during P2PConnection.").concat(r,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",r)}:void 0}async muteLocal(e){try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.muteLocal before remote SDP created.");let t=this.peerConnection.getTransceivers().filter(t=>t.mid&&-1!==e.indexOf(t.mid));if(t.length!==e.length)throw Error("Transceivers' length doesn't match mids' length.");t.map(e=>{e.direction="inactive"});let i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);let n=this.remoteSDP.toString();null==r||r(n),await this.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");let t=this.peerConnection.getTransceivers().filter(t=>t.mid&&-1!==e.indexOf(t.mid));if(t.length!==e.length)throw Error("Transceivers' length doesn't match mids' length.");t.map(async e=>{e.direction="sendonly"});let i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e);let n=this.remoteSDP.toString();null==r||r(n),await this.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}async getRemoteSSRC(e,t){var i,r;if(t=null!=t?t:null==(i=this.currentRemoteDescription)?void 0:i.sdp){let i=null==(r=TO(t).mediaDescriptions.find(t=>t.attributes.mid===e))?void 0:r.attributes.ssrcs;return null==i?void 0:i[0].ssrcId}}async setRemoteDescription(e){var t;await this.peerConnection.setRemoteDescription(e),o5(t=["connected","completed"]).call(t,this.peerConnection.iceConnectionState)||(this.isReady=!0,this.addRemoteCandidate())}mungReceiveAnswerSDP(e,t,i){let r=TO(e),n=r.mediaDescriptions.find(e=>e.attributes.mid===t);return n&&i===yc.AUDIO&&"audio"===n.media.mediaType&&IA(n),Tw(r)}constructor(t,i,r){super(t,i),mb(this,"direction",void 0),mb(this,"name",void 0),mb(this,"store",void 0),mb(this,"spec",void 0),mb(this,"peerConnection",void 0),mb(this,"initialOffer",void 0),mb(this,"transport",void 0),mb(this,"statsFilter",void 0),mb(this,"localCandidateCount",0),mb(this,"_isInRestartIce",!1),mb(this,"mutex",void 0),mb(this,"onLocalCandidate",void 0),mb(this,"remoteSDP",void 0),mb(this,"pendingCandidates",[]),mb(this,"localCapabilities",void 0),mb(this,"isReady",!1),mb(this,"restartCnt",0),mb(this,"curTurnServerIndex",0),this.store=i,this.spec=t,this.mutex=new gG("P2PConnection-mutex",i.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t,i.p2pTransport),{optional:[{googDscp:!0}]}),this.direction=null!=r?r:vW.SEND_ONLY,this.name=this.direction===vW.SEND_ONLY?"sendP2PConnection":"recvP2PConnection",this.statsFilter=Tc(this.peerConnection,TR("STATS_UPDATE_INTERVAL"),void 0,Sl()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1}},vP(rA.prototype,"establish",[DC],Object.getOwnPropertyDescriptor(rA.prototype,"establish"),rA.prototype),vP(rA.prototype,"connect",[DC],Object.getOwnPropertyDescriptor(rA.prototype,"connect"),rA.prototype),vP(rA.prototype,"receive",[DC],Object.getOwnPropertyDescriptor(rA.prototype,"receive"),rA.prototype),vP(rA.prototype,"mockReceive",[DC],Object.getOwnPropertyDescriptor(rA.prototype,"mockReceive"),rA.prototype),vP(rA.prototype,"stopReceiving",[DC],Object.getOwnPropertyDescriptor(rA.prototype,"stopReceiving"),rA.prototype),vP(rA.prototype,"restartICE",[DC],Object.getOwnPropertyDescriptor(rA.prototype,"restartICE"),rA.prototype),vP(rA.prototype,"close",[DC],Object.getOwnPropertyDescriptor(rA.prototype,"close"),rA.prototype),vP(rA.prototype,"updateEncoderConfig",[DC],Object.getOwnPropertyDescriptor(rA.prototype,"updateEncoderConfig"),rA.prototype),vP(rA.prototype,"updateSendParameters",[DC],Object.getOwnPropertyDescriptor(rA.prototype,"updateSendParameters"),rA.prototype),vP(rA.prototype,"replaceTrack",[DC],Object.getOwnPropertyDescriptor(rA.prototype,"replaceTrack"),rA.prototype),vP(rA.prototype,"muteLocal",[DC],Object.getOwnPropertyDescriptor(rA.prototype,"muteLocal"),rA.prototype),vP(rA.prototype,"unmuteLocal",[DC],Object.getOwnPropertyDescriptor(rA.prototype,"unmuteLocal"),rA.prototype),rA);function DC(e,t,i){let r=e[t];if("function"!=typeof r)throw Error("Cannot use mutex on object property.");return i.value=async function(){let e=this.mutex,i=await e.lock("From P2PConnection.".concat(t));try{for(var n=arguments.length,o=Array(n),a=0;a<n;a++)o[a]=arguments[a];return await r.apply(this,o)}finally{i()}},i}let Dv=((to={}).SEND_ONLY="SEND_ONLY",to.RECEIVE_ONLY="RECEIVE_ONLY",to);function Dy(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function DI(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
1t%2?Dy(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Dy(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let DA=(rb=Db(Dv.SEND_ONLY),rO=Db(Dv.SEND_ONLY),rw=Db(),rN=Db(Dv.RECEIVE_ONLY),rD=Db(Dv.RECEIVE_ONLY),rP=Db(Dv.RECEIVE_ONLY),rL=Db(Dv.RECEIVE_ONLY),rk=Db(Dv.RECEIVE_ONLY),rM=Db(Dv.RECEIVE_ONLY),rU=Db(),rx=Db(Dv.RECEIVE_ONLY),vP((rV=class extends S0{get state(){return this._state}set state(e){let t=this._state;this._state=e,this.emit(y_.StateChange,t,this._state)}async startP2PConnection(e,t){throw new Sx(SU.NOT_SUPPORTED,"p2p mode does not support startP2PConnection.")}async connect(e){throw new Sx(SU.NOT_SUPPORTED,"p2p mode does not support connect.")}async startP2P(e,t){let i;try{if(t){this.recvConnection&&(TY.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset recvConnection.")),this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection)),i=await this.recvMutex.lock("From P2PChannel.startP2P"),this.recvConnection=new DR(e,this.store,vW.RECEIVE_ONLY),this.bindConnectionEvents(this.recvConnection);let r=await this.recvConnection.establish(t);return{iceParameters:r.iceParameters,dtlsParameters:r.dtlsParameters,sdp:r.sdp}}{this.state=yp.New,this.sendConnection&&(TY.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset sendConnection.")),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection)),i=await this.sendMutex.lock("From P2PChannel.startP2P"),this.sendConnection=new DR(e,this.store),this.store.peerConnectionStart(),this.bindConnectionEvents(this.sendConnection);let t=await this.sendConnection.establish();return{iceParameters:t.iceParameters,dtlsParameters:t.dtlsParameters,sdp:t.sdp}}}finally{i&&i()}}async p2pConnect(e){if(!this.sendConnection)throw new Sx(SU.UNEXPECTED_ERROR,"Cannot P2PChannel2.p2pConnect before P2PChannel2.startP2PConnection .");this.store.peerConnectionStart(),await this.sendConnection.connect(e),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=yp.Connected}async addRemoteCandidate(e,t){if(t===vW.RECEIVE_ONLY){if(!this.sendConnection)throw new Sx(SU.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.sendConnection.addRemoteCandidate(e)}else{if(!this.recvConnection)throw new Sx(SU.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.recvConnection.addRemoteCandidate(e)}}publish(e,t,i){var r=this;return fT(function*(){let n=yield fC(r.sendMutex.lock("From P2PChannel.publish"));try{if(!r.sendConnection||r.state!==yp.Connected){r.throwIfTrackTypeNotMatch(e);let t=e.filter(e=>-1===r.pendingLocalTracks.indexOf(e));return void(r.pendingLocalTracks=r.pendingLocalTracks.concat(t))}r.store.pubId=r.store.pubId+1,AT.markPublishStart(r.store.clientId,r.store.pubId);let n=r.filterTobePublishedTracks(e,t,i);if(0===n.length)return void(yield fC(r.tryToUnmuteAudio(e)));n.forEach(e=>{let{track:t,type:i}=e,n=Date.now();r.store.publish(t.getTrackId(),i===yu.LocalAudioTrack?"audio":"video",n)}),r.bindLocalTrackEvents(n);let o=yield fC(r.sendConnection.send(n.map(e=>{let{track:t}=e;return t}),r.store.codec,r.store.audioCodec)),a=(yield fC(o.next())).value,s=r.createGatewayPublishMessage(n,a);try{yield s}catch(e){throw o.throw(e),(null==e?void 0:e.code)===SU.WS_ABORT&&n.forEach(e=>{let{track:t}=e;-1===r.pendingLocalTracks.indexOf(t)&&r.pendingLocalTracks.push(t)}),r.unbindLocalTrackEvents(n),e}yield fC(o.next()),n.forEach(e=>{let{type:t}=e;r.statsCollector.addLocalStats(t)}),r.statsUploader.startUploadOutboundStats(),r.assignLocalTracks(n,a),n.forEach(e=>{let{track:t,type:i}=e,n=Date.now();r.store.publish(t.getTrackId(),i===yu.LocalAudioTrack?"audio":"video",void 0,n)}),r.startUploadUplinkState()}finally{n()}})()}async unpublish(e){if(!this.sendConnection||this.state!==yp.Connected)return void(0===e.length?this.pendingLocalTracks.length=0:this.pendingLocalTracks=this.pendingLocalTracks.filter(t=>!o5(e).call(e,t)));let t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;let i=t.find(e=>"videoLowTrack"===e[0]);i&&i[1].track.close();let r=this.createGatewayUnpublishMessage(t);if(await this.sendConnection.stopSending(t.map(e=>{let[,{id:t}]=e;return t})),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map(e=>{let[t,{track:i}]=e;return{type:t,track:i}}
1)),t.forEach(e=>{let[t]=e;this.statsCollector.removeLocalStats(t)}),0===this.localTrackMap.size&&(this.statsUploader.stopUploadOutboundStats(),this.stopUploadUplinkState()),this.sendConnection&&this.state===yp.Connected)return i&&i[1].track.close(),r;e.forEach(e=>{let t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1)})}startUploadUplinkState(){if(this.uploadUnplinkStarted)return;this.uploadUnplinkStarted=!0,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval);let e=()=>{let e=[],t=[];Array.from(this.localTrackMap.entries()).forEach(i=>{let[r,{track:n,ssrcs:o}]=i,a={stream_type:function(e,t){var i;let r;switch(t){case yu.LocalAudioTrack:r=v6.Audio;break;case yu.LocalVideoTrack:r=o5(i=e._hints).call(i,RE.SCREEN_TRACK)?v6.Screen:v6.High;break;case yu.LocalVideoLowTrack:r=v6.Low}return r}(n,r),ssrcs:o};n._muted||!n._enabled?e.push(a):t.push(a)}),e.length>0&&e.forEach(e=>{gc(this,y_.RequestMuteLocal,[e])}),t.length>0&&t.forEach(e=>{gc(this,y_.RequestUnmuteLocal,[e])})};e(),this.uplinkStateUploadInterval=window.setInterval(()=>{e()},3e3)}stopUploadUplinkState(){this.uploadUnplinkStarted&&(this.uploadUnplinkStarted=!1,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval))}publishLowStream(e){return fT(function*(){throw new Sx(SU.NOT_SUPPORTED,"p2p mode does not support publishLowStream.")})()}async republish(){this.pendingLocalTracks.length>0&&(TY.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await gs(this,y_.RequestRePublish,this.pendingLocalTracks),this.emit(y_.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[])}async unpublishLowStream(){throw new Sx(SU.NOT_SUPPORTED,"p2p mode does not support unpublishLowStream.")}async subscribe(e,t,i,r){var n;if(!this.recvConnection)throw new Sx(SU.INVALID_OPERATION,"Cannot subscribe remote user when recvConnection disconnected.");if(null!=(n=this.remoteUserMap.get(e))&&n.has(t))return;let{track:o,mid:a,transceiver:s}=await this.recvConnection.receive(t,[{ssrcId:i}],String(e.uid),r);t===yc.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(o):(e._audioTrack=new CV(o,e.uid,e._uintid,this.store),TY.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),s&&e._audioTrack._updateRtpTransceiver(s),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoSSRC=i,e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(o):(e._videoTrack=new Cx(o,e.uid,e._uintid,this.store),TY.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId()))),s&&e._videoTrack._updateRtpTransceiver(s),this.bindRemoteTrackEvents(e,e._videoTrack));let c=this.remoteUserMap.get(e);c?c.set(t,a):this.remoteUserMap.set(e,new Map([[t,a]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats(),this.startUploadDownlinkState();let d=this.pendingRemoteTracks.findIndex(i=>{let{user:r,kind:n}=i;return r.uid===e.uid&&t===n});-1!==d&&(this.pendingRemoteTracks.splice(d,1),this.emit(y_.MediaReconnectEnd,e.uid))}async mockSubscribe(e,t,i,r){if(!this.recvConnection)throw new Sx(SU.INVALID_OPERATION,"Cannot subscribe remote user when recvConnection disconnected.");await this.recvConnection.mockReceive(t,[{ssrcId:i}],String(e.uid),r)}async unsubscribe(e,t,i){let r=this.pendingRemoteTracks.filter(i=>{let{user:r,kind:n}=i;return void 0!==t?r.uid===e.uid&&t===n:r.uid===e.uid});if(r.forEach(e=>{let t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)}),this.recvConnection||i||r.forEach(t=>{var i,r;let{kind:n}=t;n===yc.AUDIO?(null==(i=e._audioTrack)||i._destroy(),e._audioTrack=void 0):n===yc.VIDEO&&(null==(r=e._videoTrack)||r._destroy(),e._videoTrack=void 0)}),!this.recvConnection)return;let n=this.filterTobeUnSubscribedTracks(e,t);0!==n.length&&(await this.recvConnection.stopReceiving(n.map(e=>{let[,{id:t}]=e;return t})),this.withdrawRemoteTracks(n),0===this.remoteUserMap.size&&(this.statsUploader.stopUploadInboundStats(),this.stopUploadDownlinkState()),n.forEac
1h(e=>{var t,r,n;let[o,{kind:a}]=e;a===yc.VIDEO&&o._videoSSRC&&(null==(t=this.recvConnection)||t.setStatsRemoteVideoIsReady(o._videoSSRC,!1)),a===yc.VIDEO?(this.unbindRemoteTrackEvents(o._videoTrack),i||(null==(r=o._videoTrack)||r._destroy(),o._videoTrack=void 0)):a===yc.AUDIO&&(this.unbindRemoteTrackEvents(o._audioTrack),i||(null==(n=o._audioTrack)||n._destroy(),o._audioTrack=void 0))}),n.forEach(e=>{let[,{kind:t}]=e;gc(this,y_.RequestP2PMuteRemote,t)}))}startUploadDownlinkState(){if(this.uploadDownlinkStarted)return;this.uploadDownlinkStarted=!0,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval);let e=()=>Array.from(this.remoteUserMap.entries()).forEach(e=>{let[,t]=e;[yc.VIDEO,yc.AUDIO].forEach(e=>{t.has(e)?gc(this,y_.RequestP2PUnmuteRemote,e):gc(this,y_.RequestP2PMuteRemote,e)})});e(),this.downlinkStatsUploadInterval=window.setInterval(()=>{e()},3e3)}stopUploadDownlinkState(){this.uploadDownlinkStarted&&(this.uploadDownlinkStarted=!1,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval))}getAllDataChannels(){return this.localDataChannels}async massSubscribe(e){throw new Sx(SU.NOT_SUPPORTED,"p2p mode does not support massSubscribe.")}async massSubscribeNoLock(e){throw new Sx(SU.NOT_SUPPORTED,"p2p mode does not support massSubscribeNoLock.")}async massUnsubscribe(e){throw new Sx(SU.NOT_SUPPORTED,"p2p mode does not support massUnsubscribe.")}async massUnsubscribeNoLock(e){throw new Sx(SU.NOT_SUPPORTED,"p2p mode does not support massUnsubscribeNoLock.")}async muteRemote(e,t){if(!this.recvConnection)return;let i=this.remoteUserMap.get(e);if(!i)return void TY.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid,"."));if(!i.get(t))return void TY.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));let r=t===yc.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==r&&this.recvConnection.setStatsRemoteVideoIsReady(r,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.recvConnection)return;let i=this.remoteUserMap.get(e);if(!i)return void TY.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(e.uid,"."));i.get(t)||TY.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."))}getAllTracks(e){let t=this.localTrackMap.get(yu.LocalAudioTrack);if((null==t?void 0:t.track)instanceof CI){let i=t.track;return Array.from(this.localTrackMap.entries()).filter(e=>{let[t]=e;return t!==yu.LocalAudioTrack}).filter(t=>{let[i]=t;return!(e&&i===yu.LocalVideoLowTrack)}).map(e=>{let[,{track:t}]=e;return t}).concat(i.trackList)}return Array.from(this.localTrackMap.entries()).filter(t=>{let[i]=t;return!(e&&i===yu.LocalVideoLowTrack)}).map(e=>{let[,{track:t}]=e;return t})}reportPublishEvent(e,t,i,r,n){if(e){let i=this.localTrackMap.get(yu.LocalAudioTrack),o=r?this.localTrackMap.get(yu.LocalVideoLowTrack):this.localTrackMap.get(yu.LocalVideoTrack);T$.publish(this.store.sessionId,{eventElapse:AT.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==i?void 0:i.track.getTrackLabel(),videoName:null==o?void 0:o.track.getTrackLabel(),screenshare:-1!==(null==o?void 0:o.track._hints.indexOf(RE.SCREEN_TRACK)),audio:!!i,video:!!o,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:n})}else{var o;i||(i=[]);let a=i.find(e=>e instanceof CC),s=r?null==(o=this.localTrackMap.get(yu.LocalVideoTrack))?void 0:o.track:i.find(e=>e instanceof CP);T$.publish(this.store.sessionId,{eventElapse:AT.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==a?void 0:a.getTrackLabel(),videoName:null==s?void 0:s.getTrackLabel(),screenshare:-1!==(null==s?void 0:s._hints.indexOf(RE.SCREEN_TRACK)),audio:!!a,video:!!s,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:n})}}reportSubscribeEvent(e,t,i,r){let n=r===yc.VIDEO?i._videoSSRC:i._audioSSRC;n&&T$.subscribe(this.store.sessionId,{succ:e,ec:t,video:r===yc.VIDEO,audio:r===yc.AU
1DIO,peerid:i.uid,subscribeRequestid:r===yc.VIDEO?i._videoSSRC:i._audioSSRC,p2pid:this.store.p2pId,eventElapse:AT.measureFromSubscribeStart(this.store.clientId,n)})}reset(){TY.debug("[".concat(this.store.clientId,"] P2PChannel2.reset")),this.sendMutex=new gG("P2PChannel2-send-mutex",this.store.clientId),this.sendMutex=new gG("P2PChannel2-recv-mutex",this.store.clientId),this.sendConnection&&(this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0),this.recvConnection&&(this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();let e=this.localTrackMap.get(yu.LocalAudioTrack);if((null==e?void 0:e.track)instanceof CI){if(e.track.trackList.length>0){let t=e.track;e.track.trackList.forEach(e=>{t.removeAudioTrack(e)})}e.track.close()}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.reconnectInterval&&(window.clearInterval(this.reconnectInterval),this.reconnectInterval=void 0),this.state=yp.Disconnected}getStats(e){var t,i;return e?null==(i=this.recvConnection)?void 0:i.getStats():null==(t=this.sendConnection)?void 0:t.getStats()}getRemoteVideoIsReady(e){var t;return(null==(t=this.recvConnection)?void 0:t.getRemoteVideoIsReady(e))||!1}getLocalAudioVolume(){let e=this.localTrackMap.get(yu.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){let e=this.localTrackMap.get(yu.LocalVideoTrack);if(e)return{width:e.track.videoWidth||0,height:e.track.videoHeight||0}}getEncoderConfig(e){let t=this.localTrackMap.get(e);return t&&t.track instanceof CP||t&&t.track instanceof CC?t.track._encoderConfig:void 0}getLocalMedia(e){return this.localTrackMap.get(e)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;let i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;let i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}getRemoteMedia(e){var t;let i=Array.from(TL(t=this.remoteUserMap).call(t)).find(t=>t.uid===e);return i?{audioTrack:i.audioTrack,audioSSRC:i._audioSSRC,videoTrack:i.videoTrack,videoSSRC:i._videoSSRC}:{}}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map(e=>{let[t]=e;return{uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0}}),t=this.localTrackMap.get(yu.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=ll(e).call(e,(e,t)=>e.level-t.level)}async disconnectForReconnect(){this.sendConnection&&this.recvConnection&&(TY.debug("[".concat(this.store.clientId,"] P2PChannel2.disconnectForReconnect closing P2PConnection")),this.state=yp.Reconnecting,TR("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach(e=>{var t;let[i]=e;i._videoTrack&&i._videoTrack._player&&(null==(t=i._videoTrack._player.getVideoElement())||t.pause(),i._videoTrack._player.isKeepLastFrame=!0,i._videoTrack._originMediaStreamTrack.stop())}),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0,this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0,0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach(e=>{var t;let[i,{track:r}]=e;switch(i){case yu.LocalVideoTrack:o5(t=r._hints).call(t,RE.LOW_STREAM)?r.close():this.pendingLocalTracks.push(r);break;case yu.LocalAudioTrack:r instanceof CI?this.pendingLocalTracks=this.pendingLocalTracks.concat(r.trackList):this.pendingLocalTracks.push(r);case yu.LocalVideoLowTrack:}}
1),this.emit(y_.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t,i]=e;Array.from(TL(i).call(i)).forEach(e=>{this.setPendingRemoteMedia(t,e)}),this.emit(y_.MediaReconnectStart,t.uid)}),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),TY.debug("[".concat(this.store.clientId,"] P2PChannel2 disconnected, waiting to reconnect.")))}hasPendingRemoteMedia(e,t){for(let i of this.pendingRemoteTracks){let{user:r,kind:n}=i;if((e instanceof AA?e.uid:e)===r.uid&&t===n)return!0}return!1}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t})}async restartICE(e,t){let i,r;if(e===vW.SEND_ONLY){if(!this.sendConnection)throw new Sx(SU.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established.");i=await this.sendMutex.lock("From P2PChannel.restartICE"),r=this.sendConnection}else{if(!this.recvConnection)throw new Sx(SU.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before recvConnection established.");i=await this.recvMutex.lock("From P2PChannel.restartICE"),r=this.recvConnection}try{if(t){let e=await r.restartICE(t);return r.isInRestartIce=!1,e}{let e=await r.restartICE();if(e){let t=await gs(this,y_.RequestP2PRestartICE,{direction:vW.RECEIVE_ONLY,iceParameter:e});await r.restartICE(t),r.isInRestartIce=!1}}}finally{i()}}getUplinkNetworkQuality(){if(!this.sendConnection)return 0;let e=this.sendConnection.getStats(),t=this.localTrackMap.get(yu.LocalVideoTrack),i=this.localTrackMap.get(yu.LocalAudioTrack),r=e.videoSend.find(e=>{var i;return e.ssrc===(null==t||null==(i=t.ssrcs)?void 0:i[0].ssrcId)}),n=e.audioSend.find(e=>{var t;return e.ssrc===(null==i||null==(t=i.ssrcs)?void 0:t[0].ssrcId)});if(!r||!n)return 1;let o=gd(this,y_.NeedSignalRTT),a=r?r.rttMs:void 0,s=n?n.rttMs:void 0,c=a&&s?(a+s)/2:a||s,d=100*e.sendPacketLossRate*.7/50+.3*((c&&o?(c+o)/2:c||o)||0)/1500,l=d<.17?1:d<.36?2:d<.59?3:d<.1?4:5,h=null==t?void 0:t.track;if(h&&h._encoderConfig&&-1===h._hints.indexOf(RE.SCREEN_TRACK)){let t=h._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){let e=(1e3*t-i)/(1e3*t);return vh[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][l]}}return l}getDownlinkNetworkQuality(){if(!this.recvConnection)return 0;let e=this.recvConnection.getStats(),t=0;return Array.from(this.remoteUserMap.entries()).forEach(i=>{let[r]=i,n=r._audioSSRC,o=r._videoSSRC,a=e.audioRecv.find(e=>e.ssrc===n),s=e.videoRecv.find(e=>e.ssrc===o);if(!a&&!s)return void(t+=1);let c=gd(this,y_.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,h=a?a.jitterMs:void 0,u=e.recvPacketLossRate,p=.7*u*100/50+.3*l/1500;h&&(p=.6*u*100/50+.2*l/1500+.2*h/400),t+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5}),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t}async muteLocalTrack(e){return new dQ((t,i)=>{this.handleMuteLocalTrack(e,t,i)})}filterTobePublishedTracks(e,t,i){let r=[],n=this.getAllTracks();e=gm(e=e.filter(e=>-1===n.indexOf(e)));let o=!1,a=!1;for(let n of e){if(n instanceof CP&&(this.localTrackMap.has(yu.LocalVideoTrack)||o?new Sx(SU.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(r.push({track:n,type:yu.LocalVideoTrack}),o=!0),t)){let e=this.getLowVideoTrack(n,i);r.push({track:e,type:yu.LocalVideoLowTrack})}if(n instanceof CC){let e=this.localTrackMap.get(yu.LocalAudioTrack);if(e){if(!(e.track instanceof CI))throw new Sx(SU.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(n._bypassWebAudio)throw new Sx(SU.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(n),this.bindLocalAudioTrackEvents(n,!0)}else if(a){let e=r.find(e=>{let{type:t}=e;return t===yu.LocalAudioTrack});if(!(e.track instanceof CI))throw new Sx(SU.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(n._bypassWebAudio)throw new Sx(SU.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(n)}else{if(!T1.webAudioMediaStreamDest||n instanceof CI||n._bypassWebAudio)r.push({track:n,type:yu.LocalAudioTrack});else{let e=new CI;e.addAudioTrack(n),r.push({track:e,type:yu.LocalAudioTrack})}a=!0}}}return r}filterTobeUnpublishedTracks(e){let t=[],i=this.getAllTracks();for(let r of e=gm(e=e.filter(e=>-1!==i.indexOf(e)))){if(r instanceof CC){let e=this.localTrackMap.get(yu.LocalAudioTrack);if(!e)continue;e.track instanceof CI?(e.track.removeAudioTrack(r),this.unbindLocalAudioTrackEvents(r),
10===e.track.trackList.length&&(t.push([yu.LocalAudioTrack,e]),e.track.close())):t.push([yu.LocalAudioTrack,e])}if(r instanceof CP){let e=this.localTrackMap.get(yu.LocalVideoTrack);if(!e)continue;t.push([yu.LocalVideoTrack,e]);let i=this.localTrackMap.get(yu.LocalVideoLowTrack);i&&t.push([yu.LocalVideoLowTrack,i])}}return t}bindLocalTrackEvents(e){e.forEach(e=>{let{track:t,type:i}=e;switch(i){case yu.LocalVideoTrack:t.addListener(R_.GET_STATS,this.handleGetLocalVideoStats),t.addListener(R_.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(R_.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(R_.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(R_.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.addListener(R_.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(R_.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(R_.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case yu.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case yu.LocalVideoLowTrack:}})}bindLocalAudioTrackEvents(e,t){e instanceof CI?e.trackList.forEach(e=>{e.addListener(R_.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(R_.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(R_.GET_STATS,this.handleGetLocalAudioStats),e.addListener(R_.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(R_.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)}):(e.addListener(R_.GET_STATS,this.handleGetLocalAudioStats),e.addListener(R_.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(R_.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(R_.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(R_.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||e.addListener(R_.NEED_REPLACE_TRACK,this.handleReplaceTrack))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map(e=>{let[t,{track:i}]=e;return{track:i,type:t}})),e.forEach(e=>{let{track:t,type:i}=e;switch(i){case yu.LocalVideoTrack:t.off(R_.GET_STATS,this.handleGetLocalVideoStats),t.off(R_.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(R_.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(R_.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(R_.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.off(R_.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(R_.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(R_.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case yu.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case yu.LocalVideoLowTrack:}})}unbindLocalAudioTrackEvents(e){e instanceof CI?e.trackList.forEach(e=>{e.off(R_.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(R_.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(R_.GET_STATS,this.handleGetLocalAudioStats),e.off(R_.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(R_.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)}):(e.off(R_.GET_STATS,this.handleGetLocalAudioStats),e.off(R_.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(R_.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(R_.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(R_.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(R_.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof Cx&&t.addListener(R_.GET_STATS,t=>{t(this.handleGetRemoteVideoStats(e))}),t instanceof CV&&t.addListener(R_.GET_STATS,t=>{t(this.handleGetRemoteAudioStats(e))})}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(R_.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t,i]=e;i.has(yc.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(yc.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack)})}createGatewayPublishMessage(e,t){return e.map((e,i)=>{var r;let n,{track:o,type:a}=e;switch(a){case yu.LocalAudioTrack:n=v6.Audio;break;case yu.LocalVideoTrack:n=o5(r=o._hints).call(r,RE.SCREEN_TRACK)?v6.Screen:v6.High;break;case yu.LocalVideoLowTrack:n=v6.Low}return{kind:a===yu.LocalAudioTrack?yc.AUDIO:yc.VIDEO,stream_type:n,mid:t[i].id,ssrcs:t[i].localSSRC,isMuted:o.muted||!o.enabled}})}createGatewayUnpublishMessage(e){return e.map(e=>{var t;let i,[r,{track:n,ssrcs:o,id:a}]=e;switch(r){case yu.LocalVideoTrack:i=o5(t=n._hints).call(t,RE.SCREEN_TRACK)?v6.Screen:v6.High;break;case yu.LocalAudioTrack:i=v6.Audio;break;case yu.LocalVideoLowTrack:i=v6.Low}return{stream_type:i,ssrcs:o,mid:a}})}assignLocalTracks(e,t){e.forEach((e,i)=>{let{track:r,type:n}=e;
1this.localTrackMap.set(n,{track:r,id:t[i].id,ssrcs:t[i].localSSRC})})}withdrawLocalTracks(e){e.forEach(e=>{let[t]=e;this.localTrackMap.delete(t)})}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{var i;TY.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: ").concat(e.name,".onConnectionStateChange(").concat(t,")")),this.emit(y_.PeerConnectionStateChange,t),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),"connected"===t&&(e.isInRestartIce=!1),o5(i=this._restartStates).call(i,t)&&!e.isInRestartIce&&("disconnected"===t&&await gO(800),"disconnected"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||this.handleDisconnect(e.direction))},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),TY.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),T$.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:S5.TRACER}).onSuccess(),this.emit(y_.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{TY.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{TY.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{TY.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},e.onFirstAudioDecoded=e=>{var t,i;let r=Array.from(TL(t=this.remoteUserMap).call(t)).find(t=>t._audioSSRC===e);r&&(this.store.subscribe(r.uid,"audio",void 0,void 0,void 0,Date.now()),null==(i=r.audioTrack)||i.emit(RR.FIRST_FRAME_DECODED),T$.firstRemoteFrame(this.store.sessionId,TX.FIRST_AUDIO_DECODE,TJ.FIRST_AUDIO_DECODE,{peer:r._uintid,subscribeElapse:AT.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;let i=Array.from(TL(t=this.remoteUserMap).call(t)).find(t=>t._audioSSRC===e);i&&T$.firstRemoteFrame(this.store.sessionId,TX.FIRST_AUDIO_RECEIVED,TJ.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:AT.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,i)=>{this.reportVideoFirstFrameDecoded(e,t,i)},e.onFirstVideoReceived=e=>{var t;let i=Array.from(TL(t=this.remoteUserMap).call(t)).find(t=>t._videoSSRC===e);i&&T$.firstRemoteFrame(this.store.sessionId,TX.FIRST_VIDEO_RECEIVED,TJ.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:AT.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onSelectedLocalCandidateChanged=(e,t)=>{let i="relay"===e.candidateType,r="relay"===t.candidateType;"unknown"!==t.candidateType&&i===r||this.emit(y_.ConnectionTypeChange,i),TY.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(y6(t))," -> ").concat(JSON.stringify(y6(e)),")"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{TY.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(y6(t))," -> ").concat(JSON.stringify(y6(e)),")"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},e.onLocalCandidate=t=>{this.emit(y_.LocalCandidate,{candidate:t,direction:e.direction})}}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0,e.onLocalCandidate=void 0}async handleDisconnect(e){let t=e===vW.SEND_ONLY?this.sendConnection:this.recvConnection;t&&!t.isInRestartIce&&(t.isInRestartIce=!0,TY.debug("[".concat(this.store.clientId,"] [P2PChannel-").concat(t.name,"] start use restartICE")),e===vW.SEND_ONLY?this.restartICE(e):gs(this,y_.RequestP2PRestartICE,{direction:vW.SEND_ONLY}))}filterTobeMutedTracks(e){let t=[];if(-1===this.getAllTracks().indexOf(e))return t;let i=this.localTrackMap.get(yu.LocalAudioTrack);if(e instanceof CC&&(null==i?void 0:i.track)instanceof CI)return i.track.isActive||t.push([yu.LocalAudioTrack,i]),t;let r=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i});if(r&&(t.push(r),r[0]===yu.LocalVideoTrack)){let e=this.localTrackMap.get(yu.LocalVideoLowTrack);e&&t.push([yu.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){let t=[],i=this.localTrackMap.get(yu.LocalAudioTrack);if(e instanceof CC&&(null==i?void 0:i.track)instanceof CI)return i.track.isActive&&t.push([yu.LocalAudioTrack,i]),t;let r=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i});if(r)if(r[0]===yu.LocalVideoTrack){t.push(r);let e=this.localTrackMap.get(yu.LocalVideoLowTrack);e&&t.push([yu.LocalVideoLowTrack,e])}else t.push(r);return t}createMuteMessage(e){return e.map(e=>{var t;let i,[r,{track:n,ssrcs:o,id:a}]=e;switch(r){case yu.LocalAudioTrack:i=v6.Audio;break;case yu.LocalVideoTrack:i=o5(t=n._hints).call(t,RE.SCREEN_TRACK)?v6.Screen:v6.High;break;case yu.LocalVideoLowTrack:i=v6.Low}return{stream_type:i,ssrcs:o,mid:a}})}createUnmuteMessage(e){return e.map(e=>{var t;let i,[r,{track:n,ssrcs:o,id:a}]=e;switch(r){case yu.LocalAudioTrack:i=v6.Audio;break;case yu.LocalVideoTrack:i=o5(t=n._hints).call(t,RE.SCREEN_TRACK)?v6.Screen:v6.High;break;case yu.LocalVideoLowTrack:i=v6.Low}return{stream_type:i,ssrcs:o,mid:a}})}filterTobeUnSubscribedTracks(e,t){let i=[],r=this.remoteUserMap.get(e);if(!r)return i;if(t){let n=r.get(t);if(!n)return i;i.push([e,{kind:t,id:n}])}
1else Array.from(r.entries()).forEach(t=>{let[r,n]=t;i.push([e,{kind:r,id:n}])});return i}createUnsubscribeMessage(e){let t=[];return e.forEach(e=>{let[i,{kind:r,id:n}]=e;switch(r){case yc.VIDEO:return void(i._videoSSRC&&t.push({stream_type:yc.VIDEO,ssrcId:i._videoSSRC}));case yc.AUDIO:return void(i._audioSSRC&&t.push({stream_type:yc.AUDIO,ssrcId:i._audioSSRC}))}}),t}withdrawRemoteTracks(e){e.forEach(e=>{let[t,{kind:i}]=e,r=this.remoteUserMap.get(t);r&&(r.delete(i),0===Array.from(r.entries()).length&&this.remoteUserMap.delete(t))})}async updateBitrateLimit(e){let t=this.localTrackMap.get(yu.LocalVideoTrack),i=this.localTrackMap.get(yu.LocalVideoLowTrack);t&&(await t.track.setBitrateLimit(e.uplink),await new dQ((e,i)=>{this.handleUpdateVideoEncoder(t.track,e,i,!0)})),i&&e.low_stream_uplink&&(await i.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0}),await new dQ((e,t)=>{this.handleUpdateVideoEncoder(i.track,e,t,!0)}))}isP2PDisconnected(){if(this.sendConnection&&this.recvConnection){let e=this.sendConnection.peerConnectionState,t=this.recvConnection.peerConnectionState;return"connected"!==e&&"connected"!==t}return!0}async tryToUnmuteAudio(e){for(let t=0;t<e.length;t++)if(e[t]instanceof CC){let i=this.filterTobeUnmutedTracks(e[t]);if(0===i.length)continue;let r=this.createUnmuteMessage(i);return void await gc(this,y_.RequestUnmuteLocal,r)}}bindStatsUploaderEvents(){this.statsUploader.requestStats=e=>this.getStats(e),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()).filter(e=>{let[,{ssrcs:t}]=e;return!!t}),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return!(null==(t=this.recvConnection)||!t.getRemoteVideoIsReady(e))},this.statsUploader.requestUpload=(e,t)=>this.emit(y_.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(y_.RequestUploadStats,e),this.statsUploader.requestAllTracks=()=>this.getAllTracks()}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0}async requestReconnect(){this.dtlsFailedCount+=1,await gO(gK(this.dtlsFailedCount,gH)),this.emit(y_.RequestReconnect)}async reconnectP2P(){}canPublishLowStream(){return this.localTrackMap.has(yu.LocalVideoTrack)||this.pendingLocalTracks.some(e=>e instanceof CP)}throwIfTrackTypeNotMatch(e){if(e.filter(e=>e instanceof CP).length>1)throw new Sx(SU.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter(e=>e instanceof CC).length>1&&(e.some(e=>e instanceof CC&&e._bypassWebAudio)||!T1.webAudioMediaStreamDest))throw new Sx(SU.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(let t of e){if(t instanceof CP&&this.pendingLocalTracks.some(e=>e instanceof CP))throw new Sx(SU.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof CC&&this.pendingLocalTracks.some(e=>e instanceof CC)&&(!T1.webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some(e=>e instanceof CC&&e._bypassWebAudio)))throw new Sx(SU.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(e,t){let i,r=!TR("DISABLE_DUAL_STREAM_USE_ENCODING")&&T1.supportDualStreamEncoding,n=DI(DI({},{width:160,height:120,framerate:15,bitrate:50}),t);i=r?e._mediaStreamTrack.clone():A$(e,n);let o=gw(8,"track-low-"),a=new CP(i,DI(DI({},r&&{scaleResolutionDownBy:y4(n,e)}),{},{frameRate:n.framerate,bitrateMax:n.bitrate,bitrateMin:n.bitrate}),void 0,void 0,o);return a.on(Rg.TRANSCEIVER_UPDATED,t=>{e._updateRtpTransceiver(t,Rm.LOW_STREAM)}),a._hints.push(RE.LOW_STREAM),e.addListener(R_.NEED_CLOSE,()=>{a.close()}),a}async globalLock(){return this.recvMutex.lock("From P2PChannel2.globalLock")}reportVideoFirstFrameDecoded(e,t,i,r){var n;let o=Array.from(TL(n=this.remoteUserMap).call(n)).find(t=>t._videoSSRC===e);if(o){r||this.store.subscribe(o.uid,"video",void 0,void 0,void 0,void 0,Date.now());let n=this.store.keyMetrics,a=n.subscribe.find(e=>e.userId===o.uid&&"video"===e.type);T$.firstRemoteVideoDecode(this.store.sessionId,TX.FIRST_VIDEO_DECODE,TJ.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:i,subscribeElapse:AT.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:n.requestAPEnd||0,apStart:n.requestAPStart||0,joinGwEnd:n.joinGatewayEnd||0,joinGwStart:n.joinGatewayStart||0,pcEnd:n.peerConnectionEnd||0,pcStart:n.peerConnectionStart||0,subscriberEnd:(null==a?void 0:a.subscribeEnd)||0,subscriberStart:(null==a?void 0:a.subscribeStart)||0,videoAddNotify:(null==a?void 0:a.streamAdded)||0,state:+!!r})}}async remoteMediaSsrcChanged(e,t,i){if(!this.recvConnection)return!1;let r=this.remoteUserMap.get(e);if(!r)return!1;let n=r.get(t);if(!n)return!1;let o=await this.recvConnection.getRemoteSSRC(n);return void 0!==o&&o!==i}isPreSubScribe(e){return!1}
1async publishDataChannel(e){throw new Sx(SU.NOT_SUPPORTED)}async unpublishDataChannel(e){throw new Sx(SU.NOT_SUPPORTED)}async subscribeDataChannel(e,t){throw new Sx(SU.NOT_SUPPORTED)}async unsubscribeDataChannel(e,t){throw new Sx(SU.NOT_SUPPORTED)}hasPendingRemoteDataChannel(e,t){throw new Sx(SU.NOT_SUPPORTED)}setPendingRemoteDataChannel(e,t){throw new Sx(SU.NOT_SUPPORTED)}async preConnect(e){throw new Sx(SU.NOT_SUPPORTED)}getEstablishParams(){throw new Sx(SU.NOT_SUPPORTED)}async reSubscribe(e){throw new Sx(SU.NOT_SUPPORTED)}reportVideoFirstFrameRender(e){}async updateVideoStreamParameter(e,t){throw new Sx(SU.NOT_SUPPORTED)}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach(e=>{let[t,{track:i}]=e;t===yu.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,Rm.LOW_STREAM):i._updateRtpTransceiver(void 0)})}constructor(e,t){super(),mb(this,"isPlanB",!1),mb(this,"store",void 0),mb(this,"statsUploader",void 0),mb(this,"sendConnection",void 0),mb(this,"recvConnection",void 0),mb(this,"localTrackMap",new Map),mb(this,"remoteUserMap",new Map),mb(this,"localDataChannels",[]),mb(this,"pendingLocalTracks",[]),mb(this,"pendingRemoteTracks",[]),mb(this,"statsCollector",void 0),mb(this,"dtlsFailedCount",0),mb(this,"sendMutex",void 0),mb(this,"recvMutex",void 0),mb(this,"_state",yp.Disconnected),mb(this,"_restartStates",["disconnected","failed"]),mb(this,"reconnectInterval",void 0),mb(this,"uploadUnplinkStarted",!1),mb(this,"uploadDownlinkStarted",!1),mb(this,"uplinkStateUploadInterval",void 0),mb(this,"downlinkStatsUploadInterval",void 0),mb(this,"handleMuteLocalTrack",async(e,t,i)=>{let r=await this.sendMutex.lock("Locking from P2PChannel2.handleMuteLocalTrack");try{var n,o;if(!this.sendConnection||this.state!==yp.Connected)return void i(new Sx(SU.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established."));let r=this.filterTobeMutedTracks(e);if(0===r.length)return void t();let a=r.find(e=>"videoLowTrack"===e[0]);a&&a[1].track._originMediaStreamTrack.stop(),await this.sendConnection.muteLocal(r.map(e=>{let[,{id:t}]=e;return t}));let s=!1;s="video"===e.trackMediaType?!(null==(n=this.localTrackMap.get(yu.LocalAudioTrack))||!n.track._muted):void 0===(null==(o=this.localTrackMap.get(yu.LocalVideoTrack))?void 0:o.id);let c=this.createMuteMessage(r);await gc(this,y_.RequestMuteLocal,c);let d="video"===e.trackMediaType?yA.MUTE_LOCAL_VIDEO:yA.MUTE_LOCAL_AUDIO;await gc(this,y_.RequestP2PMuteLocal,{action:d,message:c,isMuteAll:s}),t()}catch(e){i(e)}finally{r()}}),mb(this,"handleUnmuteLocalTrack",async(e,t,i)=>{let r=await this.sendMutex.lock("Locking from P2PChannel2.handleUnmuteLocalTrack");try{if(!this.sendConnection||this.state!==yp.Connected)return void i(new Sx(SU.INVALID_OPERATION,"Cannot call P2PChannel2.handleUnmuteLocalTrack before sendConnection established."));let r=this.filterTobeUnmutedTracks(e);if(0===r.length)return void t();await this.sendConnection.unmuteLocal(r.map(e=>{let[,{id:t}]=e;return t}));let n=this.createUnmuteMessage(r),o="video"===e.trackMediaType?yA.UNMUTE_LOCAL_VIDEO:yA.UNMUTE_LOCAL_AUDIO;await gc(this,y_.RequestP2PMuteLocal,{action:o,message:n}),t()}catch(e){i(e)}finally{r()}}),mb(this,"handleUpdateVideoEncoder",async(e,t,i,r)=>{let n;"boolean"==typeof r&&r||(n=await this.sendMutex.lock("Locking from P2PChannel2.handleUpdateVideoEncoder"));try{let i=this.localTrackMap.get(yu.LocalVideoTrack);if(!this.sendConnection||!i||i.track!==e||this.state!==yp.Connected)return void t();let{id:r,track:n}=i;r&&(await this.sendConnection.updateSendParameters(r,n),await this.sendConnection.updateEncoderConfig(r,n),this.emit(y_.UpdateVideoEncoder,n)),t()}catch(e){i(e)}finally{var o;null==(o=n)||o()}}),mb(this,"handleUpdateVideoSendParameters",async(e,t,i)=>{let r=await this.sendMutex.lock("Locking from P2PChannel2.handleUpdateVideoSendParameters");try{let i=this.localTrackMap.get(yu.LocalVideoTrack);if(!this.sendConnection||!i||i.track!==e||this.state!==yp.Connected)return void t();let{id:r,track:n}=i;r&&await this.sendConnection.updateSendParameters(r,n),t()}catch(e){i(e)}finally{r()}}),mb(this,"handleReplaceTrack",async(e,t,i,r)=>{var n,o;let a;TY.debug("[".concat(this.store.clientId,"] P2PChannel2 handleReplaceTrack for [track-id-").concat(e.getTrackId(),"]")),"boolean"==typeof r&&r||(a=await this.sendMutex.lock("From P2PChannel2.handleReplaceTrack"));try{let i=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i});if(!this.sendConnection||!i||void 0===i[1].id||this.state!==yp.Connected)return void t();if(await (null==(n=this.sendConnection)?void 0:n.replaceTrack(e,i[1].id)),i[0]===yu.LocalVideoTrack&&T1.supportDualStreamEncoding){let t=this.localTrackMap.get(yu.LocalVideoLowTrack);if(t){let i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new dQ((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)})}}t()}catch(e){i(e)}finally{null==(o=a)||o()}}),mb(this,"handleGetLocalVideoStats",e=>{e(this.statsCollector.getLocalVideoTrackStats())}),mb(this,"handleGetLocalAudioStats",e=>{e(this.statsCollector.getLocalAudioTrackStats())}),mb(this,"handleGetRemoteVideoStats",e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid]),mb(this,"handleGetRemoteAudioStats",e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid]),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new be(e),this.bindStatsUploaderEvents(),this.sendMutex=new gG("P2PChannel2-sen
1d-mutex",e.clientId),this.recvMutex=new gG("P2PChannel2-recv-mutex",e.clientId),this.reconnectInterval=window.setInterval(()=>{[this.sendConnection,this.recvConnection].forEach(e=>{e&&("disconnected"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||this.handleDisconnect(e.direction))})},TR("ICE_RESTART_INTERVAL"))}}).prototype,"p2pConnect",[rb],Object.getOwnPropertyDescriptor(rV.prototype,"p2pConnect"),rV.prototype),vP(rV.prototype,"unpublish",[rO],Object.getOwnPropertyDescriptor(rV.prototype,"unpublish"),rV.prototype),vP(rV.prototype,"unpublishLowStream",[rw],Object.getOwnPropertyDescriptor(rV.prototype,"unpublishLowStream"),rV.prototype),vP(rV.prototype,"subscribe",[rN],Object.getOwnPropertyDescriptor(rV.prototype,"subscribe"),rV.prototype),vP(rV.prototype,"mockSubscribe",[rD],Object.getOwnPropertyDescriptor(rV.prototype,"mockSubscribe"),rV.prototype),vP(rV.prototype,"unsubscribe",[rP],Object.getOwnPropertyDescriptor(rV.prototype,"unsubscribe"),rV.prototype),vP(rV.prototype,"muteRemote",[rL],Object.getOwnPropertyDescriptor(rV.prototype,"muteRemote"),rV.prototype),vP(rV.prototype,"unmuteRemote",[rk],Ob
1ject.getOwnPropertyDescriptor(rV.prototype,"unmuteRemote"),rV.prototype),vP(rV.prototype,"hasRemoteMediaWithLock",[rM],Object.getOwnPropertyDescriptor(rV.prototype,"hasRemoteMediaWithLock"),rV.prototype),vP(rV.prototype,"disconnectForReconnect",[rU],Object.getOwnPropertyDescriptor(rV.prototype,"disconnectForReconnect"),rV.prototype),vP(rV.prototype,"remoteMediaSsrcChanged",[rx],Object.getOwnPropertyDescriptor(rV.prototype,"remoteMediaSsrcChanged"),rV.prototype),rV);function Db(e){return function(t,i,r){let n=t[i];if("function"!=typeof n)throw Error("Cannot use mutex on object property.");return r.value=async function(){for(var t=arguments.length,r=Array(t),o=0;o<t;o++)r[o]=arguments[o];switch(e){case Dv.SEND_ONLY:{let e=await this.sendMutex.lock("From P2PChannel2.".concat(i));try{return await n.apply(this,r)}finally{e()}}case Dv.RECEIVE_ONLY:{let e=await this.recvMutex.lock("From P2PChannel2.".concat(i));try{return await n.apply(this,r)}finally{e()}}default:{let e=await this.sendMutex.lock("From P2PChannel2.".concat(i)),t=await this.recvMutex.lock("From P2PChannel2.".concat(i));try{return await n.apply(this,r)}finally{e(),t()}}}},r}}class DO extends S0{async send(e,t,i,r,n){var o;if(0===this.userMap.size)return;let a=Array.from(d1(o=this.userMap).call(o))[0].token;"string"!=typeof t&&(t=JSON.stringify(t)),r=null!=r?r:gw(6,""),n=null!=n?n:this._sequence++;let s={_id:r,_type:e,_seq:n,_message:t,token:"".concat(this.token,"_").concat(a)};TR("SHOW_P2P_LOG")&&TY.debug("send message",s,"noNeedResponse : ".concat(i)),this.splitMessage(JSON.stringify(s)).forEach(e=>{this.signal.request(vB.DATA_STREAM,{payload:gv(this.encoder.encode(e))})});let c=new dQ((t,n)=>{let o=window.setTimeout(()=>{this.off("res-@".concat(r,"_ack"),a),this.off("res-@".concat(r),d),this.off(yI.ABORT,c),TY.debug("[external-signal] request timeout, type: ".concat(e,", requestId: ").concat(r)),0===this.userMap.size?n(new Sx(SU.INVALID_REMOTE_USER)):n(new Sx(SU.TIMEOUT))},TR("EXTERNAL_SIGNAL_REQUEST_TIMEOUT")),a=()=>{o&&window.clearTimeout(o),this.off(yI.ABORT,c),i&&t()},c=()=>{o&&window.clearTimeout(o),this.off("res-@".concat(r,"_ack"),a),this.off("res-@".concat(r),d),n(new Sx(SU.EXTERNAL_SIGNAL_ABORT,"type: ".concat(e,", requestId: ").concat(r)))};this.once(yI.ABORT,c),this.once("res-@".concat(r,"_ack"),a);let d=(i,s)=>{l=!0,o&&window.clearTimeout(o),this.off("res-@".concat(r,"_ack"),a),this.off(yI.ABORT,c),"success"===i?t(s):n(new Sx(SU.P2P_MESSAGE_FAILED,"request ".concat(e," failed, requestId: ").concat(r)))},l=!1;i||(this.once("res-@".concat(r),d),gO(TR("SIGNAL_REQUEST_TIMEOUT")).then(()=>{l||TY.warning("external_signal request timeout, type: ".concat(e,", requestId: ").concat(r,", ").concat(s))}))});try{return await c}catch(o){if(o.code===SU.TIMEOUT)return await this.send(e,t,i,r,n);throw o}}onMessage(e){var t,i;let{_uid:r}=e,n,o=this.userMap.get(r);if(o)n=o.splitMessageMap;else{if(this.userMap.size>0||!("_type"in e)||e._type!==yy.CHECK)return;let{token:t}=e;o={uid:r,isStart:!0,token:t,splitMessageMap:n=new Map,nextExpectedSequenceNumber:0,receivedMessagesMap:new Map},this.userMap.set(r,o),this.signal.emit(vG.ON_USER_ONLINE,{uid:r}),this.handleUserOnline()}if("id"in e&&"total"in e){let{id:t,total:o}=e,a=null!=(i=n.get(t))?i:[];if(a.push(e),n.has(t)||n.set(t,a),a.length!==o)return;{let i=ll(a).call(a,(e,t)=>e.index-t.index).map(e=>e.payload).join("");n.delete(t),(e=JSON.parse(i))._uid=r}}let{_type:a,token:s}=e;if(o5(t=[yy.ACK,yy.CHECK]).call(t,a))return a===yy.CHECK&&this.handleCheckToken(o,s),void this.receiveMessage(e);s==="".concat(o.token,"_").concat(this.token)?this.handleReceivedMessage(e):TY.debug('Receive unexpected message", '.concat(s,", cur_token: ").concat(o.token,"_").concat(this.token),e)}check(){let e={_id:gw(6,""),token:this.token,_type:yy.CHECK};TR("SHOW_P2P_LOG")&&TY.debug("send message",e),this.signal.request(vB.DATA_STREAM,{payload:gv(this.encoder.encode(JSON.stringify(e)))})}ack(e){let t={_id:e,_type:yy.ACK,token:this.token};TR("SHOW_P2P_LOG")&&TY.debug("send message",t),this.signal.request(vB.DATA_STREAM,{payload:gv(this.encoder.encode(JSON.stringify(t)))})}response(e,t,i){this.send(yy.RESPONSE,JSON.stringify({success:!i,message:t}),!0,e)}handleReceivedMessage(e){let t=()=>
1{this.userMap.forEach(e=>{let{receivedMessagesMap:t,nextExpectedSequenceNumber:i}=e;for(;t.has(i);){let r=t.get(i);t.delete(i),this.receiveMessage(r),e.nextExpectedSequenceNumber++}})};if(!e)return void t();let{_uid:i,_seq:r}=e,n=this.userMap.get(i),{receivedMessagesMap:o,isStart:a,nextExpectedSequenceNumber:s}=n;if(r<s)return this.ack(e._id),void TY.debug("[external-signal] receive old message, seq: ".concat(r,", ").concat(e._message));o.set(r,e),a&&r===s&&(this.receiveMessage(e),o.delete(s),n.nextExpectedSequenceNumber++,t())}receiveMessage(e){let{_id:t,_type:i,_message:r,_uid:n}=e;if(TR("SHOW_P2P_LOG")&&TY.debug("receive message",e),t){let o;switch(e._type!==yy.ACK&&(r&&(o=JSON.parse(r)),this.ack(e._id)),e._type){case yy.CANDIDATE:case yy.CONTROL:this.signal.emit(i,o,n);break;case yy.PUBLISH:case yy.UNPUBLISH:case yy.RESTART_ICE:case yy.CALL:o.uid=n,gs(this.signal,i,o).then(t=>{this.response(e._id,t)}).catch(()=>{this.response(e._id,void 0,!0)});break;case yy.ACK:this.getListeners("res-@".concat(t,"_ack")).length>0&&this.emit("res-@".concat(t,"_ack"));break;case yy.RESPONSE:{let{success:e,message:i}=o;this.emit("res-@".concat(t),e?"success":"failed",i)}}}}splitMessage(e){if(e.length<DO.MAX_MESSAGE_SIZE)return[e];let t=[],{remoteToken:i}=JSON.parse(e),r=gw(6,""),n=0,o=800,a=Math.ceil(e.length/o);for(;e.length>0;){let s={id:r,index:++n,total:a,payload:e.slice(0,o),token:"".concat(this.token,"_").concat(i)};JSON.stringify(s).length>DO.MAX_MESSAGE_SIZE?o-=50:(t.push(s),e=e.slice(o))}return t.map(e=>JSON.stringify(e))}handleCheckToken(e,t){return e.token!==t?(TY.debug("token changed, from ".concat(e.token," to ").concat(t)),this.reset(e.uid,t),!1):(this.tokenTimeout&&(window.clearTimeout(this.tokenTimeout),this.tokenTimeout=void 0),this.tokenTimeout=window.setTimeout(()=>{TY.debug("token timeout, ".concat(t)),this.reset(e.uid)},TR("MAX_P2P_TIMEOUT")),!0)}async handleUserOnline(){let e=await gs(this.signal,yy.CALL,void 0),t=await this.send(yy.CALL,e);this.signal.emit(vF.P2P_CONNECTION,t,!0)}async reset(e,t){let i=this.userMap.get(e);i&&(this.emit(yI.ABORT),this.signal.emit(vG.ON_USER_OFFLINE,{uid:i.uid,reason:yb.P2P_TOKEN_CHANGED}),this._sequence=0,this.userMap.clear(),t||(TY.debug("change local token from ".concat(t," to ").concat(t)),this.token=gw(6,"")))}clear(){this._sequence=0,this.userMap.clear(),this.tokenInterval&&window.clearTimeout(this.tokenInterval),this.tokenInterval=void 0,this.tokenTimeout&&window.clearTimeout(this.tokenTimeout),this.tokenTimeout=void 0,this.emit(yI.ABORT)}constructor(e,t){super(),mb(this,"signal",void 0),mb(this,"token",void 0),mb(this,"tokenTimeout",void 0),mb(this,"tokenInterval",void 0),mb(this,"_sequence",0),mb(this,"userMap",new Map),mb(this,"encoder",new TextEncoder),this.signal=e,this.token=t;let i=()=>{this.signal.connectionState===vV.CONNECTED&&this.check(),0===this.userMap.size?this.tokenInterval=window.setTimeout(i,1e3):this.tokenInterval=window.setTimeout(i,3*TR("P2P_TOKEN_INTERVAL"))};i()}}mb(DO,"MAX_SIZE",1),mb(DO,"MAX_MESSAGE_SIZE",1024);class Dw extends S0{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===vV.CONNECTED?this.emit(vF.WS_CONNECTED):e===vV.RECONNECTING?this.emit(vF.WS_RECONNECTING,this._websocketReconnectReason):e===vV.CLOSED&&this.emit(vF.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get rtt(){return this.rttRolling.mean()}async request(e,t,i,r){let n=gw(6,""),o=this.websocket.connectionID,a=()=>new dQ((e,t)=>{if(this.connectionState===vV.CONNECTED)return e();let i=()=>{this.off(vF.WS_CLOSED,r),e()},r=()=>{this.off(vF.WS_CONNECTED,i),t(new Sx(SU.WS_ABORT))};this.once(vF.WS_CONNECTED,i),this.once(vF.WS_CLOSED,r)});if(this.connectionState!==vV.CONNECTING&&this.connectionState!==vV.RECONNECTING||e===vB.JOIN||e===vB.REJOIN||await a(),this.websocket.sendMessage({_id:n,_type:e,_message:t},!0),r)return;let s=new dQ((i,r)=>{let a=!1,s=(r,n)=>{a=!0,i({isSuccess:"success"===r,message:n||{}}),this.off(vF.WS_CLOSED,c),this.off(vF.WS_RECONNECTING,c),this.emit
1(vF.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(n),s);let c=()=>{r(new Sx(SU.WS_ABORT,"type: ".concat(e))),this.off(vF.WS_CLOSED,c),this.off(vF.WS_RECONNECTING,c),this.off("res-@".concat(n),s)};this.once(vF.WS_CLOSED,c),this.once(vF.WS_RECONNECTING,c),gO(TR("SIGNAL_REQUEST_TIMEOUT")).then(()=>{this.websocket.connectionID!==o||a||(TY.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(vF.REQUEST_TIMEOUT,e,t))})}),c=null;try{c=await s}catch(r){if(this.connectionState===vV.CLOSED||e===vB.LEAVE)throw new Sx(SU.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?r.throw():e===vB.JOIN||e===vB.REJOIN?null:(await a(),await this.request(e,t))}if(c.isSuccess)return c.message;let d=Number(c.message.error_code||c.message.code),l=yD(d),h=new Sx(SU.UNEXPECTED_RESPONSE,"".concat(l.desc,": ").concat(c.message.error_str),{code:d,data:c.message,desc:l.desc});return"success"===l.action?c.message:(TY.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(d,", message: ").concat(l.desc,", action: ").concat(l.action)),d===vx.ERR_TOO_MANY_BROADCASTERS?((e===vB.JOIN||e===vB.REJOIN)&&(this.initError=h,this.close()),h.throw()):"failed"===l.action?h.throw():"quit"===l.action?(this.initError=h,this.close(),h.throw()):(d===vx.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=c.message.option,TY.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",gn.MULTI_IP)):this.reconnect(l.action,gn.SERVER_ERROR),e===vB.JOIN||e===vB.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new dQ(i=>{let r=n=>{(!t||t(n))&&(this.off(e,r),i(n))};this.on(e,r)})}uploadWRTCStats(e){if(!this.store.sessionId)return void TY.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));let t={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(vj.WRTC_STATS,t)}upload(e,t){let i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(t){let e=TR("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>e&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval(()=>{if(this.connectionState!==vV.CONNECTED)return;let e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message)},TR("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){this.websocket.sendMessage({_type:e,_message:t})}async sendExtensionMessage(e,t,i){return await this._external_signal.send(e,t,i)}init(e){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new dQ((t,i)=>{this.once(vF.WS_CONNECTED,()=>t(this.joinResponse)),this.once(vF.WS_CLOSED,()=>i(this.initError||new Sx(SU.WS_ABORT))),this.connectionState=vV.CONNECTING,this.websocket.init(e).catch(i)})}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._external_signal.clear(),this._disconnectedReason=e||S8.LEAVE,this.connectionState=vV.CLOSED,TY.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close(),this.p2pToken=gw(6,""),this._external_signal.clear(),this._external_signal=new DO(this,this.p2pToken)}async join(){if(!this.joinResponse){this.emit(vF.ABORT_P2P_EXECUTION);let e=await gs(this,vF.REQUEST_JOIN_INFO),t=await this.request(vB.JOIN,e);if(!t)return this.emit(vF.REPORT_JOIN_GATEWAY,SU.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(vF.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=vV.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}async downgradeCodec(e){return!1}handleDataStream(e){try{var t;let i=gC(e.payload),r=(new TextDecoder).decode(i),n=JSON.parse(r);"total"in n&&"id"in n||o5(t=Object.values(yy)).call(t,n._type)?(n._uid=e.uid,this._external_signal.onMessage(n)):this.emit
1(vG.ON_DATA_STREAM,e)}catch(t){this.emit(vG.ON_DATA_STREAM,e)}}handleNotification(e){TY.debug("[".concat(this.clientId,"] receive notification: "),e);let t=yD(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?e.code===vx.ERR_REPEAT_JOIN_CHANNEL&&TR("IGNORE_UID_CHECK")?void this.close(S8.UID_CONFLICT):("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(S8.UID_BANNED),void this.close()):void this.reconnect(t.action,gn.SERVER_ERROR);TY.error("[".concat(this.clientId,"] ignore error: "),t.desc)}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;let e=TR("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(TY.warning("[".concat(this.clientId,"] PINGPONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>TR("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",gn.TIMEOUT):this.request(vB.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;let e=Date.now()-t;this.rttRolling.add(e),TR("REPORT_STATS")&&this.send(vB.PING_BACK,{pingpongElapse:e})}).catch(e=>{})}handleWebsocketEvents(){this.websocket.on(vH.RECONNECT_CREATE_CONNECTION,e=>{this.emit(vF.WS_RECONNECT_CREATE_CONNECTION,e)}),this.websocket.on(vH.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(vH.CLOSED,()=>{this.connectionState=vV.CLOSED}),this.websocket.on(vH.FAILED,()=>{this._disconnectedReason=S8.NETWORK_ERROR,this.connectionState=vV.CLOSED}),this.websocket.on(vH.RECONNECTING,e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===vV.CONNECTED?this.connectionState=vV.RECONNECTING:this.connectionState=vV.CONNECTING}),this.websocket.on(vH.WILL_RECONNECT,(e,t,i)=>{"retry"!==e?(TY.debug("".concat(this.clientId," websocket will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0):TY.debug("".concat(this.clientId," reconnect mode is retry, no need to renew session")),i(e)}),this.websocket.on(vH.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.join().catch(e=>{if(this.emit(vF.REPORT_JOIN_GATEWAY,e,this.url||""),e instanceof Sx&&e.code===SU.UNEXPECTED_RESPONSE&&e.data.code===vx.ERR_NO_AUTHORIZED)return TY.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",gn.SERVER_ERROR);TY.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",gn.SERVER_ERROR):(this.initError=e,this.close())})}),this.websocket.on(vH.REQUEST_NEW_URLS,(e,t)=>{gs(this,vF.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)}),this.websocket.on(vH.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(vG.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})}constructor(e,t){super(),mb(this,"__name__","P2PSignal"),mb(this,"_disconnectedReason",void 0),mb(this,"_websocketReconnectReason",void 0),mb(this,"_connectionState",vV.CLOSED),mb(this,"reconnectToken",void 0),mb(this,"p2pToken",void 0),mb(this,"websocket",void 0),mb(this,"openConnectionTime",void 0),mb(this,"clientId",void 0),mb(this,"lastMsgTime",Date.now()),mb(this,"uploadCache",[]),mb(this,"uploadCacheInterval",void 0),mb(this,"rttRolling",new gq(5)),mb(this,"pingpongTimer",void 0),mb(this,"pingpongTimeoutCount",0),mb(this,"joinResponse",void 0),mb(this,"multiIpOption",void 0),mb(this,"initError",void 0),mb(this,"spec",void 0),mb(this,"store",void 0),mb(this,"_external_signal",void 0),mb(this,"onWebsocketMessage",e=>{if(e.data instanceof ArrayBuffer)return void this.emit(vF.ON_BINARY_DATA,e.data);let t=JSON.parse(e.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){let e="res-@".concat(t._id);this.emit(e,t._result,t._message)}else if(Object.prototype.hasOwnProperty.call(t,"_type")){switch(t._type){case vG.ON_DATA_STREAM:return void this.handleDataStream(t._message);case vG.MUTE_AUDIO:case vG.MUTE_VIDEO:case vG.ON_P2P_LOST:case vG.ON_USER_ONLINE:return;case vG.ON_USER_OFFLINE:let{uid:e}=t._message;return TY.debug("[".concat(this.clientId,"] user-offline uid: ").concat(e)),void this._external_signal.reset(e)}
1if(this.emit(t._type,t._message),t._type===vG.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===vG.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(S8.UID_BANNED);break;case 15:this.close(S8.IP_BANNED);break;case 16:this.close(S8.CHANNEL_BANNED)}if(t._type===vG.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case vx.ERR_LICENSE_MISSING:this.close(S8.LICENSE_MISSING);break;case vx.ERR_LICENSE_EXPIRED:this.close(S8.LICENSE_EXPIRED);break;case vx.ERR_LICENSE_MINUTES_EXCEEDED:this.close(S8.LICENSE_MINUTES_EXCEEDED);break;case vx.ERR_LICENSE_PERIOD_INVALID:this.close(S8.LICENSE_PERIOD_INVALID);break;case vx.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(S8.LICENSE_MULTIPLE_SDK_SERVICE);break;case vx.ERR_LICENSE_ILLEGAL:this.close(S8.LICENSE_ILLEGAL);break;default:this.close()}}}),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new yW("gateway-".concat(this.clientId),this.spec.retryConfig,!0,TR("JOIN_GATEWAY_USE_DUAL_DOMAIN"),TR("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===vV.CONNECTED&&this.reconnect("retry",gn.OFFLINE)}),this.p2pToken=gw(6,""),this._external_signal=new DO(this,this.p2pToken)}}function DN(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function DD(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?DN(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):DN(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}class DP{toString(){return Tw(this.sessionDesc)}send(e,t,i){let{ssrcs:r,ssrcGroups:n}=I_(t,this.cname),o=this.sessionDesc.mediaDescriptions.find(t=>e===yc.VIDEO?"video"===t.media.mediaType:"audio"===t.media.mediaType),a=r[0].attributes.label,s=r[0].attributes.mslabel;return o.attributes.ssrcs=o.attributes.ssrcs.concat(r),o.attributes.ssrcGroups=o.attributes.ssrcGroups.concat(n),{id:a,mslabel:s}}batchSend(e){return e.map(e=>{let{kind:t,ssrcMsg:i}=e;return this.send(t,i,void 0)})}stopSending(e){this.sessionDesc.mediaDescriptions.forEach(t=>{let i=[],r=[],n=[];t.attributes.ssrcs.forEach(t=>{o5(e).call(e,t.attributes.label||"")?n.push(t):i.push(t)}),t.attributes.ssrcGroups.forEach(e=>{var t;o5(t=n.map(e=>e.ssrcId)).call(t,e.ssrcIds[0])||r.push(e)}),t.attributes.ssrcs=i,t.attributes.ssrcGroups=r})}mute(e){let t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive"}unmute(e){let t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly"}receive(e,t,i){e.forEach((e,t)=>{let i=e._mediaStreamTrack,r=this.sessionDesc.mediaDescriptions.findIndex(e=>e.attributes.mid===i.kind),n=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[r],e);this.sessionDesc.mediaDescriptions[r]=n})}stopReceiving(e){}updateCandidates(e){let t=this._originCandidates.filter(e=>"udp"===e.transport),i=[];if(t.forEach(e=>{i.push(DD(DD({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))}),0!==t.length){switch(e){case yd.TCP_RELAY:this.candidates=i;break;case yd.UDP_TCP_RELAY:case yd.RELAY:this.candidates=[...t,...i];break;default:this.candidates=t}for(let e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}}restartICE(e){e=gS(e),this.iceParameters=e,this.sessionDesc.mediaDescriptions.forEach(t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd})}predictReceivingMids(e){let t=[];for(let i=0;i<e;i++)t.push((this.currentMidIndex+i+1).toString(10));return t}mungRecvMediaDsec(e,t){let i=gS(e);return IE(i,t),If(i,t),i}updateRecvMedia(e,t){let i=this.sessionDesc.mediaDescriptions.findIndex(t=>t.attributes.mid===e);if(-1!==i){let e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}bumpMid(e){this.currentMidIndex+=e}updateTrackLabel(e,t,i){let r=this.sessionDesc.mediaDescriptions.find(t=>e===yc.VIDEO?"video"===t.attributes.mid:"audio"===t.attributes.mid);if(r){var n;let e=r.attributes.ssrcs.find(e=>e.attributes.label===t);e&&(e.attributes.label=i,null==(n=e.attributes.msid)||n.replace(t,i))}}mungMediaDesc(e){let t=gS(e);return Im(t),function(e){let t=e.attributes.extmaps.find(e=>Ia(e.extensionName));t&&e.attributes.extmaps.splice(e.attributes.extmaps.indexOf(t),1),e.attributes.payloads.forEach(e
1=>{let t=e.rtcpFeedbacks.findIndex(e=>"transport-cc"===e.type);-1!==t&&e.rtcpFeedbacks.splice(t,1)})}(t),t}getSSRC(e){for(let t of this.sessionDesc.mediaDescriptions)for(let i of t.attributes.ssrcs)if(i.attributes.label===e)return[i]}constructor(e){mb(this,"sessionDesc",void 0),mb(this,"localCapabilities",void 0),mb(this,"rtpCapabilities",void 0),mb(this,"candidates",void 0),mb(this,"_originCandidates",void 0),mb(this,"iceParameters",void 0),mb(this,"dtlsParameters",void 0),mb(this,"setup",void 0),mb(this,"currentMidIndex",void 0),mb(this,"cname",void 0);let{iceParameters:t,dtlsParameters:i,candidates:r,rtpCapabilities:n,setup:o,localCapabilities:a,sdkCodec:s,cname:c}=e=gS(e),d=TO("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE audio video\na=msid-semantic: WMS\na=ice-lite\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendrecv\na=rtcp-mux\na=rtcp-rsize\na=mid:audio\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendrecv\na=rtcp-mux\na=rtcp-rsize\na=mid:video\n");this.rtpCapabilities=n,this.candidates=r,this._originCandidates=gS(r),this.iceParameters=t,this.dtlsParameters=i,this.setup=o,this.localCapabilities=a,this.cname=c;for(let e=0;e<d.mediaDescriptions.length;e++){let a=d.mediaDescriptions[e];if(a.attributes.iceUfrag=t.iceUfrag,a.attributes.icePwd=t.icePwd,a.attributes.fingerprints=i.fingerprints,a.attributes.candidates=r,a.attributes.setup=o,"video"===a.media.mediaType){a.media.fmts=n.videoCodecs.map(e=>e.payloadType.toString(10));let e=n.videoCodecs.filter(e=>{var t,i;return null==(t=e.rtpMap)?void 0:o5(i=t.encodingName.toLowerCase()).call(i,s)}),t=n.videoCodecs.filter(t=>!o5(e).call(e,t));a.attributes.payloads=[...e,...t],a.attributes.extmaps=n.videoExtensions}"audio"===a.media.mediaType&&(a.media.fmts=n.audioCodecs.map(e=>e.payloadType.toString(10)),a.attributes.payloads=n.audioCodecs,a.attributes.extmaps=n.audioExtensions),d.mediaDescriptions[e]=this.mungMediaDesc(a)}this.sessionDesc=d,this.currentMidIndex=d.mediaDescriptions.length-1}}function DL(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function Dk(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?DL(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):DL(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let DM=(vP((rF=class e extends ys{get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get localCodecs(){return[...new Set(this.localCapabilities&&this.localCapabilities.videoCodecs.map(e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").filter(e=>{var t;return o5(t=Object.keys(TI)).call(t,e)}))]}async establish(){try{let e=await this.peerConnection.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});if(!e.sdp)throw Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");let t=Il(e.sdp),i=Id(e.sdp,{filterRTX:!this.useRTX,filterVideoFec:TR("FILTER_VIDEO_FEC"),filterAudioFec:TR("FILTER_AUDIO_FEC"),filterAudioCodec:["opus"]});return this.localCapabilities=i,this.initialOffer=e,Dk(Dk({},t),{},{rtpCapabilities:{send:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},recv:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},sendrecv:i},offerSDP:e.sdp})}catch(e){throw new Sx(SU.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async updateRemoteConnect(){}async connect(e){try{if(!this.initialOffer)throw Error("Cannot establish P2PConnection without initial offer.");this.remoteSDP=new DP(Dk(Dk({},e),{},{rtpCapabilities:e.rtpCapabilities.send,localCapabilities:this.localCapabilities,sdkCodec:this.store.codec}));let t=this.remoteSDP.toString();await this.peerConnection.setLocalDescription(this.initialOffer),await this.peerConnection.setRemoteDescription({type:"answer",sdp:t})}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}async updateRemoteRTPCapabilities(e,t){throw new Sx(SU.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}getPreMedia(e){}send(e,t){var i=this;return fT(function*(){let r=yield fC(i.mutex.lock());try{let r;if(!i.remoteSDP)throw Error("Cannot call P2PConnection.send before remote SDP created");let n=e.map(e=>i.peerConnection.addTrack(e._mediaStreamTrack)),o=yield fC(i.peerConnection.createOffer()),a=TO(o.sdp),s=e.map(e=>{let t=e._mediaStreamTrack,r=a.mediaDescriptions.find(e=>e.attributes.mid===t.kind);if(!r)throw Error("Cannot extract ssrc from mediaDescription.");return function(e,t,i){let r=e.attributes.ssrcs.filter(e=>e.attributes.label===t),n=e.attributes.ssrcGroups;if(0===r.length)throw Error("Cannot extract ssrc from plan-b SDP.");if(n&&r.length>1){let e=n.find(e=>-1!==e.ssrcIds.indexOf(r[0].ssrcId));return e?[{ssrcId:e.ssrcIds[0],rtx:i?e.ssrcIds[1]:void 0}]:[{ssrcId:r[0].ssrcId}]}return[{ssrcId:r[0].ssrcId}]}(r,t.id,i.useRTX)});try{r=yield s}
1catch(e){throw n.forEach(e=>{Ss()&&e.replaceTrack(null),i.peerConnection.removeTrack(e)}),e}let c=i.mungSendOfferSDP(o.sdp,e);i.remoteSDP.receive(e,t,r);let d=i.remoteSDP.toString();return yield fC(i.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield fC(i.applySendEncodings(n,e)),yield fC(i.peerConnection.setRemoteDescription({type:"answer",sdp:d})),e.map((e,t)=>{let i=e._mediaStreamTrack.id;return{localSSRC:s[t],id:i}})}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{r()}})()}async stopSending(e){try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.stopSending before remote SDP created");let t=this.peerConnection.getSenders().filter(t=>{var i;return -1!==e.indexOf((null==(i=t.track)?void 0:i.id)||"")});if(t.length!==e.length)throw Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");t.map(e=>{Ss()&&e.replaceTrack(null),this.peerConnection.removeTrack(e)});let i=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(i),this.remoteSDP.stopReceiving(e);let r=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}}async receive(e,t,i,r){try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));let{id:i,mslabel:n}=this.remoteSDP.send(e,t,r),o=new dQ((t,r)=>{let o=setTimeout(()=>{r(Error("Cannot receive track, id: ".concat(i)))},1e4),a=r=>{let s=St();if(("Safari"===s.name&&11===Number(s.version)||Sh())&&r.track.id!==i&&r.streams[0].id===n){var c;let n=r.streams[0].getTracks()[0];return null==(c=this.remoteSDP)||c.updateTrackLabel(e,i,r.track.id),this.peerConnection.removeEventListener("track",a),clearTimeout(o),void t(n)}if(r.track.id===i)return this.peerConnection.removeEventListener("track",a),clearTimeout(o),void t(r.track)};this.peerConnection.addEventListener("track",a)}),a=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:a});let s=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(s),{track:await o,id:i}}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);let t=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});let i=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(i)}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){}async unmuteRemote(e){}async muteLocal(e){try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.muteLocal before remote SDP created.");let t=this.peerConnection.getSenders().filter(t=>{var i;return -1!==e.indexOf((null==(i=t.track)?void 0:i.id)||"")});if(t.length!==e.length)throw Error("sender' length doesn't match mids' length.");t.map(e=>{if(Ss()&&e.track)e.track.enabled=!1;else{let t=e.getParameters();
1t.encodings.forEach(e=>e.active=!1),e.setParameters(t)}})}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");let t=this.peerConnection.getSenders().filter(t=>{var i;return -1!==e.indexOf((null==(i=t.track)?void 0:i.id)||"")});if(t.length!==e.length)throw Error("Senders' length doesn't match mids' length.");t.map(async e=>{if(Ss()&&e.track)e.track.enabled=!0;else{let t=e.getParameters();t.encodings.forEach(e=>e.active=!0),await e.setParameters(t)}});let i=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(i);let r=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return fT(function*(){let i=yield fC(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw Error("Cannot restartICE before remoteSDP created.");let i=T1.supportPCSetConfiguration;if(e===yd.RELAY&&!i)return;if(i){let i=t.peerConnection.getConfiguration(),r=e===yd.RELAY?"relay":"all";i.iceTransportPolicy!==r&&(TY.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(i.iceTransportPolicy,"] to [").concat(r,"]")),i.iceTransportPolicy=r,t.peerConnection.setConfiguration(i))}e!==yd.RELAY&&t.remoteSDP.updateCandidates(e);let r=yield fC(t.peerConnection.createOffer({iceRestart:!0}));if(!r.sdp)throw Error("Cannot restartICE because restart offer SDP does not exist.");let n=Il(r.sdp),{remoteIceParameters:o}=yield n.iceParameters;t.remoteSDP.restartICE(o);let a=t.remoteSDP.toString();yield fC(t.peerConnection.setLocalDescription(r)),yield fC(t.peerConnection.setRemoteDescription({type:"answer",sdp:a}))}catch(e){TY.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{i()}})()}close(){var e;this.peerConnection.close(),null==(e=this.onConnectionStateChange)||e.call(this,"closed"),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");let e=await this.peerConnection.createOffer(),i=this.mungSendOfferSDP(e.sdp,[t]);this.remoteSDP.updateRecvMedia(t._mediaStreamTrack.kind,t);let r=this.remoteSDP.toString();await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){let i=this.peerConnection.getSenders().filter(t=>{var i;return(null==(i=t.track)?void 0:i.id)===e});1===i.length&&await this.applySendEncodings(i,[t])}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){let i=this.peerConnection.getSenders().find(e=>{var i;return(null==(i=e.track)?void 0:i.id)===t});i&&await i.replaceTrack(e._mediaStreamTrack)}createDataChannels(e,t){throw new Sx(SU.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}stopDataChannels(e){throw new Sx(SU.NOT_SUPPORTED,"Planb mode does not support stopDataChannels.")}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null==(e=this.onICEConnectionStateChange)||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;null==(e=this.onConnectionStateChange)||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,TY.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,TY.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))},TR("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){let i={iceServers:[],sdpSemantics:"plan-b"};return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(S9(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),TR("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEac
1h(e=>{e.forceturn&&(i.iceTransportPolicy="relay")}))),i}static turnServerConfigToIceServers(e){let t=[];return e.forEach(e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))}),t}async updateRtpSenderEncodings(e,t){var i,r;if(t||(t=this.peerConnection.getSenders().find(t=>{var i;return(null==(i=t.track)?void 0:i.id)===e._mediaStreamTrack.id})),!t)return TY.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(!T1.supportSetRtpSenderParameters)return TY.warn("Browser not support set rtp-sender parameters");let n={},o={};if(e instanceof CP)switch(e._optimizationMode){case"motion":n.degradationPreference="maintain-framerate";break;case"detail":n.degradationPreference="maintain-resolution";break;default:n.degradationPreference="balanced"}if(TR("DSCP_TYPE")&&SN()){let e=TR("DSCP_TYPE");o5(r=["very-low","low","medium","high"]).call(r,e)&&(o.networkPriority=e)}let a=t.getParameters(),s=null==(i=a.encodings)?void 0:i[0];s&&Object.assign(s,o),Object.assign(a,n),TY.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(a.encodings))),await t.setParameters(a)}async applySendEncodings(e,t){try{if(!T1.supportSetRtpSenderParameters||e.length!==t.length)return;for(let i=0;i<e.length;i++){let r=e[i],n=t[i];r&&n&&await this.updateRtpSenderEncodings(n,r)}}catch(e){TY.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t){let i=TO(e);return t.forEach((e,t)=>{let r=e._mediaStreamTrack,n=i.mediaDescriptions.find(e=>e.attributes.mid===r.kind);n&&IE(n,e)}),Tw(i)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null==(t=this.onFirstAudioReceived)||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null==(t=this.onFirstVideoReceived)||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null==(t=this.onFirstAudioDecoded)||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var r;null==(r=this.onFirstVideoDecoded)||r.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null==(i=this.onSelectedLocalCandidateChanged)||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null==(i=this.onSelectedRemoteCandidateChanged)||i.call(this,e,t)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0}async batchReceive(e){try{if(!this.remoteSDP)throw Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");let t=this.remoteSDP.batchSend(e).map((t,i)=>{let{id:r,mslabel:n}=t,{kind:o}=e[i];return new dQ((e,t)=>{let i=setTimeout(()=>{t(Error("Cannot receive track, id: ".concat(r)))},1e4),a=t=>{let s=St();if("Safari"===s.name&&11===Number(s.version)&&t.track.id!==r&&t.streams[0].id===n){var c;let n=t.streams[0].getTracks()[0];return null==(c=this.remoteSDP)||c.updateTrackLabel(o,r,t.track.id),this.peerConnection.removeEventListener("track",a),clearTimeout(i),void e({track:n,id:r})}if(t.track.id===r)return this.peerConnection.removeEventListener("track",a),clearTimeout(i),void e({track:t.track,id:r})};this.peerConnection.addEventListener("track",a)})}),i=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:i});let r=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(r),await dQ.all(t)}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async getRemoteSSRC(e){if(!this.remoteSDP)return;let t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId}setConfiguration(t){if(T1.supportPCSetConfiguration){let i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}}constructor(t,i){super(t,i),mb(this,"store",void 0),mb(this,"peerConnection",void 0),mb(this,"remoteSDP",void 0),mb(this,"initialOffer",void 0),mb(this,"statsFilter",void 0),mb(this,"useRTX",!1),mb(this,"localCapabilities",void 0),mb(this,"localCandidateCount",0),mb(this,"allCandidatesReceived",!1),mb(this,"establishPromise",void 0),mb(this,"mutex",void 0),this.store=i,this.mutex=new gG("P2PConnection-mutex",i.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.statsFilter=Tc(this.peerConnection,TR("STATS_UPDATE_INTERVAL"),void 0,Sl()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}}).prototype,"connect",[DU],Object.getOwnPropertyDescriptor(rF.prototype,"connect"),rF.prototype),vP(rF.prototype,"stopSending",[DU],Object.getOwnPropertyDescriptor(rF.prototype,"stopSending"),rF.prototype),vP(rF.prototype,"receive",[DU],Object.getOwnPropertyDescriptor(rF.prototype,"receive"),rF.prototype),vP(rF.prototype,"stopReceiving",[DU],Object.getOwnPropertyDescriptor(rF.prototype,"stopReceiving"),rF.prototype),vP(rF.prototype,"muteRemote",[DU],Object.getOwnPropertyDescriptor(rF.prototype,"muteRemote"),rF.prototype),vP(rF.prototype,"unmuteRemote",[DU],Object.getOwnPropertyDescriptor(rF.prototype,"unmuteRemote"),rF.prototype),vP(rF.prototype,"muteLocal",[DU],Object.getOwnPropertyDescriptor(rF.prototype,"muteLocal"),rF.prototype),vP(rF.prototype,"unmuteLocal",[DU],Object.getOwnPropertyDescriptor(rF.prototype,"unmuteLocal"),rF.prototype),vP(rF.prototype,"close",[DU],Object.getOwnPropertyDescriptor(rF.prototype,"close"),rF.prototype),vP(rF.prototype,"updateEncoderConfig",[DU],Object.getOwnPropertyDescriptor(rF.prototype,"updateEncoderConfig"),rF.prototype),vP(rF.prototype,"updateSendParameters",[DU],Object.getOwnPropertyDescriptor(rF.prototype,"updateSendParameters"),rF.prototype),vP(rF.prototype,"replaceTrack",[DU],Object.getOwnPropertyDescriptor(rF.prototype,"replaceTrack"),rF.prototype),vP(rF.prototype,"getRemoteSSRC",[DU],Object.getOwnPropertyDescriptor(rF.prototype,"getRemoteSSRC"),rF.prototype),rF);function DU(e,t,i){let r=e[t];if("function"!=typeof r)throw Error("Cannot use mutex on object property.");return i.value=async function(){let e=this.mutex,i=await e.lock("Locking from P2PConnection.".concat(t));try{for(var n=arguments.length,o=Array(n),a=0;a<n;a++)o[a]=arguments[a];return await r.apply(this,o)}finally{i()}},i}let Dx={interceptLocalAudioFrame:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!T1.supportWebRTCEncodedTransform)return void TY.warning("browser not support audio encoded transform");if(CY.has(e)||!e.track)return;let i={track:e.track};if(Sa()){if(!e.createEncodedStreams)return void TY.warning("browser not support createEncodedStreams() API");let n=null;try{n=e.createEncodedStreams()}
1catch(e){return void TY.error("create audio-encoded-streams error",e&&e.message)}let o=new TransformStream({transform(n,o){i.controller||(i.controller=o),e.track&&e.track.id!==i.track.id&&(TY.debug("audio track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",r),i.track=e.track,i.track.addEventListener("ended",r));let a=t.metadata&&t.metadata();a?function(e,t){let{chunk:i,controller:r}=t,n=CH.METADATA;i.data=function(e,t,i){let r=i.byteLength,n=r+1+2,o=3+n,a=new DataView(new ArrayBuffer(e.byteLength+o));a.setUint8(0,71),a.setUint16(1,n),a.setUint8(3,t),a.setUint16(4,r);for(let e=0;e<r;e++)a.setUint8(6+e,i[e]);let s=new Uint8Array(a.buffer);return s.set(new Uint8Array(e),o),s.buffer}(i.data,n,e),r.enqueue(i)}(a,{sender:e,chunk:n,controller:o}):o.enqueue(n)}});n.readable.pipeThrough(o).pipeTo(n.writable)}else if(Ss()){if("undefined"==typeof RTCRtpScriptTransform)return void TY.warning("browser not support RTCRtpScriptTransform");let n=CW(),o=new MessageChannel;await new dQ(e=>n.onmessage=t=>{"registered"===t.data&&e(void 0)}),e.transform=new RTCRtpScriptTransform(n,{name:"audio-metadata-tx",port:o.port2},[o.port2]),await new dQ(e=>n.onmessage=t=>{"started"===t.data&&e(void 0)}),o.port1.onmessage=n=>{var a;if(n.data.transformed&&e.track&&(null==(a=e.track)?void 0:a.id)!==i.track.id)TY.debug("audio track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",r),i.track=e.track,i.track.addEventListener("ended",r);else if(n.data.getMetadata){let e=t.metadata&&t.metadata();e&&o.port1.postMessage({metadata:e})}},i.worker=n}function r(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",r)}let t=CY.get(e);if(t){CY.delete(e);try{var i,n;null==(i=t.controller)||i.terminate(),null==(n=t.worker)||n.terminate()}catch(e){TY.warning(e&&e.message)}}}CY.set(e,i),e.track.addEventListener("ended",r)},interceptRemoteAudioFrame:async function(e){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!T1.supportWebRTCEncodedTransform)return void TY.warning("browser not support audio encoded transform");if(ve.has(e))return;let r={track:e.track,onMetadata:i.onMetadata,onPts:i.onPts};if(Sa()&&!Sh()){if(!e.createEncodedStreams)return void TY.warning("browser not support createEncodedStreams() API");S_(f8.CHROME,87,116)||(i.enableTopn=!1);let o=null;try{o=e.createEncodedStreams()}catch(e){return void TY.error("create audio-encoded-streams error",e&&e.message)}let a=new TransformStream({transform(o,a){r.controller||(r.controller=a),e.track&&e.track.id!==r.track.id&&(TY.debug("audio track changed: ".concat(r.track.id," => ").concat(e.track.id)),r.track.removeEventListener("ended",n),r.track=e.track,r.track.addEventListener("ended",n)),i.enableTopn?function(e,i,r){var n;let o=CK(new DataView(i.data));if(!o)return r.enqueue(i);let a=e.track.id;vt.set(a,e.track);let s=null==(n=o.tlv.find(e=>e.tag===CH.AUDIO_LEVEL))?void 0:n.value,c=0;"number"==typeof s&&(c=127-s);let{selected:d,speaker:l}=function(e,t){let i=C2.get(e);if(i||(i=function(e){let t=new CZ;return C2.set(e,t),C3||(C3=new C1(TR("TOPN_SILENCE_THRESHOLD")||500)).on("ActiveSpeakerChanged",e=>{null!=e&&(C5=e)}),C3.addSpeakers([t]),t}(e)),C2.size<=3)return{selected:!0,speaker:i};if(!C3)throw Error("no active speaker detector");return C3.levelChanged(i.id,t),C4=C3.loudest.map(e=>e.id),C5&&!o5(C4).call(C4,C5)&&C4.length>=3&&C4.pop(),{selected:o5(C4).call(C4,i.id)||i.id===C5,speaker:i}}(e,Math.round(Math.pow(10,c/60)-1)),h=function(e,i,r){let n=C6.get(e)||new C9(e,i);return n.score=r,C6.set(e,n),function(e){if(C8.set(e,!0),!t)return t=Date.now();let i=Date.now();i-t>1e3&&(C8.get(e)?C8.set(e,!1):(C7(e),C8.delete(e)),t=i)}(e),n}(a,e.track,l.energyScore);h.addSample(d),h.active&&(i.data=o.frame.buffer,r.enqueue(i))}(e,o,a):i.enableMetadata||i.enablePts?function(e,t,i,r){let n,o=new DataView(e.data),a=o.getUint8(0);if(0!=(128&a)&&71!==a){let t=function(e){if(e.byteLength<=0)return[];let t=[],i=0;for(;i<e.byteLength;){let r=(128&e.getUint8(i))>>7,n=127&e.getUint8(i);if(!(r&&i+4<=e.byteLength)){i++;break}{let r=e.getUint32(i,!1),o=(0xfffc00&r)>>10,a=1023&r;
1t.push({pt:n,ts_offset:o,length:a,data:new Uint8Array}),i+=4}}let r=e.byteLength-i;for(let n of t){if(n.length>r)return console.warn("Broken red payload"),[];n.length>0&&(n.data=new Uint8Array(e.buffer,e.byteOffset+i,n.length),i+=n.length,r-=n.length)}if(r>0){let n={pt:t.length>0?t[t.length-1].pt:0,ts_offset:0,length:r,data:new Uint8Array(e.buffer,e.byteOffset+i,r)};t.push(n)}return t}(o);t.length>0&&(e.data=function(e){let t=0;for(let i=0;i<e.length;i++)t+=i<e.length-1?4:1,t+=e[i].length;let i=new Uint8Array(t),r=0;for(let t=0;t<e.length;t++)if(t<e.length-1){let n=(0x80000000|(127&e[t].pt)<<24|(262143&e[t].ts_offset)<<10|1023&e[t].length)>>>0;i[r++]=n>>24&255,i[r++]=n>>16&255,i[r++]=n>>8&255,i[r++]=255&n}else i[r++]=127&e[t].pt;for(let t of e)i.set(t.data,r),r+=t.length;return i}(t.map(e=>{let t=new Uint8Array(e.length);t.set(e.data);let i=CK(new DataView(t.buffer));return null!=i&&i.frame&&(e.data=null==i?void 0:i.frame),n=i,e})).buffer)}else(n=CK(o))&&(e.data=n.frame.buffer);if(t.enqueue(e),!n)return;let s=n.tlv.find(e=>e.tag===CH.METADATA);s&&i&&s.value instanceof Uint8Array&&i(s.value);let c=n.tlv.find(e=>e.tag===CH.AUDIO_64_BIT_PTS);c&&r&&c.value instanceof Uint8Array&&8==c.value.length&&r(new DataView(c.value.buffer).getBigUint64(0,!0))}(o,a,i.onMetadata,i.onPts):a.enqueue(o)}});o.readable.pipeThrough(a).pipeTo(o.writable)}else{if("undefined"==typeof RTCRtpScriptTransform)return void TY.warning("browser not support RTCRtpScriptTransform");let t=CW(),i=new MessageChannel;await new dQ(e=>t.onmessage=t=>{"registered"===t.data&&e(void 0)}),e.transform=new RTCRtpScriptTransform(t,{name:"audio-metadata-rx",port:i.port2},[i.port2]),await new dQ(e=>t.onmessage=t=>{"started"===t.data&&e(void 0)}),i.port1.onmessage=t=>{var i;t.data.transformed&&e.track&&(null==(i=e.track)?void 0:i.id)!==r.track.id?(TY.debug("audio track changed: ".concat(r.track.id," => ").concat(e.track.id)),r.track.removeEventListener("ended",n),r.track=e.track,r.track.addEventListener("ended",n)):t.data.metadata&&r.onMetadata?r.onMetadata(t.data.metadata):t.data.pts&&r.onPts&&r.onPts(t.data.pts)},r.worker=t}function n(){e.track.removeEventListener("ended",n),function(e){let t=ve.get(e);if(t){!function(e){let t=C2.get(e);t&&(C2.delete(e),C3&&(C3.removeSpeakers([t]),0===C2.size&&(C3.destroy(),C3=null)))}(e),C7(e.track.id),ve.delete(e);try{var i,r;null==(i=t.controller)||i.terminate(),null==(r=t.worker)||r.terminate()}catch(e){TY.warning(e&&e.message)}}}(e)}ve.set(e,r),e.track.addEventListener("ended",n)},interceptLocalVideoFrame:async function(e,t){if(!T1.supportWebRTCEncodedTransform)return void TY.warning("browser not support video encoded transform");if(vs.has(e)||!e.track)return;let i={track:e.track};if(Sa()){if(!e.createEncodedStreams)return void TY.warning("browser not support createEncodedStreams() API");let n=null;try{n=e.createEncodedStreams()}catch(e){return void TY.error("create video-encoded-streams error",e&&e.message)}let o=[];t.on("sei-to-send",e=>{o.push(e)});let a=new TransformStream({transform(t,n){i.controller||(i.controller=n),e.track&&e.track.id!==i.track.id&&(TY.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",r),i.track=e.track,i.track.addEventListener("ended",r));let a=va(new Uint8Array(t.data)),s=o.shift();if(s){let e=function(e,t,i){switch(i){case vi:return function(e,t){let i=vo(t),r=i.length,n=Math.floor(r/255),o=new Uint8Array(6+n+1+r+e.byteLength);o[0]=0,o[1]=0,o[2]=0,o[3]=1,o[4]=6,o[5]=101;let a=0;for(;a<n;)o[6+a]=255,a++;return o[6+a]=r%255,a++,o.set(i,6+a),o.set(new Uint8Array(e),6+a+r),o.buffer}(e,t);case vr:return function(e,t){let i=vo(t),r=i.length,n=Math.floor(r/255),o=new Uint8Array(7+n+1+r+1+e.byteLength);o[0]=0,o[1]=0,o[2]=0,o[3]=1,o[4]=78,o[5]=1,o[6]=101;let a=0;for(;a<n;)o[7+a]=255,a++;return o[7+a]=r%255,a++,o.set(i,7+a),o[7+(a+=r)]=128,a++,o.set(new Uint8Array(e),7+a),o.buffer}(e,t);default:return null}}(t.data,s,a);e&&(t.data=e)}n.enqueue(t)}});n.readable.pipeThrough(a).pipeTo(n.writable)}else{if(!Ss())return;{if("undefined"==typeof RTCRtpScriptTransform)return void TY.warning("browser not support RTCRtpScriptTransform");let n=CW(),o=new MessageChannel;await new dQ(e=>n.onmessage=t=>{"registered"===t.data&&e(void 0)}),e.transform=new RTCRtpScriptTransform(n,{name:"sei-tx",port:o.port2},[o.port2]),await new dQ(e=>n.onmessage=t=>{"started"===t.data&&e(void 0)}),t.on("sei-to-send",e=>{o.port1.postMessage({sei:e})}),o.port1.onmessage=t=>{var n;t.data.transformed&&e.track&&(null==(n=e.track)?void 0:n.id)!==i.track.id&&(TY.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",r),i.track=e.track,i.track.addEventListener("ended",r))},i.worker=n}}function r(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",r)}let t=vs.get(e);if(t){vs.delete(e);try{var i,n;null==(i=t.controller)||i.terminate(),null==(n=t.worker)||n.terminate()}catch(e){TY.warning(e&&e.message)}}}vs.set(e,i),e.track.addEventListener("ended",r)},interceptRemoteVideoFrame:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!T1.supportWebRTCEncodedTransform)return void TY.warning("browser not support video encoded transform");if(!e.track)return;if(vc.has(e)){let i=vc.get(e);return void(i&&(i.onSei=t.onSei))}let i={track:e.track,onSei:t.onSei};if(Sa()){if(!e.createEncodedStreams)return void TY.warning("browser not support createEncodedStreams() API");let n=null;try{n=e.createEncodedStreams()}
1catch(e){return void TY.error("create video-encoded-streams error",e&&e.message)}let o=new TransformStream({transform(n,o){if(i.controller||(i.controller=o),!i.firstFrameInfo){var a;let e=n.getMetadata()||{};i.firstFrameInfo=RB({type:n.type,rtpTimestamp:n.timestamp,payloadType:e.payloadType||0,ssrc:e.synchronizationSource||0,length:n.data.byteLength},"mimeType"in e?{mimeType:e.mimeType}:{}),null==(a=t.onFirstFrame)||a.call(t,i.firstFrameInfo)}e.track&&e.track.id!==i.track.id&&(TY.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",r),i.track=e.track,i.track.addEventListener("ended",r));let s=function(e,t){switch(t){case vi:return function(e){let t=new DataView(e.data),i=0;for(;i+4<e.data.byteLength;){if(0===t.getUint8(i+0)&&0===t.getUint8(i+1)&&0===t.getUint8(i+2)&&1===t.getUint8(i+3)&&6===t.getUint8(i+4)){let r=i+6,n=0,o=0;for(;255===(o=t.getUint8(r++));)n+=255;return n+=o,new Uint8Array(vn(e.data,r,n))}i++}return null}(e);case vr:return function(e){let t=new DataView(e.data),i=0;for(;i+5<e.data.byteLength;){if(0===t.getUint8(i+0)&&0===t.getUint8(i+1)&&0===t.getUint8(i+2)&&1===t.getUint8(i+3)&&78===t.getUint8(i+4)&&1===t.getUint8(i+5)&&101===t.getUint8(i+6)){let r=i+7,n=0,o=0;for(;255===(o=t.getUint8(r++));)n+=255;return n+=o,new Uint8Array(vn(e.data,r,n))}i++}return null}(e);default:return null}}(n,va(new Uint8Array(n.data)));s&&i.onSei&&i.onSei(s),o.enqueue(n)}});n.readable.pipeThrough(o).pipeTo(n.writable)}else if(Ss()){if("undefined"==typeof RTCRtpScriptTransform)return void TY.warning("browser not support RTCRtpScriptTransform");let n=CW(),o=new MessageChannel;await new dQ(e=>n.onmessage=t=>{"registered"===t.data&&e(void 0)}),e.transform=new RTCRtpScriptTransform(n,{name:"sei-rx",port:o.port2},[o.port2]),await new dQ(e=>n.onmessage=t=>{"started"===t.data&&e(void 0)}),o.port1.onmessage=n=>{var o,a;n.data.transformed&&e.track&&(null==(o=e.track)?void 0:o.id)!==i.track.id?(TY.debug("video track changed: ".concat(i.track.id," => ").concat(e.track.id)),i.track.removeEventListener("ended",r),i.track=e.track,i.track.addEventListener("ended",r)):n.data.sei&&i.onSei?i.onSei(n.data.sei):n.data.firstFrameInfo&&t.onFirstFrame&&(null==(a=t.onFirstFrame)||a.call(t,n.data.firstFrameInfo))},i.worker=n}function r(){var t,i;if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",r)}let n=vc.get(e);if(n){vc.delete(e);try{null==(t=n.controller)||t.terminate(),null==(i=n.worker)||i.terminate()}catch(e){TY.warning(e&&e.message)}}}vc.set(e,i),e.track.addEventListener("ended",r)}};function DV(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function DF(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?DV(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):DV(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let DB=(rB=class e extends ys{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get dtlsTransportState(){var e,t;return null!=(e=null==(t=this.peerConnection.getReceivers()[0])||null==(t=t.transport)?void 0:t.state)?e:null}get localCodecs(){return[...new Set(this.localCapabilities&&this.localCapabilities.send.videoCodecs.map(e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").filter(e=>{var t;return o5(t=Object.keys(TI)).call(t,e)}))]}getPreMedia(e){return this.preMediaMap.get(e)}isPreSub(){return this.preMediaMap.size>0}async updateRemoteRTPCapabilities(e,t){if(this.remoteCodecs=t,!this.remoteSDP)return void TY.debug("[NVConnectionExtension] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: ".concat(this.localCodecs,", codecs: ").concat(t));if(this.remoteSDP.updateRemoteCodec(e,t,this.store.codec)){let e=await this.peerConnection.createOffer(),t=this.logSDPExchange(e.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(e);let i=this.remoteSDP.toString();null==t||t(i),await this.peerConnection.setRemoteDescription({type:"answer",sdp:i})}else TY.debug("[NVConnectionExtension] updateRemoteRTPCapabilities no need to exchange SDP.")}async establish(){try{let t;this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});let i=await this.peerConnection.createOffer();if(!i.sdp)throw Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");let r=Il(i.sdp),n=await IC({filterRTX:!TR("USE_PUB_RTX")&&!TR("USE_SUB_RTX"),filterVideoFec:TR("FILTER_VIDEO_FEC"),filterAudioFec:TR("FILTER_AUDIO_FEC"),filterVideoCodec:TR("FILTER_VIDEO_CODEC"),unsupportedVideoUplinkCodec:TR("UNSUPPORTED_VIDEO_UPLINK_CODEC"),unsupportedVideoDownlinkCodec:TR("UNSUPPORTED_VIDEO_DOWNLINK_CODEC")},this.extension);if(this.localCapabilities=II(n),this.initialOffer=i,TR("ENABLE_SVC")&&"av1"==this.store.codec){var e;let t=await IR();t&&(this.supportAV1RtpSpec=!0,null==(e=n.send)||e.videoExtensions.push(t))}return i.sdp&&IP(i.sdp)&&(t=gS(n),It(t)),DF(DF({},r),{},{rtpCapabilities:t||n,offerSDP:i.sdp})}catch(e){throw new Sx(SU.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e){try{if(!this.initialOffer)throw Error("Cannot establish NVConnectionExtension without initial offer.");this.initialOffer.sdp&&IP(this.initialOffer.sdp)&&Ii(e.rtpCapabilities,this.localCapabilities),this.remoteSDP=new Aw(DF(DF({},e),{},{localCapabilities:this.localCapabilities}),this.supportAV1RtpSpec,!(!TR("ENABLE_PRE_SUB_WITH_PRE_PC")||!TR("PRE_USE_LOCAL_CODECS"))&&T5(this.store),!0),e.preallocation&&(this.isPreallocation=!0),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);let t=this.remoteSDP.toString(),i=IN(this.initialOffer.sdp,this.extension),r=this.logSDPExchange(i||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),null==r||r(t),await this.peerConnection.setRemoteDescription({type:"answer",sdp:t});let n=this.peerConnection.getTransceivers()[0];if(null!=n&&n.receiver&&this.tryBindTransportEvents(n.receiver),T5(this.store))if(e.preallocation&&TR("ENABLE_PRE_SUB_WITH_PRE_PC")){let e=TR("PRE_SUB_NUM"),{mids:t,preSSRCs:i}=this.remoteSDP.preloadRemoteMedia(e);await Iw(this.peerConnection,this.remoteSDP,this.extension),TY.debug("[".concat(this.store.clientId,"] [NVConnectionExtension] preload media, in pre pc,add preload ssrcs ").concat(i)),this.presetMedia(t,i)}else{let{preSSRCs:t=[]}=e,i=t.map(e=>e.ssrcMsg[0].ssrcId);if(0===t.length)return;let{mids:r}=this.remoteSDP.batchSend(t.map(e=>Object.assign({},e)));await Iw(this.peerConnection,this.remoteSDP,this.extension),TY.debug("[NVConnectionExtension.connect] preload media, after join, add preload ssrcs ".concat(i)),this.presetMedia(r,i)}}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"NVConnectionExtension.connect failed; ".concat(e.toString()))}}presetMedia(e,t){e.forEach((e,i)=>
1{this.peerConnection.getTransceivers().forEach(r=>{if(null!=r.mid&&e===r.mid&&r.receiver.track){let n,o=r.receiver.track;"video"===o.kind&&TR("ENABLE_PRE_RENDER")&&((n=new CD({trackId:"track-".concat(o.kind,"-unknown-").concat(this.store.clientId,"_").concat(gw(5,""))},!0)).updateVideoTrack(o),n.onFirstVideoFrameRender=()=>{var e;let r=this.preMediaMap.get(t[i]);r&&(r.firstVideoRender=Date.now()),null==(e=this.onFirstVideoRender)||e.call(this,t[i])},n.onVideoBufferReady=()=>{var e;null==(e=this.onFirstVideoBufferReady)||e.call(this,t[i])},n.play(this.store.sessionId||void 0)),this.preMediaMap.set(t[i],{mid:e,track:o,player:n,transceiver:r})}}),this.store.peerReceiver()})}checkDtlsParameters(e){return!!this.remoteSDP&&e.length>0&&this.remoteSDP.updateRemoteDtlsParameters(e)}async updateRemoteConnect(e){try{if(!this.remoteSDP)throw Error("Cannot call NVConnectionExtension.updateRemoteConnect before remote SDP created");let t=!1,{rtpCapabilities:i}=e;if([,t]=this.remoteSDP.updateRemoteRTPCapabilities(i),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0){let e=this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);t=t||e}let{preSSRCs:r=[]}=e,n=r.map(e=>e.ssrcMsg[0].ssrcId);if(!this.remoteSDP.checkPreloadSsrcs(n)){let e=[],t=[];if(Array.from(this.preMediaMap.entries()).every(i=>{let[r,{mid:n,player:o,track:a}]=i;return e.push(n),t.push(r),this.preMediaMap.delete(r),o&&o.destroy(),!0}),e.length>0&&(this.remoteSDP.stopSending(e),await Iw(this.peerConnection,this.remoteSDP,this.extension),TY.warn("[NVConnectionExtension.updateRemoteConnect] preload media, failed, del preload ssrcs ".concat(t)),T$.reportApiInvoke(this.store.sessionId,{name:S3.PRELOAD_MEDIA_FAILED,options:[r,t],tag:S5.TRACER}).onSuccess()),r.length>0){let{mids:e}=this.remoteSDP.batchSend(r.map(e=>Object.assign({},e)));await Iw(this.peerConnection,this.remoteSDP,this.extension),TY.debug("[NVConnectionExtension.updateRemoteConnect] preload media, after join, add preload ssrcs ".concat(n)),this.presetMedia(e,n)}}t?(await Iw(this.peerConnection,this.remoteSDP,this.extension),TY.debug("[NVConnectionExtension] updateRemoteConnect by exchanging SDP.")):TY.debug("[NVConnectionExtension] updateRemoteConnect no need to exchange SDP, because no need to update remote codecs (use local codecs)")}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"NVConnectionExtension.updateRemoteConnect failed; ".concat(e.toString()))}}send(e,t,i){var r=this;return fT(function*(){let n=yield fC(r.mutex.lock("From NVConnectionExtension.send"));try{let n;if(!r.remoteSDP)throw Error("Cannot call NVConnectionExtension.send before remote SDP created");let o=[],a=y7();e.forEach(e=>{let t=r.peerConnection.addTransceiver(e._mediaStreamTrack,DF({direction:"sendonly"},"video"===e.trackMediaType&&r.supportAV1RtpSpec&&a?{sendEncodings:[{scalabilityMode:a}]}:{}));o.push(t),e._updateRtpTransceiver(t)}),Sl()&&!0===TR("SIMULCAST")&&(yield fC(r.applySimulcastForFirefox(o,e)));let s=yield fC(r.peerConnection.createOffer()),c=r.remoteSDP.predictReceivingMids(e.length),d=r.mungSendOfferSDP(s.sdp,e,c),l=TO(d),h=c.map(e=>{let t=l.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw Error("Cannot extract ssrc from mediaDescription.");return Ih(t,TR("USE_PUB_RTX"))});try{n=yield h}catch(a){n=[],r.remoteSDP.receive(e,t,i,n);let o=r.remoteSDP.toString();throw yield fC(r.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield fC(r.peerConnection.setRemoteDescription({type:"answer",sdp:o})),yield fC(r.stopSending(c,!0)),a}r.remoteSDP.receive(e,t,i,n);let u=r.remoteSDP.toString(),p=r.logSDPExchange(d,"offer","local","send");return yield fC(r.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield fC(r.applySimulcastEncodings(o,e)),yield fC(r.applySendEncodings(o,e)),null==p||p(u),yield fC(r.peerConnection.setRemoteDescription({type:"answer",sdp:u})),o.map((e,t)=>{let i=c[t];return{localSSRC:h[t],id:i,transceiver:e}})}catch(e){throw e instanceof Sx?e:new Sx(SU.EXCHANGE_SDP_FAILED,"NVConnectionExtension.send failed; ".concat(e.toString()))}finally{n()}})()}async createDataChannels(e,t){try{if(!this.remoteSDP)throw Error("Cannot call NVConnectionExtension.createDataChannels before remote SDP created");let i=this.dataStreamChannelMap.get(e);if(i&&"open"===i.readyState)TY.debug("[NVConnectionExtension] Channels are already available and can be reused directly.");else{let t=this.currentDataChannelId<1023?this.currentDataChannelId++:this.recoveredDataChannelIds.shift();if("number"!=typeof t)throw Error("create DataChannel error, because cannot get dc id");
1(i=this.peerConnection.createDataChannel("datastream-channel",{id:t,negotiated:!0,ordered:!1,maxRetransmits:TR("DATASTREAM_MAX_RETRANSMITS")})).binaryType="arraybuffer",this.dataStreamChannelMap.set(e,i)}t.forEach(e=>{e._updateOriginDataChannel(i)});let{needExchangeSDP:r}=this.remoteSDP.sendDataChannel();if(r){let e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});let t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t),TY.debug("[NVConnectionExtension] createDataChannels by exchanging SDP.")}else TY.debug("[NVConnectionExtension] createDataChannels no need to exchange SDP.");return}catch(e){throw e instanceof Sx?e:new Sx(SU.EXCHANGE_SDP_FAILED,"NVConnectionExtension.createDataChannels failed; ".concat(e.toString()))}}async stopDataChannels(e){try{let t=this.dataStreamChannelMap.get(e);return t&&(t.id&&this.recoveredDataChannelIds.push(t.id),t.close()),void this.dataStreamChannelMap.delete(e)}catch(e){throw e instanceof Sx?e:new Sx(SU.DATACHANNEL_FAILED,"NVConnectionExtension.stopDataChannels failed; ".concat(e.toString()))}}async stopSending(e,t){let i=t?void 0:await this.mutex.lock("From NVConnectionExtension.stopSending");try{if(!this.remoteSDP)throw Error("Cannot call NVConnectionExtension.stopSending before remote SDP created");let t=this.peerConnection.getTransceivers().filter(t=>-1!==e.indexOf(t.mid));if(t.length!==e.length)throw Error("Transceivers' length doesn't match mids' length when trying to call NVConnectionExtension.stopSending.");t.map(e=>{var t;AG(this.id+e.mid,this),e.direction="inactive",null==(t=e.stop)||t.call(e)});let i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(i),this.remoteSDP.stopReceiving(e);let n=this.remoteSDP.toString();null==r||r(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"NVConnectionExtension.stopSending failed; ".concat(e.toString()))}finally{i&&i()}}async receive(e,t,i,r){try{if(!this.remoteSDP)throw Error("Cannot call NVConnectionExtension.receive ".concat(e," before remoteSDP created."));let{mid:n,needExchangeSDP:o}=this.remoteSDP.send(e,t,i,r);o&&(await Iw(this.peerConnection,this.remoteSDP,this.extension),TY.debug("[".concat(this.store.clientId,"] [NVConnectionExtension] receive ").concat(e," by exchanging SDP.")));let a=this.peerConnection.getTransceivers().find(e=>e.mid===n);if(!a)throw Error("Cannot get transceiver after setLocalDescription.");return{track:a.receiver.track,id:n,transceiver:a}}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"NVConnectionExtension.receive failed; ".concat(e.toString()))}}async batchReceive(e){try{if(!this.remoteSDP)throw Error("Cannot call NVConnectionExtension.batchReceive before remoteSDP created.");let{mids:t,needExchangeSDP:i}=this.remoteSDP.batchSend(e);return i&&(await Iw(this.peerConnection,this.remoteSDP,this.extension),TY.debug("[".concat(this.store.clientId,"] [NVConnectionExtension] batchReceive by exchanging SDP."))),t.map(e=>{let t=this.peerConnection.getTransceivers().find(t=>t.mid===e);if(!t)throw Error("Cannot get transceiver after setLocalDescription.");return{track:t.receiver.track,id:e,transceiver:t}})}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"NVConnectionExtension.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw Error("Cannot call NVConnectionExtension.stopReceiving before remote SDP created.");e.forEach(e=>{Array.from(this.preMediaMap.entries()).some(t=>{let[i,{mid:r,player:n}]=t;if(r===e)return this.preMediaMap.delete(i),n&&n.destroy(),!0})}),this.remoteSDP.stopSending(e);let t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});let r=await this.peerConnection.createAnswer();null==i||i(r.sdp||""),await this.peerConnection.setLocalDescription(r)}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"NVConnectionExtension stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){try{if(!this.remoteSDP)throw Error("Cannot call NVConnectionExtension.muteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.mute(e);let t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});let r=await this.peerConnection.createAnswer();null==i||i(r.sdp||""),await this.peerConnection.setLocalDescription(r)}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"NVConnectionExtension.muteRemote failed; ".concat(e.toString()))}}async unmuteRemote(e){try{if(!this.remoteSDP)throw Error("Cannot call NVConnectionExtension.unmuteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.unmute(e);let t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});let r=await this.peerConnection.createAnswer();null==i||i(r.sdp||""),await this.peerConnection.setLocalDescription(r)}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"NVConnectionExtension.unmuteRemote failed; ".concat(e.toString()))}}async muteLocal(e){try{if(!this.remoteSDP)throw Error("Cannot call NVConnectionExtension.muteLocal before remote SDP created.");let t=this.peerConnection.getTransceivers().filter(t=>
1t.mid&&-1!==e.indexOf(t.mid));if(t.length!==e.length)throw Error("Transceivers' length doesn't match mids' length.");t.map(e=>{e.direction="inactive"});let i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);let n=this.remoteSDP.toString();null==r||r(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"NVConnectionExtension.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw Error("Cannot call NVConnectionExtension.unmuteLocal before remote SDP created.");let t=this.peerConnection.getTransceivers().filter(t=>t.mid&&-1!==e.indexOf(t.mid));if(t.length!==e.length)throw Error("Transceivers' length doesn't match mids' length.");t.map(async(e,t)=>{e.direction="sendonly"});let i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec(e,this.remoteCodecs,this.store.codec);let n=this.remoteSDP.toString();null==r||r(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,"NVConnectionExtension.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return fT(function*(){let i=yield fC(t.mutex.lock("From NVConnectionExtension.restartICE"));try{if(!t.remoteSDP)throw Error("Cannot restartICE before remoteSDP created.");let i=T1.supportPCSetConfiguration,r=TR("FORCE_TURN_TCP")||t.forceTurn;if(e===yd.RELAY&&!i)return;if(i&&!r){let i=e===yd.RELAY?"relay":"all",r=t.peerConnection.getConfiguration();r.iceTransportPolicy!==i&&(TY.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(r.iceTransportPolicy,"] to [").concat(i,"]")),r.iceTransportPolicy=i,t.peerConnection.setConfiguration(r))}t.remoteSDP.updateCandidates(e);let n=yield fC(t.peerConnection.createOffer({iceRestart:!0}));if(!n.sdp)throw Error("Cannot restartICE because restart offer SDP does not exist.");let o=Il(n.sdp),{remoteIceParameters:a}=yield o.iceParameters;t.remoteSDP.restartICE(a);let s=t.remoteSDP.toString(),c=t.logSDPExchange(n.sdp||"","offer","local","restartICE");t.store.descriptionStart(),yield fC(t.peerConnection.setLocalDescription(n)),null==c||c(s),yield fC(t.peerConnection.setRemoteDescription({type:"answer",sdp:s}))}catch(e){TY.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{i()}})()}async extendCandidate(){if(!this.remoteSDP||this.isFirstConnected)return;let e=await this.mutex.lock("From NVConnectionExtension.extendCandidate");try{this.remoteSDP.updateCandidates(yd.TCP_RELAY),await Iw(this.peerConnection,this.remoteSDP,this.extension)}catch(e){TY.warning("[".concat(this.store.clientId,"] extend candidate failed, abort operation"),e)}finally{e()}}close(){var e;this.peerConnection.getTransceivers().forEach(e=>{AG(this.id+e.mid,this)}),this.preMediaMap.forEach(e=>{let{player:t}=e;t&&t.destroy()}),this.preMediaMap.clear(),this.peerConnection.close(),null==(e=this.onConnectionStateChange)||e.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear(),this.recoveredDataChannelIds=[],this.currentDataChannelId=1}getStats(){return DF(DF({},this.statsFilter.getStats()),{},{qualityLimitationReason:this.qualityLimitationReason})}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw Error("Cannot call NVConnectionExtension.updateEncoderConfig before remote SDP created.");let i=await this.peerConnection.createOffer(),r=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);let n=this.remoteSDP.toString(),o=this.logSDPExchange(r,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:r}),null==o||o(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new Sx(SU.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){let i=this.peerConnection.getTransceivers().filter(t=>t.mid===e);1===i.length&&(this.isVP8Simulcast(t)?Sl()||await this.applySimulcastEncodings(i,[t]):await this.applySendEncodings(i,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){let i=this.peerConnection.getTransceivers().find(e=>e.mid===t);i&&await i.sender.replaceTrack(e._mediaStreamTrack)}async getSelectedCandidatePair(){let e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){let{local:t,remote:i}=e[0].transport.iceTransport.getSelectedCandidatePair();return{local:DF(DF({},g2),{},{candidateType:t.type,protocol:t.protocol,address:t.address,port:t.port}),remote:DF(DF({},g2),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null==(e=this.onICEConnectionStateChange)||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;"connected"===this.peerConnection.connectionState&&(this.isFirstConnected=!0),null==(e=this.onConnectionStateChange)||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidateerror=e=>{if(e&&(e.errorCode||e.errorText)){var t;let i="code: ".concat(e.errorCode,", message: ").concat(e.errorText),r=e.port?"local: ".concat(e.port):"",n=y8(e.url||"");TY.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: NVConnectionExtension.onICECandidateError(").concat(i,"), url: ").concat(n||"",", host_c
1andidate:").concat(r)),null==(t=this.onICECandidateError)||t.call(this,i)}},this.peerConnection.onicegatheringstatechange=e=>{e&&e.target&&"iceGatheringState"in e.target&&TY.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] RTCPeerConnection.onicegatheringstatechange(").concat(e.target.iceGatheringState,")"))},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,TY.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,TY.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))},TR("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){let i={iceServers:[]},r=t.cloudProxyServer||"disabled";return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&(S9(t.turnServer.servers)?i.iceServers=t.turnServer.servers:TR("NEW_TURN_MODE")&&i.iceServers&&"disabled"===r?(TR("USE_TURN_SERVER_OF_GATEWAY")?t.turnServer.serversFromGateway&&i.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.serversFromGateway)):i.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.servers)),TR("NEW_FORCE_TURN")&&(i.iceTransportPolicy="relay")):"off"!==t.turnServer.mode&&(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),TR("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),TR("FORCE_TURN_TCP")?i.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach(e=>{e.forceturn&&(i.iceTransportPolicy="relay")}))),TR("ENABLE_ENCODED_TRANSFORM")&&T1.supportWebRTCEncodedTransform&&(i.encodedInsertableStreams=!0),i}static turnServerConfigToIceServers(e){let t=[];return e.forEach(e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(yQ(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!TR("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))}),t}static newTurnServerConfigToIceServers(e){let t=[];return e.forEach(e=>{let i=TR("NEW_TURN_MODE");1===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}):2===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}):3===i?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(yQ(e.turnServerURL),":443?transport=tcp")}):4===i&&(t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(yQ(e.turnServerURL),":443?transport=tcp")}))}),t}tryBindTransportEvents(e){let t=e.transport;if(t){this.transportEventReceiver=e,t.onstatechange=()=>{var e;null!=t&&t.state&&(null==(e=this.onDTLSTransportStateChange)||e.call(this,t.state))},t.onerror=e=>{var t;null==(t=this.onDTLSTransportError)||t.call(this,"error"in e?e.error:e)};let i=t.iceTransport;i&&(i.onstatechange=()=>{var e;let i=null==t?void 0:t.iceTransport.state;i&&(null==(e=this.onICETransportStateChange)||e.call(this,i))},i.getSelectedCandidatePair&&(i.onselectedcandidatepairchange=()=>{if(i.getSelectedCandidatePair()){let{local:e,remote:t}
1=i.getSelectedCandidatePair()||{};if(e&&t){let i=e.address+":"+e.port,r=t.address+":"+t.port;TY.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(y8(i)),", remote ").concat(JSON.stringify(y8(r))))}}}))}}tryUnbindTransportEvents(){this.transportEventReceiver&&this.transportEventReceiver.transport&&(this.transportEventReceiver.transport.onstatechange=null,this.transportEventReceiver.transport.onerror=null,this.transportEventReceiver.transport.iceTransport&&(this.transportEventReceiver.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var i,r,n,o,a;if(t||(t=this.peerConnection.getSenders().find(t=>t.track===e._mediaStreamTrack)),!t)return TY.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return TY.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!T1.supportSetRtpSenderParameters)return TY.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");let s={},c={};switch(e._optimizationMode){case"motion":s.degradationPreference="maintain-framerate";break;case"detail":s.degradationPreference="maintain-resolution";break;case"balanced":s.degradationPreference="balanced"}let d=y9(this.peerConnection,e._mediaStreamTrack),l=CS(e);if(AF(e)&&d&&t&&l&&this.getLocalVideoStats&&o5(i=["vp8","vp9"]).call(i,this.store.codec)){let i=s.degradationPreference||(o5(n=e._hints).call(n,RE.CUSTOM_TRACK)?TR("CUSTOM_ADAPTATION_DEFAULT_MODE"):"maintain-framerate");Aj(this.id+d.mid,l,this,i,e=>{t&&this.updateAdaptation(t,e)},this.getLocalVideoStats.bind(this))}if(e._encoderConfig){let{bitrateMax:t,frameRate:i,scaleResolutionDownBy:r}=e._encoderConfig;t&&(c.maxBitrate=1e3*t),(o5(o=e._hints).call(o,RE.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(i&&(c.maxFramerate=y0(i)),r&&r>=1&&(c.scaleResolutionDownBy=r))}let{maxFramerate:h}=TR("ENCODER_CONFIG_LIMIT");if(h&&"number"==typeof h&&(c.maxFramerate=c.maxFramerate?Math.min(c.maxFramerate,h):h),TR("DSCP_TYPE")&&SN()){let e=TR("DSCP_TYPE");o5(a=["very-low","low","medium","high"]).call(a,e)&&(c.networkPriority=e)}let u=t.getParameters(),p=null==(r=u.encodings)?void 0:r[0];Sl()&&!p&&(s.encodings=[c]),p&&Object.assign(p,c),Object.assign(u,s),TY.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(u.encodings))),await t.setParameters(u),await ID(this.store.codec,t,TR("SVC_MODE"))}async updateAdaptation(e,t){var i,r;if(!e)return TY.debug("[updateAdaptation] no rtpSender found");if(!T1.supportSetRtpSenderParameters)return TY.debug("[updateAdaptation] Browser not support set rtp-sender parameters");let n={},{bitrateMax:o,frameRate:a,scaleResolutionDownBy:s}=t;o&&(n.maxBitrate=1e3*o),a&&(n.maxFramerate=y0(a)),s&&s>=1&&o5(i=["vp8","vp9"]).call(i,this.store.codec)&&(n.scaleResolutionDownBy=s);let c=e.getParameters(),d=null==(r=c.encodings)?void 0:r[0];d&&Object.assign(d,n),Object.assign(c,{});try{await e.setParameters(c),TY.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(c.encodings)))}catch(t){"transport"in e&&(!e.transport||"connected"!==e.transport.state)?TY.debug("[updateAdaptation] rtpSender transport not connected}"):"connected"!==this.peerConnectionState?TY.debug("[updateAdaptation] peerConnection not connected}"):TY.debug("[updateAdaptation] updateRtpSenderEncodings failed",t)}}async applySendEncodings(e,t){try{if(!T1.supportSetRtpSenderParameters||e.length!==t.length)return;for(let i=0;i<e.length;i++){let r=e[i],n=t[i];n instanceof CP&&!this.isVP8Simulcast(n)&&await this.updateRtpSenderEncodings(n,r.sender)}}catch(e){TY.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,i){let r=TO(e);return t.forEach((e,t)=>{let n=i[t],o=r.mediaDescriptions.find(e=>e.attributes.mid===n);o&&(IE(o,e),IT(o,e,this.store.codec))}),Tw(r)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null==(t=this.onFirstAudioReceived)||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null==(t=this.onFirstVideoReceived)||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null==(t=this.onFirstAudioDecoded)||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var r;null==(r=this.onFirstVideoDecoded)||r.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null==(i=this.onSelectedLocalCandidateChanged)||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null==(i=this.onSelectedRemoteCandidateChanged)||i.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null==(t=this.onFirstVideoDecodedTimeout)||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let s=0;s<e.length;s++){var i,r,n,o,a;let c=e[s],d=t[s];if(d instanceof CP&&!o5(i=d._hints).call(i,RE.LOW_STREAM)&&null!=(r=d._encoderConfig)&&r.bitrateMax&&(null==(n=d._encoderConfig)?void 0:n.bitrateMax)>
1200&&null!=(o=d._scalabilityMode)&&o.numSpatialLayers&&(null==(a=d._scalabilityMode)?void 0:a.numSpatialLayers)>1&&"vp8"===this.store.codec){let e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];let i=c.sender.getParameters();await c.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!Sl()&&e.length===t.length)for(let i=0;i<e.length;i++){let r=t[i];if(r instanceof CP&&this.isVP8Simulcast(r)){let t=e[i],n={},o={high:1e3*(r._encoderConfig.bitrateMax-50),medium:5e4};n.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:o.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:o.medium,scaleResolutionDownBy:4}];let a=t.sender.getParameters();await t.sender.setParameters(Object.assign(a,n))}}}isVP8Simulcast(e){var t,i,r,n,o;return!!(e instanceof CP&&TR("SIMULCAST")&&"vp8"===this.store.codec&&!o5(t=e._hints).call(t,RE.LOW_STREAM)&&null!=(i=e._encoderConfig)&&i.bitrateMax&&(null==(r=e._encoderConfig)?void 0:r.bitrateMax)>200&&null!=(n=e._scalabilityMode)&&n.numSpatialLayers&&(null==(o=e._scalabilityMode)?void 0:o.numSpatialLayers)>1)}logSDPExchange(e,t,i,r){if(TR("SDP_LOGGING"))return TY.upload("[".concat(this.store.clientId,"] exchanging ").concat(i," ").concat(t," SDP during NVConnectionExtension.").concat(r,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",r)}:void 0}async getRemoteSSRC(e){if(!this.remoteSDP)return;let t=this.remoteSDP.getSSRC(e);return t&&0!==t.length?t[0].ssrcId:void 0}setConfiguration(t){if(T1.supportPCSetConfiguration){let i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}t.isPreallocation&&(this.isPreallocation=!0)}constructor(e,t,i){super(e,t),mb(this,"id",gw(5,"connection-")),mb(this,"store",void 0),mb(this,"peerConnection",void 0),mb(this,"forceTurn",!1),mb(this,"remoteSDP",void 0),mb(this,"initialOffer",void 0),mb(this,"transportEventReceiver",void 0),mb(this,"statsFilter",void 0),mb(this,"extension",{useXR:TR("USE_XR")}),mb(this,"localCapabilities",void 0),mb(this,"remoteCodecs",void 0),mb(this,"localCandidateCount",0),mb(this,"allCandidatesReceived",!1),mb(this,"isPreallocation",!1),mb(this,"preMediaMap",new Map),mb(this,"dataStreamChannelMap",new Map),mb(this,"establishPromise",void 0),mb(this,"recoveredDataChannelIds",[]),mb(this,"currentDataChannelId",1),mb(this,"supportAV1RtpSpec",!1),mb(this,"mutex",void 0),mb(this,"qualityLimitationReason",Te.NONE),mb(this,"isFirstConnected",!1),this.store=t,this.forceTurn=Aq(e),this.mutex=new gG("NVConnectionExtension-mutex",t.clientId),this.peerConnection=i,this.isFirstConnected=!1,this.statsFilter=Tc(this.peerConnection,TR("STATS_UPDATE_INTERVAL"),void 0,Sl()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,e.isPreallocation&&(this.isPreallocation=!0),this.establishPromise=this.establish()}},vP(rB.prototype,"updateRemoteRTPCapabilities",[Dj],Object.getOwnPropertyDescriptor(rB.prototype,"updateRemoteRTPCapabilities"),rB.prototype),vP(rB.prototype,"connect",[Dj],Object.getOwnPropertyDescriptor(rB.prototype,"connect"),rB.prototype),vP(rB.prototype,"updateRemoteConnect",[Dj],Object.getOwnPropertyDescriptor(rB.prototype,"updateRemoteConnect"),rB.prototype),vP(rB.prototype,"createDataChannels",[Dj],Object.getOwnPropertyDescriptor(rB.prototype,"createDataChannels"),rB.prototype),vP(rB.prototype,"receive",[Dj],Object.getOwnPropertyDescriptor(rB.prototype,"receive"),rB.prototype),vP(rB.prototype,"batchReceive",[Dj],Object.getOwnPropertyDescriptor(rB.prototype,"batchReceive"),rB.prototype),vP(rB.prototype,"stopReceiving",[Dj],Object.getOwnPropertyDescriptor(rB.prototype,"stopReceiving"),rB.prototype),vP(rB.prototype,"muteRemote",[Dj],Object.getOwnPropertyDescriptor(rB.prototype,"muteRemote"),rB.prototype),vP(rB.prototype,"unmuteRemote",[Dj],Object.getOwnPropertyDescriptor(rB.prototype,"unmuteRemote"),rB.prototype),vP(rB.prototype,"muteLocal",[Dj],Object.getOwnPropertyDescriptor(rB.prototype,"muteLocal"),rB.prototype),vP(rB.prototype,"unmuteLocal",[Dj],Object.getOwnPropertyDescriptor(rB.prototype,"unmuteLocal"),rB.prototype),vP(rB.prototype,"close",[Dj],Object.getOwnPropertyDescriptor(rB.prototype,"close"),rB.prototype),vP(rB.prototype,"updateEncoderConfig",[Dj],Object.getOwnPropertyDescriptor(rB.prototype,"updateEncoderConfig"),rB.prototype),vP(rB.prototype,"updateSendParameters",[Dj],Object.getOwnPropertyDescriptor(rB.prototype,"updateSendParameters"),rB.prototype),vP(rB.prototype,"replaceTrack",[Dj],Object.getOwnPropertyDescriptor(rB.prototype,"replaceTrack"),rB.prototype),vP(rB.prototype,"updateAdaptation",[Dj],Object.getOwnPropertyDescriptor(rB.prototype,"updateAdaptation"),rB.prototype),vP(rB.prototype,"getRemoteSSRC",[Dj],Object.getOwnPropertyDescriptor(rB.prototype,"getRemoteSSRC"),rB.prototype),rB);function Dj(e,t,i){let r=e[t];if("function"!=typeof r)throw Error("Cannot use mutex on object property.");return i.value=async function(){let e=this.mutex,i=await e.lock("From NVConnectionExtension.".concat(t));try{for(var n=arguments.length,o=Array(n),a=0;a<n;a++)o[a]=arguments[a];return await r.apply(this,o)}finally{i()}},i}function DG(e){var t,i,r,n=2;for("undefined"!=typeof Symbol&&(i=fy,r=Symbol.iterator);n--;){if(i&&null!=(t=e[i]))return t.call(e);
1if(r&&null!=(t=e[r]))return new DW(t.call(e));i="@@asyncIterator",r="@@iterator"}throw TypeError("Object is not async iterable")}function DW(e){function t(e){if(Object(e)!==e)return dQ.reject(TypeError(e+" is not an object."));var t=e.done;return dQ.resolve(e.value).then(function(e){return{value:e,done:t}})}return(DW=function(e){this.s=e,this.n=e.next}).prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var i=this.s.return;return void 0===i?dQ.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?dQ.reject(e):t(i.apply(this.s,arguments))}},new DW(e)}let DH=(vP((rj=class e extends ys{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get localCodecs(){return this._p2pConnection.localCodecs}getPreMedia(e){var t;return null==(t=this._p2pConnection)?void 0:t.getPreMedia(e)}isPreSub(){var e,t;return null!=(e=null==(t=this._p2pConnection)?void 0:t.isPreSub())&&e}async establish(){return await this._p2pConnection.establish()}getP2PConnectionParams(){return this._p2pConnection.establishPromise}updateRtpSenderEncodings(e){return this._p2pConnection.updateRtpSenderEncodings(e)}async connect(e){return this.cname=e.cname,await this._p2pConnection.connect(e),await new dQ((t,i)=>{let r=setTimeout(()=>{this.closeSignal(),i(new T0(SU.DATACHANNEL_CONNECTION_TIMEOUT,"Datachannel connection timed out, candidates: ".concat(JSON.stringify(e.candidates))))},TR("DC_CONNECTION_TIMEOUT"));this.dataChannel.onopen=()=>{if("open"===this.dataChannel.readyState)return clearTimeout(r),void t()},this.dataChannel.onerror=e=>{this.closeSignal(),i(e)},this.dataChannel.addEventListener("close",()=>{i(new T0(SU.DATACHANNEL_CONNECTION_TIMEOUT))})}),{transmitter:this.dataChannel,close:this.closeSignal.bind(this)}}async updateRemoteRTPCapabilities(e,t){return this._p2pConnection.updateRemoteRTPCapabilities(e,t)}send(e,t,i){var r=this;return fT(function*(){let n=yield fC(r.mutex.lock("From DataChannelConnection.send"));try{return yield*fv(DG(r._p2pConnection.send(e,t,i)))}finally{n()}})()}async stopSending(e,t){return this._p2pConnection.stopSending(e,t)}async createDataChannels(e,t){return this._p2pConnection.createDataChannels(e,t)}
1async stopDataChannels(e){return this._p2pConnection.stopDataChannels(e)}async receive(e,t,i,r){return this._nvMedia?(TY.debug("[DataChannelConnection] receive ".concat(e," by DataChannel.")),await this._nvMedia.reveiveByRTCMedia(e,t,this.cname)):(TY.debug("[DataChannelConnection] receive ".concat(e," by WebRTC.")),await this._p2pConnection.receive(e,t,i,r))}async batchReceive(e){return[...await this._p2pConnection.batchReceive(e)]}async stopReceiving(e){return await this._p2pConnection.stopReceiving(e)}async muteRemote(e){return await this._p2pConnection.muteRemote(e)}async unmuteRemote(e){return await this._p2pConnection.unmuteRemote(e)}async muteLocal(e){return await this._p2pConnection.muteLocal(e)}async unmuteLocal(e){return await this._p2pConnection.unmuteLocal(e)}restartICE(e){var t=this;return fT(function*(){return yield*fv(DG(t._p2pConnection.restartICE(e)))})()}close(){var e;null==(e=this._nvMedia)||e.close(),this._p2pConnection.close(),this.unbindConnectionEvents(this._p2pConnection)}getStats(){return this._p2pConnection.getStats()}getRemoteVideoIsReady(e){return this._p2pConnection.getRemoteVideoIsReady(e)}updateRemoteConnect(e){var t;return null==(t=this._nvMedia)||t.setRemoteRtpCapabilities(e),this._p2pConnection.updateRemoteConnect(e)}async updateEncoderConfig(e,t){return await this._p2pConnection.updateEncoderConfig(e,t)}async updateSendParameters(e,t){return await this._p2pConnection.updateSendParameters(e,t)}setStatsRemoteVideoIsReady(e,t){this._p2pConnection.setStatsRemoteVideoIsReady(e,t)}async replaceTrack(e,t){return await this._p2pConnection.replaceTrack(e,t)}async getRemoteSSRC(e){return this._p2pConnection.getRemoteSSRC(e)}logSDPExchange(e,t,i,r){if(TR("SDP_LOGGING"))return TY.upload("exchanging ".concat(i," ").concat(t," SDP during DataChannelConnection.").concat(r,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",r)}:void 0}static resolvePCConfiguration(t){let i={iceServers:[]};return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(S9(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),TR("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),TR("FORCE_TURN_TCP")?i.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach(e=>{e.forceturn&&(i.iceTransportPolicy="relay")}))),TR("ENABLE_ENCODED_TRANSFORM")&&T1.supportWebRTCEncodedTransform&&(i.encodedInsertableStreams=!0),i}static turnServerConfigToIceServers(e){let t=[];return e.forEach(e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(yQ(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!TR("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))}),t}bindPCEvents(){this._p2pConnection.onICEConnectionStateChange=e=>{var t;return null==(t=this.onICEConnectionStateChange)?void 0:t.call(this,e)},this._p2pConnection.onConnectionStateChange=e=>{var t;return null==(t=this.onConnectionStateChange)?void 0:t.call(this,e)},this._p2pConnection.onDTLSTransportStateChange=e=>{var t;return null==(t=this.onDTLSTransportStateChange)?void 0:t.call(this,e)},this._p2pConnection.onDTLSTransportError=e=>{var t;return null==(t=this.onDTLSTransportError)?void 0:t.call(this,e)},this._p2pConnection.onICETransportStateChange=e=>{var t;return null==(t=this.onICETransportStateChange)?void 0:t.call(this,e)},this._p2pConnection.onFirstAudioReceived=e=>{var t;return null==(t=this.onFirstAudioReceived)?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoReceived=e=>{var t;return null==(t=this.onFirstVideoReceived)?void 0:t.call(this,e)},this._p2pConnection.onFirstAudioDecoded=e=>{var t;return null==(t=this.onFirstAudioDecoded)?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoRender=e=>{var t;return null==(t=this.onFirstVideoRender)?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoBufferReady=e=>{var t;return null==(t=this.onFirstVideoBufferReady)?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoDecoded=(e,t,i)=>{var r;return null==(r=this.onFirstVideoDecoded)?void 0:r.call(this,e,t,i)},this._p2pConnection.onFirstVideoDecodedTimeout=e=>{var t;return null==(t=this.onFirstVideoDecodedTimeout)?void 0:t.call(this,e)},this._p2pConnection.onSelectedLocalCandidateChanged=(e,t)=>{var i;return null==(i=this.onSelectedLocalCandidateChanged)?void 0:i.call(this,e,t)},this._p2pConnection.onSelectedRemoteCandidateChanged=(e,t)=>{var i;return null==(i=this.onSelectedRemoteCandidateChanged)?void 0:i.call(this,e,t)}}closeSignal(){this.dataChannel.close(),this.peerConnection.close()}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0}setConfiguration(e){this._p2pConnection.setConfiguration(e)}constructor(t,i){super(t,i),mb(this,"name","DataChannelConnection"),mb(this,"store",void 0),mb(this,"peerConnection",void 0),mb(this,"cname",void 0),mb(this,"mutex",new gG("DataChannelConnection-mutex")),mb(this,"dataChannel",void 0),mb(this,"_p2pConnection",void 0),mb(this,"establishPromise",void 0),mb(this,"_nvMedia",void 0),this.store=i,this.store.dcId=this.store.dcId+1,this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}
1),this.dataChannel=this.peerConnection.createDataChannel("agora-signal",{ordered:!1,maxPacketLifeTime:50}),this.dataChannel.binaryType="arraybuffer",this._p2pConnection=new DB(t,i,this.peerConnection),this.bindPCEvents(),this.establishPromise=this._p2pConnection.establishPromise}}).prototype,"connect",[DK],Object.getOwnPropertyDescriptor(rj.prototype,"connect"),rj.prototype),vP(rj.prototype,"updateRemoteRTPCapabilities",[DK],Object.getOwnPropertyDescriptor(rj.prototype,"updateRemoteRTPCapabilities"),rj.prototype),vP(rj.prototype,"createDataChannels",[DK],Object.getOwnPropertyDescriptor(rj.prototype,"createDataChannels"),rj.prototype),vP(rj.prototype,"receive",[DK],Object.getOwnPropertyDescriptor(rj.prototype,"receive"),rj.prototype),vP(rj.prototype,"stopReceiving",[DK],Object.getOwnPropertyDescriptor(rj.prototype,"stopReceiving"),rj.prototype),vP(rj.prototype,"muteRemote",[DK],Object.getOwnPropertyDescriptor(rj.prototype,"muteRemote"),rj.prototype),vP(rj.prototype,"unmuteRemote",[DK],Object.getOwnPropertyDescriptor(rj.prototype,"unmuteRemote"),rj.prototype),vP(rj.prototype,"muteLocal",[DK],Object.getOwnPropertyDescriptor(rj.prototype,"muteLocal"),rj.prototype),vP(rj.prototype,"unmuteLocal",[DK],Object.getOwnPropertyDescriptor(rj.prototype,"unmuteLocal"),rj.prototype),vP(rj.prototype,"close",[DK],Object.getOwnPropertyDescriptor(rj.prototype,"close"),rj.prototype),vP(rj.prototype,"updateEncoderConfig",[DK],Object.getOwnPropertyDescriptor(rj.prototype,"updateEncoderConfig"),rj.prototype),vP(rj.prototype,"updateSendParameters",[DK],Object.getOwnPropertyDescriptor(rj.prototype,"updateSendParameters"),rj.prototype),vP(rj.prototype,"replaceTrack",[DK],Object.getOwnPropertyDescriptor(rj.prototype,"replaceTrack"),rj.prototype),vP(rj.prototype,"getRemoteSSRC",[DK],Object.getOwnPropertyDescriptor(rj.prototype,"getRemoteSSRC"),rj.prototype),rj);function DK(e,t,i){let r=e[t];if("function"!=typeof r)throw Error("Cannot use mutex on object property.");return i.value=async function(){let e=this.mutex,i=await e.lock("From DataChannelConnection.".concat(t));try{for(var n=arguments.length,o=Array(n),a=0;a<n;a++)o[a]=arguments[a];return await r.apply(this,o)}finally{i()}},i}function DY(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}class Dz extends S0{get url(){return this._url?this._url:null}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){var t;o5(t=["tryNext","recover"]).call(t,e)&&this.resetReconnectCount(e),this._reconnectMode=e}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(yg.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(yg.CONNECTED):"closed"===this._state?this.emit(yg.CLOSED):"failed"===this._state&&this.emit(yg.FAILED))}resetReconnectCount(e){TY.debug("".concat(this._name," reset reconnect count, reason: ").concat(e)),this._reconnectCount=0}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this._reconnectInterrupter&&this._reconnectInterrupter(),this._transmitter){this._transmitter.onclose=null,this._transmitter.onopen=null,this._transmitter.onmessage=null;let e=this._transmitter;t?setTimeout(()=>e.close(),500):e.close(),this._transmitter=void 0}this.state=e?"failed":"closed",this._closeEstablishingTransmitter&&this._closeEstablishingTransmitter()}reconnect(e,t){var i;if(!this._transmitter)return void TY.warning("[".concat(this._name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),TY.debug("[".concat(this._name,"] reconnect is triggered initiative")),"number"==typeof this._joinChannelServiceRecordIndex&&(null==(i=this._store)||i.recordJoinChannelService({status:"error",errors:[Error(t)]},this._joinChannelServiceRecordIndex));let r=this._transmitter.onclose;this._transmitter.onclose=null,this._transmitter.close(),r&&r.bind(this._transmitter)({code:9999,reason:t})}getInflateData(){let e=this._inflateLength,t=this._deflateLength;return this.clearInflateData(),{inflateLength:e,deflateLength:t}}setInflateData(e){this._deflateLength=this._deflateLength+e.originLength,this._inflateLength=this._inflateLength+e.compressedLength}clearInflateData(){this._inflateLength=0,this._deflateLength=0}constructor(e,t,i,r){super(),mb(this,"connectionID",0),mb(this,"currentURLIndex",0),mb(this,"reconnectReason",void 0),mb(this,"_reconnectMode","tryNext"),mb(this,"_initMutex",void 0),mb(this,"_name",void 0),mb(this,"_state","closed"),mb(this,"_reconnectInterrupter",void 0),mb(this,"_url",void 0),mb(this,"_retryConfig",void 0),mb(this,"_reconnectCount",0),mb(this,"_forceCloseTimeout",5e3),mb(this,"_onlineReconnectListener",void 0),mb(this,"_closeEstablishingTransmitter",()=>{}),mb(this,"_store",void 0),mb(this,"_joinChannelServiceRecordIndex",void 0),mb(this,"_transmitter",void 0),mb(this,"_useCompress",void 0),mb(this,"_inflateLength",0),mb(this,"_deflateLength",0),this._store=r,this._name=e,this._retryConfig=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
1t%2?DY(Object(i),!0).forEach(function(t){mb(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):DY(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}({},t),this._useCompress=i}}let Dq=((ta={})[ta.Default=0]="Default",ta[ta.Ack=1]="Ack",ta);class DX{packetize(e,t){return{type:Dq.Default,version:this.version,packetNumber:t,payload:e}}serialize(e){switch(e.type){case Dq.Default:{let t,i=new ArrayBuffer((t="string"==typeof e.payload?(new TextEncoder).encode(e.payload):e.payload).length+15),r=new DataView(i);return r.setUint16(0,e.version),r.setUint8(2,e.type),r.setUint32(3,e.packetNumber),Sz(r,7,BigInt(e.sendTs)),new Uint8Array(r.buffer).set(t,15),i}case Dq.Ack:{let t=new ArrayBuffer(16),i=new DataView(t);return i.setUint16(0,e.version),i.setUint8(2,e.type),i.setUint32(3,e.maxAckPacketNumber),i.setUint8(7,e.shift),Sz(i,8,BigInt(e.ackSendTs)),t}}}deserialize(e){let t=new DataView(e),i=t.getUint16(0),r=t.getUint8(2);switch(r){case Dq.Default:{let n=t.getUint32(3),o=SY(t,7),a=new Uint8Array(e.slice(15));return{version:i,type:r,packetNumber:n,sendTs:Number(o),payload:a}}case Dq.Ack:{let e=t.getUint32(3);return{version:i,type:r,maxAckPacketNumber:e,shift:t.getUint8(7),ackSendTs:Number(SY(t,8))}}default:throw TY.error("[".concat(this.ID,"] Unrecognized packet type ").concat(r)),Error("Unrecognized packet type ".concat(r))}}sendMessage(e){TR("DC_DEBUG_LOG")&&"string"==typeof e&&TY.debug("[".concat(this.ID,"] sending message packet"),JSON.parse(e));let t=this.packetize(e,this.packetNumber);this.packetNumber=0xffffffff===this.packetNumber?1:this.packetNumber+1;let i=this.calculateRTO(t),r=window.setTimeout(()=>{this.resendMessage(t)},i);this.timeoutMap.set(t.packetNumber,r),this.sendPacket(t)}onData(e){let t=this.deserialize(e);t.type===Dq.Default?this.ack(t):t.type===Dq.Ack&&(this.updateRTT(t,Math.round(performance.now())),this.clearRTO(t))}close(){this.rtt=this.initialRTT,this.packetNumber=1,Array.from(this.timeoutMap.entries()).forEach(e=>{let[t,i]=e;window.clearTimeout(i)}),this.timeoutMap=new Map,this.rtoRatioMap=new Map,this.unorderedPacketQueue=[],this.batchAckPacketQueue=[],this.lastOrderedPacketNumber=0,void 0!==this.batchAckTimer&&window.clearTimeout(this.batchAckTimer)}resendMessage(e){let t=this.calculateRTO(e),i=window.setTimeout(()=>{TR("DC_DEBUG_LOG")&&"string"==typeof e.payload&&TY.debug("[".concat(this.ID,"] resending message packet"),JSON.parse(e.payload),"timeout: ".concat(t)),this.resendMessage(e)},t);this.timeoutMap.set(e.packetNumber,i),this.sendPacket(e)}calculateRTO(e){let t=this.rtoRatioMap.get(e.packetNumber);if(void 0===t)return this.rtoRatioMap.set(e.packetNumber,1),this.initialRTO;{let i=9*this.rtt/8*t;return this.rtoRatioMap.set(e.packetNumber,t+1),i>this.maxRTO?this.maxRTO:i}}updateRTT(e,t){let i=e.ackSendTs;this.rtt=this.rtt*(7/8)+(t-i-this.rtt)/8}ack(e){if(e.packetNumber===this.lastOrderedPacketNumber+1)for(this.batchAckPacketQueue.length>=this.maxBatchAckCount&&this.batchAck(),this.batchAckTimer?this.batchAckPacketQueue.push(e):(this.batchAckPacketQueue.push(e),this.batchAckTimer=window.setTimeout(()=>{this.batchAck()},this.rtt/8)),this.lastOrderedPacketNumber+=1,this.receiveImpl(e.payload);;){let e=this.unorderedPacketQueue[0];if(!e){this.unorderedPacketQueue.shift();break}this.batchAckTimer&&this.batchAck(),this.receiveImpl(e.payload),this.unorderedPacketQueue.shift(),this.lastOrderedPacketNumber+=1}else if(e.packetNumber<=this.lastOrderedPacketNumber){let t={ackSendTs:e.sendTs,maxAckPacketNumber:e.packetNumber,shift:0,type:Dq.Ack,version:this.version};TR("DC_DEBUG_LOG")&&TY.debug("[".concat(this.ID,"] sending ack packet"),t,"packetNumber: ".concat(e.packetNumber)),this.sendPacket(t)}else if(e.packetNumber>this.lastOrderedPacketNumber){this.unorderedPacketQueue[e.packetNumber-this.lastOrderedPacketNumber-2]=e;let t={ackSendTs:e.sendTs,maxAckPacketNumber:e.packetNumber,shift:0,type:Dq.Ack,version:this.version};TR("DC_DEBUG_LOG")&&TY.debug("[".concat(this.ID,"] sending ack packet"),t,"packetNumber: ".concat(e.packetNumber)),this.sendPacket(t)}}batchAck(){window.clearTimeout(this.batchAckTimer),this.batchAckTimer=void 0;let e={ackSendTs:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].sendTs,maxAckPacketNumber:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].packetNumber,shift:this.batchAckPacketQueue.length-1,type:Dq.Ack,version:this.version};TR("DC_DEBUG_LOG")&&TY.debug("[".concat(this.ID,"] sending batch ack packet"),e,"shift: ".concat(this.batchAckPacketQueue.length-1)),this.sendPacket(e),this.batchAckPacketQueue=[]}sendPacket(e){e.type===Dq.Default&&(e.sendTs=Math.round(performance.now()));let t=this.serialize(e);this.sendImpl(t)}clearRTO(e){for(let t=e.maxAckPacketNumber-e.shift;t<=e.maxAckPacketNumber;t++){let e=this.timeoutMap.get(t);void 0!==e&&window.clearTimeout(e),this.timeoutMap.delete(t),this.rtoRatioMap.delete(t)}}constructor(e,t,i){mb(this,"version",1),mb(this,"initialRTO",void 0),mb(this,"maxBatchAckCount",void 0),mb(this,"maxRTO",void 0),mb(this,"initialRTT",void 0),mb(this,"ID",void 0),mb(this,"rtt",void 0),mb(this,"packetNumber",1),mb(this,"rtoRatioMap",new Map),mb(this,"timeoutMap",new Map),mb(this,"unorderedPacketQueue",[]),mb(this,"batchAckPacketQueue",[]),mb(this,"lastOrderedPacketNumber",0),mb(this,"batchAckTimer",void 0),mb(this,"sendImpl",void 0),mb(this,"receiveImpl",void 0),this.sendImpl=e,this.receiveImpl=t,this.ID=gw(7,"transmitter-"),this.initialRTO=void 0!==(null==i?void 0:i.initialRTO)?i.initialRTO:TR("TRANSMITTER_INITIAL_RTO"),this.initialRTT=void 0!==(null==i?void 0:i.initialRTT)?i.initialRTT:TR("TRANSMITTER_INITIAL_RTT"),this.rtt=void 0!==(null==i?void 0:i.initialRTT)?i.initialRTT:TR("TRANSMITTER_INITIAL_RTT"),this.maxBatchAckCount=void 0!==(null==i?void 0:i.maxBatchAckCount)?i.maxBatchAckCount:TR("TRANSMITTER_MAX_BATCH_ACK_COUNT"),this.maxRTO=void 0!==(null==i?void 0:i.maxRTO)?i.maxRTO:TR("TRANSMITTER_MAX_RTO")}}class DJ extends Dz{getConnection(){if(this._reliableTransmission)return this._reliableTransmission}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;this._forceCloseTimeout=t;let i=(t,i)=>{this._addresses=e,this.currentURLIndex=this._addresses.findIndex(e=>e.fingerprint||TR("FINGERPRINT"));let r=this._addresses[this.currentURLIndex];this.state="connecting",this.createTransmitterConnection(r).then(t).cat
1ch(i),this.once(yg.CLOSED,()=>i(new T0(SU.WS_DISCONNECT))),this.once(yg.CONNECTED,()=>t())};return this._initMutex.lock().then(e=>new dQ((e,t)=>{i(e,t)}).then(()=>{e()}).catch(()=>{e()}))}async sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this._transmitter||!this._reliableTransmission)throw new T0(SU.WS_ABORT,"datachannel is not ready");try{t||(e=JSON.stringify(e));let i=this._textEncoder.encode(e),r=NU(i,{raw:!0});this._reliableTransmission.sendMessage(r)}catch(e){throw new T0(SU.WS_ERR,"send datachannel signal message error"+e.toString())}}unbindDcCloseEventListener(){this._transmitter&&(this._transmitter.onclose=null)}sendMessageWithJSON(e){let t=JSON.stringify(e);return{compressed:t,compressedLength:t.length,origin:e}}sendMessageWithUint8Array(e){return{compressed:e,compressedLength:e.byteLength,origin:e}}createTransmitterConnection(e){return this.connectionID+=1,this._joinChannelServiceRecordIndex=void 0,this._url="dc://".concat(e.ip,":").concat(e.port),new dQ((t,i)=>{var r;let n=()=>{TY.debug("[".concat(this._name,"] datachannel opened:"),this._url),this.reconnectMode="recover",this.state="connected",this.resetReconnectCount("opened"),t()},o=async e=>{var r;if(null==(r=this._closeEstablishingTransmitter)||r.call(this),TY.debug("[".concat(this._name,"] datachannel close ").concat(this._url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this._reconnectCount<this._retryConfig.maxRetryCount){"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");let r=gd(this,yg.WILL_RECONNECT,this.reconnectMode)||this.reconnectMode,n=await this.reconnectWithAction(r);if("closed"===this.state)return void TY.debug("[".concat(this.connectionID,"] dc is closed, no need to reconnect"));if(!n)return i(new T0(SU.WS_DISCONNECT,"datachannel reconnect failed: ".concat(e.code))),void this.close(!0);t()}else i(new T0(SU.WS_DISCONNECT,"datachannel close: ".concat(e.code))),this.close()},a=async e=>{try{var t;null==(t=this._reliableTransmission)||t.onData(e.data)}catch(e){console.log(e)}};this._transmitter&&(this._transmitter.onclose=null,this._transmitter.close()),this._reliableTransmission&&(this._reliableTransmission.close(),this._reliableTransmission=void 0),TY.debug("[".concat(this._name,"] start connect, address: ").concat(JSON.stringify(e)));let s=null==(r=this._store)?void 0:r.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"}),c=Date.now();gs(this,yg.TO_CONNECT_DATACHANNEL).then(e=>{var t,i;if(!e)throw Error("transmissonInfo not exist yet");let{transmitter:r,close:d}=e;this._transmitter=r,null==(t=this._store)||t.signalChannelOpen();let l=Date.now()-c;TY.debug("[choose dc] dc open cost ".concat(l,"ms")),this._reliableTransmission=new DX(e=>{var t;this._transmitter&&"open"===this._transmitter.readyState&&(null==(t=this._transmitter)||t.send(e))},e=>{if("string"==typeof e)this.emit(yg.ON_MESSAGE,e);else{let t=NB(e,{raw:!0}).buffer,i=this._textDecoder.decode(t);this.emit(yg.ON_MESSAGE,i)}}),this._closeEstablishingTransmitter=()=>{var e;null==(e=this._reliableTransmission)||e.close(),this._reliableTransmission=void 0,d()},n&&n(),r.onclose=o,r.onmessage=a,null==(i=this._store)||i.recordJoinChannelService({endTs:Date.now(),status:"success"},s),this._joinChannelServiceRecordIndex=s}).catch(e=>{var t;if(null==(t=this._store)||t.recordJoinChannelService({endTs:Date.now(),status:e instanceof T0&&e.code===SU.WS_ABORT?"aborted":"error",errors:[e]},s),"closed"!==this.state){if(e instanceof T0&&e.code===SU.WS_ERR){let t=new T0(SU.WS_ERR,"init datachannel failed! Error: ".concat(e.toString()));return TY.error("[".concat(this._name,"]").concat(t)),void i(t)}o&&o(e)}else i(new T0(SU.WS_DISCONNECT,"datachannel is closed: ".concat(e.toString())))})})}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this._reconnectCount>=this._retryConfig.maxRetryCount||!this._addresses||"closed"===this.state)return!1;this._onlineReconnectListener||gh.networkState!==go.OFFLINE||(this._onlineReconnectListener=gh.onlineWaiter&&gh.onlineWaiter.then(()=>{this._onlineReconnectListener=void 0}));let i=!0;if(this._reconnectInterrupter=()=>{i=!1},t){let t=gK(this._reconnectCount,this._retryConfig);TY.debug("[".concat(this._name,"] wait ").concat(t,"ms to reconnect datachannel, mode: ").concat(e)),await dQ.race([gO(t),this._onlineReconnectListener||new dQ(()=>{})])}if("closed"===this.state||!i)return!1;this._reconnectCount+=1;let r=async(e,t)=>
1{this.emit(yg.RECONNECT_CREATE_CONNECTION,t),await this.createTransmitterConnection(e)};try{if("retry"===e){let t=this._addresses[this.currentURLIndex];await r(t,e)}else if("tryNext"===e){this.currentURLIndex+=1;for(let e=this.currentURLIndex;e<this._addresses.length;e++){if(this._addresses[e].fingerprint||TR("FINGERPRINT")){this.currentURLIndex=e;break}this.currentURLIndex+=1}if(this.currentURLIndex>=this._addresses.length)return TY.debug("[".concat(this._name,"] the available addresses are exhausted, change to recover")),await this.reconnectWithAction("recover",!1);TY.debug("[".concat(this._name,"] datachannel url length: ").concat(this._addresses.length," current index: ").concat(this.currentURLIndex));let t=this._addresses[this.currentURLIndex];await r(t,e)}else"recover"===e&&(TY.debug("[".concat(this._name,"] start to failback to websocket")),this.resetReconnectCount("recover mode"),this.emit(yg.FAILBACK));return!0}catch(i){var n,o;return TY.error("[".concat(this._name,"] reconnect failed"),i.toString()),null!=i&&null!=(n=i.data)&&n.desc&&Array.isArray(i.data.desc)&&i.data.desc.length&&o5(o=i.data.desc).call(o,"dynamic key expired")?(this.emit(yg.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):await this.reconnectWithAction(e,t)}}constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3?arguments[3]:void 0),mb(this,"_initMutex",void 0),mb(this,"_reconnectInterrupter",void 0),mb(this,"_url",void 0),mb(this,"_transmitter",void 0),mb(this,"_addresses",void 0),mb(this,"_reliableTransmission",void 0),mb(this,"_textEncoder",void 0),mb(this,"_textDecoder",void 0),this._textEncoder=new TextEncoder,this._textDecoder=new TextDecoder,this._initMutex=new gG("datachannel");let{timeout:i,timeoutFactor:r}=t,n=Math.max(300,Math.floor(3*i/5)),o=Math.max(1.2,Math.floor(8*r)/10);go.ONLINE&&(this._retryConfig.timeout=n,this._retryConfig.timeoutFactor=o),gh.on(ga.NETWORK_STATE_CHANGE,(e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===go.ONLINE?(this._retryConfig.timeout=n,this._retryConfig.timeoutFactor=o):(this._retryConfig.timeout=i,this._retryConfig.timeoutFactor=r))})}}class DQ extends S0{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===vV.CONNECTED?this.emit(vF.WS_CONNECTED):e===vV.RECONNECTING?this.emit(vF.WS_RECONNECTING,this._websocketReconnectReason):e===vV.CLOSED&&this.emit(vF.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket?this.websocket.url:null}get rtt(){return this.rttRolling.mean()}processPendingNotifications(){0!==this.pendingNotifications.length&&(TY.debug("[".concat(this.clientId,"] processing ").concat(this.pendingNotifications.length," pending notifications")),this.pendingNotifications.forEach(e=>{let{type:t,message:i}=e;this.emit(t,i),t===vG.ON_NOTIFICATION&&this.handleNotification(i),t===vG.ON_USER_BANNED&&this.handleUserBanned(i)}),this.pendingNotifications=[])}handleUserBanned(e){switch(e.error_code){case 14:this.close(S8.UID_BANNED);break;case 15:this.close(S8.IP_BANNED);break;case 16:this.close(S8.CHANNEL_BANNED)}}async request(e,t,i,r){let n=gw(6,""),o={_id:n,_type:e,_message:t},a=this.websocket.connectionID,s=()=>new dQ((t,i)=>{if(this.connectionState===vV.CONNECTED)return t();let r=()=>{this.off(vF.WS_CLOSED,n),t()},n=()=>{this.off(vF.WS_CONNECTED,r),i(new T0(SU.WS_ABORT))};this.once(vF.WS_CONNECTED,r),this.once(vF.WS_CLOSED,n),e!==vB.PUBLISH&&e!==vB.SUBSCRIBE&&e!==vB.UNSUBSCRIBE&&e!==vB.UNPUBLISH&&e!==vB.CONTROL&&e!==vB.RESTART_ICE||this.once(vF.DISCONNECT_P2P,()=>{i(new T0(SU.DISCONNECT_P2P))}),e!==vB.PUBLISH&&e!==vB.RESTART_ICE||this.once(vF.ABORT_P2P_EXECUTION,()=>{i(new T0(SU.DISCONNECT_P2P))})});if(this.connectionState!==vV.CONNECTING&&this.connectionState!==vV.RECONNECTING||e===vB.JOIN||e===vB.REJOIN||await s(),e===vB.LEAVE&&(this.websocket.unbindDcCloseEventListener(),r=!0),TR("DC_DEBUG_LOG")&&TY.debug("[datachannel-signal] sendMessage",o),await this.websocket.sendMessage(o,!0,!1),r)return;let c=new dQ((i,r)=>{let o=!1,s=(r,n)=>{o=!0,i({isSuccess:"success"===r,message:n||{}}),this.off(vF.WS_CLOSED,c),this.off(vF.WS_RECONNECTING,c),this.emit
1(vF.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(n),s);let c=()=>{r(new T0(SU.WS_ABORT,"type: ".concat(e))),this.off(vF.WS_CLOSED,c),this.off(vF.WS_RECONNECTING,c),this.off("res-@".concat(n),s)};this.once(vF.WS_CLOSED,c),this.once(vF.WS_RECONNECTING,c),gO(TR("SIGNAL_REQUEST_TIMEOUT")).then(()=>{this.websocket.connectionID!==a||o||(TY.warning("dc request timeout, type: ".concat(e)),this.emit(vF.REQUEST_TIMEOUT,e,t))})}),d=null;try{d=await c}catch(r){if(this.connectionState===vV.CLOSED||e===vB.LEAVE)throw new T0(SU.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?r.throw():e===vB.JOIN||e===vB.REJOIN?null:(await s(),await this.request(e,t))}if(d.isSuccess)return d.message;let l=Number(d.message.error_code||d.message.code),h=yD(l),u=new T0(SU.UNEXPECTED_RESPONSE,"".concat(h.desc,": ").concat(d.message.error_str),{code:l,data:d.message});return"success"===h.action?d.message:(TY.warning("[".concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(h.desc,", action: ").concat(h.action)),l===vx.ERR_TOO_MANY_BROADCASTERS?((e===vB.JOIN||e===vB.REJOIN)&&(this.initError=u,this.close()),u.throw()):"failed"===h.action?u.throw():"quit"===h.action?(this.initError=u,this.close(),u.throw()):(l===vx.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,TY.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",yS.MULTI_IP)):this.reconnect(h.action,yS.SERVER_ERROR),e===vB.JOIN||e===vB.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new dQ(i=>{let r=n=>{(!t||t(n))&&(this.off(e,r),i(n))};this.on(e,r)})}uploadWRTCStats(e){if(!this.store.sessionId)return void TY.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));let t={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(vj.WRTC_STATS,t)}upload(e,t){let i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(t){let e=TR("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>e&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval(()=>{if(this.connectionState!==vV.CONNECTED)return;let e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message)},TR("UPLOAD_CACHE_INTERVAL")||2e3))}}async send(e,t){await this.websocket.sendMessage({_type:e,_message:t})}init(e){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new dQ((t,i)=>{this.once(vF.WS_CONNECTED,()=>t(this.joinResponse)),this.once(vF.WS_CLOSED,()=>i(this.initError||new T0(SU.WS_ABORT))),this.connectionState=vV.CONNECTING,this.websocket.init(e).catch(i),this.websocket.once(yg.FAILBACK,()=>{i(new T0(SU.INIT_DATACHANNEL_TIMEOUT))}),this.inflateDataTimer&&window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=window.setInterval(()=>{this.handleInflateData()},2e4),setTimeout(()=>{void 0===this.openConnectionTime&&(TY.debug("[".concat(this.clientId,"] init datachannel timeout while join with failback to websocket")),i(new T0(SU.INIT_DATACHANNEL_TIMEOUT)))},TR("DC_JOIN_WITH_FAILBACK"))})}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.inflateDataTimer&&(this.handleInflateData(),window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this.isJoining=!1,this.pendingNotifications=[],this._disconnectedReason=e||S8.LEAVE,this.connectionState=vV.CLOSED,TY.debug("[".concat(this.clientId,"] ")+"will close datachannel in signal"),this.websocket.close(),e===S8.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new DJ("gateway-".concat(this.clientId),this.spec.retryConfig,!0,this.store),this.handleWebsocketEvents())}async join(){if(this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),TR("DC_PINGPONG_INTERVAL")),!this.joinResponse){this.emit
1(vF.ABORT_P2P_EXECUTION),this.store.signalConnected();let e=await gs(this,vF.REQUEST_JOIN_INFO);this.store.joinReq(),this.isJoining=!0,this.pendingNotifications=[];let t=await this.request(vB.JOIN,e);if(this.store.joinRep(),this.ortc=null==e?void 0:e.ortc,!t)return this.emit(vF.REPORT_JOIN_GATEWAY,SU.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(vF.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=vV.CONNECTED,this.isJoining=!1,this.processPendingNotifications(),!0}async rejoin(){if(!this.reconnectToken)throw new T0(SU.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");let e=gl(this,vF.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;let t=await this.request(vB.REJOIN,e);return!!t&&(this.connectionState=vV.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),TR("DC_PINGPONG_INTERVAL")),t.peers&&t.peers.forEach(e=>{this.emit(vG.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(vG.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(vG.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(vG.MUTE_AUDIO,{uid:e.uid}):this.emit(vG.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(vG.MUTE_VIDEO,{uid:e.uid}):this.emit(vG.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(vG.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(vG.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(vG.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(vG.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(vG.ON_REMOVE_STREAM,{uid:e.uid,uint_id:e.uint_id})}),!0)}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}async downgradeCodec(e){if(!this.ortc)return!1;let t={downgrade_codec:e,ortc:this.ortc};return!!await this.request(vB.DOWNGRADE_CODEC,t)}handleNotification(e){TY.debug("[".concat(this.clientId,"] receive notification: "),e);let t=yD(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(S8.UID_BANNED),void this.close()):void this.reconnect(t.action,yS.SERVER_ERROR);TY.error("[".concat(this.clientId,"] ignore error: "),t.desc)}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1,TR("DC_DEBUG_LOG")&&console.debug("[datachannel-signal] pingpongTimeoutCount: ".concat(this.pingpongTimeoutCount));let e=TR("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(TY.warning("[datachannel-signal] PINGPONG Timeout. Last Socket Message: ".concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>TR("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("recover",yS.FALLBACK):this.request(vB.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;let e=Date.now()-t;this.rttRolling.add(e),TR("REPORT_STATS")&&this.send(vB.PING_BACK,{pingpongElapse:e})}).catch(e=>{})}handleInflateData(){let{inflateLength:e,deflateLength:t}=this.websocket.getInflateData();0!==e&&0!==t&&this.upload(vj.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(yg.RECONNECT_CREATE_CONNECTION,e=>{this.emit(vF.WS_RECONNECT_CREATE_CONNECTION,e)}),this.websocket.on(yg.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(yg.CLOSED,()=>{this.connectionState=vV.CLOSED}),this.websocket.on(yg.FAILED,()=>{this._disconnectedReason=S8.NETWORK_ERROR,this.connectionState=vV.CLOSED}),this.websocket.on(yg.RECONNECTING,e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===vV.CONNECTED?this.connectionState=vV.RECONNECTING:this.connectionState=vV.CONNECTING}),this.websocket.on(yg.WILL_RECONNECT,(e,t)=>{if(gl(this,vF.IS_P2P_DISCONNECTED)&&"retry"===e)return TY.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit(vF.NEED_RENEW_SESSION),this.emit
1(vF.DISCONNECT_P2P),t("tryNext");"retry"!==e&&(TY.debug("".concat(this.clientId," websockt will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0,this.emit(vF.NEED_RENEW_SESSION),this.emit(vF.DISCONNECT_P2P)),t(e)}),this.websocket.on(yg.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch(e=>{TY.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",yS.SERVER_ERROR)}):this.join().catch(e=>{if(this.emit(vF.REPORT_JOIN_GATEWAY,e.message||e.code,this.url||""),e instanceof T0&&e.code===SU.UNEXPECTED_RESPONSE&&e.data.code===vx.ERR_NO_AUTHORIZED)return TY.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",yS.SERVER_ERROR);TY.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",yS.SERVER_ERROR):(this.initError=e,this.close())})}),this.websocket.on(yg.REQUEST_NEW_URLS,(e,t)=>{gs(this,vF.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)}),this.websocket.on(yg.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(vG.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}),this.websocket.on(yg.TO_CONNECT_DATACHANNEL,(e,t)=>{gs(this,vF.PRE_CONNECT_PC).then(e).catch(t)}),this.websocket.on(yg.FAILBACK,()=>{void 0!==this.openConnectionTime&&this.emit(vF.DATACHANNEL_FAILBACK)})}constructor(e,t){super(),mb(this,"__name__","DataChannelSignal"),mb(this,"_disconnectedReason",void 0),mb(this,"_websocketReconnectReason",void 0),mb(this,"_connectionState",vV.CLOSED),mb(this,"reconnectToken",void 0),mb(this,"websocket",void 0),mb(this,"openConnectionTime",void 0),mb(this,"clientId",void 0),mb(this,"lastMsgTime",Date.now()),mb(this,"uploadCache",[]),mb(this,"uploadCacheInterval",void 0),mb(this,"rttRolling",new gq(5)),mb(this,"pingpongTimer",void 0),mb(this,"inflateDataTimer",void 0),mb(this,"pingpongTimeoutCount",0),mb(this,"ortc",void 0),mb(this,"joinResponse",void 0),mb(this,"multiIpOption",void 0),mb(this,"initError",void 0),mb(this,"spec",void 0),mb(this,"store",void 0),mb(this,"isJoining",!1),mb(this,"pendingNotifications",[]),mb(this,"onWebsocketMessage",e=>{if(e instanceof ArrayBuffer)return void this.emit(vF.ON_BINARY_DATA,e);let t=JSON.parse(e);if(TR("DC_DEBUG_LOG")&&TY.debug("[datachannel-signal] received packet",t),this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){let e="res-@".concat(t._id);this.emit(e,t._result,t._message)}else Object.prototype.hasOwnProperty.call(t,"_type")&&(this.isJoining?t._type===vG.ON_NOTIFICATION||t._type===vG.ON_USER_BANNED?(this.emit(t._type,t._message),t._type===vG.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===vG.ON_USER_BANNED&&this.handleUserBanned(t._message)):(this.pendingNotifications.push({type:t._type,message:t._message}),TY.debug("[".concat(this.clientId,"] cached notification during join: ").concat(t._type))):(this.emit(t._type,t._message),t._type===vG.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===vG.ON_USER_BANNED&&this.handleUserBanned(t._message)))}),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new DJ("gateway-".concat(this.clientId),this.spec.retryConfig,!0,t),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===vV.CONNECTED&&this.reconnect("retry",yS.OFFLINE)})}}Tl(),TT("PROCESS_ID","process-".concat(gw(8,""),"-").concat(gw(4,""),"-").concat(gw(4,""),"-").concat(gw(4,""),"-").concat(gw(12,""))),function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void TY.error("Error loading sdk config",e.message)}if(e)try{let t=JSON.parse(window.atob(e)),i=Date.now();TY.debug("Loading global parameters from cache",t),Object.keys(t).forEach(e=>{if(Object.prototype.hasOwnProperty.call(Tg,e)){let{value:r,expires:n}=t[e];n&&n<=i||(Tv[e]=r,Tg[e]=r)}})}catch(t){TY.error("Error loading mutableParamsCache: ".concat(e),t.message)}}(),Array.isArray(Tv.AREAS)&&Tv.AREAS.length>0&&I1(Tv.AREAS,!0);let DZ=(e,t,i)=>{TY.debug("setParameter key:".concat(e,", value:").concat(JSON.stringify(t))),TT(e,t,i)};Ix({name:"ChannelMediaRelay",create:function(e){return new NK(e.joinInfo,e.clientId,e.websocketRetryConfig||gH,e.httpRetryConfig||gH,e.resolution)}},!1),Ix({name:"LiveStreaming",create:function(e){return new NQ(e.j
1oinInfo,e.websocketRetryConfig||gH,e.httpRetryConfig||gH)}},!1),Ix({name:"ImageModeration",create:function(e){let{config:t}=e;return Os(t),new Oa(t)}},!1),Ix({name:"ContentInspect",create:function(e){let{config:t}=e;return function(e){if(!e)throw new T0(SU.INVALID_PARAMS,"inspectConfig is necessary.");if(!e.inspectType||!Array.isArray(e.inspectType))throw new T0(SU.INVALID_PARAMS,"inspectConfig.inspectType is necessary and is an instance of Array.");{let t=[...new Set(e.inspectType)];t.forEach(e=>{var t;if(!o5(t=["supervise","moderation"]).call(t,e))throw new T0(SU.INVALID_PARAMS,"".concat(e," is not a valid inspect type."))}),e.inspectType=t}if(e&&e.extraInfo&&e.extraInfo.length>1024)throw new T0(SU.INVALID_PARAMS,"inspectConfig.extraInfo length cannot exceed 1024 bytes")}(t),new Dd(t)}},!1),Ix({name:"DataStream",create:(e,t)=>{let i=t?new Cj(e):new CG(e);return i.useDataStream(new NW),i}},!1),Ix({name:"P2PChannel",create:function(e){let{store:t,statsCollector:i}=e;return new DA(t,i)},createSubmodule:function(e){let{store:t,spec:i}=e;return new Dw(i,t)}},!1),Ix({name:"PlanBConnection",create:function(e){let{store:t,spec:i}=e;return new DM(i,t)}},!1),Ix({name:"InterceptFrame",create:()=>Dx},!1),Ix({name:"DataChannelConnection",create:function(e){let{store:t,spec:i}=e;return new DH(i,t)}},!1),Ix({name:"DataChannelSignal",create:function(e){let{store:t,spec:i}=e;return new DQ(i,t)}},!1);let D$=function(e){let t=new S0,i={getListeners:t.getListeners.bind(t),on:(e,i)=>(e===yT.SECURITY_POLICY_VIOLATION&&OS(i,!0),t.on.bind(t)(e,i)),addListener:t.addListener.bind(t),once:t.once.bind(t),off:t.off.bind(t),removeAllListeners:t.removeAllListeners.bind(t),emit:t.emit.bind(t),safeEmit:t.safeEmit.bind(t)};return Om(Om({},e),i)}({__TRACK_LIST__:Ru,VERSION:Th,BUILD:Tf,ESM_BUNDLER:!1,ESM:!1,UMD:!0,DEV:!1,setParameter:DZ,getParameter:TR,getSupportedCodec:async function(){let e={audio:[],video:[]};try{let t=new RTCPeerConnection,i=await async function(e){let t;return T1.supportUnifiedPlan?(e.addTransceiver("video",{direction:"recvonly"}),e.addTransceiver("audio",{direction:"recvonly"}),t=(await e.createOffer()).sdp):t=(await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0})).sdp,t}(t);if(!i)return e;t.close(),t=null,e=function(e){let t={video:[],audio:[]};return e.match(/ VP8/i)&&t.video.push("VP8"),e.match(/ VP9/i)&&t.video.push("VP9"),e.match(/ AV1/i)&&t.video.push("AV1"),e.match(/ H264/i)&&t.video.push("H264"),e.match(/ H265/i)&&t.video.push("H265"),e.match(/ opus/i)&&t.audio.push("OPUS"),e.match(/ PCMU/i)&&t.audio.push("PCMU"),e.match(/ PCMA/i)&&t.audio.push("PCMA"),e.match(/ G722/i)&&t.audio.push("G722"),t}(i)}catch(e){throw new T0(SU.CREATE_OFFER_FAILED,e.toString&&e.toString()).print()}return e},checkSystemRequirements:function(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=T$.reportApiInvoke(null,{name:S3.CHECK_SYSTEM_REQUIREMENTS,options:[],tag:S5.TRACER}),i=function(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=!1;try{let i=window.RTCPeerConnection,r=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,n=window.WebSocket;t=!(!i||!n),e&&!r&&(t=!1),t&&SD()&&Sp(75)&&(new i).close()}catch(e){TY.error("check system requirement failed: ",e),t=!1}return t}(e),r=function(){let e=!1,t=St();return(t.name===f8.CHROME&&Number(t.version)>=58&&("WebKit"!==f7.engine.name||function(){let e=St();if(So()){if(e.os===f6.MAC_OS)return!0;if(e.os===f6.IOS){let e=f7.os.version&&f7.os.version.split(".");if(e&&14===Number(e[0])&&e[1]&&Number(e[1])>=3||e&&Number(e[0])>14)return!0}}return!1}())||t.name===f8.FIREFOX&&Number(t.version)>=56||t.name===f8.OPERA&&Number(t.version)>=45||t.name===f8.SAFARI&&Number(t.version)>=11||"WebKit"===t.name&&(Sh()||SA())&&t.osVersion&&Number(t.osVersion.split(".")[0])>=11||Sb()||St().name===f8.QQ)&&(e=!0),e}();TY.debug("checkSystemRequirements, api:",i,"browser",r);let n=i&&r;return t.onSuccess(n),TR("IGNORE_RTC_DEVICE_CHECK")?i:n},getDevices:function(e){return Ce.enumerateDevices(!0,!0,e)},getMicrophones:function(e){return Ce.getRecordingDevices(e)},getCameras:function(e){return Ce.getCamerasDevices(e)},getElectronScreenSources:R2,getPlaybackDevices:function(e){return Ce.getSpeakers(e)},createClient:Oh,createCameraVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=TR("CAMERA_CAPTURE_CONFIG"),i=gw(8,"track-cam-"),r=T$.reportApiInvoke(null,{id:i,tag:S5.TRACER,name:S3.CREATE_CAM_VIDEO_TRACK,options:[RB({},e),t]});t&&(e.encoderConfig=t);let n=CE(e),o=null;TY.info("start create camera video track with config",JSON.stringify(e),"trackId",i);try{o=(await R6({video:n},i)).getVideoTracks()[0]||null}catch(e){throw r.onError(e),e}if(!o){let e=new Sx(SU.UNEXPECTED_ERROR,"can not find track in media stream");return r.onError(e),e.throw(TY)}if(e.optimizationMode&&CM(i,o,e,Rs(e.encoderConfig)),TR("USE_STANDARD_BITRATE_DEFAULT")){let t=Rs(e.encoderConfig);e.encoderConfig=t,delete t.bitrateMax,delete t.bitrateMin}let a=new CL(o,e,n,e.scalabiltyMode?Rd(e.scalabiltyMode):{numSpatialL
1ayers:1,numTemporalLayers:1},e.optimizationMode,i);return r.onSuccess(a.getTrackId()),TY.info("create camera video success, trackId:",i),a},createCustomVideoTrack:function(e){let t=gw(8,"track-cus-"),i=T$.reportApiInvoke(null,{id:t,tag:S5.TRACER,name:S3.CREATE_CUSTOM_VIDEO_TRACK,options:[e]});TR("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin);let r=new CP(e.mediaStreamTrack,{width:e.width,height:e.height,frameRate:e.frameRate,bitrateMax:e.bitrateMax,bitrateMin:e.bitrateMin},e.scalabiltyMode?Rd(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,t,[RE.CUSTOM_TRACK]);return i.onSuccess(r.getTrackId()),TY.info("create custom video track success with config",e,"trackId",r.getTrackId()),r},createScreenVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"disable",i="object"==typeof t?function(e){let t=Cm(e);return T8()&&e.suppressLocalAudioPlayback&&(t.suppressLocalAudioPlayback=e.suppressLocalAudioPlayback),T9()&&e.restrictOwnAudio&&(t.restrictOwnAudio=!0),t}(t):void 0;i&&(t="auto");let r=gw(8,"track-scr-v-"),n=T$.reportApiInvoke(null,{id:r,tag:S5.TRACER,name:S3.CREATE_SCREEN_VIDEO_TRACK,options:[RB({},e),t]});e.encoderConfig?"string"==typeof e.encoderConfig||e.encoderConfig.width&&e.encoderConfig.height||(e.encoderConfig.width={max:1920},e.encoderConfig.height={max:1080}):e.encoderConfig="1080p_2";let o=function(e){let t={};e.screenSourceType&&(t.mediaSource=e.screenSourceType),e.extensionId&&Sa()&&(t.extensionId=e.extensionId);let{displaySurface:i,selfBrowserSurface:r,surfaceSwitching:n,systemAudio:o,preferCurrentTab:a,windowAudio:s,monitorTypeSurfaces:c}=e;(Su(107)||SE(107)||SR(93))&&(i&&(SF(i,"displaySurface",["browser","window","monitor"]),t.displaySurface=i),r?(SF(r,"selfBrowserSurface",["exclude","include"]),t.selfBrowserSurface=r):t.selfBrowserSurface="include",n&&(SF(n,"surfaceSwitching",["exclude","include"]),t.surfaceSwitching=n)),(Su(105)||SE(105)||SR(91))&&o&&(SF(o,"systemAudio",["exclude","include"]),t.systemAudio=o),(Su(94)||SE(94)||SR(80))&&a&&(t.preferCurrentTab=!0),(Su(141)||SE(141)||SR(125))&&s&&(SF(s,"windowAudio",["exclude","system"]),t.windowAudio=s),(Su(119)||SE(119)||SR(105))&&c&&(SF(c,"monitorTypeSurfaces",["exclude","include"]),t.monitorTypeSurfaces=c),e.electronScreenSourceId&&(t.sourceId=e.electronScreenSourceId);let d=e.encoderConfig?Rc(e.encoderConfig):null;return t.mandatory={chromeMediaSource:"desktop",maxWidth:d?d.width:void 0,maxHeight:d?d.height:void 0},d&&(d.frameRate&&("number"==typeof d.frameRate?(t.mandatory.maxFrameRate=d.frameRate,t.mandatory.minFrameRate=d.frameRate):(t.mandatory.maxFrameRate=d.frameRate.max||d.frameRate.ideal||d.frameRate.exact||void 0,t.mandatory.minFrameRate=d.frameRate.min||d.frameRate.ideal||d.frameRate.exact||void 0),t.frameRate=d.frameRate),d.width&&(t.width=d.width),d.height&&(t.height=d.height)),t}(e),a=null,s=null;if(!T1.supportShareAudio&&"enable"===t){let e=new Sx(SU.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return n.onError(e),e.throw(TY)}TY.info("start create screen video track with config",e,"withAudio",t,"trackId",r);let c=T1.supportShareAudio&&"disable"!==t;try{let e=await R6({screen:o,screenAudio:c?i||!0:void 0},r);a=e.getVideoTracks()[0]||null,s=e.getAudioTracks()[0]||null}catch(e){throw n.onError(e),e}if(!a){let e=new Sx(SU.UNEXPECTED_ERROR,"can not find track in media stream");return n.onError(e),e.throw(TY)}if(!s&&"enable"===t){a&&a.stop();let e=new Sx(SU.SHARE_AUDIO_NOT_ALLOWED);return n.onError(e),e.throw(TY)}e.optimizationMode||(e.optimizationMode="detail"),e.optimizationMode&&(CM(r,a,e,e.encoderConfig&&Rc(e.encoderConfig)||void 0),e.encoderConfig&&"string"!=typeof e.encoderConfig&&(e.encoderConfig.bitrateMin=e.encoderConfig.bitrateMax));let d=new CP(a,e.encoderConfig?Rc(e.encoderConfig):{},e.scalabiltyMode?Rd(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,r,[RE.SCREEN_TRACK]);if(!s)return n.onSuccess(d.getTrackId()),TY.info("create screen video track success","video:",d.getTrackId()),d;let l=new CC(s,void 0,gw(8,"track-scr-a-"),!1);return n.onSuccess([d.getTrackId(),l.getTrackId()]),TY.info("create screen video track success","video:",d.getTrackId(),"audio:",l.getTrackId()),[d,l]},createMicrophoneAndCameraTracks:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=TR("CAMERA_CAPTURE_CONFIG"),r=gw(8,"track-mic-"),n=gw(8,"track-cam-"),o=T$.reportApiInvoke(null,{id:"".concat(r,"-").concat(n),tag:S5.TRACER,name:S3.CREATE_MIC_AND_CAM_TRACKS,options:[e,t,i]});i&&(t.encoderConfig=i);let a=CE(t),s=Cf(e),c=null,d=null;TY.info("start create camera video track(".concat(n,") and microphone audio track(").concat(r,") with config, audio: ").concat(JSON.stringify(e),", video: ").concat(JSON.stringify(t)));try{let e=await R6({audio:s,video:a},"".concat(r,"-").concat(n));c=e.getAudioTracks()[0],d=e.getVideoTracks()[0]}catch(e){throw o.onError(e),e}if(!c||!d){let e=new Sx(SU.UNEXPECTED_ERROR,"can not find tracks in media stream");return o.onError(e),e.throw(TY)}if(t.optimizationMode&&CM(n,d,t,Rs(t.encoderConfig)),TR("USE_STANDARD_BITRATE_DEFAULT")){let e=Rs(t.encoderConfig);t.encoderConfig=e,delete e.bitrateMax,delete e.bitrateMin}
1let l=new Cv(c,e,s,r),h=new CL(d,t,a,t.scalabiltyMode?Rd(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,n);return o.onSuccess([l.getTrackId(),h.getTrackId()]),TY.info("create camera video track(".concat(n,") and microphone audio track(").concat(r,") success")),[l,h]},createMicrophoneAudioTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=gw(8,"track-mic-"),i=T$.reportApiInvoke(null,{id:t,tag:S5.TRACER,name:S3.CREATE_MIC_AUDIO_TRACK,options:[e]}),r=Cf(e),n=null;TY.info("start create microphone audio track with config",JSON.stringify(e),"trackId",t);try{n=(await R6({audio:r},t)).getAudioTracks()[0]||null}catch(e){throw i.onError(e),e}if(!n){let e=new Sx(SU.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(e),e.throw(TY)}let o=new Cv(n,e,r,t);return i.onSuccess(o.getTrackId()),TY.info("create microphone audio track success, trackId:",t),o},createCustomAudioTrack:Ck,createBufferSourceAudioTrack:async function(e){var t;let{cacheOnlineFile:i,encoderConfig:r}=e,{source:n}=e,o={source:n instanceof AudioBuffer?"AudioBuffer":n instanceof File?null!=(t=File.name)?t:"File":n,cacheOnlineFile:i,encoderConfig:r},a=gw(8,"track-buf-"),s=T$.reportApiInvoke(null,{id:a,tag:S5.TRACER,name:S3.CREATE_BUFFER_AUDIO_TRACK,options:[o]});if(TR("DISABLE_WEBAUDIO"))throw new Sx(SU.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");TY.info("start create buffer source audio track with config",JSON.stringify(o),"trackId",a);let c=n;if(!(n instanceof AudioBuffer))try{n=await async function(e,t){let i=null;if("string"==typeof e){let t=Cb.get(e);if(t)return TY.debug("use cached audio resource: ",e),t;try{i=(await gY(()=>f0.get(e,{responseType:"arraybuffer"}),void 0,void 0,{maxRetryCount:3})).data}catch(e){throw new Sx(SU.FETCH_AUDIO_FILE_FAILED,e.toString())}}else{let t=new dQ((t,i)=>{let r=new FileReader;r.onload=e=>{e.target?t(e.target.result):i(new Sx(SU.READ_LOCAL_AUDIO_FILE_ERROR))},r.onerror=()=>{i(new Sx(SU.READ_LOCAL_AUDIO_FILE_ERROR))},r.readAsArrayBuffer(e)});i=await t}let r=await function(e){let t=Rz();return new dQ((i,r)=>{t.decodeAudioData(e,e=>{i(e)},e=>{r(new Sx(SU.DECODE_AUDIO_FILE_FAILED,e.toString()))})})}(i);return"string"==typeof e&&t&&Cb.set(e,r),r}(n,i)}catch(e){return s.onError(e),e.throw(TY)}let d=new Cy(c,new CA(n),r?Rh(r):{},a);return TY.info("create buffer source audio track success, trackId:",a),s.onSuccess(d.getTrackId()),d},setAppType:function(e){if(TY.debug("setAppType: ".concat(e)),!(Number.isInteger(e)&&e>=0))throw TY.debug("Invalid appType"),new T0(SU.INVALID_PARAMS,"invalid app type",e);TT("APP_TYPE",Math.floor(e))},setLogLevel:function(e){TY.setLogLevel(e)},enableLogUpload:function(){TR("USE_NEW_LOG")?TT("UPLOAD_LOG",!0):TY.enableLogUpload()},disableLogUpload:function(){TR("USE_NEW_LOG")?TT("UPLOAD_LOG",!1):TY.disableLogUpload()},createChannelMediaRelayConfiguration:function(){return new Ay},checkAudioTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3,i=T$.reportApiInvoke(null,{tag:S5.TRACER,name:S3.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof CC||e instanceof CV)){let e=new T0(SU.INVALID_TRACK,"the parameter is not a audio track");return i.onError(e),e.throw()}t&&t<1e3&&(t=1e3);
1let r=e instanceof CC?e.getTrackLabel():"remote_track",n=e.getVolumeLevel(),o=n,a=n,s=Date.now();return new dQ(n=>{let c=setInterval(()=>{let d=e.getVolumeLevel(),l=(o=d>o?d:o)-(a=d<a?d:a)>1e-4,h=Date.now()-s;if(l||h>t){clearInterval(c);let t={duration:h,deviceLabel:r,maxVolumeLevel:o,result:l};TY.info("[track-".concat(e.getTrackId(),"] check audio track active completed. ").concat(JSON.stringify(t))),i.onSuccess(t),n(l)}},200)})},checkVideoTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3,i=T$.reportApiInvoke(null,{tag:S5.TRACER,name:S3.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof CP||e instanceof Cx)){let e=new T0(SU.INVALID_TRACK,"the parameter is not a video track");return i.onError(e),e.throw()}t&&t<1e3&&(t=1e3);let r=e instanceof CP?e.getTrackLabel():"remote_track",n=e.getMediaStreamTrack(!0),o=document.createElement("video");o.style.width="1px",o.style.height="1px",o.setAttribute("muted",""),o.muted=!0,o.setAttribute("playsinline",""),o.controls=!1,(Ss()||So())&&(o.style.opacity="0.01",o.style.position="fixed",o.style.left="0",o.style.top="0",document.body.appendChild(o)),o.srcObject=new MediaStream([n]),o.play();let a=document.createElement("canvas");a.width=160,a.height=120;let s=0,c=0;try{var d;let e,i,r,n=Date.now();s=await (d=t,i=0,r=null,new dQ((t,n)=>{setTimeout(()=>{e&&(e(),t(i))},d),e=RJ(()=>{!function(){i>4&&e&&(e(),t(i));let s=a.getContext("2d");if(!s){let e=new T0(SU.UNEXPECTED_ERROR,"can not get canvas 2d context.");return TY.error(e.toString()),n(e)}s.drawImage(o,0,0,160,120);let c=s.getImageData(0,0,a.width,a.height),d=Math.floor(c.data.length/3);if(r){for(let e=0;e<d;e+=3)if(c.data[e]!==r[e])return i+=1,void(r=c.data);r=c.data}else r=c.data}()},30)})),c=Date.now()-n}catch(e){throw i.onError(e),e}bT===f8.SAFARI&&(o.pause(),o.remove()),o.srcObject=null;let l=s>4,h={duration:c,changedPicNum:s,deviceLabel:r,result:l};return TY.info("[track-".concat(e.getTrackId(),"] check video track active completed. ").concat(JSON.stringify(h))),i.onSuccess(h),l},setArea:I1,audioElementPlayCenter:Ca,resumeAudioContext:function(){return Ca.autoResumeAfterInterruption(!0)},processExternalMediaAEC:function(e){O_.processExternalMediaAEC(e)},registerExtensions:function(e){let t=TR("PLUGIN_INFO")||[];e.forEach(e=>{"name"in e&&!o5(t).call(t,e.name)&&t.push(e.name),e.__registered__=!0,e.logger.hookLog=TY.extLog,e.reporter.hookApiInvoke=T$.extApiInvoke,e.parameters&&Object.keys(e.parameters).forEach(t=>{e.parameters[t]=TR(t)})}),DZ("PLUGIN_INFO",t)},ChannelMediaRelayError:v4,ChannelMediaRelayEvent:v3,ChannelMediaRelayState:v5,RemoteStreamFallbackType:RS,RemoteStreamType:Rf,ConnectionDisconnectedReason:S8,AudienceLatencyLevelType:S6,AREAS:ye,preload:async function(e,t,i,r){return bM(e,t,i,r)},startLastmileProbeTest:async function(e,t,i,r){let n={state:"unavailable"};await bM(e,t,i,r);let o=await bU({appId:e,cname:t,token:i||e,uid:r,cloudProxyServer:"disabled"});if(!o)return n;await bV(o);let a,s=Oh({mode:"rtc",codec:"vp8"});try{a=await s.join(e,t,i,r,{networkQualityProbe:!0})}catch(e){return n}let c=new bk,d=c.createMuteAudioTrack(),l=await Ck({mediaStreamTrack:d});await s.publish([l]);let[h,u,p]=await new dQ((e,t)=>{let i=setTimeout(()=>{clearTimeout(i),e([!0,null,"audio"])},5e3);s.on("user-published",async(t,r)=>{t.uid===a&&(clearTimeout(i),e([!1,t,r]))})});if(h||!u)return await s.unpublish([l]),await s.leave(),l.close(),c.close(),n;await s.subscribe(u,p),await new dQ((e,t)=>{let i=setTimeout(()=>{clearTimeout(i),e(null)},5e3)});let _=s.getRTCStats(),E=s.getLocalAudioStats(),m=_.RTT,f=E.sendJitterMs,S=E.currentPacketLossRate;return n={state:"complete",rtt:m,packetLossRate:S,jitter:f,networkQuality:((e,t,i)=>{let r=1;if(i>0){let e=Math.log(100*i)/Math.log(2)+1;r=1-(e=Math.min(5,Math.max(0,e)))/5}let n=1;if(e>0){let t=Math.log(e/40)/Math.log(2)+1;n=1-(t=Math.min(5,Math.max(0,t)))/5}let o=1;if(t>0){let e=Math.log(t/10)/Math.log(2.5)+1;o=1-(e=Math.min(5,Math.max(0,e)))/5}let a=.5*r+.3*n+.2*o;return a>=.8?1:a>=.6?2:a>=.4?3:a>=.2?4:5})(m,f,S)},await s.unsubscribe(u),await s.unpublish([l]),await s.leave(),l.close(),c.close(),await bV(o),n}});return Object.defineProperties(D$,{onAudioAutoplayFailed:{get:()=>Ci.onAudioAutoplayFailed,set:e=>{Ci.onAudioAutoplayFailed=e}},onAutoplayFailed:{get:()=>Ci.onAutoplayFailed,set:e=>{Ci.onAutoplayFailed=e}},_onSecurityPolicyViolation:{value:void 0,writable:!0},_cspEventHandlerPointer:{value:void 0,writable:!0},onSecurityPolicyViolation:{get:()=>D$._onSecurityPolicyViolation,set(e){D$._onSecurityPolicyViolation=e,OS(e)}},__CLIENT_LIST__:{get:()=>TR("SHOW_GLOBAL_CLIENT_LIST")?vu:[]}}),Ce.on(RP.CAMERA_DEVICE_CHANGED,e=>{TY.info("camera device changed",JSON.stringify(e)),D$.onCameraChanged&&D$.onCameraChanged(e),D$.safeEmit(yT.CAMERA_CHANGED,e)}),Ce.on(RP.RECORDING_DEVICE_CHANGED,e=>{TY.info("microphone device changed",JSON.stringify(e)),D$.onMicrophoneChanged&&D$.onMicrophoneChanged(e),D$.safeEmit(yT.MICROPHONE_CHANGED,e)}),Ce.on(RP.PLAYOUT_DEVICE_CHANGED,e=>{TY.debug("playout device changed",JSON.stringify(e)),D$.onPlaybackDeviceChanged&&D$.onPlaybackDeviceChanged(e),D$.safeEmit(yT.PLAYBACK_DEVICE_CHANGED,e)}),Ca.onAutoplayFailed=()=>{TY.info("detect audio element autoplay failed"),Ci.onAudioAutoplayFailed&&Ci.onAudioAutoplayFailed()},RY.on("autoplay-failed",()=>{TY.info("detect webaudio autoplay failed"),Ci.onAudioAutoplayFailed&&Ci.onAudioAutoplayFailed(),D$.safeEmit(yT.AUTOPLAY_FAILED)}),RY.on(T7.STATE_CHANGE,(e,t)=>{TY.info("audio context state changed: ".concat(t," => ").concat(e)),D$.onAudioContextStateChanged&&D$.onAudioContextStateChanged(e,t),D$.safeEmit(yT.AUDIO_CONTEXT_STATE_CHANGED,e,t)}),gh.on(ga.NETWORK_STATE_CHANGE,(e,t)=>{TY.info("[network-indicator] network state changed, ".concat(t," => ").concat(e))}),window&&(window.__ARTC__=D$),D$}()}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.