PageSourceSearch

https://static.tiptip.id/webapp/current/_next/static/chunks/789b6097.a0cf9ead8c0cea90.js

js tiptip.id collected 2026-09-24 11:16:15 UTC 867,990 bytes, 1 lines download raw bytes

1(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8669],{76860:function(e,t,i){var r=i(88220).Buffer,n=i(99742);e.exports=function(){"use strict";let e,t,o,s,a,c,d,l,u,h,p,_,E,m,f,S,T,g,R,I,C,v,y,A,O,b,N,w,D,P,L,k,M,U,x,V,F,j,B,G,W,H,K,Y,q,J,X,z,Q,Z,$,ee,et,ei,er,en,eo,es,ea,ec,ed,el,eu,eh,ep,e_,eE,em,ef,eS,eT;var eg,eR,eI,eC,ev,ey,eA,eO,eb,eN,ew,eD,eP,eL,ek,eM,eU,ex,eV,eF,ej,eB,eG,eW,eH,eK,eY,eq,eJ,eX,ez,eQ,eZ,e$,e0,e1,e2,e3,e4,e5,e6,e8,e7,e9,te,tt,ti,tr,tn,to,ts,ta,tc,td,tl,tu,th,tp,t_,tE,tm="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==i.g?i.g:"undefined"!=typeof self?self:{},tf=function(e){try{return!!e()}catch(e){return!0}},tS=!tf(function(){var e=(function(){}).bind();return"function"!=typeof e||e.hasOwnProperty("prototype")}),tT=Function.prototype,tg=tT.bind,tR=tT.call,tI=tS&&tg.bind(tR,tR),tC=tS?function(e){return e&&tI(e)}:function(e){return e&&function(){return tR.apply(e,arguments)}},tv=tC({}.isPrototypeOf),ty=function(e){return e&&e.Math==Math&&e},tA=ty("object"==typeof globalThis&&globalThis)||ty("object"==typeof window&&window)||ty("object"==typeof self&&self)||ty("object"==typeof tm&&tm)||function(){return this}()||Function("return this")(),tO=Function.prototype,tb=tO.apply,tN=tO.call,tw="object"==typeof Reflect&&Reflect.apply||(tS?tN.bind(tb):function(){return tN.apply(tb,arguments)}),tD=function(e){return"function"==typeof e},tP={},tL=!tf(function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]}),tk=Function.prototype.call,tM=tS?tk.bind(tk):function(){return tk.apply(tk,arguments)},tU={},tx={}.propertyIsEnumerable,tV=Object.getOwnPropertyDescriptor;tU.f=tV&&!tx.call({1:2},1)?function(e){var t=tV(this,e);return!!t&&t.enumerable}:tx;var tF,tj,tB=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},tG=tC({}.toString),tW=tC("".slice),tH=function(e){return tW(tG(e),8,-1)},tK=tA.Object,tY=tC("".split),tq=tf(function(){return!tK("z").propertyIsEnumerable(0)})?function(e){return"String"==tH(e)?tY(e,""):tK(e)}:tK,tJ=tA.TypeError,tX=function(e){if(null==e)throw tJ("Can't call method on "+e);return e},tz=function(e){return tq(tX(e))},tQ=function(e){return"object"==typeof e?null!==e:tD(e)},tZ={},t$=function(e){return tD(e)?e:void 0},t0=function(e,t){return arguments.length<2?t$(tZ[e])||t$(tA[e]):tZ[e]&&tZ[e][t]||tA[e]&&tA[e][t]},t1=t0("navigator","userAgent")||"",t2=tA.process,t3=tA.Deno,t4=t2&&t2.versions||t3&&t3.version,t5=t4&&t4.v8;t5&&(tj=(tF=t5.split("."))[0]>0&&tF[0]<4?1:+(tF[0]+tF[1])),!tj&&t1&&(!(tF=t1.match(/Edge\/(\d+)/))||tF[1]>=74)&&(tF=t1.match(/Chrome\/(\d+)/))&&(tj=+tF[1]);var t6=tj,t8=!!Object.getOwnPropertySymbols&&!tf(function(){var e=Symbol();return!String(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&t6&&t6<41}),t7=t8&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,t9=tA.Object,ie=t7?function(e){return"symbol"==typeof e}:function(e){var t=t0("Symbol");return tD(t)&&tv(t.prototype,t9(e))},it=tA.String,ii=function(e){try{return it(e)}catch(e){return"Object"}},ir=tA.TypeError,io=function(e){if(tD(e))return e;throw ir(ii(e)+" is not a function")},is=function(e,t){var i=e[t];return null==i?void 0:io(i)},ia=tA.TypeError,ic={exports:{}},id=Object.defineProperty,il="__core-js_shared__",iu=tA[il]||function(e,t){try{id(tA,e,{value:t,configurable:!0,writable:!0})}catch(i){tA[e]=t}return t}(il,{});(ic.exports=function(e,t){return iu[e]||(iu[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.20.3",mode:"pure",copyright:"\xa9 2014-2022 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.20.3/LICENSE",source:"https://github.com/zloirock/core-js"});var ih=tA.Object,ip=function(e){return ih(tX(e))},i_=tC({}.hasOwnProperty),iE=Object.hasOwn||function(e,t){return i_(ip(e),t)},im=0,iS=Math.random(),iT=tC(1..toString),ig=function(e){return"Symbol("+(void 0===e?"":e)+")_"+iT(++im+iS,36)},iR=(0,ic.exports)("wks"),iI=tA.Symbol,iC=iI&&iI.for,iv=t7?iI:iI&&iI.withoutSetter||ig,iy=function(e){if(!iE(iR,e)||!t8&&"string"!=typeof iR[e]){var t="Symbol."+e;t8&&iE(iI,e)?iR[e]=iI[e]:iR[e]=t7&&iC?iC(t):iv(t)}return iR[e]},iA=function(e,t){var i,r;if("string"===t&&tD(i=e.toString)&&!tQ(r=tM(i,e))||tD(i=e.valueOf)&&!tQ(r=tM(i,e))||"string"!==t&&tD(i=e.toString)&&!tQ(r=tM(i,e)))return r;throw ia("Can't convert object to primitive value")},iO=tA.TypeError,ib=iy("toPrimitive"),iN=function(e,t){if(!tQ(e)||ie(e))return e;var i,r=is(e,ib);if(r){if(void 0===t&&(t="default"),!tQ(i=tM(r,e,t))||ie(i))return i;throw iO("Can't convert object to primitive value")}return void 0===t&&(t="number"),iA(e,t)},iw=function(e){var t=iN(e,"string");return ie(t)?t:t+""},iD=tA.document,iP=tQ(iD)&&tQ(iD.createElement),iL=function(e){return iP?iD.createElement(e):{}},ik=!tL&&!tf(function(){return 7!=Object.defineProperty(iL("div"),"a",{get:function(){return 7}}).a}),iM=Object.getOwnPropertyDescriptor;tP.f=tL?iM:function(e,t){if(e=tz(e),t=iw(t),ik)try{return iM(e,t)}catch(e){}if(iE(e,t))return tB(!tM(tU.f,e,t),e[t])};var iU=/#|\.prototype\./,ix=function(e,t){var i=iF[iV(e)];return i==iB||i!=ij&&(tD(t)?tf(t):!!t)},iV=ix.normalize=function(e){return String(e).replace(iU,".").toLowerCase()},iF=ix.data={},ij=ix.NATIVE="N",iB=ix.POLYFILL="P",iG=tC(tC.bind),iW=function(e,t){return io(e),void 0===t?e:tS?iG(e,t):function(){return e.apply(t,arguments)}},iH={},iK=tL&&tf(function(){return 42!=Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype}),iY=tA.String,iq=tA.TypeError,iJ=function(e){if(tQ(e))return e;throw iq(iY(e)+" is not an object")},iX=tA.TypeError,iz=Object.defineProperty,iQ=Object.getOwnPropertyDescriptor;iH.f=tL?iK?function(e,t,i){if(iJ(e),t=iw(t),iJ(i),"function"==typeof e&&"prototype"===t&&"value"in i&&"writable"in i&&!i.writable){var r=iQ(e,t);r&&r.writable&&(e[t]=i.value,i={configurable:"configurable"in i?i.configurable:r.configurable,enumerable:"enumerable"in i?i.enumerable:r.enumerable,writable:!1})}return iz(e,t,i)}:iz:function(e,t,i){if(iJ(e),t=iw(t),iJ(i),ik)try{return iz(e,t,i)}catch(e){}if("get"in i||"set"in i)throw iX("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var iZ=tL?function(e,t,i){return iH.f(e,t,tB(1,i))}:function(e,t,i){return e[t]=i,e},i$=tP.f,i0=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 tw(e,this,arguments)};return t.prototype=e.prototype,t},i1=function(e,t){var i,r,n,o,s,a,c,d,l=e.target,u=e.global,h=e.stat,p=e.proto,_=u?tA:h?tA[l]:(tA[l]||{}).prototype,E=u?tZ:tZ[l]||iZ(tZ,l,{})[l],m=E.prototype;for(n in t)i=!ix(u?n:l+(h?".":"#")+n,e.forced)&&_&&iE(_,n),s=E[n],i&&(a=e.noTargetGet?(d=i$(_,n))&&d.value:_[n]),o=i&&a?a:t[n],i&&typeof s==typeof o||(c=e.bind&&i?iW(o,tA):e.wrap&&i?i0(o):p&&tD(o)?tC(o):o,(e.sham||o&&o.sham||s&&s.sham)&&iZ(c,"sham",!0),iZ(E,n,c),p&&(iE(tZ,r=l+"Prototype")||iZ(tZ,r,{}),iZ(tZ[r],n,o),e.real&&m&&!m[n]&&iZ(m,n,o)))},i2=Math.ceil,i3=Math.floor,i4=function(e){var t=+e;return t!=t||0===t?0:(t>0?i3:i2)(t)},i5=Math.min,i6=function(e){var t;return(t=e.length)>0?i5(i4(t),0x1fffffffffffff):0},i8=tA.TypeError,i7=function(e){return function(t,i,r,n){io(i);var o=ip(t),s=tq(o),a=i6(o),c=e?a-1:0,d=e?-1:1;if(r<2)for(;;){if(c in s){n=s[c],c+=d;break}
1if(c+=d,e?c<0:a<=c)throw i8("Reduce of empty array with no initial value")}for(;e?c>=0:a>c;c+=d)c in s&&(n=i(n,s[c],c,o));return n}},i9={left:i7(!1),right:i7(!0)},re=function(e,t){var i=[][e];return!!i&&tf(function(){i.call(null,t||function(){throw 1},1)})},rt="process"==tH(tA.process),ri=i9.left;i1({target:"Array",proto:!0,forced:!re("reduce")||!rt&&t6>79&&t6<83},{reduce:function(e){var t=arguments.length;return ri(this,e,t,t>1?arguments[1]:void 0)}});var rr=function(e){return tZ[e+"Prototype"]},rn=rr("Array").reduce,ro=Array.prototype,rs=function(e){var t=e.reduce;return e===ro||tv(ro,e)&&t===ro.reduce?rn:t};let ra=!0,rc=!0;function rd(e,t,i){let r=e.match(t);return r&&r.length>=i&&parseInt(r[i],10)}function rl(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 ru(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(ra=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function rh(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(rc=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function rp(){"object"==typeof window&&(ra||"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments))}function r_(e,t){rc&&console.warn(e+" is deprecated, please use "+t+" instead.")}function rE(e){return"[object Object]"===Object.prototype.toString.call(e)}function rm(e,t,i){let r=i?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;let o=[];return 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).forEac
vendor: 4,878 bytes, line 1
1h(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}var rf=(0,ic.exports)("keys"),rS=function(e){return rf[e]||(rf[e]=ig(e))},rT=!tf(function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}),rg=rS("IE_PROTO"),rR=tA.Object,rI=rR.prototype,rC=rT?rR.getPrototypeOf:function(e){var t=ip(e);if(iE(t,rg))return t[rg];var i=t.constructor;return tD(i)&&t instanceof i?i.prototype:t instanceof rR?rI:null},rv=tA.String,ry=tA.TypeError,rA=function(e){if("object"==typeof e||tD(e))return e;throw ry("Can't set "+rv(e)+" as a prototype")},rO=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=tC(Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set))(i,[]),t=i instanceof Array}catch(e){}return function(i,r){return iJ(i),rA(r),t?e(i,r):i.__proto__=r,i}}():void 0),rb={},rN=Math.max,rw=Math.min,rD=function(e,t){var i=i4(e);return i<0?rN(i+t,0):rw(i,t)},rP=function(e){return function(t,i,r){var n,o=tz(t),s=i6(o),a=rD(r,s);if(e&&i!=i){for(;s>a;)if((n=o[a++])!=n)return!0}else for(;s>a;a++)if((e||a in o)&&o[a]===i)return e||a||0;return!e&&-1}},rL={includes:rP(!0),indexOf:rP(!1)},rk={},rM=rL.indexOf,rU=tC([].push),rx=function(e,t){var i,r=tz(e),n=0,o=[];for(i in r)!iE(rk,i)&&iE(r,i)&&rU(o,i);for(;t.length>n;)iE(r,i=t[n++])&&(~rM(o,i)||rU(o,i));return o},rV=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],rF=rV.concat("length","prototype");rb.f=Object.getOwnPropertyNames||function(e){return rx(e,rF)};var rj={};rj.f=Object.getOwnPropertySymbols;var rB=tC([].concat),rG=t0("Reflect","ownKeys")||function(e){var t=rb.f(iJ(e)),i=rj.f;return i?rB(t,i(e)):t},rW={},rH=Object.keys||function(e){return rx(e,rV)};rW.f=tL&&!iK?Object.defineProperties:function(e,t){iJ(e);for(var i,r=tz(t),n=rH(t),o=n.length,s=0;o>s;)iH.f(e,i=n[s++],r[i]);return e};var rK,rY=t0("document","documentElement"),rq=rS("IE_PROTO"),rJ=function(){},rX=function(e){return"<script>"+e+"<\/script>"},rz=function(e){e.write(rX("")),e.close();var t=e.parentWindow.Object;return e=null,t},rQ=function(){try{rK=new ActiveXObject("htmlfile")}catch(e){}rQ="undefined"!=typeof document?document.domain&&rK?rz(rK):((t=iL("iframe")).style.display="none",rY.appendChild(t),t.src=String("javascript:"),(e=t.contentWindow.document).open(),e.write(rX("document.F=Object")),e.close(),e.F):rz(rK);for(var e,t,i=rV.length;i--;)delete rQ.prototype[rV[i]];return rQ()};rk[rq]=!0;var rZ=Object.create||function(e,t){var i;return null!==e?(rJ.prototype=iJ(e),i=new rJ,rJ.prototype=null,i[rq]=e):i=rQ(),void 0===t?i:rW.f(i,t)},r$=tC("".replace),r0=String(Error("zxcasd").stack),r1=/\n\s*at [^:]*:[^\n]*/,r2=r1.test(r0),r3={},r4=iy("iterator"),r5=Array.prototype,r6={};r6[iy("toStringTag")]="z";var r8="[object z]"===String(r6),r7=iy("toStringTag"),r9=tA.Object,ne="Arguments"==tH(function(){return arguments}()),nt=r8?tH: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){}}(t=r9(e),r7))?i:ne?tH(t):"Object"==(r=tH(t))&&tD(t.callee)?"Arguments":r},ni=iy("iterator"),nr=function(e){if(null!=e)return is(e,ni)||is(e,"@@iterator")||r3[nt(e)]},nn=tA.TypeError,no=function(e,t){var i=arguments.length<2?nr(e):t;if(io(i))return iJ(tM(i,e));throw nn(ii(e)+" is not iterable")},ns=function(e,t,i){var r,n;iJ(e);try{if(!(r=is(e,"return"))){if("throw"===t)throw i;return i}r=tM(r,e)}catch(e){n=!0,r=e}if("throw"===t)throw i;if(n)throw r;return iJ(r),i},na=tA.TypeError,nc=function(e,t){this.stopped=e,this.result=t},nd=nc.prototype,nl=function(e,t,i){var r,n,o,s,a,c,d,l=i&&i.that,u=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_ITERATOR),p=!(!i||!i.INTERRUPTED),_=iW(t,l),E=function(e){return r&&ns(r,"normal",e),new nc(!0,e)},m=function(e){return u?(iJ(e),p?_(e[0],e[1],E):_(e[0],e[1])):p?_(e,E):_(e)};if(h)r=e;else{if(!(n=nr(e)))throw na(ii(e)+" is not iterable");if(void 0!==n&&(r3.Array===n||r5[r4]===n)){for(o=0,s=i6(e);s>o;o++)if((a=m(e[o]))&&tv(nd,a))return a;return new nc(!1)}r=no(e,n)}for(c=r.next;!(d=tM(c,r)).done;){try{a=m(d.value)}catch(e){ns(r,"throw",e)}if("object"==typeof a&&a&&tv(nd,a))return a}return new nc(!1)},nu=tA.String,nh=function(e){if("Symbol"===nt(e))throw TypeError("Cannot convert a Symbol value to a string");return nu(e)},np=!tf(function(){var e=Error("a");return!("stack"in e)||(Object.defineProperty(e,"stack",tB(1,7)),7!==e.stack)}),n_=function(e,t){if(r2&&"string"==typeof e)for(;t--;)e=r$(e,r1,"");return e},nE=function(e,t){tQ(t)&&"cause"in t&&iZ(e,"cause",t.cause)},nm=iy("toStringTag"),nf=tA.Error,nS=[].push,nT=function(e,t){var i,r=arguments.length>2?arguments[2]:void 0,n=tv(ng,this);rO?i=rO(new nf,n?rC(this):ng):iZ(i=n?this:rZ(ng),nm,"Error"),void 0!==t&&iZ(i,"message",function(e,t){return void 0===e?arguments.length<2?"":t:nh(e)}
1(t)),np&&iZ(i,"stack",n_(i.stack,1)),nE(i,r);var o=[];return nl(e,nS,{that:o}),iZ(i,"errors",o),i};rO?rO(nT,nf):function(e,t,i){for(var r=rG(t),n=iH.f,o=tP.f,s=0;s<r.length;s++){var a=r[s];iE(e,a)||i&&iE(i,a)||n(e,a,o(t,a))}}(nT,nf,{name:!0});var ng=nT.prototype=rZ(nf.prototype,{constructor:tB(1,nT),message:tB(1,""),name:tB(1,"AggregateError")});i1({global:!0},{AggregateError:nT});var nR=tC(Function.toString);tD(iu.inspectSource)||(iu.inspectSource=function(e){return nR(e)});var nI,nC,nv,ny=iu.inspectSource,nA=tA.WeakMap,nO=tD(nA)&&/native code/.test(ny(nA)),nb="Object already initialized",nN=tA.TypeError,nw=tA.WeakMap;if(nO||iu.state){var nD=iu.state||(iu.state=new nw),nP=tC(nD.get),nL=tC(nD.has),nk=tC(nD.set);nI=function(e,t){if(nL(nD,e))throw new nN(nb);return t.facade=e,nk(nD,e,t),t},nC=function(e){return nP(nD,e)||{}},nv=function(e){return nL(nD,e)}}else{var nM=rS("state");rk[nM]=!0,nI=function(e,t){if(iE(e,nM))throw new nN(nb);return t.facade=e,iZ(e,nM,t),t},nC=function(e){return iE(e,nM)?e[nM]:{}},nv=function(e){return iE(e,nM)}}var nU,nx,nV,nF=nI,nj=function(e){return function(t){var i;if(!tQ(t)||(i=nC(t)).type!==e)throw nN("Incompatible receiver, "+e+" required");return i}},nB=Function.prototype,nG=tL&&Object.getOwnPropertyDescriptor,nW=iE(nB,"name"),nH={EXISTS:nW,PROPER:nW&&"something"===(function(){}).name,CONFIGURABLE:nW&&(!tL||tL&&nG(nB,"name").configurable)},nK=function(e,t,i,r){r&&r.enumerable?e[t]=i:iZ(e,t,i)},nY=iy("iterator"),nq=!1;[].keys&&("next"in(nV=[].keys())?(nx=rC(rC(nV)))!==Object.prototype&&(nU=nx):nq=!0),tD((nU=null==nU||tf(function(){var e={};return nU[nY].call(e)!==e})?{}:rZ(nU))[nY])||nK(nU,nY,function(){return this});var nJ=nU,nX=nq,nz=iH.f,nQ=r8?({}).toString:function(){return"[object "+nt(this)+"]"},nZ=iy("toStringTag"),n$=function(e,t,i,r){if(e){var n=i?e:e.prototype;iE(n,nZ)||nz(n,nZ,{configurable:!0,value:t}),r&&!r8&&iZ(n,"toString",nQ)}},n0=function(){return this},n1=function(e,t,i,r){var n=t+" Iterator";return e.prototype=rZ(nJ,{next:tB(+!r,i)}),n$(e,n,!1,!0),r3[n]=n0,e},n2=nH.PROPER,n3=iy("iterator"),n4="keys",n5="values",n6="entries",n8=function(){return this},n7=function(e,t,i,r,n,o,s){n1(i,t,r);var a,c,d,l=function(e){if(e===n&&E)return E;if(!nX&&e in p)return p[e];switch(e){case n4:case n5:case n6:return function(){return new i(this,e)}}return function(){return new i(this)}},u=t+" Iterator",h=!1,p=e.prototype,_=p[n3]||p["@@iterator"]||n&&p[n],E=!nX&&_||l(n),m="Array"==t&&p.entries||_;if(m&&(a=rC(m.call(new e)))!==Object.prototype&&a.next&&(n$(a,u,!0,!0),r3[u]=n8),n2&&n==n5&&_&&_.name!==n5&&(h=!0,E=function(){return tM(_,this)}),n)if(c={values:l(n5),keys:o?E:l(n4),entries:l(n6)},s)for(d in c)!nX&&!h&&d in p||nK(p,d,c[d]);else i1({target:t,proto:!0,forced:nX||h},c);return s&&p[n3]!==E&&nK(p,n3,E,{name:n}),r3[t]=E,c};iH.f;var n9="Array Iterator",oe=nj(n9);n7(Array,"Array",function(e,t){nF(this,{type:n9,target:tz(e),index:0,kind:t})},function(){var e=oe(this),t=e.target,i=e.kind,r=e.index++;return!t||r>=t.length?(e.target=void 0,{value:void 0,done:!0}):"keys"==i?{value:r,done:!1}:"values"==i?{value:t[r],done:!1}:{value:[r,t[r]],done:!1}},"values"),r3.Arguments=r3.Array;var ot=tA.Promise,oi=iy("species"),or=tA.TypeError,on=iy("iterator"),oo=!1;try{var os=0,oa={next:function(){return{done:!!os++}},return:function(){oo=!0}};oa[on]=function(){return this},Array.from(oa,function(){throw 2})}catch(e){}var oc=function(){},od=[],ol=t0("Reflect","construct"),ou=/^\s*(?:class|function)\b/,oh=tC(ou.exec),op=!ou.exec(oc),o_=function(e){if(!tD(e))return!1;try{return ol(oc,od,e),!0}catch(e){return!1}},oE=function(e){if(!tD(e))return!1;switch(nt(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return op||!!oh(ou,ny(e))}catch(e){return!0}};oE.sham=!0;var om,of,oS,oT,og=!ol||tf(function(){var e;return o_(o_.call)||!o_(Object)||!o_(function(){e=!0})||e})?oE:o_,oR=tA.TypeError,oI=function(e){if(og(e))return e;throw oR(ii(e)+" is not a constructor")},oC=iy("species"),ov=function(e,t){var i,r=iJ(e).constructor;return void 0===r||null==(i=iJ(r)[oC])?t:oI(i)}
1,oy=tC([].slice),oA=/(?:ipad|iphone|ipod).*applewebkit/i.test(t1),oO=tA.setImmediate,ob=tA.clearImmediate,oN=tA.process,ow=tA.Dispatch,oD=tA.Function,oP=tA.MessageChannel,oL=tA.String,ok=0,oM={};try{om=tA.location}catch(e){}var oU=function(e){if(iE(oM,e)){var t=oM[e];delete oM[e],t()}},ox=function(e){return function(){oU(e)}},oV=function(e){oU(e.data)},oF=function(e){tA.postMessage(oL(e),om.protocol+"//"+om.host)};oO&&ob||(oO=function(e){var t=oy(arguments,1);return oM[++ok]=function(){tw(tD(e)?e:oD(e),void 0,t)},of(ok),ok},ob=function(e){delete oM[e]},rt?of=function(e){oN.nextTick(ox(e))}:ow&&ow.now?of=function(e){ow.now(ox(e))}:oP&&!oA?(oT=(oS=new oP).port2,oS.port1.onmessage=oV,of=iW(oT.postMessage,oT)):tA.addEventListener&&tD(tA.postMessage)&&!tA.importScripts&&om&&"file:"!==om.protocol&&!tf(oF)?(of=oF,tA.addEventListener("message",oV,!1)):of="onreadystatechange"in iL("script")?function(e){rY.appendChild(iL("script")).onreadystatechange=function(){rY.removeChild(this),oU(e)}}:function(e){setTimeout(ox(e),0)});var oj,oB,oG,oW,oH,oK,oY,oq,oJ=oO,oX=/ipad|iphone|ipod/i.test(t1)&&void 0!==tA.Pebble,oz=/web0s(?!.*chrome)/i.test(t1),oQ=tP.f,oZ=oJ,o$=tA.MutationObserver||tA.WebKitMutationObserver,o0=tA.document,o1=tA.process,o2=tA.Promise,o3=oQ(tA,"queueMicrotask"),o4=o3&&o3.value;o4||(oj=function(){var e,t;for(rt&&(e=o1.domain)&&e.exit();oB;){t=oB.fn,oB=oB.next;try{t()}catch(e){throw oB?oW():oG=void 0,e}}oG=void 0,e&&e.enter()},oA||rt||oz||!o$||!o0?!oX&&o2&&o2.resolve?((oY=o2.resolve(void 0)).constructor=o2,oq=iW(oY.then,oY),oW=function(){oq(oj)}):rt?oW=function(){o1.nextTick(oj)}:(oZ=iW(oZ,tA),oW=function(){oZ(oj)}):(oH=!0,oK=o0.createTextNode(""),new o$(oj).observe(oK,{characterData:!0}),oW=function(){oK.data=oH=!oH}));var o5=o4||function(e){var t={fn:e,next:void 0};oG&&(oG.next=t),oB||(oB=t,oW()),oG=t},o6={},o8=function(e){var t,i;this.promise=new e(function(e,r){if(void 0!==t||void 0!==i)throw TypeError("Bad Promise constructor");t=e,i=r}),this.resolve=io(t),this.reject=io(i)};o6.f=function(e){return new o8(e)};var o7=function(e,t){if(iJ(e),tQ(t)&&t.constructor===e)return t;var i=o6.f(e);return(0,i.resolve)(t),i.promise},o9=function(e){try{return{error:!1,value:e()}}catch(e){return{error:!0,value:e}}},se=function(){this.head=null,this.tail=null};se.prototype={add:function(e){var t={item:e,next:null};this.head?this.tail.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return this.head=e.next,this.tail===e&&(this.tail=null),e.item}};var st,si,sr,sn="object"==typeof window,so=function(e,t){if(tv(t,e))return e;throw or("Incorrect invocation")},ss=function(e,t){var i=tA.console;i&&i.error&&(1==arguments.length?i.error(e):i.error(e,t))},sa=iy("species"),sc="Promise",sd=nj(sc),sl=nj(sc),su=ot&&ot.prototype,sh=ot,sp=su,s_=tA.TypeError,sE=tA.document,sm=tA.process,sf=o6.f,sS=sf,sT=!!(sE&&sE.createEvent&&tA.dispatchEvent),sg=tD(tA.PromiseRejectionEvent),sR="unhandledrejection",sI=ix(sc,function(){var e=ny(sh),t=e!==String(sh);if(!t&&66===t6||!sp.finally)return!0;if(t6>=51&&/native code/.test(e))return!1;var i=new sh(function(e){e(1)}),r=function(e){e(function(){},function(){})};return(i.constructor={})[sa]=r,!(i.then(function(){})instanceof r)||!t&&sn&&!sg}),sC=sI||!function(e,t){if(!oo)return!1;var i=!1;try{var r={};r[on]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch(e){}return i}(function(e){sh.all(e).catch(function(){})}),sv=function(e){var t;return!(!tQ(e)||!tD(t=e.then))&&t},sy=function(e,t){var i,r,n,o=t.value,s=1==t.state,a=s?e.ok:e.fail,c=e.resolve,d=e.reject,l=e.domain;try{a?(s||(2===t.rejection&&sw(t),t.rejection=1),!0===a?i=o:(l&&l.enter(),i=a(o),l&&(l.exit(),n=!0)),i===e.promise?d(s_("Promise-chain cycle")):(r=sv(i))?tM(r,i,c,d):c(i)):d(o)}catch(e){l&&!n&&l.exit(),d(e)}},sA=function(e,t){e.notified||(e.notified=!0,o5(function(){for(var i,r=e.reactions;i=r.get();)sy(i,e);e.notified=!1,t&&!e.rejection&&sb(e)}))},sO=function(e,t,i){var r,n;sT?((r=sE.createEvent("Event")).promise=t,r.reason=i,r.initEvent(e,!1,!0),tA.dispatchEvent(r)):r={promise:t,reason:i},!sg&&(n=tA["on"+e])?n(r):e===sR&&ss("Unhandled promise rejection",i)},sb=function(e){tM(oJ,tA,function(){var t,i=e.facade,r=e.value;if(sN(e)&&(t=o9(function(){rt?sm.emit("unhandledRejection",r,i):sO(sR,i,r)}),e.rejection=rt||sN(e)?2:1,t.error))throw t.value})},sN=function(e){return 1!==e.rejection&&!e.parent},sw=function(e){tM(oJ,tA,function(){var t=e.facade;rt?sm.emit("rejectionHandled",t):sO("rejectionhandled",t,e.value)})},sD=function(e,t,i){return function(r){e(t,r,i)}},sP=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,sA(e,!0))},sL=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);
1try{if(e.facade===t)throw s_("Promise can't be resolved itself");var r=sv(t);r?o5(function(){var i={done:!1};try{tM(r,t,sD(sL,i,e),sD(sP,i,e))}catch(t){sP(i,t,e)}}):(e.value=t,e.state=1,sA(e,!1))}catch(t){sP({done:!1},t,e)}}};sI&&(sp=(sh=function(e){so(this,sp),io(e),tM(st,this);var t=sd(this);try{e(sD(sL,t),sD(sP,t))}catch(e){sP(t,e)}}).prototype,(st=function(e){nF(this,{type:sc,done:!1,notified:!1,parent:!1,reactions:new se,rejection:!1,state:0,value:void 0})}).prototype=function(e,t,i){for(var r in t)nK(e,r,t[r],void 0);return e}(sp,{then:function(e,t){var i=sl(this),r=sf(ov(this,sh));return i.parent=!0,r.ok=!tD(e)||e,r.fail=tD(t)&&t,r.domain=rt?sm.domain:void 0,0==i.state?i.reactions.add(r):o5(function(){sy(r,i)}),r.promise},catch:function(e){return this.then(void 0,e)}}),si=function(){var e=new st,t=sd(e);this.promise=e,this.resolve=sD(sL,t),this.reject=sD(sP,t)},o6.f=sf=function(e){return e===sh||e===sr?new si(e):sS(e)}),i1({global:!0,wrap:!0,forced:sI},{Promise:sh}),n$(sh,sc,!1,!0),cd=t0(sc),cl=iH.f,tL&&cd&&!cd[oi]&&cl(cd,oi,{configurable:!0,get:function(){return this}}),sr=t0(sc),i1({target:sc,stat:!0,forced:sI},{reject:function(e){var t=sf(this);return tM(t.reject,void 0,e),t.promise}}),i1({target:sc,stat:!0,forced:!0},{resolve:function(e){return o7(this===sr?sh:this,e)}}),i1({target:sc,stat:!0,forced:sC},{all:function(e){var t=this,i=sf(t),r=i.resolve,n=i.reject,o=o9(function(){var i=io(t.resolve),o=[],s=0,a=1;nl(e,function(e){var c=s++,d=!1;a++,tM(i,t,e).then(function(e){d||(d=!0,o[c]=e,--a||r(o))},n)}),--a||r(o)});return o.error&&n(o.value),i.promise},race:function(e){var t=this,i=sf(t),r=i.reject,n=o9(function(){var n=io(t.resolve);nl(e,function(e){tM(n,t,e).then(i.resolve,r)})});return n.error&&r(n.value),i.promise}}),i1({target:"Promise",stat:!0},{allSettled:function(e){var t=this,i=o6.f(t),r=i.resolve,n=i.reject,o=o9(function(){var i=io(t.resolve),n=[],o=0,s=1;nl(e,function(e){var a=o++,c=!1;s++,tM(i,t,e).then(function(e){c||(c=!0,n[a]={status:"fulfilled",value:e},--s||r(n))},function(e){c||(c=!0,n[a]={status:"rejected",reason:e},--s||r(n))})}),--s||r(n)});return o.error&&n(o.value),i.promise}});var sk="No one promise resolved";i1({target:"Promise",stat:!0},{any:function(e){var t=this,i=t0("AggregateError"),r=o6.f(t),n=r.resolve,o=r.reject,s=o9(function(){var r=io(t.resolve),s=[],a=0,c=1,d=!1;nl(e,function(e){var l=a++,u=!1;c++,tM(r,t,e).then(function(e){u||d||(d=!0,n(e))},function(e){u||d||(u=!0,s[l]=e,--c||o(new i(s,sk)))})}),--c||o(new i(s,sk))});return s.error&&o(s.value),r.promise}}),i1({target:"Promise",proto:!0,real:!0,forced:!!ot&&tf(function(){ot.prototype.finally.call({then:function(){}},function(){})})},{finally:function(e){var t=ov(this,t0("Promise")),i=tD(e);return this.then(i?function(i){return o7(t,e()).then(function(){return i})}:e,i?function(i){return o7(t,e()).then(function(){throw i})}:e)}});var sM=tC("".charAt),sU=tC("".charCodeAt),sx=tC("".slice),sV=function(e){return function(t,i){var r,n,o=nh(tX(t)),s=i4(i),a=o.length;return s<0||s>=a?e?"":void 0:(r=sU(o,s))<55296||r>56319||s+1===a||(n=sU(o,s+1))<56320||n>57343?e?sM(o,s):r:e?sx(o,s,s+2):n-56320+(r-55296<<10)+65536}},sF={codeAt:sV(!1),charAt:sV(!0)}.charAt,sj="String Iterator",sB=nj(sj);n7(String,"String",function(e){nF(this,{type:sj,string:nh(e),index:0})},function(){var e,t=sB(this),i=t.string,r=t.index;return r>=i.length?{value:void 0,done:!0}:(e=sF(i,r),t.index+=e.length,{value:e,done:!1})});var sG=tZ.Promise,sW={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},sH=iy("toStringTag");for(var sK in sW){var sY=tA[sK],sq=sY&&sY.prototype;sq&&nt(sq)!==sH&&iZ(sq,sH,sK),r3[sK]=r3.Array}function sJ(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=>
1{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 s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then(i=>{let s=(i=i.filter(e=>"videoinput"===e.kind)).find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!s&&i.length&&t.includes("back")&&(s=i[i.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=r(e.video),rp("chrome: "+JSON.stringify(e)),n(e)})}e.video=r(e.video)}return rp("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=>sG.reject(o(e))))}}}function sX(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function sz(e){if("object"!=typeof e||!e.RTCPeerConnection||"ontrack"in e.RTCPeerConnection.prototype)rl(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)}),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 sQ(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().forEac
1h(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 sZ(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 sG((e,i)=>{t.apply(this,[function(t){e(o(n(t)))},i])}).then(i,r)}}function s$(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=>rm(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}),rl(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>rm(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];return 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?sG.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):e?e.getStats():t?t.getStats():sG.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function s0(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||{}
1,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 s1(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return s0(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),sG.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)}return 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 s=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}))),s.apply(this,arguments)};let a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){let e=a.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 s2(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 s3(e,t){rl(e,"negotiationneeded",e=>{let i=e.target;
1if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e})}var s4=Object.freeze({__proto__:null,shimMediaStream:sX,shimOnTrack:sz,shimGetSendersWithDtmf:sQ,shimGetStats:sZ,shimSenderReceiverGetStats:s$,shimAddTrackRemoveTrackWithNative:s0,shimAddTrackRemoveTrack:s1,shimPeerConnection:s2,fixNegotiationNeeded:s3,shimGetUserMedia:sJ,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"))}});function s5(e,t){let i=e&&e.navigator,r=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,r){r_("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 s6(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 s8(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",remotecandidate:"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 s7(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):sG.resolve(new Map)}}function s9(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,[]);
1return e.forEach(e=>e._pc=this),e}),rl(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function ae(e){!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){r_("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function at(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function ai(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 ar(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 an(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?sG.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function ao(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?sG.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var as=Object.freeze({__proto__:null,shimOnTrack:s6,shimPeerConnection:s8,shimSenderGetStats:s7,shimReceiverGetStats:s9,shimRemoveStream:ae,shimRTCDataChannel:at,shimAddTransceiver:ai,shimGetParameters:ar,shimCreateOffer:an,shimCreateAnswer:ao,shimGetUserMedia:s5,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,sG.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})}});function aa(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(i=>t.call(this,i,e)),e.getVideoTracks().forEach(i=>t.call(this,i,e))},e.RTCPeerConnection.prototype.addTrack=function(e){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=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);let t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);let i=e.getTracks();
1this.getSenders().forEach(e=>{i.includes(e.track)&&this.removeTrack(e)})})}}function ac(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);let t=new Event("addstream");t.stream=e,this.dispatchEvent(t)})})}});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 ad(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,s=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),sG.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),sG.resolve()):n};let a=function(e,t,i){let r=n.apply(this,[e]);return i?(r.then(t,i),sG.resolve()):r};t.setLocalDescription=a,t.setRemoteDescription=a=function(e,t,i){let r=o.apply(this,[e]);return i?(r.then(t,i),sG.resolve()):r},t.addIceCandidate=a=function(e,t,i){let r=s.apply(this,[e]);return i?(r.then(t,i),sG.resolve()):r}}function al(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(au(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=(function(e,i,r){t.mediaDevices.getUserMedia(e).then(i,r)}).bind(t))}function au(e){return e&&void 0!==e.video?Object.assign({},e,{video:function e(t){var i;return rE(t)?rs(i=Object.keys(t)).call(i,function(i,r){let n=rE(t[r]),o=n?e(t[r]):t[r],s=n&&!Object.keys(o).length;return void 0===o||s?i:Object.assign(i,{[r]:o})},{}):t}(e.video)}):e}function ah(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")?(r_("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 ap(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 a_(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 aE(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var am=Object.freeze({__proto__:null,shimLocalStreamsAPI:aa,shimRemoteStreamsAPI:ac,shimCallbacksAPI:ad,shimGetUserMedia:al,shimConstraints:au,shimRTCIceServerUrls:ah,shimTrackEventTransceiver:ap,shimCreateOfferLegacy:a_,shimAudioContext:aE}),af=tC("".replace),aS="[	\n\v\f\r \xa0               \u2028\u2029\uFEFF]",aT=RegExp("^"+aS+aS+"*"),ag=RegExp(aS+aS+"*$"),aR=function(e){return function(t){var i=nh(tX(t));return 1&e&&(i=af(i,aT,"")),2&e&&(i=af(i,ag,"")),i}},aI={start:aR(1),end:aR(2),trim:aR(3)},aC=nH.PROPER,av="	\n\v\f\r \xa0               \u2028\u2029\uFEFF",ay=aI.trim;i1({target:"String",proto:!0,forced:(cu="trim",tf(function(){return!!av[cu]()||"​\x85᠎"!=="​\x85᠎"[cu]()||aC&&av[cu].name!==cu}))},{trim:function(){return ay(this)}});
1var aA=rr("String").trim,aO=String.prototype,ab=function(e){var t=e.trim;return"string"==typeof e||e===aO||tv(aO,e)&&t===aO.trim?aA:t},aN={exports:{}};let aw={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};aw.localCName=aw.generateIdentifier(),aw.splitLines=function(e){return ab(e).call(e).split("\n").map(e=>ab(e).call(e))},aw.splitSections=function(e){return e.split("\nm=").map((e,t)=>{var i;return ab(i=t>0?"m="+e:e).call(i)+"\r\n"})},aw.getDescription=function(e){let t=aw.splitSections(e);return t&&t[0]},aw.getMediaSections=function(e){let t=aw.splitSections(e);return t.shift(),t},aw.matchPrefix=function(e,t){return aw.splitLines(e).filter(e=>0===e.indexOf(t))},aw.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},aw.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.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.pu
1sh(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},aw.parseIceOptions=function(e){return e.substr(14).split(" ")},aw.parseRtpMap=function(e){let t=e.substr(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},aw.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"},aw.parseExtmap=function(e){let t=e.substr(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1]}},aw.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+"\r\n"},aw.parseFmtp=function(e){let t,i={},r=e.substr(e.indexOf(" ")+1).split(";");for(let e=0;e<r.length;e++){var n,o;t=ab(n=r[e]).call(n).split("="),i[ab(o=t[0]).call(o)]=t[1]}return i},aw.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},aw.parseRtcpFb=function(e){let t=e.substr(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},aw.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},aw.parseSsrcMedia=function(e){let t=e.indexOf(" "),i={ssrc:parseInt(e.substr(7,t-7),10)},r=e.indexOf(":",t);return r>-1?(i.attribute=e.substr(t+1,r-t-1),i.value=e.substr(r+1)):i.attribute=e.substr(t+1),i},aw.parseSsrcGroup=function(e){let t=e.substr(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},aw.getMid=function(e){let t=aw.matchPrefix(e,"a=mid:")[0];if(t)return t.substr(6)},aw.parseFingerprint=function(e){let t=e.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},aw.getDtlsParameters=function(e,t){return{role:"auto",fingerprints:aw.matchPrefix(e+t,"a=fingerprint:").map(aw.parseFingerprint)}},aw.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},aw.parseCryptoLine=function(e){let t=e.substr(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},aw.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?aw.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},aw.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;let t=e.substr(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},aw.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},aw.getCryptoParameters=function(e,t){return aw.matchPrefix(e+t,"a=crypto:").map(aw.parseCryptoLine)},aw.getIceParameters=function(e,t){let i=aw.matchPrefix(e+t,"a=ice-ufrag:")[0],r=aw.matchPrefix(e+t,"a=ice-pwd:")[0];return i&&r?{usernameFragment:i.substr(12),password:r.substr(10)}:null},aw.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},aw.parseRtpParameters=function(e){let t={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=aw.splitLines(e)[0].split(" ");for(let r=3;r<i.length;r++){let n=i[r],o=aw.matchPrefix(e,"a=rtpmap:"+n+" ")[0];if(o){let i=aw.parseRtpMap(o),r=aw.matchPrefix(e,"a=fmtp:"+n+" ");switch(i.parameters=r.length?aw.parseFmtp(r[0]):{},i.rtcpFeedback=aw.matchPrefix(e,"a=rtcp-fb:"+n+" ").map(aw.parseRtcpFb),t.codecs.push(i),i.name.toUpperCase()){case"RED":case"ULPFEC":t.fecMechanisms.push(i.name.toUpperCase())}}}
1return aw.matchPrefix(e,"a=extmap:").forEach(e=>{t.headerExtensions.push(aw.parseExtmap(e))}),t},aw.writeRtpDescription=function(e,t){let i="";i+="m="+e+" ",i+=t.codecs.length>0?"9":"0",i+=" 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+=aw.writeRtpMap(e),i+=aw.writeFmtp(e),i+=aw.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+=aw.writeExtmap(e)}),i},aw.parseRtpEncodingParameters=function(e){let t,i=[],r=aw.parseRtpParameters(e),n=-1!==r.fecMechanisms.indexOf("RED"),o=-1!==r.fecMechanisms.indexOf("ULPFEC"),s=aw.matchPrefix(e,"a=ssrc:").map(e=>aw.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute),a=s.length>0&&s[0].ssrc,c=aw.matchPrefix(e,"a=ssrc-group:FID").map(e=>e.substr(17).split(" ").map(e=>parseInt(e,10)));c.length>0&&c[0].length>1&&c[0][0]===a&&(t=c[0][1]),r.codecs.forEach(e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let r={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&t&&(r.rtx={ssrc:t}),i.push(r),n&&((r=JSON.parse(JSON.stringify(r))).fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},i.push(r))}}),0===i.length&&a&&i.push({ssrc:a});let d=aw.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substr(7),10):0===d[0].indexOf("b=AS:")?1e3*parseInt(d[0].substr(5),10)*.95-16e3:void 0,i.forEach(e=>{e.maxBitrate=d})),i},aw.parseRtcpParameters=function(e){let t={},i=aw.matchPrefix(e,"a=ssrc:").map(e=>aw.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute)[0];i&&(t.cname=i.value,t.ssrc=i.ssrc);let r=aw.matchPrefix(e,"a=rtcp-rsize");return t.reducedSize=r.length>0,t.compound=0===r.length,t.mux=aw.matchPrefix(e,"a=rtcp-mux").length>0,t},aw.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},aw.parseMsid=function(e){let t,i=aw.matchPrefix(e,"a=msid:");if(1===i.length)return{stream:(t=i[0].substr(7).split(" "))[0],track:t[1]};let r=aw.matchPrefix(e,"a=ssrc:").map(e=>aw.parseSsrcMedia(e)).filter(e=>"msid"===e.attribute);return r.length>0?{stream:(t=r[0].value.split(" "))[0],track:t[1]}:void 0},aw.parseSctpDescription=function(e){let t,i=aw.parseMLine(e),r=aw.matchPrefix(e,"a=max-message-size:");r.length>0&&(t=parseInt(r[0].substr(19),10)),isNaN(t)&&(t=65536);let n=aw.matchPrefix(e,"a=sctp-port:");if(n.length>0)return{port:parseInt(n[0].substr(12),10),protocol:i.fmt,maxMessageSize:t};let o=aw.matchPrefix(e,"a=sctpmap:");if(o.length>0){let e=o[0].substr(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:t}}},aw.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("")},aw.generateSessionId=function(){return Math.random().toString().substr(2,21)},aw.writeSessionBoilerplate=function(e,t,i){return"v=0\r\no="+(i||"thisisadapterortc")+" "+(e||aw.generateSessionId())+" "+(void 0!==t?t:2)+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},aw.getDirection=function(e,t){let i=aw.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].substr(2)}return t?aw.getDirection(t):"sendrecv"},aw.getKind=function(e){return aw.splitLines(e)[0].split(" ")[0].substr(2)},aw.isRejected=function(e){return"0"===e.split(" ",2)[1]},aw.parseMLine=function(e){let t=aw.splitLines(e)[0].substr(2).split(" ");return{kind:t[0],port:parseInt(t[1],10),protocol:t[2],fmt:t.slice(3).join(" ")}},aw.parseOLine=function(e){let t=aw.matchPrefix(e,"o=")[0].substr(2).split(" ");return{username:t[0],sessionId:t[1],sessionVersion:parseInt(t[2],10),netType:t[3],addressType:t[4],address:t[5]}},aw.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;let t=aw.splitLines(e);for(let e=0;e<t.length;e++)if(t[e].length<2||"="!==t[e].charAt(1))return!1;return!0},aN.exports=aw;var aD=aN.exports,aP=Object.freeze((ch={__proto__:null,default:aD}
1,[aN.exports].forEach(function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach(function(t){if("default"!==t&&!(t in ch)){var i=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(ch,t,i.get?i:{enumerable:!0,get:function(){return e[t]}})}})}),Object.freeze(ch)));function aL(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),aD.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,rl(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function ak(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||rl(e,"icecandidate",e=>{if(e.candidate){let t=aD.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol=({0:"tls",1:"tcp",2:"udp"})[t.priority>>24])}return e})}function aM(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=aD.splitSections(e.sdp);return t.shift(),t.some(e=>{let t=aD.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=aD.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},s=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),s=o(arguments[0],t);e=0===i&&0===s?Number.POSITIVE_INFINITY:0===i||0===s?Math.max(i,s):Math.min(i,s);let a={};Object.defineProperty(a,"maxMessageSize",{get:()=>e}),this._sctp=a}return s.apply(this,arguments)}}function aU(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},rl(e,"datachannel",e=>(t(e.channel,e.target),e))}function ax(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}
1),["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 aV(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"!==ab(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 aF(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?sG.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),sG.resolve())})}function aj(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 aB=Object.freeze({__proto__:null,shimRTCIceCandidate:aL,shimRTCIceCandidateRelayProtocol:ak,shimMaxMessageSize:aM,shimSendThrowTypeError:aU,shimConnectionState:ax,removeExtmapAllowMixed:aV,shimAddIceCandidateNullOrEmpty:aF,shimParameterlessSetLocalDescription:aj});!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=rd(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=rd(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!i.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=rd(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),r={browserDetails:i,commonShim:aB,extractVersion:rd,disableLog:ru,disableWarnings:rh,sdp:aP};switch(i.browser){case"chrome":if(!s4||!s2||!t.shimChrome)return rp("Chrome shim is not included in this adapter release.");if(null===i.version)return rp("Chrome shim can not determine version, not shimming.");rp("adapter.js shimming chrome."),r.browserShim=s4,aF(e,i),aj(e),sJ(e,i),sX(e),s2(e,i),sz(e),s1(e,i),sQ(e),sZ(e),s$(e),s3(e,i),aL(e),ak(e),ax(e),aM(e,i),aU(e),aV(e,i);break;case"firefox":if(!as||!s8||!t.shimFirefox)return rp("Firefox shim is not included in this adapter release.");rp("adapter.js shimming firefox."),r.browserShim=as,aF(e,i),aj(e),s5(e,i),s8(e,i),s6(e),ae(e),s7(e),s9(e),at(e),ai(e),ar(e),an(e),ao(e),aL(e),ax(e),aM(e,i),aU(e);break;case"safari":if(!am||!t.shimSafari)return rp("Safari shim is not included in this adapter release.");rp("adapter.js shimming safari."),r.browserShim=am,aF(e,i),aj(e),ah(e),a_(e),ad(e),aa(e),ac(e),ap(e),al(e),aE(e),aL(e),ak(e),aM(e,i),aU(e),aV(e,i);break;default:rp("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window}),(cp=e||(e={})).WIN_10="Windows 10",cp.WIN_81="Windows 8.1",cp.WIN_8="Windows 8",cp.WIN_7="Windows 7",cp.WIN_VISTA="Windows Vista",cp.WIN_SERVER_2003="Windows Server 2003",cp.WIN_XP="Windows XP",cp.WIN_2000="Windows 2000",cp.ANDROID="Android",cp.OPEN_BSD="Open BSD",cp.SUN_OS="Sun OS",cp.LINUX="Linux",cp.IOS="iOS",cp.MAC_OS="Mac OS",cp.QNX="QNX",cp.UNIX="UNIX",cp.BEOS="BeOS",cp.OS_2
vendor: 4,151 bytes, line 1
1="OS/2",cp.SEARCH_BOT="Search Bot",(c_=t||(t={})).CHROME="Chrome",c_.SAFARI="Safari",c_.EDGE="Edge",c_.FIREFOX="Firefox",c_.OPERA="OPR",c_.QQ="QQBrowser",c_.WECHAT="MicroMessenger";var aG={exports:{}};cE=aG.exports,function(e,t){var i="function",r="undefined",n="object",o="string",s="model",a="name",c="type",d="vendor",l="version",u="architecture",h="console",p="mobile",_="tablet",E="smarttv",m="wearable",f="embedded",S="Amazon",T="Apple",g="ASUS",R="BlackBerry",I="Google",C="Huawei",v="Microsoft",y="Motorola",A="Samsung",O="Sharp",b="Sony",N="Xiaomi",w="Zebra",D="Facebook",P="Chromium OS",L="Mac OS",k=function(e){for(var t={},i=0;i<e.length;i++)t[e[i].toUpperCase()]=e[i];return t},M=function(e,t){return typeof e===o&&-1!==U(t).indexOf(U(e))},U=function(e){return e.toLowerCase()},x=function(e,t){if(typeof e===o)return e=e.replace(/^\s\s*/,""),typeof t===r?e:e.substring(0,350)},V=function(e,r){for(var o,s,a,c,d,l,u=0;u<r.length&&!d;){var h=r[u],p=r[u+1];for(o=s=0;o<h.length&&!d&&h[o];)if(d=h[o++].exec(e))for(a=0;a<p.length;a++)l=d[++s],typeof(c=p[a])===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;u+=2}},F=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(M(i[r][o],e))return"?"===r?t:r}else if(M(i[r],e))return"?"===r?t:r;return e},j={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"},B={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[l,[a,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[l,[a,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[a,l],[/opios[\/ ]+([\w\.]+)/i],[l,[a,"Opera Mini"]],[/\bopr\/([\w\.]+)/i],[l,[a,"Opera"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,/(ba?idubrowser)[\/ ]?([\w\.]+)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(weibo)__([\d\.]+)/i],[a,l],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[l,[a,"UCBrowser"]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[l,[a,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[l,[a,"WeChat"]],[/konqueror\/([\w\.]+)/i],[l,[a,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[l,[a,"IE"]],[/yabrowser\/([\w\.]+)/i],[l,[a,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[a,/(.+)/,"$1 Secure Browser"],l],[/\bfocus\/([\w\.]+)/i],[l,[a,"Firefox Focus"]],[/\bopt\/([\w\.]+)/i],[l,[a,"Opera Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[l,[a,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[l,[a,"Dolphin"]],[/coast\/([\w\.]+)/i],[l,[a,"Opera Coast"]],[/miuibrowser\/([\w\.]+)/i],[l,[a,"MIUI Browser"]],[/fxios\/([-\w\.]+)/i],[l,[a,"Firefox"]],[/\bqihu|(qi?ho?o?|360)browser/i],[[a,"360 Browser"]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[a,/(.+)/,"$1 Browser"],l],[/(comodo_dragon)\/([\w\.]+)/i],[[a,/_/g," "],l],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[a,l],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[a],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[a,D],l],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/ ]([-\w\.]+)/i],[a,l],[/\bgsa\/([\w\.]+) .*safari\//i],[l,[a,"GSA"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[l,[a,"Chrome Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[a,"Chrome WebView"],l],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[l,[a,"Android Browser"]],[/(chrome|omniweb|arora|[t
vendor: 4,824 bytes, line 1
1izenoka]{5} ?browser)\/v?([\w\.]+)/i],[a,l],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[l,[a,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[l,a],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[a,[l,F,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[a,l],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[a,"Netscape"],l],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[l,[a,"Firefox Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[a,l],[/(cobalt)\/([\w\.]+)/i],[a,[l,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[u,"amd64"]],[/(ia32(?=;))/i],[[u,U]],[/((?:i[346]|x)86)[;\)]/i],[[u,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[u,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[u,"armhf"]],[/windows (ce|mobile); ppc;/i],[[u,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[u,/ower/,"",U]],[/(sun4\w)[;\)]/i],[[u,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[u,U]]],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,[d,A],[c,_]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[s,[d,A],[c,p]],[/\((ip(?:hone|od)[\w ]*);/i],[s,[d,T],[c,p]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[s,[d,T],[c,_]],[/(macintosh);/i],[s,[d,T]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[s,[d,O],[c,p]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[s,[d,C],[c,_]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[s,[d,C],[c,p]],[/\b(poco[\w ]+)(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[s,/_/g," "],[d,N],[c,p]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[s,/_/g," "],[d,N],[c,_]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[s,[d,"OPPO"],[c,p]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[s,[d,"Vivo"],[c,p]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[s,[d,"Realme"],[c,p]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[s,[d,y],[c,p]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[s,[d,y],[c,_]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[s,[d,"LG"],[c,_]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[s,[d,"LG"],[c,p]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[s,[d,"Lenovo"],[c,_]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[s,/_/g," "],[d,"Nokia"],[c,p]],[/(pixel c)\b/i],[s,[d,I],[c,_]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[s,[d,I],[c,p]],[/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,[d,b],[c,p]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[s,"Xperia Tablet"],[d,b],[c,_]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[s,[d,"OnePlus"],[c,p]],[/(alexa)webm/i,/(kf[a-z]{2}wi)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[s,[d,S],[c,_]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[s,/(.+)/g,"Fire Phone $1"],[d,S],[c,p]],[/(playbook);[-\w\),; ]+(rim)/i],[s,d,[c,_]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[s,[d,R],[c,p]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[s,[d,g],[c,_]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[s,[d,g],[c,p]],[/(nexus 9)/i],[s,[d,"HTC"],[c,_]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[d,[s,/_/g," "],[c,p]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[s,[d,"Acer"],[c,_]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[s,[d,"Meizu"],[c,p]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asu
1s)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[d,s,[c,p]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/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],[d,s,[c,_]],[/(surface duo)/i],[s,[d,v],[c,_]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[s,[d,"Fairphone"],[c,p]],[/(u304aa)/i],[s,[d,"AT&T"],[c,p]],[/\bsie-(\w*)/i],[s,[d,"Siemens"],[c,p]],[/\b(rct\w+) b/i],[s,[d,"RCA"],[c,_]],[/\b(venue[\d ]{2,7}) b/i],[s,[d,"Dell"],[c,_]],[/\b(q(?:mv|ta)\w+) b/i],[s,[d,"Verizon"],[c,_]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[s,[d,"Barnes & Noble"],[c,_]],[/\b(tm\d{3}\w+) b/i],[s,[d,"NuVision"],[c,_]],[/\b(k88) b/i],[s,[d,"ZTE"],[c,_]],[/\b(nx\d{3}j) b/i],[s,[d,"ZTE"],[c,p]],[/\b(gen\d{3}) b.+49h/i],[s,[d,"Swiss"],[c,p]],[/\b(zur\d{3}) b/i],[s,[d,"Swiss"],[c,_]],[/\b((zeki)?tb.*\b) b/i],[s,[d,"Zeki"],[c,_]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[d,"Dragon Touch"],s,[c,_]],[/\b(ns-?\w{0,9}) b/i],[s,[d,"Insignia"],[c,_]],[/\b((nxa|next)-?\w{0,9}) b/i],[s,[d,"NextBook"],[c,_]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[d,"Voice"],s,[c,p]],[/\b(lvtel\-)?(v1[12]) b/i],[[d,"LvTel"],s,[c,p]],[/\b(ph-1) /i],[s,[d,"Essential"],[c,p]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[s,[d,"Envizen"],[c,_]],[/\b(trio[-\w\. ]+) b/i],[s,[d,"MachSpeed"],[c,_]],[/\btu_(1491) b/i],[s,[d,"Rotor"],[c,_]],[/(shield[\w ]+) b/i],[s,[d,"Nvidia"],[c,_]],[/(sprint) (\w+)/i],[d,s,[c,p]],[/(kin\.[onetw]{3})/i],[[s,/\./g," "],[d,v],[c,p]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[s,[d,w],[c,_]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[s,[d,w],[c,p]],[/smart-tv.+(samsung)/i],[d,[c,E]],[/hbbtv.+maple;(\d+)/i],[[s,/^/,"SmartTV"],[d,A],[c,E]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[d,"LG"],[c,E]],[/(apple) ?tv/i],[d,[s,"Apple TV"],[c,E]],[/crkey/i],[[s,"Chromecast"],[d,I],[c,E]],[/droid.+aft(\w)( bui|\))/i],[s,[d,S],[c,E]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[s,[d,O],[c,E]],[/(bravia[\w ]+)( bui|\))/i],[s,[d,b],[c,E]],[/(mitv-\w{5}) bui/i],[s,[d,N],[c,E]],[/Hbbtv.*(technisat) (.*);/i],[d,s,[c,E]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[d,x],[s,x],[c,E]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[c,E]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[d,s,[c,h]],[/droid.+; (shield) bui/i],[s,[d,"Nvidia"],[c,h]],[/(playstation [345portablevi]+)/i],[s,[d,b],[c,h]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[s,[d,v],[c,h]],[/((pebble))app/i],[d,s,[c,m]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[s,[d,T],[c,m]],[/droid.+; (glass) \d/i],[s,[d,I],[c,m]],[/droid.+; (wt63?0{2,3})\)/i],[s,[d,w],[c,m]],[/(quest( 2| pro)?)/i],[s,[d,D],[c,m]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[d,[c,f]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[s,[c,p]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[s,[c,_]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[c,_]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[c,p]],[/(android[-\w\. ]{0,9});.+buil/i],[s,[d,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[l,[a,"EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[l,[a,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i],[a,l],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[l,a]],os:[[/microsoft (windows) (vista|xp)/i],[a,l],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[a,[l,F,j]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[a,"Windows"],[l,F,j]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/cfnetwork\/.+darwin/i],[[l,/_/g,"."],[a,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[a,L],[l,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[l,a],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[a,l],[/\(bb(10);/i],[l,[a,R]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[l,[a,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[l,[a,"Firefox OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[l,[a,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[l,[a,"watchOS"]],[/crkey\/([\d\.]+)/i],[l,[a,"Chromecast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[a,P],l],[/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) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[a,l],[/(sunos) ?([\w\.\d]*)/i],[[a,"Solaris"],l],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux)/i,/(unix) ?([\w\.]*)/i],[a,l]]},G=function(s,a){if(typeof s===n&&(a=s,s=t),!(this instanceof G))return new G(s,a).getResult();var c=typeof e!==r&&e.navigator?e.navigator:t,d=s||(c&&c.userAgent?c.userAgent:""),l=c&&c.userAgentData?c.userAgentData:t,u=a?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}(B,a):B;return this.getBrowser=function(){var e,r={};return r.name=t,r.version=t,V.call(r,d,u.browser),r.major=typeof(e=r.version)===o?e.replace(/[^\d\.]/g,"").split(".")[0]:t,c&&c.brave&&typeof c.brave.isBrave==i&&(r.name="Brave"),r},this.getCPU=function(){var e={};return e.architecture=t,V.call(e,d,u.cpu),e},this.getDevice=function(){var e={};return e.vendor=t,e.model=t,e.type=t,V.call(e,d,u.device),!e.type&&l&&l.mobile&&(e.type=p),"Macintosh"==e.model&&c&&typeof c.standalone!==r&&c.maxTouchPoints&&c.maxTouchPoints>2&&(e.model="iPad",e.type=_),e},this.getEngine=function(){var e={};return e.name=t,e.version=t,V.call(e,d,u.engine),e},this.getOS=function(){var e={};return e.name=t,e.version=t,V.call(e,d,u.os),!e.name&&l&&"Unknown"!=l.platform&&(e.name=l.platform.replace(/chrome os/i,P).replace(/macos/i,L)),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 d},this.setUA=function(e){return d=typeof e===o&&e.length>350?x(e,350):e,this},this.setUA(d),this};G.VERSION="0.7.34",G.BROWSER=k([a,l,"major"]),G.CPU=k([u]),G.DEVICE=k([s,d,c,h,p,E,_,m,f]),G.ENGINE=G.OS=k([a,l]),aG.exports&&(cE=aG.exports=G),cE.UAParser=G;var W=typeof e!==r&&(e.jQuery||e.Zepto);if(W&&!W.ua){var H=new G;W.ua=H.getResult(),W.ua.get=function(){return H.getUA()},W.ua.set=function(e){H.setUA(e);var t=H.getResult();for(var i in t)W.ua[i]=t[i]}}}("object"==typeof window?window:tm);let aW=new(0,aG.exports),aH,aK=aW.getResult();function aY(e){var i,r;return e&&aW.setUA(e),{name:function(e){if("Blink"===e.engine.name&&"WeChat"!==e.browser.name)return t.CHROME;switch(e.browser.name){case"Chrome Headless":case"Chrome":case"Chromium":return t.CHROME;case"Safari":case"Mobile Safari":return t.SAFARI;case"Edge":return t.EDGE;case"Firefox":return t.FIREFOX;case"QQBrowser":return t.QQ;
1case"Opera":return t.OPERA;case"WeChat":return t.WECHAT;default:return e.browser.name||""}}(aK=aW.getResult()),version:("Blink"===(i=aK).engine.name?i.engine.version||"":i.browser.version||"").split(".")[0],os:"Windows"===(r=aK).os.name?r.os.version?r.os.name+" "+r.os.version:r.os.name:r.os.name||"",osVersion:aK.os.version}}function aq(){let i=aY();return!!("WebKit"===aK.engine.name&&i.os===e.MAC_OS&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0&&i.name!==t.SAFARI||aQ()&&i.name!==t.SAFARI)}function aJ(){return aY().name===t.CHROME}function aX(){return aY().name===t.SAFARI}function az(){return aY().name===t.FIREFOX}function aQ(){return aY().os===e.IOS}function aZ(e){let i=aY();return!(i.name!==t.CHROME||!i.osVersion)&&Number(i.version)>=e}function a$(e){let i=aY();return!(i.name!==t.EDGE||!i.osVersion)&&Number(i.version)>=e}function a0(e){let i=aY();return!(i.name!==t.OPERA||!i.osVersion)&&Number(i.version)>=e}function a1(){let e=aY();return!(e.name!==t.CHROME||!e.osVersion)&&90>=Number(e.version)}function a2(){let t=aY();if(t.os!==e.IOS||!t.osVersion)return!1;let i=t.osVersion.split(".");return 14>Number(i[0])||14===Number(i[0])&&6>=Number(i[1])}function a3(){let t=aY();return t.os===e.IOS&&!!t.osVersion&&15===Number(t.osVersion.split(".")[0])}function a4(){let t=aY();if(t.os!==e.IOS||!t.osVersion)return!1;let i=t.osVersion.split(".");return 15===Number(i[0])&&0===Number(i[1])}function a5(){let t=aY();if(t.os!==e.IOS||!t.osVersion)return!1;let i=t.osVersion.split(".");return 15===Number(i[0])&&Number(i[1])>=1}function a6(){let t=aY();if(t.os!==e.IOS||!t.osVersion)return!1;let i=t.osVersion.split(".");return 15===Number(i[0])&&Number(i[1])>=2}function a8(){return aX()&&navigator.maxTouchPoints>0}function a7(){return aY().name===t.WECHAT}function a9(){return window.navigator.appVersion&&null!==window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)&&window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)[1]<=35}function ce(){let e=aY();return e.name!==t.EDGE&&e.name!==t.SAFARI&&!!navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]./i)}function ct(){return aY().os===e.ANDROID}function ci(){let e=aY();return"Android"===e.os&&("Chrome"===e.name||e.name===t.WECHAT||/chrome|chromium/i.test(navigator.userAgent))}(cm=aH||(aH={})).CERTIFICATE="certificate",cm.CODEC="codec",cm.CANDIDATE_PAIR="candidate-pair",cm.LOCAL_CANDIDATE="local-candidate",cm.REMOTE_CANDIDATE="remote-candidate",cm.INBOUND="inbound-rtp",cm.TRACK="track",cm.OUTBOUND="outbound-rtp",cm.PC="peer-connection",cm.REMOTE_INBOUND="remote-inbound-rtp",cm.REMOTE_OUTBOUND="remote-outbound-rtp",cm.TRANSPORT="transport",cm.CSRC="csrc",cm.DATA_CHANNEL="data-channel",cm.STREAM="stream",cm.SENDER="sender",cm.RECEIVER="receiver";var cr={exports:{}},cn=iH.f;i1({target:"Object",stat:!0,forced:Object.defineProperty!==cn,sham:!tL},{defineProperty:cn});var co=tZ.Object,cs=cr.exports=function(e,t,i){return co.defineProperty(e,t,i)};co.defineProperty.sham&&(cs.sham=!0);var ca=cr.exports;function cc(e,t,i){return t in e?ca(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}var cd,cl,cu,ch,cp,c_,cE,cm,cf,cS={exports:{}},cT=function(e,t){return function(){for(var i=Array(arguments.length),r=0;r<i.length;r++)i[r]=arguments[r];return e.apply(t,i)}},cg=Object.prototype.toString,cR=(cf=Object.create(null),function(e){var t=cg.call(e);return cf[t]||(cf[t]=t.slice(8,-1).toLowerCase())});function cI(e){return e=e.toLowerCase(),function(t){return cR(t)===e}}function cC(e){return Array.isArray(e)}function cv(e){return void 0===e}var cy=cI("ArrayBuffer");function cA(e){return null!==e&&"object"==typeof e}function cO(e){if("object"!==cR(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}var cb=cI("Date"),cN=cI("File"),cw=cI("Blob"),cD=cI("FileList");function cP(e){return"[object Function]"===cg.call(e)}function cL(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),cC(e))for(var i=0,r=e.length;i<r;i++)t.call(null,e[i],i,e);else for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.call(null,e[n],n,e)}var ck,cM={isArray:cC,isArrayBuffer:cy,isBuffer:function(e){return null!==e&&!cv(e)&&null!==e.constructor&&!cv(e.constructor)&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)},isFormData:function(e){var t="[object FormData]";return e&&("function"==typeof FormData&&e instanceof FormData||cg.call(e)===t||cP(e.toString)&&e.toString()===t)},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&cy(e.buffer)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:cA,isPlainObject:cO,isUndefined:cv,isDate:cb,isFile:cN,isBlob:cw,isFunction:cP,isStream:function(e){return cA(e)&&cP(e.pipe)},isURLSearchParams:cI("URLSearchParams"),isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&"undefined"!=typeof window&&"undefined"!=typeof document},forEach:cL,merge:function e(){var t={};function i(i,r){cO(t[r])&&cO(i)?t[r]=e(t[r],i):cO(i)?t[r]=e({},i):cC(i)?t[r]=i.slice():t[r]=i}for(var r=0,n=arguments.length;r<n;r++)cL(arguments[r],i);return t},extend:function(e,t,i){return cL(t,function(t,r){e[r]=i&&"function"==typeof t?cT(t,i):t}),e},trim:function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")},stripBOM:function(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),e},inherits:function(e,t,i,r){e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,i&&Object.assign(e.prototype,i
1)},toFlatObject:function(e,t,i){var r,n,o,s={};t=t||{};do{for(n=(r=Object.getOwnPropertyNames(e)).length;n-- >0;)s[o=r[n]]||(t[o]=e[o],s[o]=!0);e=Object.getPrototypeOf(e)}while(e&&(!i||i(e,t))&&e!==Object.prototype);return t},kindOf:cR,kindOfTest:cI,endsWith:function(e,t,i){e=String(e),(void 0===i||i>e.length)&&(i=e.length),i-=t.length;var r=e.indexOf(t,i);return -1!==r&&r===i},toArray:function(e){if(!e)return null;var t=e.length;if(cv(t))return null;for(var i=Array(t);t-- >0;)i[t]=e[t];return i},isTypedArray:(ck="undefined"!=typeof Uint8Array&&Object.getPrototypeOf(Uint8Array),function(e){return ck&&e instanceof ck}),isFileList:cD};function cU(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var cx=function(e,t,i){if(!t)return e;if(i)r=i(t);else if(cM.isURLSearchParams(t))r=t.toString();else{var r,n=[];cM.forEach(t,function(e,t){null!=e&&(cM.isArray(e)?t+="[]":e=[e],cM.forEach(e,function(e){cM.isDate(e)?e=e.toISOString():cM.isObject(e)&&(e=JSON.stringify(e)),n.push(cU(t)+"="+cU(e))}))}),r=n.join("&")}if(r){var o=e.indexOf("#");-1!==o&&(e=e.slice(0,o)),e+=(-1===e.indexOf("?")?"?":"&")+r}return e};function cV(){this.handlers=[]}function cF(e,t,i,r,n){Error.call(this),this.message=e,this.name="AxiosError",t&&(this.code=t),i&&(this.config=i),r&&(this.request=r),n&&(this.response=n)}cV.prototype.use=function(e,t,i){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!i&&i.synchronous,runWhen:i?i.runWhen:null}),this.handlers.length-1},cV.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},cV.prototype.forEach=function(e){cM.forEach(this.handlers,function(t){null!==t&&e(t)})},cM.inherits(cF,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:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var cj=cF.prototype,cB={};["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"].forEach(function(e){cB[e]={value:e}}),Object.defineProperties(cF,cB),Object.defineProperty(cj,"isAxiosError",{value:!0}),cF.from=function(e,t,i,r,n,o){var s=Object.create(cj);return cM.toFlatObject(e,s,function(e){return e!==Error.prototype}),cF.call(s,e.message,t,i,r,n),s.name=e.name,o&&Object.assign(s,o),s};var cG={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},cW=function(e,t){t=t||new FormData;var i=[];function n(e){return null===e?"":cM.isDate(e)?e.toISOString():cM.isArrayBuffer(e)||cM.isTypedArray(e)?"function"==typeof Blob?new Blob([e]):r.from(e):e}return function e(r,o){if(cM.isPlainObject(r)||cM.isArray(r)){if(-1!==i.indexOf(r))throw Error("Circular reference detected in "+o);i.push(r),cM.forEach(r,function(i,r){if(!cM.isUndefined(i)){var s,a=o?o+"."+r:r;if(i&&!o&&"object"==typeof i){if(cM.endsWith(r,"{}"))i=JSON.stringify(i);else if(cM.endsWith(r,"[]")&&(s=cM.toArray(i)))return void s.forEach(function(e){cM.isUndefined(e)||t.append(a,n(e))})}e(i,a)}}),i.pop()}else t.append(o,n(r))}(e),t},cH=cM.isStandardBrowserEnv()?{write:function(e,t,i,r,n,o){var s=[];s.push(e+"="+encodeURIComponent(t)),cM.isNumber(i)&&s.push("expires="+new Date(i).toGMTString()),cM.isString(r)&&s.push("path="+r),cM.isString(n)&&s.push("domain="+n),!0===o&&s.push("secure"),document.cookie=s.join("; ")},read:function(e){var t=document.cookie.match(RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}},cK=function(e,t){return e&&!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e:t},cY=["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"],cq=cM.isStandardBrowserEnv()?function(){var e,t=/(msie|trident)/i.test(navigator.userAgent),i=document.createElement("a");function r(e){var r=e;return t&&(i.setAttribute("href",r),r=i.href),i.setAttribute("href",r),{href:i.href,protocol:i.protocol?i.protocol.replace(/:$/,""):"",host:i.host,search:i.search?i.search.replace(/^\?/,""):"",hash:i.hash?i.hash.replace(/^#/,""):"",hostname:i.hostname,port:i.port,pathname:"/"===i.pathname.charAt(0)?i.pathname:"/"+i.pathname}}return e=r(window.location.href),function(t){var i=cM.isString(t)?r(t):t;return i.protocol===e.protocol&&i.host===e.host}}():function(){return!0};function cJ(e){cF.call(this,null==e?"canceled":e,cF.ERR_CANCELED),this.name="CanceledError"}cM.inherits(cJ,cF,{__CANCEL__:!0});var cX=function(e,t,i){var r=i.config.validateStatus;i.status&&r&&!r(i.status)?t(new cF("Request failed with status code "+i.status,[cF.ERR_BAD_REQUEST,cF.ERR_BAD_RESPONSE][Math.floor(i.status/100)-4],i.c
1onfig,i.request,i)):e(i)},cz=function(e){var t,i,r,n={};return e&&cM.forEach(e.split("\n"),function(e){r=e.indexOf(":"),t=cM.trim(e.substr(0,r)).toLowerCase(),i=cM.trim(e.substr(r+1)),t&&(n[t]&&cY.indexOf(t)>=0||(n[t]="set-cookie"===t?(n[t]?n[t]:[]).concat([i]):n[t]?n[t]+", "+i:i))}),n},cQ=function(e){var t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""},cZ=function(e,t){cM.forEach(e,function(i,r){r!==t&&r.toUpperCase()===t.toUpperCase()&&(e[t]=i,delete e[r])})},c$={"Content-Type":"application/x-www-form-urlencoded"};function c0(e,t){!cM.isUndefined(e)&&cM.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var c1,c2={transitional:cG,adapter:(("undefined"!=typeof XMLHttpRequest||void 0!==n&&"[object process]"===Object.prototype.toString.call(n))&&(c1=function(e){return new Promise(function(t,i){var r,n=e.data,o=e.headers,s=e.responseType;function a(){e.cancelToken&&e.cancelToken.unsubscribe(r),e.signal&&e.signal.removeEventListener("abort",r)}cM.isFormData(n)&&cM.isStandardBrowserEnv()&&delete o["Content-Type"];var c=new XMLHttpRequest;e.auth&&(o.Authorization="Basic "+btoa((e.auth.username||"")+":"+(e.auth.password?unescape(encodeURIComponent(e.auth.password)):"")));var d=cK(e.baseURL,e.url);function l(){if(c){var r="getAllResponseHeaders"in c?cz(c.getAllResponseHeaders()):null;cX(function(e){t(e),a()},function(e){i(e),a()},{data:s&&"text"!==s&&"json"!==s?c.response:c.responseText,status:c.status,statusText:c.statusText,headers:r,config:e,request:c}),c=null}}if(c.open(e.method.toUpperCase(),cx(d,e.params,e.paramsSerializer),!0),c.timeout=e.timeout,"onloadend"in c?c.onloadend=l:c.onreadystatechange=function(){c&&4===c.readyState&&(0!==c.status||c.responseURL&&0===c.responseURL.indexOf("file:"))&&setTimeout(l)},c.onabort=function(){c&&(i(new cF("Request aborted",cF.ECONNABORTED,e,c)),c=null)},c.onerror=function(){i(new cF("Network Error",cF.ERR_NETWORK,e,c,c)),c=null},c.ontimeout=function(){var t=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded",r=e.transitional||cG;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),i(new cF(t,r.clarifyTimeoutError?cF.ETIMEDOUT:cF.ECONNABORTED,e,c)),c=null},cM.isStandardBrowserEnv()){var u=(e.withCredentials||cq(d))&&e.xsrfCookieName?cH.read(e.xsrfCookieName):void 0;u&&(o[e.xsrfHeaderName]=u)}"setRequestHeader"in c&&cM.forEach(o,function(e,t){void 0===n&&"content-type"===t.toLowerCase()?delete o[t]:c.setRequestHeader(t,e)}),cM.isUndefined(e.withCredentials)||(c.withCredentials=!!e.withCredentials),s&&"json"!==s&&(c.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&c.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&c.upload&&c.upload.addEventListener("progress",e.onUploadProgress),(e.cancelToken||e.signal)&&(r=function(e){c&&(i(!e||e&&e.type?new cJ:e),c.abort(),c=null)},e.cancelToken&&e.cancelToken.subscribe(r),e.signal&&(e.signal.aborted?r():e.signal.addEventListener("abort",r))),n||(n=null);var h=cQ(d);h&&-1===["http","https","file"].indexOf(h)?i(new cF("Unsupported protocol "+h+":",cF.ERR_BAD_REQUEST,e)):c.send(n)})}),c1),transformRequest:[function(e,t){if(cZ(t,"Accept"),cZ(t,"Content-Type"),cM.isFormData(e)||cM.isArrayBuffer(e)||cM.isBuffer(e)||cM.isStream(e)||cM.isFile(e)||cM.isBlob(e))return e;if(cM.isArrayBufferView(e))return e.buffer;if(cM.isURLSearchParams(e))return c0(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString();var i,r=cM.isObject(e),n=t&&t["Content-Type"];if((i=cM.isFileList(e))||r&&"multipart/form-data"===n){var o=this.env&&this.env.FormData;return cW(i?{"files[]":e}:e,o&&new o)}return r||"application/json"===n?(c0(t,"application/json"),function(e,t,i){if(cM.isString(e))try{return(0,JSON.parse)(e),cM.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(0,JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){var t=this.transitional||c2.transitional,i=t&&t.silentJSONParsing,r=t&&t.forcedJSONParsing,n=!i&&"json"===this.responseType;if(n||r&&cM.isString(e)&&e.length)try{return JSON.parse(e)}catch(e){if(n){if("SyntaxError"===e.name)throw cF.from(e,cF.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:null},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};
1cM.forEach(["delete","get","head"],function(e){c2.headers[e]={}}),cM.forEach(["post","put","patch"],function(e){c2.headers[e]=cM.merge(c$)});var c3=function(e){return!(!e||!e.__CANCEL__)},c4=function(e,t,i){var r=this||c2;return cM.forEach(i,function(i){e=i.call(r,e,t)}),e};function c5(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new cJ}var c6=function(e,t){t=t||{};var i={};function r(e,t){return cM.isPlainObject(e)&&cM.isPlainObject(t)?cM.merge(e,t):cM.isPlainObject(t)?cM.merge({},t):cM.isArray(t)?t.slice():t}function n(i){return cM.isUndefined(t[i])?cM.isUndefined(e[i])?void 0:r(void 0,e[i]):r(e[i],t[i])}function o(e){if(!cM.isUndefined(t[e]))return r(void 0,t[e])}function s(i){return cM.isUndefined(t[i])?cM.isUndefined(e[i])?void 0:r(void 0,e[i]):r(void 0,t[i])}function a(i){return i in t?r(e[i],t[i]):i in e?r(void 0,e[i]):void 0}var c={url:o,method:o,data:o,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:a};return cM.forEach(Object.keys(e).concat(Object.keys(t)),function(e){var t=c[e]||n,r=t(e);cM.isUndefined(r)&&t!==a||(i[e]=r)}),i},c8="0.27.2",c7={};["object","boolean","number","function","string","symbol"].forEach(function(e,t){c7[e]=function(i){return typeof i===e||"a"+(t<1?"n ":" ")+e}});var c9={};c7.transitional=function(e,t,i){function r(e,t){return"[Axios v"+c8+"] Transitional option '"+e+"'"+t+(i?". "+i:"")}return function(i,n,o){if(!1===e)throw new cF(r(n," has been removed"+(t?" in "+t:"")),cF.ERR_DEPRECATED);return t&&!c9[n]&&(c9[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)}};var de=function(e){return c5(e),e.headers=e.headers||{},e.data=c4.call(e,e.data,e.headers,e.transformRequest),e.headers=cM.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),cM.forEach(["delete","get","head","post","put","patch","common"],function(t){delete e.headers[t]}),(e.adapter||c2.adapter)(e).then(function(t){return c5(e),t.data=c4.call(e,t.data,t.headers,e.transformResponse),t},function(t){return c3(t)||(c5(e),t&&t.response&&(t.response.data=c4.call(e,t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)})},dt={assertOptions:function(e,t,i){if("object"!=typeof e)throw new cF("options must be an object",cF.ERR_BAD_OPTION_VALUE);for(var r=Object.keys(e),n=r.length;n-- >0;){var o=r[n],s=t[o];if(s){var a=e[o],c=void 0===a||s(a,o,e);if(!0!==c)throw new cF("option "+o+" must be "+c,cF.ERR_BAD_OPTION_VALUE)}else if(!0!==i)throw new cF("Unknown option "+o,cF.ERR_BAD_OPTION)}},validators:c7},di=dt.validators;function dr(e){this.defaults=e,this.interceptors={request:new cV,response:new cV}}function dn(e){if("function"!=typeof e)throw TypeError("executor must be a function.");this.promise=new Promise(function(e){t=e});var t,i=this;this.promise.then(function(e){if(i._listeners){var t,r=i._listeners.length;for(t=0;t<r;t++)i._listeners[t](e);i._listeners=null}}),this.promise.then=function(e){var t,r=new Promise(function(e){i.subscribe(e),t=e}).then(e);return r.cancel=function(){i.unsubscribe(t)},r},e(function(e){i.reason||(i.reason=new cJ(e),t(i.reason))})}dr.prototype.request=function(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},(t=c6(this.defaults,t)).method?t.method=t.method.toLowerCase():this.defaults.method?t.method=this.defaults.method.toLowerCase():t.method="get";var i=t.transitional;void 0!==i&&dt.assertOptions(i,{silentJSONParsing:di.transitional(di.boolean),forcedJSONParsing:di.transitional(di.boolean),clarifyTimeoutError:di.transitional(di.boolean)},!1);var r=[],n=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(n=n&&e.synchronous,r.unshift(e.fulfilled,e.rejected))});var o,s=[];if(this.interceptors.response.forEach(function(e){s.push(e.fulfilled,e.rejected)}),!n){var a=[de,void 0];for(Array.prototype.unshift.apply(a,r),a=a.concat(s),o=Promise.resolve(t);a.length;)o=o.then(a.shift(),a.shift());return o}for(var c=t;r.length;){var d=r.shift(),l=r.shift();try{c=d(c)}catch(e){l(e);break}}try{o=de(c)}catch(e){return Promise.reject(e)}for(;s.length;)o=o.then(s.shift(),s.shift());return o},dr.prototype.getUri=function(e){return cx(cK((e=c6(this.defaults,e)).baseURL,e.url),e.params,e.paramsSerializer)}
1,cM.forEach(["delete","get","head","options"],function(e){dr.prototype[e]=function(t,i){return this.request(c6(i||{},{method:e,url:t,data:(i||{}).data}))}}),cM.forEach(["post","put","patch"],function(e){function t(t){return function(i,r,n){return this.request(c6(n||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:i,data:r}))}}dr.prototype[e]=t(),dr.prototype[e+"Form"]=t(!0)}),dn.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},dn.prototype.subscribe=function(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]},dn.prototype.unsubscribe=function(e){if(this._listeners){var t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}},dn.source=function(){var e;return{token:new dn(function(t){e=t}),cancel:e}};var ds=function e(t){var i=new dr(t),r=cT(dr.prototype.request,i);return cM.extend(r,dr.prototype,i),cM.extend(r,i),r.create=function(i){return e(c6(t,i))},r}(c2);ds.Axios=dr,ds.CanceledError=cJ,ds.CancelToken=dn,ds.isCancel=c3,ds.VERSION=c8,ds.toFormData=cW,ds.AxiosError=cF,ds.Cancel=ds.CanceledError,ds.all=function(e){return Promise.all(e)},ds.spread=function(e){return function(t){return e.apply(null,t)}},ds.isAxiosError=function(e){return cM.isObject(e)&&!0===e.isAxiosError},cS.exports=ds,cS.exports.default=ds;var da=cS.exports;class dc{constructor(e){cc(this,"logger",void 0),cc(this,"prefixLists",[]),this.logger=e}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}}class dd{constructor(){cc(this,"_events",{}),cc(this,"addListener",this.on)}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||[])}}_indexOfListener(e,t){let i=e.length;for(;i--;)if(e[i].listener===t)return i;return -1}}let dl=new class extends dd{reportLogUploadError(e){this.emit("REPORT_LOG_UPLOAD",e)}};(_t=o||(o={})).UNEXPECTED_ERROR="UNEXPECTED_ERROR",_t.UNEXPECTED_RESPONSE="UNEXPECTED_RESPONSE",_t.TIMEOUT="TIMEOUT",_t.INVALID_PARAMS="INVALID_PARAMS",_t.NOT_READABLE="NOT_READABLE",_t.NOT_SUPPORTED="NOT_SUPPORTED",_t.INVALID_OPERATION="INVALID_OPERATION",_t.OPERATION_ABORTED="OPERATION_ABORTED",_t.WEB_SECURITY_RESTRICT="WEB_SECURITY_RESTRICT",_t.EXCHANGE_SDP_FAILED="EXCHANGE_SDP_FAILED",_t.NETWORK_ERROR="NETWORK_ERROR",_t.NETWORK_TIMEOUT="NETWORK_TIMEOUT",_t.NETWORK_RESPONSE_ERROR="NETWORK_RESPONSE_ERROR",_t.API_INVOKE_TIMEOUT="API_INVOKE_TIMEOUT",_t.ENUMERATE_DEVICES_FAILED="ENUMERATE_DEVICES_FAILED",_t.DEVICE_NOT_FOUND="DEVICE_NOT_FOUND",_t.ELECTRON_IS_NULL="ELECTRON_IS_NULL",_t.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR="ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR",_t.CHROME_PLUGIN_NO_RESPONSE="CHROME_PLUGIN_NO_RESPONSE",_t.CHROME_PLUGIN_NOT_INSTALL="CHROME_PLUGIN_NOT_INSTALL",_t.MEDIA_OPTION_INVA
1LID="MEDIA_OPTION_INVALID",_t.PERMISSION_DENIED="PERMISSION_DENIED",_t.CONSTRAINT_NOT_SATISFIED="CONSTRAINT_NOT_SATISFIED",_t.TRACK_IS_DISABLED="TRACK_IS_DISABLED",_t.GET_VIDEO_ELEMENT_VISIBLE_ERROR="GET_VIDEO_ELEMENT_VISIBLE_ERROR",_t.SHARE_AUDIO_NOT_ALLOWED="SHARE_AUDIO_NOT_ALLOWED",_t.LOW_STREAM_ENCODING_ERROR="LOW_STREAM_ENCODING_ERROR",_t.SET_ENCODING_PARAMETER_ERROR="SET_ENCODING_PARAMETER_ERROR",_t.TRACK_STATE_UNREACHABLE="TRACK_STATE_UNREACHABLE",_t.INVALID_UINT_UID_FROM_STRING_UID="INVALID_UINT_UID_FROM_STRING_UID",_t.CAN_NOT_GET_PROXY_SERVER="CAN_NOT_GET_PROXY_SERVER",_t.CAN_NOT_GET_GATEWAY_SERVER="CAN_NOT_GET_GATEWAY_SERVER",_t.VOID_GATEWAY_ADDRESS="VOID_GATEWAY_ADDRESS",_t.UID_CONFLICT="UID_CONFLICT",_t.MULTI_UNILBS_RESPONSE_ERROR="MULTI_UNILBS_RESPONSE_ERROR",_t.UPDATE_TICKET_FAILED="UPDATE_TICKET_FAILED",_t.INVALID_LOCAL_TRACK="INVALID_LOCAL_TRACK",_t.INVALID_TRACK="INVALID_TRACK",_t.SENDER_NOT_FOUND="SENDER_NOT_FOUND",_t.CREATE_OFFER_FAILED="CREATE_OFFER_FAILED",_t.SET_ANSWER_FAILED="SET_ANSWER_FAILED",_t.ICE_FAILED="ICE_FAILED",_t.PC_CLOSED="PC_CLOSED",_t.SENDER_REPLACE_FAILED="SENDER_REPLACE_FAILED",_t.GET_LOCAL_CAPABILITIES_FAILED="GET_LOCAL_CAPABILITIES_FAILED",_t.GET_LOCAL_CONNECTION_PARAMS_FAILED="GET_LOCAL_CONNECTION_PARAMS_FAILED",_t.SUBSCRIBE_FAILED="SUBSCRIBE_FAILED",_t.UNSUBSCRIBE_FAILED="UNSUBSCRIBE_FAILED",_t.GATEWAY_P2P_LOST="GATEWAY_P2P_LOST",_t.NO_ICE_CANDIDATE="NO_ICE_CANDIDATE",_t.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS="CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS",_t.EXIST_DISABLED_VIDEO_TRACK="EXIST_DISABLED_VIDEO_TRACK",_t.INVALID_REMOTE_USER="INVALID_REMOTE_USER",_t.REMOTE_USER_IS_NOT_PUBLISHED="REMOTE_USER_IS_NOT_PUBLISHED",_t.CUSTOM_REPORT_SEND_FAILED="CUSTOM_REPORT_SEND_FAILED",_t.CUSTOM_REPORT_FREQUENCY_TOO_HIGH="CUSTOM_REPORT_FREQUENCY_TOO_HIGH",_t.FETCH_AUDIO_FILE_FAILED="FETCH_AUDIO_FILE_FAILED",_t.READ_LOCAL_AUDIO_FILE_ERROR="READ_LOCAL_AUDIO_FILE_ERROR",_t.DECODE_AUDIO_FILE_FAILED="DECODE_AUDIO_FILE_FAILED",_t.WS_ABORT="WS_ABORT",_t.WS_DISCONNECT="WS_DISCONNECT",_t.WS_ERR="WS_ERR",_t.LIVE_STREAMING_TASK_CONFLICT="LIVE_STREAMING_TASK_CONFLICT",_t.LIVE_STREAMING_INVALID_ARGUMENT="LIVE_STREAMING_INVALID_ARGUMENT",_t.LIVE_STREAMING_INTERNAL_SERVER_ERROR="LIVE_STREAMING_INTERNAL_SERVER_ERROR",_t.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED="LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED",_t.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED="LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED",_t.LIVE_STREAMING_CDN_ERROR="LIVE_STREAMING_CDN_ERROR",_t.LIVE_STREAMING_INVALID_RAW_STREAM="LIVE_STREAMING_INVALID_RAW_STREAM",_t.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT="LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT",_t.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE="LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE",_t.LIVE_STREAMING_WARN_FREQUENT_REQUEST="LIVE_STREAMING_WARN_FREQUENT_REQUEST",_t.WEBGL_INTERNAL_ERROR="WEBGL_INTERNAL_ERROR",_t.BEAUTY_PROCESSOR_INTERNAL_ERROR="BEAUTY_PROCESSOR_INTERNAL_ERROR",_t.CROSS_CHANNEL_WAIT_STATUS_ERROR="CROSS_CHANNEL_WAIT_STATUS_ERROR",_t.CROSS_CHANNEL_FAILED_JOIN_SRC="CROSS_CHANNEL_FAILED_JOIN_SEC",_t.CROSS_CHANNEL_FAILED_JOIN_DEST="CROSS_CHANNEL_FAILED_JOIN_DEST",_t.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST="CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST",_t.CROSS_CHANNEL_SERVER_ERROR_RESPONSE="CROSS_CHANNEL_SERVER_ERROR_RESPONSE",_t.METADATA_OUT_OF_RANGE="METADATA_OUT_OF_RANGE",_t.LOCAL_AEC_ERROR="LOCAL_AEC_ERROR",_t.INVALID_PLUGIN="INVALID_PLUGIN",_t.DISCONNECT_P2P="DISCONNECT_P2P",_t.INIT_WEBSOCKET_TIMEOUT="INIT_WEBSOCKET_TIMEOUT",_t.CONVERTING_IMAGEDATA_TO_BLOB_FAILED="CONVERTING_IMAGEDATA_TO_BLOB_FAILED",_t.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED="CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED",_t.INIT_DATACHANNEL_TIMEOUT="INIT_DATACHANNEL_TIMEOUT",_t.DATACHANNEL_CONNECTION_TIMEOUT="DATACHANNEL_CONNECTION_TIMEOUT",_t.PROHIBITED_OPERATION="PROHIBITED_OPERATION";class du extends Error{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",i=arguments.length>2?arguments[2]:void 0;super(t),cc(this,"code",void 0),cc(this,"message",void 0),cc(this,"data",void 0),cc(this,"name","AgoraRTCException"),this.code=e,this.message="AgoraRTCError ".concat(this.code,": ").concat(t),this.data=i}toString(){return this.data?"data: ".concat(JSON.stringify(this.data),"\n").concat(this.stack):"".concat(this.stack)}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error";return"error"===e&&dg.error(this.toString()),"warning"===e&&dg.warning(this.toString()),this}throw(){throw this.print(),this}}let dh={timeout:500,timeoutFactor:1.5,maxRetryCount:1/0,maxRetryTimeout:1e4};function dp(e,t){let i=Math.floor(t.timeout*Math.pow(t.timeoutFactor,e));return Math.min(t.maxRetryTimeout,i)}function d_(e,t,i,r){let n=Object.assign({},dh,r),s=n.timeout,a=async()=>{var e;await (e=s,new sG(t=>{window.setTimeout(t,e)})),s*=n.timeoutFactor,s=Math.min(n.maxRetryTimeout,s)},c=!1,d=new sG(async(r,s)=>{t=t||(()=>!1),i=i||(()=>!0);for(let d=0;d<n.maxRetryCount;d+=1){if(c)return s(new du(o.OPERATION_ABORTED));try{let i=await e();if(!t(i,d)||d+1===n.maxRetryCount)return r(i);await a()}catch(e){if(!i(e,d)||d+1===n.maxRetryCount)return s(e);await a()}}});return d.cancel=()=>c=!0,d}function dE(){let e=new Date;
1return e.toTimeString().split(" ")[0]+":"+e.getMilliseconds()}function dm(){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 df={DEBUG:0,INFO:1,WARNING:2,ERROR:3,NONE:4},dS=Date.now(),dT=e=>{for(let t in df)if(Object.prototype.hasOwnProperty.call(df,t)&&df[t]===e)return t;return"DEFAULT"},dg=new class{constructor(){cc(this,"proxyServerURL",void 0),cc(this,"logLevel",df.DEBUG),cc(this,"uploadState","collecting"),cc(this,"uploadLogWaitingList",[]),cc(this,"uploadLogUploadingList",[]),cc(this,"uploadErrorCount",0),cc(this,"currentLogID",0),cc(this,"url",void 0),cc(this,"extLog",(e,t)=>{this.appendLogToWaitingList(e,...t)})}debug(){for(var e=arguments.length,t=Array(e),i=0;i<e;i++)t[i]=arguments[i];let r=[df.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=[df.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=[df.WARNING].concat(t);this.log.apply(this,r)}error(){for(var e=arguments.length,t=Array(e),i=0;i<e;i++)t[i]=arguments[i];let r=[df.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=[df.DEBUG].concat(t);this.uploadLog.apply(this,r)}setLogLevel(e){e=Math.min(Math.max(0,e),4),this.logLevel=e}enableLogUpload(){dk("UPLOAD_LOG",!0)}disableLogUpload(){dk("UPLOAD_LOG",!1),this.uploadLogUploadingList=[],this.uploadLogWaitingList=[]}setProxyServer(e){this.proxyServerURL=e}prefix(e){return new dc(this).prefix(e)}log(){for(var e=arguments.length,t=Array(e),i=0;i<e;i++)t[i]=arguments[i];if(Date.now()-dS<100)return void setTimeout(()=>{this.log(...t)},Date.now()-dS);let r=Math.max(0,Math.min(4,t[0]));if(t[0]=dE()+" Agora-SDK [".concat(dT(r),"]:"),this.appendLogToWaitingList(r,...t),r<this.logLevel)return;let n=dE()+" %cAgora-SDK [".concat(dT(r),"]:"),o=[];if(!dM.USE_NEW_LOG)switch(r){case df.DEBUG:o=[n,"color: #64B5F6;"].concat(t.slice(1)),console.log.apply(console,o);break;case df.INFO:o=[n,"color: #1E88E5; font-weight: bold;"].concat(t.slice(1)),console.log.apply(console,o);break;case df.WARNING:o=[n,"color: #FB8C00; font-weight: bold;"].concat(t.slice(1)),console.warn.apply(console,o);break;case df.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()-dS<100)return void setTimeout(()=>{this.uploadLog(...t)},Date.now()-dS);let r=Math.max(0,Math.min(4,t[0]));t[0]=dE()+" Agora-SDK [".concat(dT(r),"]:"),this.appendLogToWaitingList(r,...t)}appendLogToWaitingList(e){if(!dM.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]=dm()+" Agora-SDK [".concat(dT(e),"]:"):i[0]=dm()+" Agora-SDK [".concat(dT(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:dI,process_id:dM.PROCESS_ID,payload:JSON.stringify(e)};return d_(async()=>{let e=await da.post(this.url||(this.proxyServerURL?"https://".concat(this.proxyServerURL,"/ls/?h=").concat(dM.LOG_UPLOAD_SERVER,"&p=443&d=upload/v1"):"https://".concat(dM.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),e=>(e.response?dl.reportLogUploadError({status:e.response.status,data:e.response.data,headers:e.response.headers,message:e.message}):e.request?dl.reportLogUploadError({status:e.request.status,message:e.message}):dl.reportLogUploadError({status:-1,message:e.message}),!0),{timeout:dM.UPLOAD_LOG_REQUEST_RETRY_INTERVAL,maxRetryTimeout:dM.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,dM.UPLOAD_LOG_LENGTH_EACH_TIME)),this.uploadLogs().then(()=>{this.uploadErrorCount=0,this.uploadLogWaitingList.length>0&&window.setTimeout(()=>this.uploadLogInterval(),dM.UPLOAD_LOG_INTERVAL)}).catch(e=>{this.uploadErrorCount+=1,this.uploadErrorCount<2?window.setTimeout(()=>this.uploadLogInterval(),dM.UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1):window.setTimeout(()=>this.uploadLogInterval(),dM.UPLOAD_LOG_RETRY_INTERVAL_V1)}))}},dR="v4.17.2-0-gb960eec4-dirty(4/20/2023, 10:39:51 AM)",dI=function(e){if(e.match(/[0-9]+\.[0-9]+\.[0-9]+$/))return e;let t=e.match(/([0-9]+\.[0-9]+\.[0-9]+)\-alpha\.([0-9]+)/);if(t&&t[1]&&t[2]){let e=t[1],i=t[2];return"".concat(e,".").concat(i)}let i=e.match(/([0-9]+\.[0-9]+\.[0-9]+)\-special\.([0-9]+)/);if(i&&i[1]&&i[2]){let e=i[1],t=i[2];return"".concat(e,".").concat(100*(Number(t)+1))}return"4.0.0.999"}("4.17.2"),dC=function(){try{return!0===JSON.parse("true")}catch(e){return!0}}(),dv=["CHINA","GLOBAL"],dy=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=dy;let dA={"90p":dV(160,90),"90p_1":dV(160,90),"120p":dV(160,120,15,30,65),"120p_1":dV(160,120,15,30,65),"120p_3":dV(120,120,15,30,50),"120p_4":dV(212,120),"180p":dV(320,180,15,30,140),"180p_1":dV(320,180,15,30,140),"180p_3":dV(180,180,15,30,100),"180p_4":dV(240,180,15,30,120),"240p":dV(320,240,15,40,200),"240p_1":dV(320,240,15,40,200),"240p_3":dV(240,240,15,40,140),"240p_4":dV(424,240,15,40,220),"360p":dV(640,360,15,80,400),"360p_1":dV(640,360,15,80,400),"360p_3":dV(360,360,15,80,260),"360p_4":dV(640,360,30,80,600),"360p_6":dV(360,360,30,80,400),"360p_7":dV(480,360,15,80,320),"360p_8":dV(480,360,30,80,490),"360p_9":dV(640,360,15,80,800),"360p_10":dV(640,360,24,80,800),"360p_11":dV(640,360,24,80,1e3),"480p":dV(640,480,15,100,500),"480p_1":dV(640,480,15,100,500),"480p_2":dV(640,480,30,100,1e3),"480p_3":dV(480,480,15,100,400),"480p_4":dV(640,480,30,100,750),"480p_6":dV(480,480,30,100,600),"480p_8":dV(848,480,15,100,610),"480p_9":dV(848,480,30,100,930),"480p_10":dV(640,480,10,100,400),"720p":dV(1280,720,15,120,1130),"720p_1":dV(1280,720,15,120,1130),"720p_2":dV(1280,720,30,120,2e3),"720p_3":dV(1280,720,30,120,1710),"720p_5":dV(960,720,15,120,910),"720p_6":dV(960,720,30,120,1380),"1080p":dV(1920,1080,15,120,2080),"1080p_1":dV(1920,1080,15,120,2080),"1080p_2":dV(1920,1080,30,120,3e3),"1080p_3":dV(1920,1080,30,120,3150),"1080p_5":dV(1920,1080,60,120,4780),"1440p":dV(2560,1440,30,120,4850),"1440p_1":dV(2560,1440,30,120,4850),"1440p_2":dV(2560,1440,60,120,7350),"4k":dV(3840,2160,30,120,8910),"4k_1":dV(3840,2160,30,120,8910),"4k_3":dV(3840,2160,60,120,13500)},dO={"480p":dF(640,480,5),"480p_1":dF(640,480,5),"480p_2":dF(640,480,30),"480p_3":dF(640,480,15),"720p":dF(1280,720,5),"720p_1":dF(1280,720,5),"720p_2":dF(1280,720,30),"720p_3":dF(1280,720,15),"1080p":dF(1920,1080,5),"1080p_1":dF(1920,1080,5),"1080p_2":dF(1920,1080,30),"1080p_3":dF(1920,1080,15)},db={"1SL1TL":dj(1,1),"3SL3TL":dj(3,3),"2SL3TL":dj(2,3)};function dN(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},dA[e]):e}function dw(e){return"string"==typeof e?Object.assign({},dO[e]):e}function dD(e){return"string"==typeof e?Object.assign({},db[e]):e}let dP={speech_low_quality:dx(16e3,!1),speech_standard:dx(32e3,!1,18),music_standard:dx(48e3,!1),standard_stereo:dx(48e3,!0,56),high_quality:dx(48e3,!1,128),high_quality_stereo:dx(48e3,!0,192)};function dL(e){return"string"==typeof e?Object.assign({},dP[e]):e}function dk(e,t,i){Object.keys(dM).includes(e)&&(!i&&Object.keys(dU).includes(e)||(dM[e]=t))}let dM={PROCESS_ID:"",ENCRYPT_AES:!0,AREAS:dv,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",ENABLE_EVENT_REPORT:!0,GATEWAY_ADDRESS:[],GATEWAY_WSS_ADDRESS:"",LIVE_STREAMING_ADDRESS:"",HTTP_CONNECT_TIMEOUT:5e3,SIGNAL_REQUEST_TIMEOUT:1e4,REPORT_STATS:!0,UPLOAD_LOG:!1,NOT_REPORT_EVENT:[],SUBSCRIBE_TWCC:!1,PUBLISH_TWCC:!1,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,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"],WORKER_DOMAIN:"edge.agora.io",TURN_DOMAIN:"edge.agora.io",EVENT_REPORT_RETRY:!0,CHROME_FORCE_PLAN_B:!1,AUDIO_SOURCE_VOLUME_UPDATE_INTERVAL:400,AU
1DIO_SOURCE_AVG_VOLUME_DURATION:3e3,AUDIO_VOLUME_INDICATION_INTERVAL:2e3,VOLUME_VOICE_WEIGHT:10,GET_VOLUME_OF_MUTED_AUDIO_TRACK:!1,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,PRELOAD_MEDIA_COUNT:0,USE_RTX:!1,CHECK_VIDEO_VISIBLE_INTERVAL:3e4,ENUMERATE_DEVICES_INTERVAL:!1,ENUMERATE_DEVICES_INTERVAL_TIME:1e4,USE_NEW_TOKEN:!1,CLOSE_AFB_FOR_LOCAL_AP:!0,JOIN_WITH_FALLBACK_SIGNAL_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE:!1,JOIN_WITH_FALLBACK_PROXY_PENDING_DURATION:2e3,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:!0,BITRATE_ADAPTER_TYPE:"STANDARD_BITRATE",AI_DENOISER_PARAMETERS:{},ADJUST_3A_FROM_PLUGINS:!0,RAISE_H264_BASELINE_PRIORITY:!0,FILTER_SEND_H264_BASELINE:!1,ENABLE_PUBLISHED_USER_LIST:!0,MAX_
1SUBSCRIPTION:50,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,VIDEO_INSPECT_WORKER_MANAGER_HOST:"edge.agora.io",VIDEO_INSPECT_WORKER_MANAGER_PORT:"",VIDEO_INSPECT_WORKER_PORT:"",SHOW_VIDEO_INSPECT_WORKER_MESSAGE:!1,STATS_COLLECTOR_PORT:443,FORCE_TURN_TCP:!1,SUBSCRIBE_AUDIO_FILTER_TOPN:void 0,ENABLE_PUBLISH_AUDIO_FILTER:void 0,WEBAUDIO_INIT_OPTIONS:void 0,FILTER_VIDEO_FEC:!0,FILTER_AUDIO_FEC:!1,CHROME_DUAL_STREAM_USE_ENCODING:!0,EXTENSION_USAGE_UPLOAD_INTERVAL:1e4,ICE_RESTART:!0,ENABLE_USER_LICENSE_CHECK:!0,SIGNAL_CHANNEL:0,TRANSMITTER_INITIAL_RTT:30,TRANSMITTER_INITIAL_RTO:30,TRANSMITTER_MAX_BATCH_ACK_COUNT:2,TRANSMITTER_MAX_RTO:500,DATACHANNEL_COMPRESS:!1,FINGERPRINT:null,DC_JOIN_WITH_FAILBACK:5e3,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,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}},dU={};function dx(e,t,i){return{sampleRate:e,stereo:t,bitrate:i}}function dV(e,t,i,r,n){return{width:e,height:t,frameRate:i,bitrateMin:r,bitrateMax:n}}function dF(e,t,i,r,n){return{width:{max:e},height:{max:t},frameRate:i,bitrateMin:r,bitrateMax:n}}function dj(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}dC||(dM.WEBCS_DOMAIN=["ap-web-1-oversea.agora.io","ap-web-1-north-america.agora.io"],dM.WEBCS_DOMAIN_BACKUP_LIST=["ap-web-2-oversea.agora.io","ap-web-2-north-america.agora.io"],dM.PROXY_CS=["proxy-ap-web-oversea.agora.io","proxy-ap-web-america.agora.io"],dM.CDS_AP=["cds-ap-web-oversea.agora.io","cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],dM.ACCOUNT_REGISTER=["sua-ap-web-oversea.agora.io","sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],dM.UAP_AP=["uap-ap-web-oversea.agora.io","uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],dM.LOG_UPLOAD_SERVER="logservice-oversea.agora.io",dM.EVENT_REPORT_DOMAIN="statscollector-1-oversea.agora.io",dM.EVENT_REPORT_BACKUP_DOMAIN="statscollector-2-oversea.agora.io",dM.PROXY_SERVER_TYPE3="webrtc-cloud-proxy.agora.io",dM.AREAS=["NORTH_AMERICA","OVERSEA"]);let dB=[[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]],dG=[],dW=[];function dH(e,t){return!!t&&dG.some(i=>i.uid===e&&i.channelName===t)}var dK=function(e,t,i){var r=iw(t);r in e?iH.f(e,r,tB(0,i)):e[r]=i},dY=tA.Array,dq=Math.max,dJ=function(e,t,i){for(var r=i6(e),n=rD(t,r),o=rD(void 0===i?r:i,r),s=dY(dq(o-n,0)),a=0;n<o;n++,a++)dK(s,a,e[n]);return s.length=a,s},dX=Math.floor,dz=function(e,t){var i=e.length,r=dX(i/2);return i<8?dQ(e,t):dZ(e,dz(dJ(e,0,r),t),dz(dJ(e,r),t),t)},dQ=function(e,t){for(var i,r,n=e.length,o=1;o<n;){for(r=o,i=e[o];r&&t(e[r-1],i)>0;)e[r]=e[--r];r!==o++&&(e[r]=i)}return e},dZ=function(e,t,i,r){for(var n=t.length,o=i.length,s=0,a=0;s<n||a<o;)e[s+a]=s<n&&a<o?0>=r(t[s],i[a])?t[s++]:i[a++]:s<n?t[s++]:i[a++];return e},d$=t1.match(/firefox\/(\d+)/i),d0=!!d$&&+d$[1],d1=/MSIE|Trident/.test(t1),d2=t1.match(/AppleWebKit\/(\d+)\./),d3=!!d2&&+d2[1],d4=[],d5=tC(d4.sort),d6=tC(d4.push),d8=tf(function(){d4.sort(void 0)}),d7=tf(function(){d4.sort(null)}),d9=re("sort"),le=!tf(function(){if(t6)return t6<70;if(!(d0&&d0>3)){if(d1)return!0;if(d3)return d3<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++)d4.push({k:t+r,v:i})}for(d4.sort(function(e,t){return t.v-e.v}),r=0;r<d4.length;r++)t=d4[r].k.charAt(0),n.charAt(n.length-1)!==t&&(n+=t);return"DGBEFHACIJK"!==n}});i1({target:"Array",proto:!0,forced:d8||!d7||!d9||!le},{sort:function(e){void 0!==e&&io(e);var t=ip(this);if(le)return void 0===e?d5(t):d5(t,e);var i,r,n=[],o=i6(t);for(r=0;r<o;r++)r in t&&d6(n,t[r]);for(dz(n,function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:nh(t)>nh(i)?1:-1}),i=n.length,r=0;r<i;)t[r]=n[r++];for(;r<o;)delete t[r++];return t}});var lt=rr("Array").sort,li=Array.prototype,lr=function(e){var t=e.sort;return e===li||tv(li,e)&&t===li.sort?lt:t};function ln(e,t){if("boolean"!=typeof e)throw new du(o.INVALID_PARAMS,"Invalid ".concat(t,": The value is of the boolean type."))}function lo(e,t,i){if(!i.includes(e))throw new du(o.INVALID_PARAMS,"".concat(t," can only be set as ").concat(JSON.str
1ingify(i)))}function ls(e,t){var i;let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e4,s=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];if(e<r||e>n||s&&("number"!=typeof(i=e)||i%1!=0))throw new du(o.INVALID_PARAMS,"invalid ".concat(t,": the value range is [").concat(r,", ").concat(n,"]. integer only"))}function la(e,t){if("number"!=typeof e){if(!(e.min||e.max||e.ideal||e.exact))throw new du(o.INVALID_PARAMS,"".concat(t," is not a valid ConstrainLong"));void 0!==e.min&&ls(e.min,"".concat(t,".min"),0,1/0),void 0!==e.max&&ls(e.max,"".concat(t,".max"),1,1/0),void 0!==e.exact&&ls(e.exact,"".concat(t,".exact"),1,1/0),void 0!==e.ideal&&ls(e.ideal,"".concat(t,".ideal"),1,1/0)}else ls(e,t,1,1/0)}function lc(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 du(o.INVALID_PARAMS,"".concat(t||"param"," cannot be empty"));if(!lp(e,i,r,n))throw new du(o.INVALID_PARAMS,"Invalid ".concat(t||"string param",": Length of the string: [").concat(i,",").concat(r,"].").concat(n?" ASCII characters only.":""))}function ld(e,t){if(!Array.isArray(e))throw new du(o.INVALID_PARAMS,"".concat(t," should be an array"))}function ll(e){if("string"!=typeof e||!/^[a-zA-Z0-9 \!\#\$\%\&\(\)\+\-\:\;\<\=\.\>\?\@\[\]\^\_\{\}\|\~\,]{1,64}$/.test(e))throw dg.error("Invalid Channel Name ".concat(e)),new du(o.INVALID_PARAMS,"The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _,  {, }, |, ~, ,")}function lu(e){if(!("number"==typeof e&&Math.floor(e)===e&&0<=e&&e<=0xffffffff||lp(e,1,255)))throw dg.error("Invalid UID ".concat(e," ").concat(typeof e)),new du(o.INVALID_PARAMS,"[String uid] Length of the string: [1,255]. ASCII characters only. [Number uid] The value range is [0,10000]");"string"==typeof e&&dg.warning("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.")}function lh(e){return null==e}function lp(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>255)return!1}return!0}(e))}(_i=s||(s={})).FREE="free",_i.UPLOADING="uploading",(_r=a||(a={}))[_r.MISC=0]="MISC",_r[_r.INTERNAL_EVENT=1]="INTERNAL_EVENT",_r[_r.PUBLIC_EVENT=2]="PUBLIC_EVENT",_r[_r.WEB_EVENT=3]="WEB_EVENT",_r[_r.INTERNAL_API=4]="INTERNAL_API",_r[_r.WEB_API=5]="WEB_API",_r[_r.PUBLIC_API=6]="PUBLIC_API",(_n=c||(c={})).NONE="none",_n.INIT="init",_n.CANPLAY="canplay",_n.PLAYING="playing",_n.PAUSED="paused",_n.SUSPEND="suspend",_n.STALLED="stalled",_n.WAITING="waiting",_n.ERROR="error",_n.DESTROYED="destroyed",_n.ABORT="abort",_n.ENDED="ended",_n.EMPTIED="emptied",_n.LOADEDDATA="loadeddata";let l_={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};function lE(e){return lc(e.reportId,"params.reportId",0,100,!1),lc(e.category,"params.category",0,100,!1),lc(e.event,"params.event",0,100,!1),lc(e.label,"params.label",0,100,!1),ls(e.value,"params.value",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,!1),!0}let lm={sid:"",lts:0,success:null,cname:null,uid:null,peer:null,cid:null,elapse:null,extend:null,vid:0};function lf(e){return ls(e.timeout,"config.timeout",0,1e5),ls(e.timeoutFactor,"config.timeoutFactor",0,100,!1),ls(e.maxRetryCount,"config.maxRetryConfig",0,1/0),ls(e.maxRetryTimeout,"config.maxRetryTimeout",0,1/0),!0}function lS(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 lT(e){return lc(e.turnServerURL,"turnServerURL"),lc(e.username,"username"),lc(e.password,"password"),e.udpport&&ls(e.udpport,"udpport",1,99999,!0),e.forceturn&&ln(e.forceturn,"forceturn"),e.security&&ln(e.security,"security"),e.tcpport&&ls(e.tcpport,"tcpport",1,99999,!0),!0}function lg(e){return void 0!==e.level&&lo(e.level,"level",[1,2,3]),!0}(_o=d||(d={})).PUBLISH="publish",_o.SUBSCRIBE="subscribe",_o.WS_COMPRESSOR_INIT="ws_compressor_init",_o.SESSION_INIT="session_init",_o.JOIN_CHOOSE_SERVER="join_choose_server",_o.REQ_USER_ACCOUNT="req_user_account",_o.JOIN_GATEWAY="join_gateway",_o.REJOIN_GATEWAY="rejoin_gateway",_o.STREAM_SWITCH="stream_switch",_o.REQUEST_PROXY_WORKER_MANAGER="request_proxy_worker_manager",_o.REQUEST_PROXY_APPCENTER="request_proxy_a
1ppcenter",_o.FIRST_VIDEO_RECEIVED="first_video_received",_o.FIRST_AUDIO_RECEIVED="first_audio_received",_o.FIRST_VIDEO_DECODE="first_video_decode",_o.FIRST_AUDIO_DECODE="first_audio_decode",_o.ON_ADD_AUDIO_STREAM="on_add_audio_stream",_o.ON_ADD_VIDEO_STREAM="on_add_video_stream",_o.ON_UPDATE_STREAM="on_update_stream",_o.ON_REMOVE_STREAM="on_remove_stream",_o.USER_ANALYTICS="req_user_analytics",(_s=l||(l={})).SESSION="io.agora.pb.Wrtc.Session",_s.JOIN_CHOOSE_SERVER="io.agora.pb.Wrtc.JoinChooseServer",_s.REQ_USER_ACCOUNT="io.agora.pb.Wrtc.ReqUserAccount",_s.JOIN_GATEWAY="io.agora.pb.Wrtc.JoinGateway",_s.RE_JOIN_GATEWAY="io.agora.pb.Wrtc.ReJoinGateway",_s.PUBLISH="io.agora.pb.Wrtc.Publish",_s.SUBSCRIBE="io.agora.pb.Wrtc.Subscribe",_s.WS_COMPRESSOR_INIT="io.agora.pb.Wrtc.WsCompressorInit",_s.STREAM_SWITCH="io.agora.pb.Wrtc.StreamSwitch",_s.AUDIO_SENDING_STOPPED="io.agora.pb.Wrtc.AudioSendingStopped",_s.VIDEO_SENDING_STOPPED="io.agora.pb.Wrtc.VideoSendingStopped",_s.REQUEST_PROXY_APPCENTER="io.agora.pb.Wrtc.RequestProxyAppCenter",_s.REQUEST_PROXY_WORKER_MANAGER="io.agora.pb.Wrtc.RequestProxyWorkerManager",_s.API_INVOKE="io.agora.pb.Wrtc.ApiInvoke",_s.FIRST_VIDEO_RECEIVED="io.agora.pb.Wrtc.FirstVideoReceived",_s.FIRST_AUDIO_RECEIVED="io.agora.pb.Wrtc.FirstAudioReceived",_s.FIRST_VIDEO_DECODE="io.agora.pb.Wrtc.FirstVideoDecode",_s.FIRST_AUDIO_DECODE="io.agora.pb.Wrtc.FirstAudioDecode",_s.ON_ADD_AUDIO_STREAM="io.agora.pb.Wrtc.OnAddAudioStream",_s.ON_ADD_VIDEO_STREAM="io.agora.pb.Wrtc.OnAddVideoStream",_s.ON_UPDATE_STREAM="io.agora.pb.Wrtc.OnUpdateStream",_s.ON_REMOVE_STREAM="io.agora.pb.Wrtc.OnRemoveStream",_s.JOIN_CHANNEL_TIMEOUT="io.agora.pb.Wrtc.JoinChannelTimeout",_s.PEER_PUBLISH_STATUS="io.agora.pb.Wrtc.PeerPublishStatus",_s.WORKER_EVENT="io.agora.pb.Wrtc.WorkerEvent",_s.AP_WORKER_EVENT="io.agora.pb.Wrtc.APWorkerEvent",_s.JOIN_WEB_PROXY_AP="io.agora.pb.Wrtc.JoinWebProxyAP",_s.WEBSOCKET_QUIT="io.agora.pb.Wrtc.WebSocketQuit",_s.USER_ANALYTICS="io.agora.pb.Wrtc.UserAnalytics",_s.AUTOPLAY_FAILED="io.agora.pb.Wrtc.AutoplayFailed",(_a=u||(u={}))[_a.WORKER_EVENT=156]="WORKER_EVENT",_a[_a.AP_WORKER_EVENT=160]="AP_WORKER_EVENT",(_c=h||(h={}))[_c.SESSION=26]="SESSION",_c[_c.JOIN_CHOOSE_SERVER=27]="JOIN_CHOOSE_SERVER",_c[_c.REQ_USER_ACCOUNT=196]="REQ_USER_ACCOUNT",_c[_c.JOIN_GATEWAY=28]="JOIN_GATEWAY",_c[_c.PUBLISH=30]="PUBLISH",_c[_c.SUBSCRIBE=29]="SUBSCRIBE",_c[_c.WS_COMPRESSOR_INIT=9430]="WS_COMPRESSOR_INIT",_c[_c.STREAM_SWITCH=32]="STREAM_SWITCH",_c[_c.AUDIO_SENDING_STOPPED=33]="AUDIO_SENDING_STOPPED",_c[_c.VIDEO_SENDING_STOPPED=34]="VIDEO_SENDING_STOPPED",_c[_c.REQUEST_PROXY_APPCENTER=35]="REQUEST_PROXY_APPCENTER",_c[_c.REQUEST_PROXY_WORKER_MANAGER=36]="REQUEST_PROXY_WORKER_MANAGER",_c[_c.API_INVOKE=41]="API_INVOKE",_c[_c.FIRST_VIDEO_RECEIVED=348]="FIRST_VIDEO_RECEIVED",_c[_c.FIRST_AUDIO_RECEIVED=349]="FIRST_AUDIO_RECEIVED",_c[_c.FIRST_VIDEO_DECODE=350]="FIRST_VIDEO_DECODE",_c[_c.FIRST_AUDIO_DECODE=351]="FIRST_AUDIO_DECODE",_c[_c.ON_ADD_AUDIO_STREAM=352]="ON_ADD_AUDIO_STREAM",_c[_c.ON_ADD_VIDEO_STREAM=353]="ON_ADD_VIDEO_STREAM",_c[_c.ON_UPDATE_STREAM=356]="ON_UPDATE_STREAM",_c[_c.ON_REMOVE_STREAM=355]="ON_REMOVE_STREAM",_c[_c.JOIN_CHANNEL_TIMEOUT=407]="JOIN_CHANNEL_TIMEOUT",_c[_c.PEER_PUBLISH_STATUS=408]="PEER_PUBLISH_STATUS",_c[_c.WORKER_EVENT=156]="WORKER_EVENT",_c[_c.AP_WORKER_EVENT=160]="AP_WORKER_EVENT",_c[_c.JOIN_WEB_PROXY_AP=700]="JOIN_WEB_PROXY_AP",_c[_c.WEBSOCKET_QUIT=671]="WEBSOCKET_QUIT",_c[_c.USER_ANALYTICS=1e4]="USER_ANALYTICS",_c[_c.AUTOPLAY_FAILED=9178]="AUTOPLAY_FAILED",(_d=p||(p={})).CREATE_CLIENT="createClient",_d.CHECK_SYSTEM_REQUIREMENTS="checkSystemRequirements",_d.SET_AREA="setArea",_d.CHECK_VIDEO_TRACK_IS_ACTIVE="checkVideoTrackIsActive",_d.CHECK_AUDIO_TRACK_IS_ACTIVE="checkAudioTrackIsActive",_d.CREATE_MIC_AUDIO_TRACK="createMicrophoneAudioTrack",_d.CREATE_CUSTOM_AUDIO_TRACK="createCustomAudioTrack",_d.CREATE_BUFFER_AUDIO_TRACK="createBufferSourceAudioTrack",_d.CREATE_CAM_VIDEO_TRACK="createCameraVideoTrack",_d.CREATE_CUSTOM_VIDEO_TRACK="createCustomVideoTrack",_d.CREATE_MIC_AND_CAM_TRACKS="createMicrophoneAndCameraTracks",_d.CREATE_SCREEN_VIDEO_TRACK="createScreenVideoTrack",_d.SET_ENCRYPTION_CONFIG="Client.setEncryptionConfig",_d.START_PROXY_SERVER="Client.startProxyServer",_d.STOP_PROXY_SERVER="Client.stopProxyServer",_d.SET_PROXY_SERVER="Client.setProxyServer",_d.SET_TURN_SERVER="Client.setTurnServer",_d.SET_CLIENT_ROLE="Client.setClientRole",_d.SET_LOW_STREAM_PARAMETER="Client.setLowStreamParameter",_d.ENABLE_DUAL_STREAM="Client.enableDualStream",_d.DISABLE_DUAL_STREAM="Client.disableDualStream",_d.JOIN="Client.join",_d.LEAVE="Client.leave",_d.PUBLISH="Client.publish",_d.UNPUBLISH="Client.unpublish",_d.SUBSCRIBE="Client.subscribe",_d.MASS_SUBSCRIBE="Client.massSubscribe",_d.MASS_UNSUBSCRIBE="Client.massUnsubscribe",_d.UNSUBSCRIBE="Client.unsubscribe",_d.RENEW_TOKEN="Client.renewToken",_d.SET_REMOTE_VIDEO_STREAM_TYPE="Client.setRemoteVideoStreamType",_d.SET_STREAM_FALLBACK_OPTION="Client.setStreamFallbackOption",_d.ENABLE_AUDIO_VOLUME_INDICATOR="Client.enableAudioVolumeIndicator",_d.SEND_CUSTOM_REPORT_MESSAGE="Client.sendCustomReportMessage",_d.INSPECT_VIDEO_CONTENT="Client.inspectVideoContent",_d.STOP_INSPECT_VIDEO_CONTENT="Client.stopInspectVideoContent",_d.JOIN_FALLBACK_TO_PROXY="Client._joinFallbackToProxy",_d.DATACHANNEL_FAILBACK="Client._datachannelFailback",_d.ON_LIVE_STREAM_WARNING="Client.onLiveStreamWarning",_d.ON_LIVE_STREAM_ERROR="Client.onLiveStreamingError",_d.START_LIVE_STREAMING="Client.startLiveStreaming",_d.SET_LIVE_TRANSCODING="Client.setLiveTranscoding",_d.STOP_LIVE_STREAMING="Client.stopLiveStreaming",_d.ADD_INJECT_STREAM_URL="Client.addInjectStreamUrl",_d.REMOVE_INJECT_STREAM_URL="Client.removeInjectStreamUrl",_d.START_CHANNEL_MEDIA_RELAY="Client.startChannelMediaRelay",_d.UPDATE_CHANNEL_MEDIA_RELAY="Client.updateChannelMediaRelay",_d.STOP_CHANNEL_MEDIA_RELAY="Client.stopChannelMediaRelay",_d.REQUEST_CONFIG_DISTRIBUTE="_config-distribute-request",_d.SET_CONFIG_DISTRIBUTE="_configDistribute",_d.LOCAL_TRACK_SET_MUTED="LocalTrack.setMute",_d.LOCAL_AUDIO_TRACK_PLAY="LocalAudioTrack.play",_d.LOCAL_AUDIO_TRACK_PLAY_IN_ELEMENT="LocalAudioTrack.playInElement",_d.LOCAL_AUDIO_TRACK_STOP="LocalAudioTrack.stop",_d.LOCAL_AUDIO_TRACK_SET_
1VOLUME="LocalAudioTrack.setVolume",_d.MIC_AUDIO_TRACK_SET_DEVICE="MicrophoneAudioTrack.setDevice",_d.BUFFER_AUDIO_TRACK_START="BufferSourceAudioTrack.startProcessAudioBuffer",_d.BUFFER_AUDIO_TRACK_STOP="BufferSourceAudioTrack.stopProcessAudioBuffer",_d.BUFFER_AUDIO_TRACK_PAUSE="BufferSourceAudioTrack.pauseProcessAudioBuffer",_d.BUFFER_AUDIO_TRACK_RESUME="BufferSourceAudioTrack.resumeProcessAudioBuffer",_d.BUFFER_AUDIO_TRACK_SEEK="BufferSourceAudioTrack.seekAudioBuffer",_d.LOCAL_VIDEO_TRACK_PLAY="LocalVideoTrack.play",_d.LOCAL_VIDEO_TRACK_STOP="LocalVideoTrack.stop",_d.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE="LocalVideoTrack.getVideoElementVisibleStatus",_d.LOCAL_VIDEO_TRACK_BEAUTY="LocalVideoTrack.setBeautyEffect",_d.CAM_VIDEO_TRACK_SET_DEVICE="CameraVideoTrack.setDevice",_d.CAM_VIDEO_TRACK_SET_ENCODER_CONFIG="CameraVideoTrack.setEncoderConfiguration",_d.REMOTE_VIDEO_TRACK_PLAY="RemoteVideoTrack.play",_d.REMOTE_VIDEO_TRACK_STOP="RemoteVideoTrack.stop",_d.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE="RemoteVideoTrack.getVideoElementVisibleStatus",_d.REMOTE_AUDIO_TRACK_PLAY="RemoteAudioTrack.play",_d.REMOTE_AUDIO_TRACK_STOP="RemoteAudioTrack.stop",_d.REMOTE_AUDIO_SET_VOLUME="RemoteAudioTrack.setVolume",_d.REMOTE_AUDIO_SET_OUTPUT_DEVICE="RemoteAudioTrack.setOutputDevice",_d.GET_MEDIA_STREAM_TRACK="Track.getMediaStreamTrack",_d.STREAM_TYPE_CHANGE="streamTypeChange",_d.CONNECTION_STATE_CHANGE="connectionStateChange",_d.LOAD_CONFIG_FROM_LOCALSTORAGE="loadConfigFromLocalStorage",(_||(_={})).TRACER="tracer",(_l=E||(E={})).IDLE="IDLE",_l.INITING="INITING",_l.INITEND="INITEND",(_u=m||(m={})).STATE_CHANGE="state_change",_u.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",_u.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",_u.CAMERA_DEVICE_CHANGED="cameraDeviceChanged",(_h=f||(f={}))[_h.ACCESS_POINT=101]="ACCESS_POINT",_h[_h.UNILBS=201]="UNILBS",_h[_h.STRING_UID_ALLOCATOR=901]="STRING_UID_ALLOCATOR",(_p=S||(S={}))[_p.IIIEGAL_APPID=1]="IIIEGAL_APPID",_p[_p.IIIEGAL_UID=2]="IIIEGAL_UID",_p[_p.INTERNAL_ERROR=3]="INTERNAL_ERROR",(__=T||(T={}))[__.INVALID_VENDOR_KEY=5]="INVALID_VENDOR_KEY",__[__.INVALID_CHANNEL_NAME=7]="INVALID_CHANNEL_NAME",__[__.INTERNAL_ERROR=8]="INTERNAL_ERROR",__[__.NO_AUTHORIZED=9]="NO_AUTHORIZED",__[__.DYNAMIC_KEY_TIMEOUT=10]="DYNAMIC_KEY_TIMEOUT",__[__.NO_ACTIVE_STATUS=11]="NO_ACTIVE_STATUS",__[__.DYNAMIC_KEY_EXPIRED=13]="DYNAMIC_KEY_EXPIRED",__[__.STATIC_USE_DYNAMIC_KEY=14]="STATIC_USE_DYNAMIC_KEY",__[__.DYNAMIC_USE_STATIC_KEY=15]="DYNAMIC_USE_STATIC_KEY",__[__.USER_OVERLOAD=16]="USER_OVERLOAD",__[__.FORBIDDEN_REGION=18]="FORBIDDEN_REGION",__[__.CANNOT_MEET_AREA_DEMAND=19]="CANNOT_MEET_AREA_DEMAND",(_E=g||(g={}))[_E.NO_FLAG_SET=100]="NO_FLAG_SET",_E[_E.FLAG_SET_BUT_EMPTY=101]="FLAG_SET_BUT_EMPTY",_E[_E.INVALID_FALG_SET=102]="INVALID_FALG_SET",_E[_E.FLAG_SET_BUT_NO_RE=103]="FLAG_SET_BUT_NO_RE",_E[_E.INVALID_SERVICE_ID=104]="INVALID_SERVICE_ID",_E[_E.NO_SERVICE_AVAILABLE=200]="NO_SERVICE_AVAILABLE",_E[_E.NO_SERVICE_AVAILABLE_P2P=201]="NO_SERVICE_AVAILABLE_P2P",_E[_E.NO_SERVICE_AVAILABLE_VOICE=202]="NO_SERVICE_AVAILABLE_VOICE",_E[_E.NO_SERVICE_AVAILABLE_WEBRTC=203]="NO_SERVICE_AVAILABLE_WEBRTC",_E[_E.NO_SERVICE_AVAILABLE_CDS=204]="NO_SERVICE_AVAILABLE_CDS",_E[_E.NO_SERVICE_AVAILABLE_CDN=205]="NO_SERVICE_AVAILABLE_CDN",_E[_E.NO_SERVICE_AVAILABLE_TDS=206]="NO_SERVICE_AVAILABLE_TDS",_E[_E.NO_SERVICE_AVAILABLE_REPORT=207]="NO_SERVICE_AVAILABLE_REPORT",_E[_E.NO_SERVICE_AVAILABLE_APP_CENTER=208]="NO_SERVICE_AVAILABLE_APP_CENTER",_E[_E.NO_SERVICE_AVAILABLE_ENV0=209]="NO_SERVICE_AVAILABLE_ENV0",_E[_E.NO_SERVICE_AVAILABLE_VOET=210]="NO_SERVICE_AVAILABLE_VOET",_E[_E.NO_SERVICE_AVAILABLE_STRING_UID=211]="NO_SERVICE_AVAILABLE_STRING_UID",_E[_E.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS=212]="NO_SERVICE_AVAILABLE_WEBRTC_UNILBS",_E[_E.NO_SERVICE_AVAILABLE_UNILBS_FLV=213]="NO_SERVICE_AVAILABLE_UNILBS_FLV",(_m=R||(R={}))[_m.K_TIMESTAMP_EXPIRED=2]="K_TIMESTAMP_EXPIRED",_m[_m.K_CHANNEL_PERMISSION_INVALID=3]="K_CHANNEL_PERMISSION_INVALID",_m[_m.K_CERTIFICATE_INVALID=4]="K_CERTIFICATE_INVALID",_m[_m.K_CHANNEL_NAME_EMPTY=5]="K_CHANNEL_NAME_EMPTY",_m[_m.K_CHANNEL_NOT_FOUND=6]="K_CHANNEL_NOT_FOUND",_m[_m.K_TICKET_INVALID=7]="K_TICKET_INVALID",_m[_m.K_CHANNEL_CONFLICTED=8]="K_CHANNEL_CONFLICTED",_m[_m.K_SERVICE_NOT_READY=9]="K_SERVICE_NOT_READY",_m[_m.K_SERVICE_TOO_HEAVY=10]="K_SERVICE_TOO_HEAVY",_m[_m.K_UID_BANNED=14]="K_UID_BANNED",_m[_m.K_IP_BANNED=15]="K_IP_BANNED",_m[_m.K_CHANNEL_BANNED=16]="K_CHANNEL_BANNED",_m[_m.WARN_NO_AVAILABLE_CHANNEL=103]="WARN_NO_AVAILABLE_CHANNEL",_m[_m.WARN_LOOKUP_CHANNEL_TIMEOUT=104]="WARN_LOOKUP_CHANNEL_TIMEOUT",_m[_m.WARN_LOOKUP_CHANNEL_REJECTED=105]="WARN_LOOKUP_CHANNEL_REJECTED",_m[_m.WARN_OPEN_CHANNEL_TIMEOUT=106]="WARN_OPEN_CHANNEL_TIMEOUT",_m[_m.WARN_OPEN_CHANNEL_REJECTED=107]="WARN_OPEN_CHANNEL_REJECTED",_m[_m.WARN_REQUEST_DEFERRED=108]="WARN_REQUEST_DEFERRED",_m[_m.ERR_DYNAMIC_KEY_TIMEOUT=109]="ERR_DYNAMIC_KEY_TIMEOUT",_m[_m.ERR_NO_AUTHORIZED=110]="ERR_NO_AUTHORIZED",_m[_m.ERR_VOM_SERVICE_UNAVAILABLE=111]="ERR_VOM_SERVICE_UNAVAILABLE",_m[_m.ERR_NO_CHANNEL_AVAILABLE_CODE=112]="ERR_NO_CHANNEL_AVAILABLE_CODE",_m[_m.ERR_MASTER_VOCS_UNAVAILABLE=114]="ERR_MASTER_VOCS_UNAVAILABLE",_m[_m.ERR_INTERNAL_ERROR=115]="ERR_INTERNAL_ERROR",_m[_m.ERR_NO_ACTIVE_STATUS=116]="ERR_NO_ACTIVE_STATUS",_m[_m.ERR_INVALID_UID=117]="ERR_INVALID_UID",_m[_m.ERR_DYNAMIC_KEY_EXPIRED=118]="ERR_DYNAMIC_KEY_EXPIRED",_m[_m.ERR_STATIC_USE_DYANMIC_KE=119]="ERR_STATIC_USE_DYANMIC_KE",_m[_m.ERR_DYNAMIC_USE_STATIC_KE=120]="ERR_DYNAMIC_USE_STATIC_KE",_m[_m.ERR_NO_VOCS_AVAILABLE=2e3]="ERR_NO_VOCS_AVAILABLE",_m[_m.ERR_NO_VOS_AVAILABLE=2001]="ERR_NO_VOS_AVAILABLE",_m[_m.ERR_JOIN_CHANNEL_TIMEOUT=2002]="ERR_JOIN_CHANNEL_TIMEOUT",_m[_m.ERR_REPEAT_JOIN_CHANNEL=2003]="ERR_REPEAT_JOIN_CHANNEL",_m[_m.ERR_JOIN_BY_MULTI_IP=2004]="ERR_JOIN_BY_MULTI_IP",_m[_m.ERR_NOT_JOINED=2011]="ERR_NOT_JOINED",_m[_m.ERR_REPEAT_JOIN_REQUEST=2012]="ERR_REPEAT_JOIN_REQUEST",_m[_m.ERR_INVALID_VENDOR_KEY=2013]="ERR_INVALID_VENDOR_KEY",_m[_m.ERR_INVALID_CHANNEL_NAME=2014]="ERR_INVALID_CHANNEL_NAME",_m[_m.ERR_INVALID_STRINGUID=2015]="ERR_INVALID_STRINGUID",_m[_m.ERR_TOO_MANY_USERS=2016]="ERR_TOO_MANY_USERS",_m[_m.ERR_SET_CLIENT_ROLE_TIMEOUT=2017]="ERR_SET_CLIENT_ROLE_TIMEOUT",_m[_m.ERR_SET_CLIENT_ROLE_NO_PERMISSION=2018]="ERR_SET_CLIENT_ROLE_NO_PERMISSION",_m[_m.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE=2019]="ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",_m[_m.ERR_PUBLISH_REQUEST_INVALID=2020]="ERR_PUBLISH_REQUEST_INVALID",_m[_m.ERR_SUBSCRIBE_REQUEST_INVALID=2021]="ERR_SUBSCRIBE_REQUEST_INVALID",_m[_m.ERR_NOT_SUPPORTED_MESSAGE=2022]="ERR_NOT_SUPPORTED_MESSAGE",_m[_m.ERR_ILLEAGAL_PLUGIN=2023]="ERR_ILLEAGAL_PLUGIN",_m[_m.ERR_REJOIN_TOKEN_INVALID=2024]="ERR_REJOIN_TOKEN_INVALID",_m[_m.ERR_REJOIN_USER_NOT_JOINED=2025]="ERR_REJOIN_USER_NOT_JOINED",_m[_m.ERR_INVALID_OPTIONAL_INFO=2027]="ERR_INVALID_OPTIONAL_INFO",_m[_m.ILLEGAL_AES_PASSWORD=2028]="ILLEGAL_AES_PASSWORD",_m[_m.ILLEGAL_CLIENT_ROLE_LEVEL=2029]="ILLEGAL_CLIENT_ROLE_LEVEL",_m[_m.ERR_TOO_MANY_BROADCASTERS=2031]="ERR_TOO_MANY_BROADCASTERS",_m[_m.ERR_TOO_MANY_SUBSCRIBERS=2032]="ERR_TOO_MANY_SUBSCRIBERS",_m[_m.ERR_LICENSE_MISSING=32769]="ERR_LICENSE_MISSING",_m[_m.ERR_LICENSE_EXPIRED=32771]="ERR_LICENSE_EXPIRED",_m[_m.ERR_LICENSE_MINUTES_EXCEEDED=32773]="ERR_LICENSE_MINUTES_EXCEEDED",_m[_m.ERR_LICENSE_PERIOD_INVALID=32774]="ERR_LICENSE_PERIOD_INVALID",_m[_m.ERR_LICENSE_MULTIPLE_SDK_SERVICE=32778]="ERR_LICENSE_MULTIPLE_SDK_SERVICE",_m[_m.ERR_LICENSE_ILLEGAL=32783]="ERR_LICENSE_ILLEGAL",_m[_m.ERR_TEST_RECOVER=9e3]="ERR_TEST_RECOVER",_m[_m.ERR_TEST_TRYNEXT=9001]="ERR_TEST_TRYNEXT",_m[_m.ERR_TEST_RETRY=9002]="ERR_TEST_RETRY",(_f=I||(I={}))[_f.AUDIENCE_LEVEL_LOW_LATENCY=1]="AUDIENCE_LEVEL_LOW_LATENCY",_f[_f.AUDIENCE_LEVEL_ULTRA_LOW_LATENCY=2]="AUDIENCE_LEVEL_ULTRA_LOW_LATENCY",_f[_f.AUDIENCE_LEVEL_SYNC_LATENCY=3]="AUDIENCE_LEVEL_SYNC_LATENCY",(_S=C||(C={}
1)).LEAVE="LEAVE",_S.NETWORK_ERROR="NETWORK_ERROR",_S.SERVER_ERROR="SERVER_ERROR",_S.UID_BANNED="UID_BANNED",_S.IP_BANNED="IP_BANNED",_S.CHANNEL_BANNED="CHANNEL_BANNED",_S.FALLBACK="FALLBACK",_S.LICENSE_MISSING="LICENSE_MISSING",_S.LICENSE_EXPIRED="LICENSE_EXPIRED",_S.LICENSE_MINUTES_EXCEEDED="LICENSE_MINUTES_EXCEEDED",_S.LICENSE_PERIOD_INVALID="LICENSE_PERIOD_INVALID",_S.LICENSE_MULTIPLE_SDK_SERVICE="LICENSE_MULTIPLE_SDK_SERVICE",_S.LICENSE_ILLEGAL="LICENSE_ILLEGAL",(_T=v||(v={})).CONNECTION_STATE_CHANGE="connection-state-change",_T.MEDIA_RECONNECT_START="media-reconnect-start",_T.MEDIA_RECONNECT_END="media-reconnect-end",_T.IS_USING_CLOUD_PROXY="is-using-cloud-proxy",_T.USER_JOINED="user-joined",_T.USER_LEAVED="user-left",_T.USER_PUBLISHED="user-published",_T.USER_UNPUBLISHED="user-unpublished",_T.USER_INFO_UPDATED="user-info-updated",_T.CLIENT_BANNED="client-banned",_T.CHANNEL_MEDIA_RELAY_STATE="channel-media-relay-state",_T.CHANNEL_MEDIA_RELAY_EVENT="channel-media-relay-event",_T.VOLUME_INDICATOR="volume-indicator",_T.CRYPT_ERROR="crypt-error",_T.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="token-privilege-will-expire",_T.ON_TOKEN_PRIVILEGE_DID_EXPIRE="token-privilege-did-expire",_T.NETWORK_QUALITY="network-quality",_T.STREAM_TYPE_CHANGED="stream-type-changed",_T.STREAM_FALLBACK="stream-fallback",_T.RECEIVE_METADATA="receive-metadata",_T.STREAM_MESSAGE="stream-message",_T.LIVE_STREAMING_ERROR="live-streaming-error",_T.LIVE_STREAMING_WARNING="live-streaming-warning",_T.INJECT_STREAM_STATUS="stream-inject-status",_T.EXCEPTION="exception",_T.ERROR="error",_T.P2P_LOST="p2p_lost",_T.JOIN_FALLBACK_TO_PROXY="join-fallback-to-proxy",_T.CHANNEL_FALLBACK_TO_WEBSOCKET="channel-fallback-to-websocket",_T.MEDIA_CONNECTION_TYPE_CHANGE="media-connection-type-change",_T.PUBLISHED_USER_LIST="published-user-list",_T.CONTENT_INSPECT_CONNECTION_STATE_CHANGE="content-inspect-connection-state-change",_T.CONTENT_INSPECT_ERROR="content-inspect-error",_T.CONTENT_INSPECT_RESULT="content-inspect-result",(_g=y||(y={})).NETWORK_ERROR="NETWORK_ERROR",_g.SERVER_ERROR="SERVER_ERROR",_g.MULTI_IP="MULTI_IP",_g.TIMEOUT="TIMEOUT",_g.OFFLINE="OFFLINE",_g.LEAVE="LEAVE",_g.P2P_FAILED="P2P_FAILED",_g.FALLBACK="FALLBACK",(_R=A||(A={})).CONNECTING="connecting",_R.CONNECTED="connected",_R.RECONNECTING="reconnecting",_R.CLOSED="closed",(_I=O||(O={})).WS_CONNECTED="ws_connected",_I.WS_RECONNECTING="ws_reconnecting",_I.WS_CLOSED="ws_closed",_I.WS_RECONNECT_WAITTING_FINISH="ws_reconnect_waitting_finish",_I.WS_RECONNECT_CREATE_CONNECTION="ws_reconnect_create_connection",_I.ON_BINARY_DATA="on_binary_data",_I.REQUEST_RECOVER="request_recover",_I.REQUEST_JOIN_INFO="request_join_info",_I.REQUEST_REJOIN_INFO="req_rejoin_info",_I.IS_P2P_DISCONNECTED="is_p2p_dis",_I.DISCONNECT_P2P="dis_p2p",_I.ABORT_P2P_EXECUTION="abort_p2p_execution",_I.NEED_RENEW_SESSION="need-sid",_I.REPORT_JOIN_GATEWAY="report_join_gateway",_I.REQUEST_TIMEOUT="request_timeout",_I.REQUEST_SUCCESS="request_success",_I.JOIN_RESPONSE="join_response",_I.DATACHANNEL_PRECONNECT="datachannel_preconnect",_I.DATACHANNEL_CONNECTING="datachannel_connecting",_I.DATACHANNEL_FAILBACK="datachannel_failback",(_C=b||(b={})).PING="ping",_C.PING_BACK="ping_back",_C.JOIN="join_v3",_C.REJOIN="rejoin_v3",_C.LEAVE="leave",_C.SET_CLIENT_ROLE="set_client_role",_C.PUBLISH="publish",_C.UNPUBLISH="unpublish",_C.SUBSCRIBE="subscribe",_C.SUBSCRIBE_STREAMS="subscribe_streams",_C.UNSUBSCRIBE="unsubscribe",_C.UNSUBSCRIBE_STREAMS="unsubscribe_streams",_C.SUBSCRIBE_CHANGE="subscribe_change",_C.TRAFFIC_STATS="traffic_stats",_C.RENEW_TOKEN="renew_token",_C.SWITCH_VIDEO_STREAM="switch_video_stream",_C.DEFAULT_VIDEO_STREAM="default_video_stream",_C.SET_FALLBACK_OPTION="set_fallback_option",_C.GATEWAY_INFO="gateway_info",_C.CONTROL="control",_C.SEND_METADATA="send_metadata",_C.DATA_STREAM="data_stream",_C.PICK_SVC_LAYER="pick_svc_layer",_C.RESTART_ICE="restart_ice",_C.CONNECT_PC="connect_pc",_C.SET_VIDEO_PROFILE="set_video_profile",_C.SET_PARAMETER="set_parameter",(_v=N||(N={})).PUBLISH_STATS="publish_stats",_v.PUBLISH_RELATED_STATS="publish_related_stats",_v.SUBSCRIBE_STATS="subscribe_stats",_v.SUBSCRIBE_RELATED_STATS="subscribe_related_stats",_v.WS_INFLATE_DATA_LENGTH="ws_inflate_data_length",_v.DENOISER_STATS="denoiser_stats",_v.TRANSPORT_STATS="transport_stats",_v.EXTENSION_USAGE_STATS="extension_usage_stats",(_y=w||(w={})).ON_USER_ONLINE="on_user_online",_y.ON_USER_OFFLINE="on_user_offline",_y.ON_STREAM_FALLBACK_UPDATE="on_stream_fallback_update",_y.ON_PUBLISH_STREAM="on_publish_stream",_y.ON_UPLINK_STATS="on_uplink_stats",_y.ON_P2P_LOST="on_p2p_lost",_y.ON_REMOVE_STREAM="on_remove_stream",_y.ON_ADD_AUDIO_STREAM="on_add_audio_stream",_y.ON_ADD_VIDEO_STREAM="on_add_video_stream",_y.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="on_token_privilege_will_expire",_y.ON_TOKEN_PRIVILEGE_DID_EXPIRE="on_token_privilege_did_expire",_y.ON_USER_BANNED="on_user_banned",_y.ON_USER_LICENSE_BANNED="on_user_license_banned",_y.ON_NOTIFICATION="on_notification",_y.ON_CRYPT_ERROR="on_crypt_error",_y.MUTE_AUDIO="mute_audio",_y.MUTE_VIDEO="mute_video",_y.UNMUTE_AUDIO="unmute_audio",_y.UNMUTE_VIDEO="unmute_video",_y.ON_P2P_OK="on_p2p_ok",_y.RECEIVE_METADATA="receive_metadata",_y.ON_DATA_STREAM="on_data_stream",_y.ENABLE_LOCAL_VIDEO="enable_local_video",_y.DISABLE_LOCAL_VIDEO="disable_local_video",_y.ENABLE_LOCAL_AUDIO="enable_local_audio",_y.DISABLE_LOCAL_AUDIO="disable_local_audio",_y.ON_PUBLISHED_USER_LIST="on_published_user_list",(_A=D||(D={})).CONNECTION_STATE_CHANGE="CONNECTION_STATE_CHANGE",_A.NEED_ANSWER="NEED_ANSWER",_A.NEED_RENEGOTIATE="NEED_RENEGOTIATE",_A.P2P_LOST="P2P_LOST",_A.GATEWAY_P2P_LOST="GATEWAY_P2P_LOST",_A.NEED_UNPUB="NEED_UNPUB",_A.NEED_UNSUB="NEED_UNSUB",_A.NEED_UPLOAD="NEED_UPLOAD",_A.NEED_CONTROL="NEED_CONTROL",_A.START_RECONNECT="START_RECONNECT",_A.END_RECONNECT="END_RECONNECT",_A.NEED_SIGNAL_RTT="NEED_SIGNAL_RTT",(_O=P||(P={})).AUDIO_SOURCE_STATE_CHANGE="audio_source_state_change",_O.RECEIVE_TRACK_BUFFER="receive_track_buffer",_O.ON_AUDIO_BUFFER="on_audio_buffer",_O.UPDATE_SOURCE="update_source";let lR={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,currentPacketLossRate:0},lI={sendBytes:0,sendBitrate:0,sendPackets:0,sendPacketsLost:0,send
1ResolutionHeight:0,sendResolutionWidth:0,captureResolutionHeight:0,captureResolutionWidth:0,targetSendBitrate:0,totalDuration:0,totalFreezeTime:0,currentPacketLossRate:0},lC={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveLevel:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1},lv={uplinkNetworkQuality:0,downlinkNetworkQuality:0},ly={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};(_b=L||(L={})).CONNECTED="websocket:connected",_b.RECONNECTING="websocket:reconnecting",_b.WILL_RECONNECT="websocket:will_reconnect",_b.CLOSED="websocket:closed",_b.FAILED="websocket:failed",_b.ON_MESSAGE="websocket:on_message",_b.REQUEST_NEW_URLS="websocket:request_new_urls",_b.RECONNECT_WAITTING_FINISH="websocket:reconnect_waitting_finish",_b.RECONNECT_CREATE_CONNECTION="websocket:reconnect_create_connection",_b.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire",(_N=k||(k={})).TRANSCODE="mix_streaming",_N.RAW="raw_streaming",_N.INJECT="inject_streaming",(_w=M||(M={}))[_w.INJECT_STREAM_STATUS_START_SUCCESS=0]="INJECT_STREAM_STATUS_START_SUCCESS",_w[_w.INJECT_STREAM_STATUS_START_ALREADY_EXISTS=1]="INJECT_STREAM_STATUS_START_ALREADY_EXISTS",_w[_w.INJECT_STREAM_STATUS_START_UNAUTHORIZED=2]="INJECT_STREAM_STATUS_START_UNAUTHORIZED",_w[_w.INJECT_STREAM_STATUS_START_TIMEOUT=3]="INJECT_STREAM_STATUS_START_TIMEOUT",_w[_w.INJECT_STREAM_STATUS_START_FAILED=4]="INJECT_STREAM_STATUS_START_FAILED",_w[_w.INJECT_STREAM_STATUS_STOP_SUCCESS=5]="INJECT_STREAM_STATUS_STOP_SUCCESS",_w[_w.INJECT_STREAM_STATUS_STOP_NOT_FOUND=6]="INJECT_STREAM_STATUS_STOP_NOT_FOUND",_w[_w.INJECT_STREAM_STATUS_STOP_UNAUTHORIZED=7]="INJECT_STREAM_STATUS_STOP_UNAUTHORIZED",_w[_w.INJECT_STREAM_STATUS_STOP_TIMEOUT=8]="INJECT_STREAM_STATUS_STOP_TIMEOUT",_w[_w.INJECT_STREAM_STATUS_STOP_FAILED=9]="INJECT_STREAM_STATUS_STOP_FAILED",_w[_w.INJECT_STREAM_STATUS_BROKEN=10]="INJECT_STREAM_STATUS_BROKEN";let lA={alpha:1,height:640,width:360,x:0,y:0,zOrder:0,audioChannel:0},lO={x:0,y:0,width:160,height:160,zOrder:255,alpha:1};function lb(e,t){lc(e.url,"".concat(t,".url"),1,1e3,!1),lh(e.x)||ls(e.x,"".concat(t,".x"),0,1e4),lh(e.y)||ls(e.y,"".concat(t,".y"),0,1e4),lh(e.width)||ls(e.width,"".concat(t,".width"),0,1e4),lh(e.height)||ls(e.height,"".concat(t,".height"),0,1e4),lh(e.zOrder)||ls(e.zOrder,"".concat(t,".zOrder"),0,255),lh(e.alpha)||ls(e.alpha,"".concat(t,".alpha"),0,1,!1)}let lN={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:""},lw={audioBitrate:48,audioChannels:2,audioVolume:100,audioSampleRate:48e3,height:0,width:0,videoBitrate:400,videoFramerate:15,videoGop:30};function lD(e){if(!e.channelName)throw new du(o.INVALID_PARAMS,"invalid channelName in info");if("number"!=typeof e.uid)throw new du(o.INVALID_PARAMS,"invalid uid in info, uid must be a number");return e.token&&lc(e.token,"info.token",1,2047),lu(e.uid),ll(e.channelName),!0}function lP(e){return lo(e,"mediaSource",["screen","window","application"]),!0}(_D=U||(U={})).WARNING="@live_uap-warning",_D.ERROR="@line_uap-error",_D.PUBLISH_STREAM_STATUS="@live_uap-publish-status",_D.INJECT_STREAM_STATUS="@live_uap-inject-status",_D.WORKER_STATUS="@live_uap-worker-status",_D.REQUEST_NEW_ADDRESS="@live_uap-request-address",(x||(x={})).REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager",(_P=V||(V={}))[_P.LIVE_STREAM_RESPONSE_SUCCEED=200]="LIVE_STREAM_RESPONSE_SUCCEED",_P[_P.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM=454]="LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM",_P[_P.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR=450]="LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR",_P[_P.LIVE_STREAM_RESPONSE_BAD_STREAM=451]="LIVE_STREAM_RESPONSE_BAD_STREAM",_P[_P.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR=400]="LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR",_P[_P.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST=404]="LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST",_P[_P.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED=456]="LIVE_STREAM_RESPONSE_NOT_AUTHORIZED",_P[_P.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE=457]="LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE",_P[_P.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN=429]="LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN",_P[_P.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH=452]="LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH",_P[_P.LIVE_STREAM_RESPONSE_NOT_SUPPORTED=453]="LIVE_STREAM_RESPONSE_NOT_SUPPORTED",_P[_P.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM=455]="LIVE_STREAM_RESPONSE_MAX_STREAM_NUM",_P[_P.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR=500]="LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR",_P[_P.LIVE_STREAM_RESPONSE_WORKER_LOST=501]="LIVE_STREAM_RESPONSE_WORKER_LOST",_P[_P.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT=502]="LIVE_STREAM_RESPONSE_RESOURCE_LIMIT",_P[_P.LIVE_STREAM_RESPONSE_WORKER_QUIT=503]="LIVE_STREAM_RESPONSE_WORKER_QUIT",_P[_P.ER
1ROR_FAIL_SEND_MESSAGE=504]="ERROR_FAIL_SEND_MESSAGE",_P[_P.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE=30]="PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE",_P[_P.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT=31]="PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT",_P[_P.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH=32]="PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH",_P[_P.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN=33]="PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN",(_L=F||(F={})).CONNECT_FAILED="connect failed",_L.CONNECT_TIMEOUT="connect timeout",_L.WS_DISCONNECTED="websocket disconnected",_L.REQUEST_TIMEOUT="request timeout",_L.REQUEST_FAILED="request failed",_L.WAIT_STATUS_TIMEOUT="wait status timeout",_L.WAIT_STATUS_ERROR="wait status error",_L.BAD_STATE="bad state",_L.WS_ABORT="ws abort",_L.AP_REQUEST_TIMEOUT="AP request timeout",_L.AP_JSON_PARSE_ERROR="AP json parse error",_L.AP_REQUEST_ERROR="AP request error",_L.AP_REQUEST_ABORT="AP request abort",(_k=j||(j={}))[_k.SetSdkProfile=0]="SetSdkProfile",_k[_k.SetSourceChannel=1]="SetSourceChannel",_k[_k.SetSourceUserId=2]="SetSourceUserId",_k[_k.SetDestChannel=3]="SetDestChannel",_k[_k.StartPacketTransfer=4]="StartPacketTransfer",_k[_k.StopPacketTransfer=5]="StopPacketTransfer",_k[_k.UpdateDestChannel=6]="UpdateDestChannel",_k[_k.Reconnect=7]="Reconnect",_k[_k.SetVideoProfile=8]="SetVideoProfile",(_M=B||(B={})).NETWORK_DISCONNECTED="NETWORK_DISCONNECTED",_M.NETWORK_CONNECTED="NETWORK_CONNECTED",_M.PACKET_JOINED_SRC_CHANNEL="PACKET_JOINED_SRC_CHANNEL",_M.PACKET_JOINED_DEST_CHANNEL="PACKET_JOINED_DEST_CHANNEL",_M.PACKET_SENT_TO_DEST_CHANNEL="PACKET_SENT_TO_DEST_CHANNEL",_M.PACKET_RECEIVED_VIDEO_FROM_SRC="PACKET_RECEIVED_VIDEO_FROM_SRC",_M.PACKET_RECEIVED_AUDIO_FROM_SRC="PACKET_RECEIVED_AUDIO_FROM_SRC",_M.PACKET_UPDATE_DEST_CHANNEL="PACKET_UPDATE_DEST_CHANNEL",_M.PACKET_UPDATE_DEST_CHANNEL_REFUSED="PACKET_UPDATE_DEST_CHANNEL_REFUSED",_M.PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE="PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE",(_U=G||(G={})).RELAY_STATE_IDLE="RELAY_STATE_IDLE",_U.RELAY_STATE_CONNECTING="RELAY_STATE_CONNECTING",_U.RELAY_STATE_RUNNING="RELAY_STATE_RUNNING",_U.RELAY_STATE_FAILURE="RELAY_STATE_FAILURE",(_x=W||(W={})).RELAY_OK="RELAY_OK",_x.SERVER_CONNECTION_LOST="SERVER_CONNECTION_LOST",_x.SRC_TOKEN_EXPIRED="SRC_TOKEN_EXPIRED",_x.DEST_TOKEN_EXPIRED="DEST_TOKEN_EXPIRED",(_V=H||(H={})).High="high",_V.Low="low",_V.Audio="audio",_V.Screen="screen",_V.ScreenLow="screen_low",(_F=K||(K={})).DISCONNECT="disconnect",_F.CONNECTION_STATE_CHANGE="connection-state-change",_F.NETWORK_QUALITY="network-quality",_F.STREAM_TYPE_CHANGE="stream-type-change",_F.IS_P2P_DISCONNECTED="is-p2p-dis",_F.DISCONNECT_P2P="dis-p2p",_F.REQUEST_NEW_GATEWAY_LIST="req-gate-url",_F.NEED_RENEW_SESSION="need-sid",_F.REQUEST_P2P_CONNECTION_PARAMS="request-p2p-connection-params",_F.JOIN_RESPONSE="join-response",_F.REQUEST_DC_CONNECTION_PARAMS="request-dc-connection-params",_F.RESET_CONNECTION_EVENTS="reset-connection-events",_F.DATACHANNEL_PRECONNECT="datachannel_preconnect",_F.DATACHANNEL_FAILBACK="datachannel_failback",_F.RESET_SIGNAL="reset-signal",(_j=Y||(Y={}))[_j.Nothing=0]="Nothing",_j[_j.Audio=1]="Audio",_j[_j.LwoVideo=2]="LwoVideo",_j[_j.Video=4]="Video",_j[_j.Data=8]="Data",(_B=q||(q={}))[_B.websocket=0]="websocket",_B[_B.datachannel=1]="datachannel",(_G=J||(J={})).NEED_RENEGOTIATE="@need_renegotiate",_G.NEED_REPLACE_TRACK="@need_replace_track",_G.NEED_CLOSE="@need_close",_G.NEED_ENABLE_TRACK="@need_enable_track",_G.NEED_DISABLE_TRACK="@need_disable_track",_G.NEED_SESSION_ID="@need_sid",_G.SET_OPTIMIZATION_MODE="@set_optimization_mode",_G.GET_STATS="@get_stats",_G.GET_LOW_VIDEO_TRACK="@get_low_video_track",_G.NEED_RESET_REMOTE_SDP="@need_reset_remote_sdp",_G.NEED_UPDATE_VIDEO_ENCODER="@need_update_video_encoder",_G.NEED_MUTE_TRACK="@need_mute_track",_G.NEED_UNMUTE_TRACK="@need_unmute_track",(_W=X||(X={})).SCREEN_TRACK="screen_track",_W.CUSTOM_TRACK="custome_track",_W.LOW_STREAM="low_stream",(_H=z||(z={}))[_H.HIGH_STREAM=0]="HIGH_STREAM",_H[_H.LOW_STREAM=1]="LOW_STREAM",(_K=Q||(Q={}))[_K.DISABLE=0]="DISABLE",_K[_K.LOW_STREAM=1]="LOW_STREAM",_K[_K.AUDIO_ONLY=2]="AUDIO_ONLY",(_Y=Z||(Z={})).SOURCE_STATE_CHANGE="source-state-change",_Y.TRACK_ENDED="track-ended",_Y.BEAUTY_EFFECT_OVERLOAD="beauty-effect-overload",_Y.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",_Y.CLOSED="closed",(_q=$||($={})).FIRST_FRAME_DECODED="first-frame-decoded",_q.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",(_J=ee||(ee={})).CHINA="CHINA",_J.ASIA="ASIA",_J.NORTH_AMERICA="NORTH_AMERICA",_J.EUROPE="EUROPE",_J.JAPAN="JAPAN",_J.INDIA="INDIA",_J.KOREA="KOREA",_J.HKMC="HKMC",_J.US="US",_J.OCEANIA="OCEANIA",_J.SOUTH_AMERICA="SOUTH_AMERICA",_J.AFRICA="AFRICA",_J.OVERSEA="OVERSEA",_J.GLOBAL="GLOBAL",_J.EXTENSIONS="EXTENSIONS";let lL=[ee.AFRICA,ee.ASIA,ee.CHINA,ee.EUROPE,ee.GLOBAL,ee.INDIA,ee.JAPAN,ee.NORTH_AMERICA,ee.OCEANIA,ee.OVERSEA,ee.SOUTH_AMERICA];(_X=et||(et={})).CHINA="CN",_X.ASIA="AS",_X.NORTH_AMERICA="NA",_X.EUROPE="EU",_X.JAPAN="JP",_X.INDIA="IN",_X.KOREA="KR",_X.HKMC="HK",_X.US="US",_X.OCEANIA="OC",_X.SOUTH_AMERICA="SA",_X.AFR
1ICA="AF",_X.OVERSEA="OVERSEA",_X.GLOBAL="GLOBAL",_X.EXTENSIONS="GLOBAL";let lk={CHINA:{},ASIA:{CODE:et.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:et.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:et.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:et.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:et.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:et.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:et.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:et.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:et.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:["statscollector-2-oversea.agora.io"],LOG_UPLOAD_SERVER:["logservice-oversea.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.agora.io"]},GLOBAL:{CODE:et.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:et.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:et.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:et.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:{}};dC&&(lk.CHINA={CODE:et.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"]}),(ei||(ei={})).UPDATE_BITRATE_LIMIT="update_bitrate_limit";class lM extends dd{constructor(e,t){super(),cc(this,"onICEConnectionStateChange",void 0),cc(this,"onConnectionStateChange",void 0),cc(this,"onDTLSTransportStateChange",void 0),cc(this,"onDTLSTransportError",void 0),cc(this,"onICETransportStateChange",void 0),cc(this,"onFirstAudioReceived",void 0),cc(this,"onFirstVideoReceived",void 0),cc(this,"onFirstAudioDecoded",void 0),cc(this,"onFirstVideoDecoded",void 0),cc(this,"onFirstVideoDecodedTimeout",void 0),cc(this,"onSelectedLocalCandidateChanged",void 0),cc(this,"onSelectedRemoteCandidateChanged",void 0),cc(this,"establishPromise",void 0)}}(_z=er||(er={})).SEND="sendonly",_z.RECV="recvonly",_z.SENDRECV="sendrecv",_z.INACTIVE="inactive",(_Q=en||(en={})).VIDEO="video",_Q.AUDIO="audio",(_Z=eo||(eo={})).LocalVideoTrack="videoTrack",_Z.LocalAudioTrack="audioTrack",_Z.LocalVideoLowTrack="videoLowTrack",(_$
1=es||(es={})).New="new",_$.Connected="connected",_$.Reconnecting="reconnecting",_$.Disconnected="disconnected",(_0=ea||(ea={})).StateChange="stateChange",_0.IceConnectionStateChange="iceConnectionStateChange",_0.RequestMuteLocal="requestMuteLocal",_0.RequestUnmuteLocal="requestUnmuteLocal",_0.RequestRePublish="requestRePublish",_0.RequestReSubscribe="requestReSubscribe",_0.RequestUploadStats="requestUploadStats",_0.MediaReconnectStart="MediaReconnectStart",_0.MediaReconnectEnd="MediaReconnectEnd",_0.NeedSignalRTT="NeedSignalRTT",_0.RequestRestartICE="RequestRestartIce",_0.PeerConnectionStateChange="PeerConnectionStateChange",_0.RequestReconnect="RequestReconnect",_0.RequestReconnectPC="RequestReconnectPC",_0.RequestUnpublishForReconnectPC="RequestUnpublishForReconnectPC",_0.P2PLost="P2PLost",_0.UpdateVideoEncoder="UpdateVideoEncoder",_0.ConnectionTypeChange="ConnectionTypeChange",_0.RequestLowStreamParameter="RequestLowStreamParameter",_0.QueryClientConnectionState="QueryClientConnectionState",(_1=ec||(ec={})).ONLINE="ONLINE",_1.OFFLINE="OFFLINE",(_2=ed||(ed={})).NETWORK_STATE_CHANGE="NETWORK_STATE_CHANGE",_2.ONLINE="ONLINE",_2.OFFLINE="OFFLINE",(_3=el||(el={})).ON_TRACK="on_track",_3.ON_NODE="on_node",(_4=eu||(eu={})).REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",_4.REQUEST_CONSTRAINTS="request_constraints",(_5=eh||(eh={})).CONNECTING="CONNECTING",_5.RECONNECTING="RECONNECTING",_5.CONNECTED="CONNECTED",_5.CLOSED="CLOSED",(_6=ep||(ep={}))[_6.CONNECT_AP=0]="CONNECT_AP",_6[_6.AP_CONNECTED=1]="AP_CONNECTED",_6[_6.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",_6[_6.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",_6[_6.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",_6[_6.CONNECT_WORKER=5]="CONNECT_WORKER",_6[_6.WORKER_CONNECTED=6]="WORKER_CONNECTED",_6[_6.CLOSED=7]="CLOSED",(_8=e_||(e_={})).CONNECTION_STATE_CHANGE="connection-state-change",_8.STATE_CHANGE="state-change",_8.INSPECT_RESULT="inspect-result",_8.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",_8.REQUEST_NEW_WORKER_URL="request-new-worker-url",(_7=eE||(eE={})).NETWORK_ERROR="NETWORK_ERROR",_7.SERVER_ERROR="SERVER_ERROR",_7.MULTI_IP="MULTI_IP",_7.TIMEOUT="TIMEOUT",_7.OFFLINE="OFFLINE",_7.LEAVE="LEAVE",_7.P2P_FAILED="P2P_FAILED",_7.FALLBACK="FALLBACK",(_9=em||(em={})).CONNECTED="transmitter:connected",_9.RECONNECTING="transmitter:reconnecting",_9.WILL_RECONNECT="transmitter:will_reconnect",_9.CLOSED="transmitter:closed",_9.FAILED="transmitter:failed",_9.ON_MESSAGE="transmitter:on_message",_9.REQUEST_NEW_URLS="transmitter:request_new_urls",_9.RECONNECT_WAITTING_FINISH="transmitter:reconnect_waitting_finish",_9.RECONNECT_CREATE_CONNECTION="transmitter:reconnect_create_connection",_9.ON_TOKEN_PRIVILEGE_DID_EXPIRE="transmitter:on_token_privilege_did_expire",_9.TO_CONNECT_DATACHANNEL="transmitter:to_connect_datachannel",_9.FAILBACK="transmitter:failback";let lU={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};(Ee=ef||(ef={}))[Ee.CHOOSE_SERVER=11]="CHOOSE_SERVER",Ee[Ee.CLOUD_PROXY=18]="CLOUD_PROXY",Ee[Ee.CLOUD_PROXY_5=20]="CLOUD_PROXY_5",Ee[Ee.CLOUD_PROXY_FALLBACK=26]="CLOUD_PROXY_FALLBACK";var lx=Array.isArray||function(e){return"Array"==tH(e)},lV=iy("species"),lF=tA.Array,lj=function(e){var t;return lx(e)&&(og(t=e.constructor)&&(t===lF||lx(t.prototype))||tQ(t)&&null===(t=t[lV]))&&(t=void 0),void 0===t?lF:t},lB=function(e,t){return new(lj(e))(0===t?0:t)},lG=tC([].push),lW=function(e){var t=1==e,i=2==e,r=3==e,n=4==e,o=6==e,s=7==e,a=5==e||o;return function(c,d,l,u){for(var h,p,_=ip(c),E=tq(_),m=iW(d,l),f=i6(E),S=0,T=u||lB,g=t?T(c,f):i||s?T(c,0):void 0;f>S;S++)if((a||S in E)&&(p=m(h=E[S],S,_),e))if(t)g[S]=p;else if(p)switch(e){case 3:return!0;case 5:return h;case 6:return S;case 2:lG(g,h)}else switch(e){case 4:return!1;case 7:lG(g,h)}return o?-1:r||n?n:g}},lH={forEach:lW(0),map:lW(1),filter:lW(2),some:lW(3),every:lW(4),find:lW(5),findIndex:lW(6),filterReject:lW(7)},lK=lH.forEach,lY=re("forEach")?[].forEach:function(e){return lK(this,e,arguments.length>1?arguments[1]:void 0)};i1({target:"Array",proto:!0,forced:[].forEach!=lY},{forEach:lY});var lq=rr("Array").forEach,lJ=Array.prototype,lX={DOMTokenList:!0,NodeList:!0},lz=function(e){var t=e.forEach;
1return e===lJ||tv(lJ,e)&&t===lJ.forEach||iE(lX,nt(e))?lq:t};i1({target:"Object",stat:!0,forced:tf(function(){rH(1)})},{keys:function(e){return rH(ip(e))}});var lQ=tZ.Object.keys,lZ=tC([].reverse),l$=[1,2];i1({target:"Array",proto:!0,forced:String(l$)===String(l$.reverse())},{reverse:function(){return lx(this)&&(this.length=this.length),lZ(this)}});var l0=rr("Array").reverse,l1=Array.prototype,l2=function(e){var t=e.reverse;return e===l1||tv(l1,e)&&t===l1.reverse?l0:t},l3=iy("species"),l4=function(e){return t6>=51||!tf(function(){var t=[];return(t.constructor={})[l3]=function(){return{foo:1}},1!==t[e](Boolean).foo})},l5=l4("slice"),l6=iy("species"),l8=tA.Array,l7=Math.max;i1({target:"Array",proto:!0,forced:!l5},{slice:function(e,t){var i,r,n,o=tz(this),s=i6(o),a=rD(e,s),c=rD(void 0===t?s:t,s);if(lx(o)&&((og(i=o.constructor)&&(i===l8||lx(i.prototype))||tQ(i)&&null===(i=i[l6]))&&(i=void 0),i===l8||void 0===i))return oy(o,a,c);for(r=new(void 0===i?l8:i)(l7(c-a,0)),n=0;a<c;a++,n++)a in o&&dK(r,n,o[a]);return r.length=n,r}});var l9=rr("Array").slice,ue=Array.prototype,ut=function(e){var t=e.slice;return e===ue||tv(ue,e)&&t===ue.slice?l9:t};function ui(e,t,i,r,n){var o,s,a,c={};return lz(o=lQ(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=rs(s=l2(a=ut(i).call(i)).call(a)).call(s,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&&(ca(e,t,c),c=null),c}var ur=rr("Array").keys,un=Array.prototype,uo={DOMTokenList:!0,NodeList:!0},us=function(e){var t=e.keys;return e===un||tv(un,e)&&t===un.keys||iE(uo,nt(e))?ur:t};function ua(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 uc(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?ua(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):ua(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let ud=0,ul=0;function uu(e,t,i,r){return new sG((n,s)=>{var a;let c;t.timeout=t.timeout||dM.HTTP_CONNECT_TIMEOUT,t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),ud+=hU(t.data)):i&&(t.data.size?ud+=t.data.size:t.data instanceof FormData?ud+=(a=t.data,c=0,/DingTalk/i.test(navigator.userAgent)&&a.realFormData&&(a=a.realFormData),a.forEach(e=>{c+="string"==typeof e?hU(e):e.size}),c+138):ud+=hU(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,da.request(t).then(e=>{"string"==typeof e.data?ul+=hU(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?ul+=e.data.byteLength:ul+=hU(JSON.stringify(e.data)),r&&n({data:e.data,headers:e.headers}),n(e.data)}).catch(e=>{da.isCancel(e)?s(new du(o.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?s(new du(o.NETWORK_TIMEOUT,e.message)):e.response?s(new du(o.NETWORK_RESPONSE_ERROR,e.response.status)):s(new du(o.NETWORK_ERROR,e.message))})})}async function uh(e,t){let i=new Blob([t.data],{type:"buffer"});return await uu(e,uc(uc({},t),{},{data:i,headers:{"Content-Type":"application/octet-stream"}}),!0)}let up=new class extends dd{set networkState(e){dg.info("[".concat(this._moduleName,"]")+"network state changed, "+this._networkState+" -> "+e),this.emit(ed.NETWORK_STATE_CHANGE,e,this._networkState),e===ec.ONLINE?this.emit(ed.ONLINE):e===ec.OFFLINE&&(this.onlineWaiter=new sG(e=>{this.once(ed.ONLINE,()=>{this.onlineWaiter=void 0,e(ec.ONLINE)})}),this.emit(ed.OFFLINE)),this._networkState=e}get networkState(){return this._networkState}constructor(){super(),cc(this,"_moduleName","network-indicator"),cc(this,"_networkState",ec.ONLINE),cc(this,"onlineWaiter",void 0),window.addEventListener("online",()=>{this.networkState=ec.ONLINE}),window.addEventListener("offline",()=>{this.networkState=ec.OFFLINE})}},u_=!1,uE=new class extends dd{constructor(){super(...arguments),cc(this,"onAutoplayFailed",void 0),cc(this,"onAudioAutoplayFailed",void 0)}};function um(){if(aY(),!u_){let e=t=>{t.preventDefault(),u_=!1,ci()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};u_=!0,ci()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),dg.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),uE.onAutoplayFailed?uE.onAutoplayFailed():uE.onAudioAutoplayFailed?dg.warning("AgoraRTC.onAudioAutoplayFailed has been deprecated 
1in 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 ."):dg.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 ."),uE.emit("autoplay-failed")}}function uf(e){return(new TextEncoder).encode(e)}let uS=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},uT=async e=>{var t;let i;return t=await crypto.subtle.digest("SHA-256",uf(e)),i="",new Uint8Array(t).forEach(e=>{i+=e.toString(16).padStart(2,"0")}),i};function ug(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 uR(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?ug(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):ug(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}function uI(){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=arguments.length,r=Array(t),s=0;s<t;s++)r[s]=arguments[s];let a=r;if(e.argsMap)try{a=e.argsMap(this,...r)}catch(e){dg.warning(e),a=[]}try{JSON.stringify(a)}catch(e){dg.warning("arguments for method ".concat(o,".").concat(i," not serializable for apiInvoke.")),a=[]}let c=(e.report||uC).reportApiInvoke(this._sessionId||null,{name:"".concat(o,".").concat(i),options:a,tag:_.TRACER,reportResult:e.reportResult},e.throttleTime);try{let t=n.apply(this,r);return t instanceof sG?t.then(t=>(c.onSuccess(e.reportResult&&t),t)).catch(e=>{throw c.onError(e),e}):(c.onSuccess(e.reportResult&&t),t)}catch(e){throw c.onError(e),e}}}return r}}let uC=new class{constructor(){cc(this,"baseInfoMap",new Map),cc(this,"proxyServer",void 0),cc(this,"clientList",dG),cc(this,"eventUploadTimer",void 0),cc(this,"setSessionIdTimer",void 0),cc(this,"url",void 0),cc(this,"backupUrl",void 0),cc(this,"_appId",void 0),cc(this,"keyEventUploadPendingItems",[]),cc(this,"normalEventUploadPendingItems",[]),cc(this,"apiInvokeUploadPendingItems",[]),cc(this,"apiInvokeCount",0),cc(this,"ltsList",[]),cc(this,"lastSendNormalEventTime",Date.now()),cc(this,"customReportCounterTimer",void 0),cc(this,"customReportCount",0),cc(this,"extApiInvoke",async e=>{for(let t of e){let e=uR(uR({},t),{},{sid:null,invokeId:++this.apiInvokeCount,tag:_.TRACER});this.sendApiInvoke(e)}}),this.eventUploadTimer=window.setInterval(this.doSend.bind(this),dM.EVENT_REPORT_SEND_INTERVAL),this.setSessionIdTimer=window.setInterval(this.appendSessionId.bind(this),dM.EVENT_REPORT_SEND_INTERVAL)}adjustSessionStartTime(e){if(!this.baseInfoMap.has(e)&&!this.baseInfoMap.get(e))return void dg.error("adjust session ".concat(e," start time, sid is not exist or info is undefined"));let t=this.baseInfoMap.get(e),i=Date.now(),r=t.startTime;t.startTime=i,dg.debug("rewrite session ".concat(e," startTime: ").concat(i," , ").concat(i-r,"ms")),this.baseInfoMap.set(e,t)}setAppId(e){this._appId=e}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,s=()=>({tag:t.tag,invokeId:n,sid:e,name:t.name,apiInvokeTime:r,options:t.options,states:t.states||null}),a=!!dM.SHOW_REPORT_INVOKER_LOG;a&&dg.info("".concat(t.name," start"),t.options);let c=!1;hx(t.timeout).then(()=>{c||(this.sendApiInvoke(uR(uR({},s()),{},{error:o.API_INVOKE_TIMEOUT,success:!1})),dg.debug("".concat(t.name," timeout")))});let d=new du(o.UNEXPECTED_ERROR,"".concat(t.name,": this api invoke is end"));return{onSuccess:e=>{let r=()=>{if(c)throw d;return c=!0,this.sendApiInvoke(uR(uR({},s()),{},{success:!0},t.reportResult&&{result:e})),a&&dg.info("".concat(t.name," onSuccess")),e};return i?h2(r,t.name+"Success",i,()=>c=!0):r()},onError:e=>{let r=()=>{if(c)throw e;c=!0,this.sendApiInvoke(uR(uR({},s()),{},{success:!1,error:e})),a&&dg.info("".concat(t.name," onFailure"),e.toString())};return i?h2(r,t.name+"Error",i,()=>c=!0):r()}}}sessionInit(e,t){if(this.baseInfoMap.has(e))return;let i=Date.now(),r=this.createBaseInfo(e,i);r.cname=t.cname;let n=Object.assign({},{willUploadConsoleLog:dM.UPLOAD_LOG,maxTouchPoints:navigator.maxTouchPoints,areaVersion:dC?"global":"oversea",areas:dM.AREAS&&dM.AREAS.join(",")},t.extend),o=Date.now(),s=uR(uR({},r),{},{eventType:d.SESSION_INIT,appid:t.appid,browser:navigator.userAgent,build:dR,lts:o,elapse:o-i,extend:JSON.stringify(n),mode:t.mode,process:dM.PROCESS_ID,appType:dM.APP_TYPE,success:!0,version:dI});this.send({type:l.SESSION,data:s},!0)}joinChooseServer(e,t){let i=this.baseInfoMap.get(e);if(!i)return;let r=i.info,n=Date.now(),o=uR(uR({},r),{},{eventType:d.JOIN_CHOOSE_SERVER,lts:n,eventElapse: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});this.send({type:l.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=uR(uR({},r),{},{eventType:d.REQ_USER_ACCOUNT,lts:n,success:t.success,serverAddress:t.serverAddr,stringUid:t.stringUid,uid:t.uid,errorCode:t.errorCode,elapse:n-i.startTime,eventElapse:n-t.lts,extend:JSON.stringify(t.extend)});this.send({type:l.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,avoidJoinStartTime:s,isProxy:a,addr:c}=t,u=n-(o&&s?s:i.startTime),h=uR(uR({},r),{},{eventType:d.JOIN_GATEWAY,lts:n,gatewayAddr:t.addr,success:t.succ,errorCode:t.ec,elapse:u,eventElapse:n-t.lts,firstSuccess:o,signalChannel:t.signalChannel}),p=+!!h.success;if(t.succ&&(i.lastJoinSuccessTime=n),o)this.send({type:l.JOIN_GATEWAY,data:h},!0);else{let e;if(c)if(a){let t=c.match(/h=(\d{1,3}-){3}\d{1,3}/g),i=c.match(/p=[0-9]{1,6}/g);e={isSuccess:p,gatewayIp:t&&t.length?t[0].split("=")[1].replace(/-/g,"."):"",port:i&&i.length?i[0].split("=")[1]:"",isProxy:+!!a}}else{let t=c.match(/wss:\/\/(\d{1,3}-){3}\d{1,3}/g),i=c.match(/:[0-9]{1,6}/g);e={isSuccess:p,gatewayIp:t&&t.length?t[0].split("//")[1].replace(/-/g,"."):"",port:i&&i.length?i[0].split(":")[1]:"",isProxy:+!!a}}else e={isSuccess:p,gatewayIp:"",port:"",isProxy:+!!a};delete h.success,delete h.eventType,delete h.firstSuccess,h.vid=Number(h.vid);let t=Object.assign({},h,e,{eventType:d.REJOIN_GATEWAY});this.send({type:l.RE_JOIN_GATEWAY,data:t},!0)}}joinChannelTimeout(e,t){let i=this.baseInfoMap.get(e);if(!i)return;let r=Date.now(),n=uR(uR({},i.info),{},{lts:r,timeout:t,elapse:r-i.startTime});this.send({type:l.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=uR(uR({},r),{},{eventType:d.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:l.PUBLISH,data:o},!0)}subscribe(e,t,i){let r=this.baseInfoMap.get(e);if(!r)return;let n=r.info,o=Date.now(),s=uR(uR({},n),{},{eventType:d.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},i&&{extend:JSON.stringify({isMassSubscribe:!0})});"string"==typeof t.peerid?s.peerSuid=t.peerid:s.peer=t.peerid,this.send({type:l.SUBSCRIBE,data:s},!0)}wsCompressorInit(e){var t;let i=[...us(t=this.baseInfoMap).call(t)],r=i.length?i[0]:"UnableToGetSid",n=this.baseInfoMap.get(r);if(!n)return;let o=n.info,s=Date.now(),a=uR(uR({},o),{},{eventType:d.WS_COMPRESSOR_INIT,lts:s,eventElapse:e.eventElapse,elapse:s-n.startTime,status:e.status?1:2});this.send({type:l.WS_COMPRESSOR_INIT,data:a},!0)}firstRemoteVideoDecode(e,t,i,r){let n=this.baseInfoMap.get(e);if(!n)return;let o=n.info,s=Date.now(),a=uR(uR(uR({},o),r),{},{elapse:s-n.startTime,eventType:t,lts:s,firstDecodeFrame:Math.max(s-n.startTime,0),apEnd:Math.max(r.apEnd-n.startTime,0),apStart:Math.max(r.apStart-n.startTime,0),joinGwEnd:Math.max(r.
1joinGwEnd-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:a},!0)}firstRemoteFrame(e,t,i,r){let n=this.baseInfoMap.get(e);if(!n)return;let o=n.info,s=Date.now(),a=uR(uR(uR({},o),r),{},{elapse:s-n.startTime,eventType:t,lts:s});this.send({type:i,data:a},!0)}onGatewayStream(e,t,i,r){let n=this.baseInfoMap.get(e);if(!n)return;let o=n.info,s=Date.now(),a=uR(uR(uR({},o),r),{},{eventType:t,lts:s});this.send({type:i,data:a},!0)}streamSwitch(e,t){let i=this.baseInfoMap.get(e);if(!i)return;let r=i.info,n=Date.now(),o=uR(uR({},r),{},{eventType:d.STREAM_SWITCH,lts:n,isDual:t.isdual,elapse:n-i.startTime,success:t.succ});this.send({type:l.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=uR(uR({},r),{},{eventType:d.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:l.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=uR(uR({},r),{},{eventType:d.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:l.REQUEST_PROXY_WORKER_MANAGER,data:o},!0)}setProxyServer(e){this.proxyServer=e,e?dg.debug("reportProxyServerurl: ".concat(e)):dg.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=uR(uR({},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:l.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=hU(JSON.stringify(e)),o=0,s=[],a=0;for(let i=0;i<r.length;i++)(a+=127>=r.charCodeAt(i)?1:3)<=1300-n||(s[s.length]=hM(hM({},e),{},{[t]:r.substring(o,i)}),o=i,a=127>=r.charCodeAt(i)?1:3);return o!==r.length-1&&(s[s.length]=hM(hM({},e),{},{[t]:r.substring(o)})),s})(uR(uR(uR({},r),t),{},{elapse:n-i.startTime,lts:n,productType:"WebRTC"}),"payload",0).forEach(e=>this.send({type:l.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=uR(uR(uR({},r),t),{},{elapse:n-i.startTime,lts:n});this.send({type:l.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=uR(uR(uR({},r),t),{},{elapse:n-i.startTime,lts:n,extend:t.extend||void 0});this.send({type:l.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=uR(uR(uR({},r),t),{},{elapse:n-i.startTime,lts:n});this.send({type:l.WEBSOCKET_QUIT,data:o},!0)}async sendCustomReportMessage(e,t){if(this.customReportCount+=t.length,this.customReportCount>dM.CUSTOM_REPORT_LIMIT)throw new du(o.CUSTOM_REPORT_FREQUENCY_TOO_HIGH);this.customReportCounterTimer||(this.customReportCounterTimer=window.setInterval(()=>{this.customReportCount=0},5e3));let i=Date.now(),r=t.map(t=>({type:l.USER_ANALYTICS,data:uR(uR({sid:e},t),{},{lts:i})}));try{dM.NEW_REPORT_SERVER?await this.postDataToStatsCollector2(r):await this.postDataToStatsCollector(r)}catch(e){throw dg.error("send custom report message failed",e.toString()),new du(o.CUSTOM_REPORT_SEND_FAILED,e.message)}}autoplayFailed(e,t,i,r){if(!e)return;let n=this.baseInfoMap.get(e);if(!n)return;let o=n.info,s=Date.now(),a=uR(uR({},o),{},{vid:void 0===o.vid?0:Number(o.vid),lts:s,elapse:s-n.startTime,cbRegistered:uE.onAutoplayFailed||uE.onAudioAutoplayFailed?1:-1,errorMsg:i,mediaType:t,trackId:r,extend:void 0});this.send({type:l.AUTOPLAY_FAILED,data:a},!0)}sendApiInvoke(e){let t,i=dM.NOT_REPORT_EVENT;if(e.tag&&i.includes&&i.includes(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:s}=r.info;if(e.lts=e.lts||Date.now(),e.error)if(e.error instanceof du){let{c
1ode:i,message:r}=e.error;t=i||r||e.error.toString()}else t=e.error.toString();let a={invokeId:e.invokeId,sid:e.sid,cname:n,cid:s,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:l.API_INVOKE,data:a},!1),!0}appendSessionId(){this.clientList.forEach(e=>{if(e._sessionId){let t=this.apiInvokeUploadPendingItems.length;for(let i=0;i<t;i++){let t=this.apiInvokeUploadPendingItems.shift();t&&(t.sid=e._sessionId,this.sendApiInvoke(Object.assign({},t)))}}})}send(e,t){if(t)return this.keyEventUploadPendingItems.push(e),void this.sendItems(this.keyEventUploadPendingItems,!0);this.normalEventUploadPendingItems.push(e),this.normalEventUploadPendingItems.length>dM.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),lr(n=this.ltsList).call(n,(e,t)=>e-t))}
1return t||(this.lastSendNormalEventTime=Date.now()),dM.ENABLE_EVENT_REPORT&&i.length&&(dM.NEW_REPORT_SERVER?this.postDataToStatsCollector2(i):this.postDataToStatsCollector(i)).catch(e=>{dM.EVENT_REPORT_RETRY&&(t?this.keyEventUploadPendingItems=this.keyEventUploadPendingItems.concat(i):(this.normalEventUploadPendingItems=this.normalEventUploadPendingItems.concat(i),this.normalEventUploadPendingItems.length>dM.NORMAL_EVENT_QUEUE_CAPACITY&&(this.normalEventUploadPendingItems.splice(0,this.normalEventUploadPendingItems.length-dM.NORMAL_EVENT_QUEUE_CAPACITY),dg.warning("report: drop normal events"))))}),e}async postDataToStatsCollector2(e){up.networkState===ec.OFFLINE&&await sG.race([up.onlineWaiter,hx(2*dh.maxRetryTimeout)]);let t=e=>{let t=new Uint8Array;return e.forEach(e=>{let i,r=uf(JSON.stringify(e.data)),n=new ArrayBuffer(5),o=(i=0,Object.entries(l).forEach(t=>{let[r,n]=t;n===e.type&&(i=h[r])}),i),s=new DataView(n);s.setUint16(0,r.byteLength,!0),s.setUint8(2,255&o),s.setUint8(3,o>>>8&255),s.setUint8(4,o>>>16&255),t=uS(t,new Uint8Array(n)),t=uS(t,r)}
1),t},i="event",r=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(dM.NEW_REPORT_SERVER_DOMAINS[0],"&p=443&d=").concat(i):"https://".concat(dM.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(dM.NEW_REPORT_SERVER_DOMAINS[1],"&p=443&d=").concat(i):"https://".concat(dM.NEW_REPORT_SERVER_DOMAINS[1],"/").concat(i));try{await uu(r,{timeout:1e4,data:t(e),headers:uR(uR({token:"32f24ab2ddb74f508aa9286c356cec84",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={msgType:"EventMessages",sentTs:Math.round(Date.now()/1e3),payloads:e.map(e=>JSON.stringify(e)),vid:(e=>{let t=e&&e.data.sid&&this.baseInfoMap.get(e.data.sid);return t&&t.info.vid&&+t.info.vid||0})(e[0])};up.networkState===ec.OFFLINE&&await sG.race([up.onlineWaiter,hx(2*dh.maxRetryTimeout)]);let r=t?"/events/proto-raws":"/events/messages",n=this.url||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(dM.EVENT_REPORT_DOMAIN,"&p=").concat(dM.STATS_COLLECTOR_PORT,"&d=").concat(r):"https://".concat(dM.EVENT_REPORT_DOMAIN,":").concat(dM.STATS_COLLECTOR_PORT).concat(r));for(let e=0;e<2;e+=1){1===e&&(n=this.backupUrl||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(dM.EVENT_REPORT_BACKUP_DOMAIN,"&p=").concat(dM.STATS_COLLECTOR_PORT,"&d=").concat(r):"https://".concat(dM.EVENT_REPORT_BACKUP_DOMAIN,":").concat(dM.STATS_COLLECTOR_PORT).concat(r)));try{t?await uh(n,{timeout:1e4,data:i}):await uu(n,{timeout:1e4,data:i})}catch(t){if(1===e)throw t;continue}return}}createBaseInfo(e,t){let i=Object.assign({},lm);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:_.TRACER}).onSuccess()}};dl.on("REPORT_LOG_UPLOAD",e=>{e.networkState=up.networkState,uC.reportApiInvoke(null,{name:"logUploadError",options:e,tag:_.TRACER})});class uv extends dd{constructor(e,t){super(),cc(this,"trackMediaType",void 0),cc(this,"_ID",void 0),cc(this,"_hints",[]),cc(this,"_isClosed",!1),cc(this,"_originMediaStreamTrack",void 0),cc(this,"_mediaStreamTrack",void 0),cc(this,"_external",{}),this._ID=t||hV(8,"track-"),this._originMediaStreamTrack=e,this._mediaStreamTrack=e,dW.includes(this)||dW.push(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){if(!e){let e=uC.reportApiInvoke(null,{name:p.GET_MEDIA_STREAM_TRACK,options:[],tag:_.TRACER});this._mediaStreamTrack&&"string"==typeof this._mediaStreamTrack.label?e.onSuccess(this._mediaStreamTrack.label):e.onSuccess("")}return this._mediaStreamTrack}getMediaStreamTrackSettings(){return this.getMediaStreamTrack(!0).getSettings()}close(){this._isClosed=!0,function(e){let t=dW.indexOf(e);-1!==t&&dW.splice(t,1)}(this),this.emit(Z.CLOSED)}}let uy,uA=1;class uO{constructor(e){cc(this,"lockingPromise",sG.resolve()),cc(this,"locks",0),cc(this,"name",""),cc(this,"lockId",void 0),this.lockId=uA++,e&&(this.name=e),dg.debug("[lock-".concat(this.name,"-").concat(this.lockId,"] is created."))}get isLocked(){return this.locks>0}lock(e){let t;this.locks+=1,dg.debug("[lock-".concat(this.name,"-").concat(this.lockId,"] is locked, current queue ").concat(this.locks,". ").concat("string"==typeof e?e:""));let i=new sG(i=>{t=()=>{this.locks-=1,dg.debug("[lock-".concat(this.name,"-").concat(this.lockId,"] is not locked, current queue ").concat(this.locks,". ").concat("string"==typeof e?e:"")),i()}}),r=this.lockingPromise.then(()=>t);return this.lockingPromise=this.lockingPromise.then(()=>i),r}}function ub(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 s=arguments.length,a=Array(s),c=0;c<s;c++)a[c]=arguments[c];return await o.apply(this,a)}finally{n()}},n}}class uN extends uv{get isExternalTrack(){return this._isExternalTrack}get muted(){return this._muted}get enabled(){return this._enabled}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}constructor(e,t){super(e,t),cc(this,"_enabled",!0),cc(this,"_muted",!1),cc(this,"_isExternalTrack",!1),cc(this,"_isClosed",!1),cc(this,"_enabledMutex",void 0),cc(this,"processor",void 0),cc(this,"_processorContext",void 0),cc(this,"_handleTrackEnded",()=>{this.onTrackEnded()}),this._enabledMutex=new uO("".concat(this.getTrackId())),e.addEventListener("ended",this._handleTrackEnded)}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,dg.debug("[".concat(this.getTrackId(),"] close")),this.emit
1(J.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.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 hH(this,J.NEED_REPLACE_TRACK,this),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){dg.debug("[".concat(this.getTrackId(),"] track ended")),this.emit(Z.TRACK_ENDED)}stateCheck(e,t){if(dg.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(t,"]")),ln(t,e),this._enabled&&this._muted&&"enabled"===e&&!1===t)throw new du(o.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print();if(!this._enabled&&!this._muted&&"muted"===e&&!0===t)throw new du(o.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}function uw(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}(Et=uy||(uy={})).IOS_15_INTERRUPTION_START="ios15-interruption-start",Et.IOS_15_INTERRUPTION_END="ios15-interruption-end",Et.IOS_INTERRUPTION_START="ios-interruption-start",Et.IOS_INTERRUPTION_END="ios-interruption-end",Et.STATE_CHANGE="state-change";let uD=window.AudioContext||window.webkitAudioContext,uP=null,uL=new class extends dd{constructor(){super(...arguments),cc(this,"prevState",void 0),cc(this,"curState",void 0),cc(this,"currentTime",void 0),cc(this,"currentTimeStuckAt",void 0),cc(this,"interruptDetectorTrack",void 0),cc(this,"onLocalAudioTrackMute",()=>{dg.info("ios15-interruption-start"),this.emit(uy.IOS_15_INTERRUPTION_START)}),cc(this,"onLocalAudioTrackUnmute",async()=>{dg.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?dg.info("ios15-interruption-end-canceled"):(uP&&await uP.suspend(),this.emit(uy.IOS_15_INTERRUPTION_END))})}get duringInterruption(){return"running"===this.prevState&&"interrupted"===this.curState}bindInterruptDetectorTrack(e){dg.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){dg.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)}};function uk(){if(!uP&&(function(){if(!uD)return dg.error("your browser is not support web audio");dg.info("create audio context");let e=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?uw(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):uw(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}({},dM.WEBAUDIO_INIT_OPTIONS);dg.debug("audio context init option:",JSON.stringify(e)),uL.curState=(uP=new uD(e)).state,uP.onstatechange=()=>{uL.prevState=uL.curState,uL.curState=uP?uP.state:void 0,(aQ()||a8())&&"running"===uL.prevState&&"interrupted"===uL.curState&&(dg.info("ios-interruption-start"),uL.emit(uy.IOS_INTERRUPTION_START)),(aQ()||a8())&&"interrupted"===uL.prevState&&"running"===uL.curState&&(dg.info("ios-interruption-end"),uL.emit(uy.IOS_INTERRUPTION_END)),uL.prevState!==uL.curState&&(dg.debug("AudioContext State Change","".concat(uL.prevState,"=>").concat(uL.curState)),uL.emit(uy.STATE_CHANGE))},setInterval(()=>{var e;let t=null==(e=uP)?void 0:e.currentTime;uL.currentTime!==t?(uL.currentTimeStuckAt&&(dg.debug("AudioContext current time resume at ".concat(t)),uL.currentTimeStuckAt=void 0),uL.currentTime=t):(t!==uL.currentTimeStuckAt&&(uC.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:t},tag:_.TRACER}).onSuccess(),dg.warning("AudioContext current time stuck at ".concat(t))),uL.currentTimeStuckAt=t)},5e3),async function(e){let t=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","touchend","keydown","keyup"],i,r=!1,n=!1,o=!1;function s(t){"running"===e.state?a(!1):aQ()||a8()?"suspended"===e.state&&(a(!0),t&&e.resume().then(c,c)):"closed"!==e.state&&(a(!0),t&&e.resume().then(c,c))}function a(e){if(r!==e){r=e;for(let i=0;i<t.length;i+=1){let r=t[i];e?window.addEventListener(r,d,{capture:!0,passive:!0}):window.removeEventListener(r,d,{capture:!0,passive:!0})}}}function c(){s(!1)}function d(){s(!0)}function l(e){if(!o)if(i.paused)if(e){let e;u(!1),o=!0;try{(e=i.play())?e.then(h,h):(i.addEventListener("playing",h),i.addEventListener("abort",h),i.addEventListener("error",h))}catch(e){h()}}else u(!0);else u(!1)}function u(e){if(n!==e){n=e;for(let i=0;i<t.length;i++){let r=t[i];e?window.addEventListener(r,p,{capture:!0,passive:!0}):window.removeEventListener(r,p,{capture:!0,passive:!0})}}}function h(){i.removeEventListener("playing",h),i.removeEventListener("abort",h),i.removeEventListener("error",h),o=!1,l(!1)}function p(){l(!0)}if(aQ()){let t=e.createMediaStreamDestination(),r=document.createElement("div");r.innerHTML="<audio x-webkit-airplay='deny'></audio>",(i=r.children.item(0)).controls=!1,i.disableRemotePlayback=!0,i.preload="auto",i.srcObject=t.stream,l(!0)}uL.on(uy.STATE_CHANGE,function(){s(!0)}),s(!1)}(uP)}(),!uP))throw new du(o.NOT_SUPPORTED,"can not create audio context");return uP}function uM(e){if(function(){if(null!==uU)return uU;let e=uk(),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(),uU=n,n}())return;let t=e.connect,i=e.disconnect;e.connect=(i,r,n)=>(e._inputNodes||(e._inputNodes=[]),e._inputNodes.includes(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?hq(e._inputNodes,r):e._inputNodes=[],e._inputNodes))t.call(e,n)}}let uU=null;function ux(e,t){let i=!1,r=1/t;if(dM.DISABLE_WEBAUDIO){let t=window.setInterval(()=>{i?window.clearInterval(t):e(performance.now()/1e3)},1e3*r)}else{let t=uk(),n=t.createGain();n.gain.value=0,n.connect(t.destination);let o=()=>
1{if(i)return void(n=null);let s=t.createOscillator();s.onended=o,s.connect(n),s.start(0),s.stop(t.currentTime+r),e(t.currentTime)};o()}return()=>{i=!0}}class uV{constructor(){cc(this,"context",void 0),cc(this,"analyserNode",void 0),cc(this,"sourceNode",void 0),this.context=uk(),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4}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||aQ()||a8()||"running"!==this.context.state&&this.context.resume(),!this.analyserNode))return 0;let e=new Float32Array(this.analyserNode.fftSize);if(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(rs(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){dg.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}}class uF extends dd{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}constructor(){super(),cc(this,"outputNode",void 0),cc(this,"outputTrack",void 0),cc(this,"isPlayed",!1),cc(this,"sourceNode",void 0),cc(this,"context",void 0),cc(this,"audioBufferNode",void 0),cc(this,"destNode",void 0),cc(this,"audioOutputLevel",0),cc(this,"volumeLevelAnalyser",void 0),cc(this,"_processedNode",void 0),cc(this,"playNode",void 0),cc(this,"isDestroyed",!1),cc(this,"onNoAudioInput",void 0),cc(this,"isNoAudioInput",!1),cc(this,"_noAudioInputCount",0),this.context=uk(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),uM(this.outputNode),this.volumeLevelAnalyser=new uV}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(P.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(!lU.webAudioMediaStreamDest)throw new du(o.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&&hX(()=>{uL.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;aQ()||a8()?"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 hx(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)}}class uj extends uF{get isFreeze(){return!1}constructor(t,i,r){var n;if(super(),cc(this,"sourceNode",void 0),cc(this,"track",void 0),cc(this,"clonedTrack",void 0),cc(this,"audioElement",void 0),cc(this,"isCurrentTrackCloned",!1),cc(this,"isRemoteTrack",!1),cc(this,"originVolumeLevelAnalyser",void 0),cc(this,"rebuildWebAudio",async()=>
1{if(dg.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 dg.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then(()=>dg.info("resume success")),dg.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),uM(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();let i=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(i,this.context.currentTime),uM(this.outputNode),this.emit(P.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()}),"audio"!==t.kind)throw new du(o.UNEXPECTED_ERROR);this.track=t;let s=new MediaStream([this.track]);if(this.isRemoteTrack=!!i,this.sourceNode=this.context.createMediaStreamSource(s),uM(this.sourceNode),r){let e=r.clone();e.enabled=!0,this.clonedTrack=e,dg.debug("create an unmuted track ".concat(e.id," from the original track ").concat(r.id," to get the volume"));let t=this.context.createMediaStreamSource(new MediaStream([e]));uM(t),this.originVolumeLevelAnalyser=new uV,this.originVolumeLevelAnalyser.updateSource(t)}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=s;let a=aY();i&&a.os===e.IOS&&15>Number(null==(n=a.osVersion)?void 0:n.split(".")[0])&&(uL.on(uy.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)}))}updateTrack(e){this.sourceNode.disconnect(),this.track=e,this.isCurrentTrackCloned=!1;let t=new MediaStream([e]);this.sourceNode=this.context.createMediaStreamSource(t),uM(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(P.UPDATE_SOURCE),this.audioElement.srcObject=t}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),uL.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),dg.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]));uM(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}}async function uB(e,t){let i=(e,t)=>e?"number"!=typeof e?e.max||e.exact||e.ideal||e.min||t:e:t,r={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e,maxHeight:i(t.height,1080),maxWidth:i(t.width,1920)}}};return t.frameRate&&"number"!=typeof t.frameRate?(r.video.mandatory.maxFrameRate=t.frameRate.max,r.video.mandatory.minFrameRate=t.frameRate.min):"number"==typeof t.frameRate&&(r.video.mandatory.maxFrameRate=t.frameRate),await navigator.mediaDevices.getUserMedia(r)}async function uG(e){let t=await uW(e.mediaSource),i=await new sG((e,i)=>{let r=document.createElement("div");r.innerText="share screen",r.setAttribute("style","text-align: center; height: 25px; line-height: 25px; border-radius: 4px 4px 0 0; background: #D4D2D4; border-bottom:  solid 1px #B9B8B9;");let n=document.createElement("div");n.setAttribute("style","width: 100%; height: 500px; padding: 15px 25px ; box-sizing: border-box;");let o=document.createElement("div");o.innerText="Agora Web Screensharing wants to share the contents of your screen with webdemo.agorabeckon.com. Choose what you'd like to share.",o.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 a=document.createElement("div");a.setAttribute("style","text-align: right; padding: 16px 0;");let c=document.createElement("button");c.innerHTML="cancel",c.setAttribute("style","width: 85px;"),c.onclick=()=>{document.body.removeChild(d);let e=Error("NotAllowedError");e.name="NotAllowedError",i(e)},a.appendChild(c),n.appendChild(o),n.appendChild(s),n.appendChild(a);let d=document.createElement("div");d.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%);"),d.appendChild(r),d.appendChild(n),document.body.appendChild(d),t.map(t=>{if(t.id){let i=document.createElement("div");i.setAttribute("style","width: 30%; height: 160px; padding: 20px 0; text-align: center;box-sizing: content-box;");let r=t.thumbnail,{width:n}=r.getSize();n>1920&&(r=r.resize({width:1920})),i.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;">'+t.name.replace(/[\u00A0-\u9999<>\&]/g,function(e){return"&#"+e.charCodeAt(0)+";"})+"</span>",i.onclick=()=>{document.body.removeChild(d),e(t.id)},s.appendChild(i)}})});return await uB(i,e)}
1async function uW(e){let t=["window","screen"];"application"!==e&&"window"!==e||(t=["window"]),"screen"===e&&(t=["screen"]);let i=uK();if(!i)throw new du(o.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 sG((e,r)=>{i.desktopCapturer.getSources({types:t},(t,i)=>{t?r(t):e(i)})}));try{return await r}catch(e){throw new du(o.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}let uH=null;function uK(){if(uH)return uH;try{return uH=window.require("electron")}catch(e){return null}}function uY(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 uq=new uO("safari"),uJ=!1,uX=!1;async function uz(e,t){let i=0,r=null;for(;i<2;)try{r=await uQ(e,t,i>0);break}catch(r){if(r instanceof du)throw dg.error("[".concat(t,"] ").concat(r.toString())),r;let e=uZ(r.name||r.code||r,r.message);
1if(e.code===o.MEDIA_OPTION_INVALID){dg.debug("[".concat(t,"] detect media option invalid, retry")),i+=1,await hx(500);continue}throw dg.error("[".concat(t,"] ").concat(e.toString())),e}if(!r)throw new du(o.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return r}async function uQ(e,t,i){var r,n;if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new du(o.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 s=new MediaStream;if(e.audioSource&&s.addTrack(e.audioSource),e.videoSource&&s.addTrack(e.videoSource),!e.audio&&!e.video&&!e.screen)return dg.debug("Using Video Source/ Audio Source"),s;if(e.screen)if(uK())e.screen.sourceId?u$(s,await uB(e.screen.sourceId,e.screen)):u$(s,await uG(e.screen));else if(aJ()&&e.screen.extensionId&&e.screen.mandatory){if(!lU.getStreamFromExtension)throw new du(o.NOT_SUPPORTED,"This browser does not support screen sharing");dg.debug("[".concat(t,'] Screen access on chrome stable, looking for extension"'));let i=await (n=e.screen.extensionId,new sG((e,i)=>{try{chrome.runtime.sendMessage(n,{getStream:!0},r=>{if(!r||!r.streamId)return dg.error("[".concat(t,"] No response from Chrome Plugin. Plugin not installed properly"),r),void i(new du(o.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));e(r.streamId)})}catch(e){dg.error("[".concat(t,"] AgoraRTC screensharing plugin is not accessible(").concat(n,")"),e.toString()),i(new du(o.CHROME_PLUGIN_NOT_INSTALL))}}));e.screen.mandatory.chromeMediaSourceId=i,u$(s,await navigator.mediaDevices.getUserMedia({video:{mandatory:e.screen.mandatory}}))}else if(lU.getDisplayMedia){e.screen.mediaSource&&lP(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:o,systemAudio:a}=e.screen,c={selfBrowserSurface:n,surfaceSwitching:o,systemAudio:a};n||delete c.selfBrowserSurface,o||delete c.surfaceSwitching,a||delete c.systemAudio,dg.debug("[".concat(t,"] getDisplayMedia:"),JSON.stringify({video:i,audio:!!e.screenAudio,controls:c})),u$(s,await navigator.mediaDevices.getDisplayMedia(function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?uY(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):uY(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}({video:i,audio:!!e.screenAudio},c)))}else{if(!az())throw dg.error("[".concat(t,"] This browser does not support screenSharing")),new du(o.NOT_SUPPORTED,"This browser does not support screen sharing");{e.screen.mediaSource&&lP(e.screen.mediaSource);let i={video:{mediaSource:e.screen.mediaSource,width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate}};dg.debug("[".concat(t,"] getUserMedia: ").concat(JSON.stringify(i))),u$(s,await navigator.mediaDevices.getUserMedia(i))}}if(!e.video&&!e.audio)return s;let a={video:e.video,audio:e.audio},c=dM.MEDIA_DEVICE_CONSTRAINTS;if(c)try{"string"==typeof c&&(c=JSON.parse(c)),a=function e(t,i){if(!h4(t)||!h4(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=hM({},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,c)}catch(e){}dg.debug("[".concat(t,"] GetUserMedia"),JSON.stringify(a)),aY();let d,l=null;(aX()||aQ()||aq())&&(l=await uq.lock());try{d=await navigator.mediaDevices.getUserMedia(a)}catch(e){throw l&&l(),e}return a.audio&&(uJ=!0),a.video&&(uX=!0),u$(s,d),l&&l(),s}function uZ(e,t){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new du(o.MEDIA_OPTION_INVA
1LID,"".concat(e,": ").concat(t));case"NotFoundError":case"DevicesNotFoundError":return new du(o.DEVICE_NOT_FOUND,"".concat(e,": ").concat(t));case"NotSupportedError":return new du(o.NOT_SUPPORTED,"".concat(e,": ").concat(t));case"NotReadableError":return new du(o.NOT_READABLE,"".concat(e,": ").concat(t));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new du(o.PERMISSION_DENIED,"".concat(e,": ").concat(t));case"ConstraintNotSatisfiedError":return new du(o.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(t));default:return dg.error("getUserMedia unexpected error",e),new du(o.UNEXPECTED_ERROR,"".concat(e,": ").concat(t))}}function u$(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 u0=new class extends dd{get state(){return this._state}set state(e){e!==this._state&&(this.emit(m.STATE_CHANGE,e),this._state=e)}constructor(){super(),cc(this,"_state",E.IDLE),cc(this,"isAccessMicrophonePermission",!1),cc(this,"isAccessCameraPermission",!1),cc(this,"lastAccessMicrophonePermission",!1),cc(this,"lastAccessCameraPermission",!1),cc(this,"checkdeviceMatched",!1),cc(this,"deviceInfoMap",new Map),this.init().then(()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval(()=>{(dM.ENUMERATE_DEVICES_INTERVAL||ct()&&ce())&&this.updateDevicesInfo()},dM.ENUMERATE_DEVICES_INTERVAL_TIME)}).catch(e=>dg.error(e.toString()))}async enumerateDevices(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)return new du(o.NOT_SUPPORTED,"enumerateDevices() not supported.").throw();let r=await navigator.mediaDevices.enumerateDevices(),n=this.checkMediaDeviceInfoIsOk(r),s=!this.isAccessMicrophonePermission&&e,a=!this.isAccessCameraPermission&&t;n.audio&&(s=!1),n.video&&(a=!1);let c=null,d=null,l=null;if(!i&&(s||a)){if(uq.isLocked&&(dg.debug("[device manager] wait GUM lock"),(await uq.lock())(),dg.debug("[device manager] GUM unlock")),uJ&&(s=!1,this.isAccessMicrophonePermission=!0),uX&&(a=!1,this.isAccessCameraPermission=!0),dg.debug("[device manager] check media device permissions",e,t,s,a),s&&a){try{l=await navigator.mediaDevices.getUserMedia({audio:!0,video:!0})}catch(t){let e=uZ(t.name||t.code||t,t.message);if(e.code===o.PERMISSION_DENIED)throw e;dg.warning("getUserMedia failed in getDevices",e)}this.isAccessCameraPermission=!0,this.isAccessMicrophonePermission=!0}else if(s){try{c=await navigator.mediaDevices.getUserMedia({audio:e})}catch(t){let e=uZ(t.name||t.code||t,t.message);if(e.code===o.PERMISSION_DENIED)throw e;dg.warning("getUserMedia failed in getDevices",e)}this.isAccessMicrophonePermission=!0}else if(a){try{d=await navigator.mediaDevices.getUserMedia({video:t})}catch(t){let e=uZ(t.name||t.code||t,t.message);if(e.code===o.PERMISSION_DENIED)throw e;dg.warning("getUserMedia failed in getDevices",e)}this.isAccessCameraPermission=!0}dg.debug("[device manager] mic permission",e,"cam permission",t)}try{let e=await navigator.mediaDevices.enumerateDevices();return c&&c.getTracks().forEach(e=>e.stop()),d&&d.getTracks().forEach(e=>e.stop()),l&&l.getTracks().forEach(e=>e.stop()),c=null,d=null,l=null,e}catch(e){return c&&c.getTracks().forEach(e=>e.stop()),d&&d.getTracks().forEach(e=>e.stop()),l&&l.getTracks().forEach(e=>e.stop()),c=null,d=null,l=null,new du(o.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)}
1searchDeviceIdByName(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 du(o.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return t}async init(){this.state=E.INITING;try{await this.updateDevicesInfo(),this.state=E.INITEND}catch(e){throw dg.warning("Device Detection functionality cannot start properly.",e.toString()),this.state=E.IDLE,("boolean"==typeof isSecureContext?isSecureContext:"https:"===location.protocol||"file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname||"::1"===location.hostname)||new du(o.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.").throw(),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?dg.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is the same group")):dg.warning("[device-check] default input ".concat(t.label," and output ").concat(i.label," is not the same group")):dg.debug("[device-check] default input or output not found")}let r=this.checkMediaDeviceInfoIsOk(e);if(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!==E.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(m.RECORDING_DEVICE_CHANGED,e);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(m.CAMERA_DEVICE_CHANGED,e);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(m.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}},u1=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],u2=new class{constructor(){cc(this,"onAutoplayFailed",void 0),cc(this,"elementMap",new Map),cc(this,"elementStateMap",new Map),cc(this,"elementsNeedToResume",[]),cc(this,"sinkIdMap",new Map),cc(this,"autoResumeAfterInterruption",()=>{Array.from(this.elementMap.entries()).forEach(e=>{let[t,i]=e,r=this.elementStateMap.get(t),n=i.srcObject.getAudioTracks()[0];a3()?n&&"live"===n.readyState&&"running"===uL.curState&&(dg.debug("auto resume after interruption for iOS 15"),i.pause(),i.play()):r&&"paused"===r&&n&&"live"===n.readyState&&"running"===uL.curState&&(dg.debug("auto resume after interruption for iOS"),i.play())})}),cc(this,"autoResumeAfterInterruptionOnIOS15",()=>{Array.from(this.elementMap.entries()).forEach(e=>{let[t,i]=e,r=i.srcObject.getAudioTracks()[0];r&&"live"===r.readyState&&(dg.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),i.pause(),i.play())})}),this.autoResumeAudioElement(),uL.on(uy.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),uL.on(uy.IOS_15_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15),uL.on(uy.STATE_CHANGE,()=>{aQ()&&"suspended"===uL.prevState&&"running"===uL.curState&&this.autoResumeAfterInterruption()})}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 du(o.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,c.INIT),this.setVolume(t,i);let o=this.sinkIdMap.get(t);if(o)try{n.setSinkId(o).catch(e=>{dg.warning("[".concat(t,"] set sink id failed"),e.toString())})}catch(e){dg.warning("[".concat(t,"] set sink id failed"),e.toString())}let s=n.play();s&&s.then&&s.catch(e=>{r&&uC.autoplayFailed(r,"audio",e.message,t),dg.warning("audio element play warning",e.toString()),this.elementMap.has(t)&&"NotAllowedError"===e.name&&(dg.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(n),hX(()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),um()}))})}updateTrack(e,t){let i=this.elementMap.get(e);i&&(i.srcObject=new MediaStream([t]))}isPlaying(e){return this.elementMap.has(e)}setVolume(e,t){let i=this.elementMap.get(e);i&&(i.volume=(t=Math.max(0,Math.min(100,t)))/100)}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){u1.forEach(i=>{t.addEventListener(i,i=>{let r=this.elementStateMap.get(e),n="pause"===i.type?"paused":i.type;if(dg.debug("[".concat(e,"] audio-element-status change ").concat(r," => ").concat(n)),"error"===i.type){let i=null==t?void 0:t.error;i&&dg.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=>{dg.debug("Auto resume audio element success")}).catch(e=>{dg.warning("Auto resume audio element failed!",e)})}),this.elementsNeedToResume=[]};new sG(e=>{document.body?e():window.addEventListener("load",()=>e())}).then(()=>{ci()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0))})}};function u3(){return function(e,t,i){let r=i.value;return"function"==typeof r&&(i.value=function(){this._isClosed&&new du(o.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning");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 sG?new sG((e,t)=>{n.then(e).catch(t)}):n}),i}}var u4=rr("Array").values,u5=Array.prototype,u6={DOMTokenList:!0,NodeList:!0},u8=function(e){var t=e.values;return e===u5||tv(u5,e)&&t===u5.values||iE(u6,nt(e))?u4:t};function u7(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 u9(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?u7(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):u7(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}class he extends dd{constructor(e){super(),cc(this,"name","VideoProcessorDestination"),cc(this,"ID","0"),cc(this,"_source",void 0),cc(this,"videoContext",void 0),cc(this,"inputTrack",void 0),this.videoContext=e}get kind(){return"video"}get enabled(){return!0}pipe(){throw new du(o.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor")}unpipe(){throw new du(o.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(el.ON_TRACK,e.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit
1(el.ON_TRACK,void 0)}}class ht extends dd{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t){super(),cc(this,"constraintsMap",new Map),cc(this,"statsRegistry",[]),cc(this,"usageRegistry",[]),cc(this,"trackId",void 0),cc(this,"direction",void 0),cc(this,"_chained",!1),this.trackId=e,this.direction=t}async getConstraints(){return await hW(this,eu.REQUEST_CONSTRAINTS)}async requestApplyConstraints(e,t){var i;return dg.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),hH(this,eu.REQUEST_UPDATE_CONSTRAINTS,Array.from(u8(i=this.constraintsMap).call(i)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return dg.info("processor ".concat(e.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(e),hH(this,eu.REQUEST_UPDATE_CONSTRAINTS,Array.from(u8(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){dg.error(new du(o.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 sG&&(i=await i),e.push(u9(u9({},i),{},{direction:this.direction}))}catch(e){dg.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class hi extends dd{constructor(e){super(),cc(this,"name","AudioProcessorDestination"),cc(this,"ID","0"),cc(this,"inputTrack",void 0),cc(this,"inputNode",void 0),cc(this,"audioProcessorContext",void 0),cc(this,"_source",void 0),this.audioProcessorContext=e}get kind(){return"audio"}get enabled(){return!0}pipe(){throw new du(o.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new du(o.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(el.ON_TRACK,void 0),this.emit(el.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(el.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(el.ON_NODE,this.inputNode))}}class hr extends dd{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t,i){super(),cc(this,"constraintsMap",new Map),cc(this,"statsRegistry",[]),cc(this,"audioContext",void 0),cc(this,"trackId",void 0),cc(this,"direction",void 0),cc(this,"usageRegistry",[]),cc(this,"_chained",!1),this.audioContext=e,this.trackId=t,this.direction=i}async getConstraints(){return hW(this,eu.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(e,t){var i;return dg.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),hH(this,eu.REQUEST_UPDATE_CONSTRAINTS,Array.from(u8(i=this.constraintsMap).call(i)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),hH(this,eu.REQUEST_UPDATE_CONSTRAINTS,Array.from(u8(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){dg.error(new du(o.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 sG&&(i=await i),e.push(u9(u9({},i),{},{direction:this.direction}))}catch(e){dg.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class hn extends dd{get isPlayed(){return!0}get isFreeze(){return!1}constructor(){super(),cc(this,"context",void 0),cc(this,"processSourceNode",void 0),cc(this,"outputTrack",void 0),cc(this,"processedNode",void 0),cc(this,"clonedTrack",void 0),cc(this,"outputNode",void 0),this.outputNode=new ho}setVolume(){}createOutputTrack(){throw new du(o.NOT_SUPPORTED,"can not create output MediaStreamTrack when WebAudio disabled")}getOriginVolumeLevel(){return 0}getAccurateVolumeLevel(){return 0}stopGetAudioBuffer(){}startGetAudioBuffer(){}play(){}stop(){}destroy(){}updateTrack(){}updateOriginTrack(){}createMediaStreamSourceNode(){}}class ho{disconnect(){}connect(){}}let hs,ha=null;class hc{constructor(){cc(this,"state","open"),cc(this,"trigger",void 0),cc(this,"tasks",[]),dg.debug("[macro-task-queue] is created."),this.trigger=setTimeout(()=>{this.state="closed",dg.debug("[macro-task-queue] will be closed, all remaining tasks will execute. [".concat(this.tasks.map(e=>e.key),"]")),this.trigger=void 0,this.tasks.forEach(e=>{let{func:t}=e;return t()}),this.tasks.length=0,dg.debug("[macro-task-queue] is closed.")})}enqueue(e,t){"closed"!==this.state&&(this.tasks.push({key:e,func:t}),dg.debug("[macro-task-queue] is queued, current queue ".concat(this.tasks.length,". ").concat("string"==typeof e?e:"")))}runTask(e){if("closed"===this.state)return;let t=this.tasks.findIndex(t=>t.key===e);if(-1!==t){let i=this.tasks.splice(t,1);dg.debug("[macro-task-queue] is unqueued, current queue ".concat(this.tasks.length,". ").concat("string"==typeof e?e:"")),i[0].func()}}release(){this.trigger&&(this.state="closed",clearTimeout(this.trigger),this.trigger=void 0,this.tasks.length=0,dg.debug("[macro-task-queue] is closed."))}}function hd(e){return function(t,i,r){var n;let o=null!=(n=r.value)?n:r.get,s=function(){ha&&"open"===ha.state&&ha.runTask(e);for(var t=arguments.length,i=Array(t),r=0;r<t;r++)i[r]=arguments[r];return null==o?void 0:o.apply(this,...i)};return r.value?r.value=s:r.get=s,r}}function hl(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 hu(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?hl(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):hl(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}(hs||(hs={})).UPDATE_TRACK_SOURCE="update-track-source";let hh=(Eo=hd("INIT_WEBAUDIO"),Es=hd("INIT_WEBAUDIO"),Ea=hd("INIT_WEBAUDIO"),Ec=uI({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),Ed=uI({argsMap:(e,t)=>[e.getTrackId(),t]}),El=u3(),Eu=ub("LocalAudioTrack","_enabledMutex"),Eh=uI({argsMap:(e,t)=>[e.getTrackId(),t]}),Ep=u3(),E_=ub("LocalAudioTrack","_enabledMutex"),EE=uI({argsMap:(e,t)=>[e.getTrackId(),t]}),Em=u3(),Ef=u3(),ES=u3(),ET=uI({argsMap:e=>[e.getTrackId()]}),Eg=u3(),ER=uI({argsMap:e=>[e.getTrackId()]}),EI=u3(),EC=uI({argsMap:e=>[e.getTrackId()]}),Ev=uI({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Ey=uI({argsMap:e=>[e.getTrackId()]}),ui((EA=class extends uN{get _source(){return this._trackSource}set _source(e){this._trackSource=e}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}get processorDestination(){return this._processorDestination}set processorDestination(e){this._processorDestination=e}get isPlaying(){return this._useAudioElement?u2.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"LocalAudioTrack"}constructor(e,t,i,r,n){super(e,i),cc(this,"trackMediaType","audio"),cc(this,"_encoderConfig",void 0),cc(this,"_trackSource",void 0),cc(this,"_enabled",!0),cc(this,"_volume",100),cc(this,"_useAudioElement",!1),cc(this,"_bypassWebAudio",!1),cc(this,"processor",void 0),cc(this,"_processorContext",void 0),cc(this,"_processorDestination",void 0),cc(this,"_getOriginVolumeLevel",void 0),this._encoderConfig=t,this._getOriginVolumeLevel=!!r;let o=()=>{this.processorContext=new hr(this._source.context,this.getTrackId(),"local"),this.processorDestination=new hi(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(P.UPDATE_SOURCE,()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})})}
1,s=n&&aX()&&!uP;dM.DISABLE_WEBAUDIO?(this._source=new hn,this._useAudioElement=!0,this._bypassWebAudio=!0):s?this._source=new hn:(this._source=new uj(e,!1,this._getOriginVolumeLevel?e:void 0),dM.LOCAL_AUDIO_TRACK_USES_WEB_AUDIO||(this._useAudioElement=!0)),o(),!dM.DISABLE_WEBAUDIO&&s&&(ha||(ha=new hc),ha).enqueue("INIT_WEBAUDIO",()=>{this._source=new uj(e,!1,this._getOriginVolumeLevel?e:void 0),dM.LOCAL_AUDIO_TRACK_USES_WEB_AUDIO||(this._useAudioElement=!0),o(),this.emit(hs.UPDATE_TRACK_SOURCE)})}setVolume(e){ls(e,"volume",0,1e3),this._volume=e,this._source.setVolume(e/100),this._useAudioElement&&u2.setVolume(this.getTrackId(),e);try{if(this._bypassWebAudio)return void dg.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));let e=this._source.createOutputTrack();this._mediaStreamTrack!==e&&(this._mediaStreamTrack=e,hH(this,J.NEED_REPLACE_TRACK,this).then(()=>{dg.debug("[".concat(this.getTrackId(),"] replace web audio track success"))}).catch(e=>{dg.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)throw new du(o.NOT_SUPPORTED,"your browser does not support setting the audio output device");await u2.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(dg.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){this._originMediaStreamTrack.enabled=!0;try{i||(this._enabled=!0),await hH(this,J.NEED_ENABLE_TRACK,this),dg.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(e," success"))}catch(e){throw i||(this._enabled=!1),dg.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}}else{this._originMediaStreamTrack.enabled=!1,i||(this._enabled=!1);try{await hH(this,J.NEED_DISABLE_TRACK,this)}catch(e){throw i||(this._enabled=!0),dg.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}}}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,dg.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await hH(this,J.NEED_MUTE_TRACK,this):await hH(this,J.NEED_UNMUTE_TRACK,this))}getStats(){return hZ(()=>{dg.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")},"localAudioTrackGetStatsWarning"),hK(this,J.GET_STATS)||hu({},lR)}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(P.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(P.ON_AUDIO_BUFFER),this._source.on(P.ON_AUDIO_BUFFER,t=>e(t))}play(){dg.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(dg.debug("[".concat(this.getTrackId(),"] start audio playback in element")),u2.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){dg.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?u2.stop(this.getTrackId()):this._source.stop()}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe(),this._source.destroy()}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];dg.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&u2.updateTrack(this.getTrackId(),this._mediaStreamTrack)}async _updateOriginMediaStreamTrack(e,t){this._originMediaStreamTrack!==e&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),e.addEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop(),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this.processor&&this.processor.updateInput({track:e,context:this.processorContext}),this._mediaStreamTrack!==this._source.outputTrack?(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await hH(this,J.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(e))}renewMediaStreamTrack(e){return sG.resolve(void 0)}pipe(e){if(this._bypassWebAudio)throw new du(o.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===e)return e;if(e._source)throw new du(o.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(){this.processorDestination.on(el.ON_TRACK,async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e),await hH(this,J.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await hH(this,J.NEED_REPLACE_TRACK,this))}),this.processorDestination.on(el.ON_NODE,e=>{this._source.processedNode=e})}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(el.ON_TRACK),this.processorDestination.removeAllListeners(el.ON_NODE)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(eu.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(eu.REQUEST_CONSTRAINTS)}}).prototype,"_source",[Eo],Object.getOwnPropertyDescriptor(EA.prototype,"_source"),EA.prototype),ui(EA.prototype,"processorContext",[Es],Object.getOwnPropertyDescriptor(EA.prototype,"processorContext"),EA.prototype),ui(EA.prototype,"processorDestination",[Ea],Object.getOwnPropertyDescriptor(EA.prototype,"processorDestination"),EA.prototype),ui(EA.prototype,"setVolume",[Ec],Object.getOwnPropertyDescriptor(EA.prototype,"setVolume"),EA.prototype),ui(EA.prototype,"setPlaybackDevice",[Ed,El],Object.getOwnPropertyDescriptor(EA.prototype,"setPlaybackDevice"),EA.prototype),ui(EA.prototype,"setEnabled",[Eu,Eh,Ep],Object.getOwnPropertyDescriptor(EA.prototype,"setEnabled"),EA.prototype),ui(EA.prototype,"setMuted",[E_,EE,Em],Object.getOwnPropertyDescriptor(EA.prototype,"setMuted"),EA.prototype),ui(EA.prototype,"getStats",[Ef],Object.getOwnPropertyDescriptor(EA.prototype,"getStats"),EA.prototype),ui(EA.prototype,"setAudioFrameCallback",[ES],Object.getOwnPropertyDescriptor(EA.prototype,"setAudioFrameCallback"),EA.prototype),ui(EA.prototype,"play",[ET,Eg],Object.getOwnPropertyDescriptor(EA.prototype,"play"),EA.prototype),ui(EA.prototype,"stop",[ER,EI],Object.getOwnPropertyDescriptor(EA.prototype,"stop"),EA.prototype),ui(EA.prototype,"close",[EC],Object.getOwnPropertyDescriptor(EA.prototype,"close"),EA.prototype),ui(EA.prototype,"pipe",[Ev],Object.getOwnPropertyDescriptor(EA.prototype,"pipe"),EA.prototype),ui(EA.prototype,"unpipe",[Ey],Object.getOwnPropertyDescriptor(EA.prototype,"unpipe"),EA.prototype),EA),hp=(EO=uI({argsMap:(e,t)=>[e.getTrackId(),t]}),Eb=u3(),EN=ub("MicrophoneAudioTrack","_enabledMutex"),Ew=uI({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),ED=u3(),EP=uI({argsMap:e=>[e.getTrackId()]}),ui((EL=class extends hh{get __className__(){return"MicrophoneAudioTrack"}constructor(e,t,i,r){super(e,t.encoderConfig?dL(t.encoderConfig):{},r,dM.GET_VOLUME_OF_MUTED_AUDIO_TRACK,!0),cc(this,"_config",void 0),cc(this,"_deviceName","default"),cc(this,"_constraints",void 0),cc(this,"_originalConstraints",void 0),cc(this,"_enabled",!0),this._config=t,this._constraints=i,this._originalConstraints=i,this._deviceName=e.label,"boolean"==typeof t.bypassWebAudio&&(this._bypassWebAudio=t.bypassWebAudio),a3()&&uL.bindInterruptDetectorTrack(this),this.on(hs.UPDATE_TRACK_SOURCE,()=>{this.bindProcessorContextEvents()}),uP&&this.bindProcessorContextEvents()}async setDevice(e){if(dg.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{let t=await u0.getDeviceById(e),i={};i.audio=hu({},this._constraints),i.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let r=null;try{r=await uz(i,this.getTrackId())}catch(e){throw dg.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),r=await uz({video: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 dg.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{let t=await u0.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw dg.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}dg.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"))}async setEnabled(e,t,i){if(t)return dg.debug("[".concat(this.getTrackId(),"] setEnabled false (
1do not close microphone)")),await super._setEnabled(e);if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(dg.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){var r;this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop(),null==(r=this._source.clonedTrack)||r.stop(),i||(this._enabled=!1);try{await hH(this,J.NEED_DISABLE_TRACK,this)}catch(e){throw dg.error("[".concat(this.getTrackId(),"] setEnabled false failed"),e.toString()),e}return}let n=hu({},this._constraints),o=u0.searchDeviceIdByName(this._deviceName);o&&!n.deviceId&&(n.deviceId=o);try{i||(this._enabled=!0);let e=await uz({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1),await hH(this,J.NEED_ENABLE_TRACK,this)}catch(e){throw i||(this._enabled=!1),dg.error("[".concat(this.getTrackId(),"] setEnabled true failed"),e.toString()),e}dg.info("[".concat(this.getTrackId(),"] setEnabled success"))}close(){super.close(),a3()&&uL.unbindInterruptDetectorTrack(this)}onTrackEnded(){if((aQ()||a8())&&this._enabled&&!this._isClosed&&uL.duringInterruption){let e=async()=>{uL.off(uy.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(dg.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};uL.on(uy.IOS_INTERRUPTION_END,e)}else dg.debug("[".concat(this.getTrackId(),"] track ended")),this.emit(Z.TRACK_ENDED)}async renewMediaStreamTrack(e){let t=e||this._constraints,i=u0.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId=i),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();let e=await uz({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0)}}bindProcessorContextEvents(){this.processorContext.on(eu.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(eu.REQUEST_CONSTRAINTS,async e=>{e(this._originMediaStreamTrack.getSettings())})}}).prototype,"setDevice",[EO,Eb],Object.getOwnPropertyDescriptor(EL.prototype,"setDevice"),EL.prototype),ui(EL.prototype,"setEnabled",[EN,Ew,ED],Object.getOwnPropertyDescriptor(EL.prototype,"setEnabled"),EL.prototype),ui(EL.prototype,"close",[EP],Object.getOwnPropertyDescriptor(EL.prototype,"close"),EL.prototype),EL),h_=(Ek=uI({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),EM=u3(),EU=uI({argsMap:e=>[e.getTrackId()]}),Ex=u3(),EV=uI({argsMap:e=>[e.getTrackId()]}),EF=u3(),Ej=uI({argsMap:e=>[e.getTrackId()]}),EB=u3(),EG=uI({argsMap:e=>[e.getTrackId()]}),EW=u3(),ui((EH=class extends hh{get __className__(){return"BufferSourceAudioTrack"}constructor(e,t,i,r){super(t.createOutputTrack(),i,r),cc(this,"source",void 0),cc(this,"_bufferSource",void 0),this.source=e,this._bufferSource=t,this._bufferSource.on(P.AUDIO_SOURCE_STATE_CHANGE,e=>{this.emit(Z.SOURCE_STATE_CHANGE,e)});try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}}get currentState(){return this._bufferSource.currentState}get duration(){return this._bufferSource.duration}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()}}).prototype,"startProcessAudioBuffer",[Ek,EM],Object.getOwnPropertyDescriptor(EH.prototype,"startProcessAudioBuffer"),EH.prototype),ui(EH.prototype,"pauseProcessAudioBuffer",[EU,Ex],Object.getOwnPropertyDescriptor(EH.prototype,"pauseProcessAudioBuffer"),EH.prototype),ui(EH.prototype,"seekAudioBuffer",[EV,EF],Object.getOwnPropertyDescriptor(EH.prototype,"seekAudioBuffer"),EH.prototype),ui(EH.prototype,"resumeProcessAudioBuffer",[Ej,EB],Object.getOwnPropertyDescriptor(EH.prototype,"resumeProcessAudioBuffer"),EH.prototype),ui(EH.prototype,"stopProcessAudioBuffer",[EG,EW],Object.getOwnPropertyDescriptor(EH.prototype,"stopProcessAudioBuffer"),EH.prototype),EH);class hE extends hh{get __className__(){return"MixingAudioTrack"}get isActive(){for(let e of this.trackList)if(e._enabled&&!e._isClosed&&!e.muted)return!0;return!1}constructor(){let e=uk().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,hV(8,"track-mix-")),cc(this,"trackList",void 0),cc(this,"destNode",void 0);try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}this.destNode=e,this.trackList=[]}hasAudioTrack(e){return -1!==this.trackList.indexOf(e)}addAudioTrack(e){-1===this.trackList.indexOf(e)?(dg.debug("add ".concat(e.getTrackId()," to mixing track")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):dg.debug("track ".concat(e.getTrackId()," is already added"))}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){dg.debug("remove ".concat(e.getTrackId()," from mixing track"));try{e._source.outputNode.disconnect(this.destNode)}catch(e){}hq(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}}class hm extends dd{constructor(){super(...arguments),cc(this,"resultStorage",new Map)}setLocalAudioStats(e,t,i){this.record("AUDIO_INPUT_LEVEL_TOO_LOW",e,this.checkAudioInput
1Level(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))}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){this.resultStorage.has(e)||this.resultStorage.set(e,{result:[],isPrevNormal:!0});let r=this.resultStorage.get(e);if(r&&(r.result.push(i),r.result.length>=5)){let i=r.result.includes(!0);r.isPrevNormal&&!i&&this.emit("exception",hf[e],e,t),!r.isPrevNormal&&i&&this.emit("exception",hf[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 hE&&!t.isActive||!!t.muted||0!==e.sendVolumeLevel}checkFramerateInput(e,t){let i=null;t._encoderConfig&&t._encoderConfig.frameRate&&(i=hO(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)}checkSendVideoBitrate(e,t){return!!t.muted||0!==e.sendBitrate}checkSendAudioBitrate(e,t){return t instanceof hE&&!t.isActive||!!t.muted||0!==e.sendBitrate}checkVideoDecode(e){return 0===e.receiveBitrate||0!==e.decodeFrameRate}}let hf={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},hS=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 hT(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 hg(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?hT(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):hT(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}class hR{constructor(e){cc(this,"store",void 0),cc(this,"onStatsException",void 0),cc(this,"onUploadPublishDuration",void 0),cc(this,"localStats",new Map),cc(this,"remoteStats",new Map),cc(this,"updateStatsInterval",void 0),cc(this,"trafficStats",void 0),cc(this,"trafficStatsPeerList",[]),cc(this,"uplinkStats",void 0),cc(this,"exceptionMonitor",void 0),cc(this,"p2pChannel",void 0),cc(this,"updateStats",()=>{this.p2pChannel&&(this.updateRemoteStats(this.p2pChannel),this.updateLocalStats(this.p2pChannel))}),this.store=e,this.updateStatsInterval=window.setInterval(this.updateStats,1e3),this.exceptionMonitor=new hm,this.exceptionMonitor.on("exception",(e,t,i)=>{this.onStatsException&&this.onStatsException(e,t,i)})}reset(){this.localStats=new Map,this.remoteStats=new Map,this.trafficStats=void 0,this.trafficStatsPeerList=[],this.uplinkStats=void 0}getLocalAudioTrackStats(){return this.localStats.get(eo.LocalAudioTrack)||hg({},lR)}getLocalVideoTrackStats(){return this.localStats.get(eo.LocalVideoTrack)||hg({},lI)}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))}
1else 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}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(eo.LocalAudioTrack);n&&(e+=n.sendBytes,t+=n.sendBitrate);let o=this.localStats.get(eo.LocalVideoTrack);o&&(e+=o.sendBytes,t+=o.sendBitrate);let s=this.localStats.get(eo.LocalVideoLowTrack);s&&(e+=s.sendBytes,t+=s.sendBitrate),this.remoteStats.forEac
1h(e=>{let{audioStats:t,videoStats:n}=e;t&&(i+=t.receiveBytes,r+=t.receiveBitrate),n&&(i+=n.receiveBytes,r+=n.receiveBitrate)});let a=1;return this.trafficStats&&(a+=this.trafficStats.peer_delay.length),{Duration:0,UserCount:a,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?hS.measureFromSubscribeStart(this.store.clientId,i.videoSSRC):0,n=null!=i&&i.audioSSRC?hS.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&&dg.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 eo.LocalVideoTrack:case eo.LocalVideoLowTrack:{let t=hg({},lI),n=e.getStats(),o=e.getLocalMedia(i);if(n){let i=n.videoSend.find(e=>e.ssrc===(null==o?void 0:o.ssrcs[0].ssrcId));if(i){let n=e.getLocalVideoSize(),o=e.getEncoderConfig(eo.LocalVideoTrack);"H264"!==i.codec&&"VP8"!==i.codec&&"VP9"!==i.codec&&"AV1X"!==i.codec&&"AV1"!==i.codec||(t.codecType=i.codec),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):n&&(t.captureResolutionWidth=n.width,t.captureResolutionHeight=n.height),i.sentFrame?(t.sendFrameRate=i.sentFrame.frameRate,t.sendResolutionHeight=i.sentFrame.height,t.sendResolutionWidth=i.sentFrame.width):n&&(t.sendResolutionWidth=n.width,t.sendResolutionHeight=n.height),i.avgEncodeMs&&(t.encodeDelay=i.avgEncodeMs),o&&o.bitrateMax&&(t.targetSendBitrate=1e3*o.bitrateMax),t.sendPackets=i.packets,t.sendPacketsLost=i.packetsLost,t.totalDuration=r?r.totalDuration+1:1,t.totalFreezeTime=r?r.totalFreezeTime:0,this.isLocalVideoFreeze(i)&&(t.totalFreezeTime+=1)}this.trafficStats&&(t.sendPacketsLost=this.trafficStats.B_pvlr4/100)}this.localStats.set(i,t),t&&o&&this.exceptionMonitor.setLocalVideoStats(this.store.uid,o.track,t);break}case eo.LocalAudioTrack:{let t=hg({},lR),n=e.getStats(),o=e.getLocalMedia(i);if(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.sendBitrate=r?8*Math.max(0,t.sendBytes-r.sendBytes):0}}this.trafficStats&&(t.sendPacketsLost=this.trafficStats.B_pvlr4/100),this.localStats.set(eo.LocalAudioTrack,t),t&&o&&this.exceptionMonitor.setLocalAudioStats(this.store.uid,o.track,t)}}})}updateRemoteStats(e){Array.from(this.remoteStats.entries()).forEach(t=>{let[i,{videoStats:r,audioStats:n,videoPcStats:o}]=t,s=hg({},lC),a=hg({},ly),c=hg({},lv),{audioTrack:d,videoTrack:l,audioSSRC:u,videoSSRC:h}=e.getRemoteMedia(i),p=e.getStats(),_=null==p?void 0:p.audioRecv.find(e=>e.ssrc===u),E=null==p?void 0:p.videoRecv.find(e=>e.ssrc===h),m=this.trafficStats&&this.trafficStats.peer_delay.find(e=>e.peer_uid===i);if(_&&("opus"!==_.codec&&"aac"!==_.codec&&"PCMU"!==_.codec&&"PCMA"!==_.codec&&"G722"!==_.codec||(s.codecType=_.codec),_.outputLevel?s.receiveLevel=Math.round(32767*_.outputLevel):d&&(s.receiveLevel=Math.round(32767*d.getVolumeLevel())),s.receiveBytes=_.bytes,s.receivePackets=_.packets,s.receivePacketsLost=_.packetsLost,s.packetLossRate=s.receivePacketsLost/(s.receivePackets+s.receivePacketsLost),s.receiveBitrate=n?8*Math.max(0,s.receiveBytes-n.receiveBytes):0,s.totalDuration=n?n.totalDuration+1:1,s.totalFreezeTime=n?n.totalFreezeTime:0,s.freezeRate=s.totalFreezeTime/s.totalDuration,s.receiveDelay=_.jitterBufferMs,s.totalDuration>
110&&hR.isRemoteAudioFreeze(d)&&(s.totalFreezeTime+=1)),E){"H264"!==E.codec&&"VP8"!==E.codec&&"VP9"!==E.codec&&"AV1X"!==E.codec&&"AV1"!==E.codec||(a.codecType=E.codec),a.receiveBytes=E.bytes,a.receiveBitrate=r?8*Math.max(0,a.receiveBytes-r.receiveBytes):0,a.decodeFrameRate=E.decodeFrameRate<0?0:E.decodeFrameRate,a.renderFrameRate=E.decodeFrameRate<0?0:E.decodeFrameRate,E.outputFrame&&(a.renderFrameRate=E.outputFrame.frameRate),E.receivedFrame?(a.receiveFrameRate=E.receivedFrame.frameRate,a.receiveResolutionHeight=E.receivedFrame.height,a.receiveResolutionWidth=E.receivedFrame.width):l&&(a.receiveResolutionHeight=l._videoHeight||0,a.receiveResolutionWidth=l._videoWidth||0),void 0!==E.framesRateFirefox&&(a.receiveFrameRate=Math.round(E.framesRateFirefox)),a.receivePackets=E.packets,a.receivePacketsLost=E.packetsLost,a.packetLossRate=a.receivePacketsLost/(a.receivePackets+a.receivePacketsLost),a.totalDuration=r?r.totalDuration+1:1,a.totalFreezeTime=r?r.totalFreezeTime:0,a.receiveDelay=E.jitterBufferMs||0;let t=!!h&&e.getRemoteVideoIsReady(h);l&&t&&hR.isRemoteVideoFreeze(l,E,o)&&(a.totalFreezeTime+=1),a.freezeRate=a.totalFreezeTime/a.totalDuration}m&&(s.end2EndDelay=m.B_ad,a.end2EndDelay=m.B_vd,s.transportDelay=m.B_ed,a.transportDelay=m.B_ed,s.currentPacketLossRate=m.B_ealr4/100,a.currentPacketLossRate=m.B_evlr4/100,c.uplinkNetworkQuality=m.B_punq?m.B_punq:0,c.downlinkNetworkQuality=m.B_pdnq?m.B_pdnq:0),this.remoteStats.set(i,{audioStats:s,videoStats:a,videoPcStats:E,networkStats:c}),d&&this.exceptionMonitor.setRemoteAudioStats(d,s),l&&this.exceptionMonitor.setRemoteVideoStats(l,a)})}}let hI=new class extends dd{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}constructor(){super(),cc(this,"_lastHiddenTime",0),cc(this,"_lastVisibleTime",0),document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),dg.debug("document visibility went ".concat(document.visibilityState)),this.emit("VISIBILITY_CHANGE",document.visibilityState)})}};function hC(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 hv(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?hC(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):hC(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}function hy(e){return e.match(/^[\.\:\d]+$/)?"".concat(e.replace(/[^\d]/g,"-"),".").concat(dM.TURN_DOMAIN):(dg.info("Cannot recognized as IP address ".concat(e,". Used As Host instead")),e)}function hA(e,t){var i,r,n;let o=dM.GATEWAY_DOMAINS,s=o[1]&&-1!==t.indexOf(o[1])?1:0;e.addresses=e.addresses||[];let a=e.addresses.map(e=>e.domain_prefix?{address:"".concat(e.domain_prefix,".").concat(o[s++%o.length],":").concat(e.port)}:e.ip.match(/^[\.\:\d]+$/)?{ip:e.ip,port:e.port,address:"".concat(e.ip.replace(/[^\d]/g,"-"),".").concat(o[s++%o.length],":").concat(e.port)}:(dg.info("Cannot recognized as IP address ".concat(e.ip,". Used As Host instead")),{ip:e.ip,port:e.port,address:"".concat(e.ip,":").concat(e.port)}));if(null!=(i=e.detail)&&i[18]&&"string"==typeof(null==(r=e.detail)?void 0:r[18])){let t=e.detail[18],i=null==t?void 0:t.split(";");for(let e=0;e<i.length;e++){let t=ab(n=i[e]).call(n);a[e]&&t&&(a[e].ip6=t)}}return{gatewayAddrs:a,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 hO(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function hb(e){let t=e._encoderConfig;if(!t)return{};let i={resolution:t.width&&t.height?"".concat(hO(t.width),"x").concat(hO(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 hN(e,t,i){var r,n,o,s,a,c,d,l;let u=t.videoSend.find(t=>t.ssrc===e);if(!u)return null;let h={id:hV(10,""),timestamp:new Date(t.timestamp).toISOString(),mediaType:"video",type:"ssrc",ssrc:u.ssrc.toString()},p=null!=(r=null!=(n=null==(o=u.inputFrame)?void 0:o.height)?n:null==i?void 0:i._videoHeight)?r:0,_=null!=(s=null!=(a=null==(c=u.inputFrame)?void 0:c.width)?a:null==i?void 0:i._videoWidth)?s:0,E=null!=(d=null==(l=u.inputFrame)?void 0:l.frameRate)?d:0;return p&&(h.A_fhi=p+""),_&&(h.A_fwi=_+""),E&&(h.A_fri=E+""),h}function hw(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 hD(e,t){let i,r,n;switch(t){case ef.CHOOSE_SERVER:i=4096,r="choose server";break;case ef.CLOUD_PROXY:i=1048576,r="proxy";break;case ef.CLOUD_PROXY_5:i=4194304,r="proxy5";break;case ef.CLOUD_PROXY_FALLBACK:i=4194310,r="proxy fallback";break;default:throw new du(o.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===i&&(n={code:t.buffer.code,addresses:(t.buffer.edges_services||[]).map(e=>hv(hv({},e),{},{ticket:t.buffer.cert})),server_ts:e.enter_ts,uid:t.buffer.uid,cid:t.buffer.cid,cname:t.buffer.cname,detail
1:hv(hv({},t.buffer.detail),e.detail),flag:t.buffer.flag,opid:e.opid,cert:t.buffer.cert})}),!n)throw new du(o.MULTI_UNILBS_RESPONSE_ERROR,"cannot parse response ".concat(r," from multi unilbs response"),{csIp:e.detail&&e.detail[502]});return n}async function hP(e,t){return await sG.all(e.addresses.map(async e=>({address:hy(e.ip),tcpport:e.port,udpport:e.port,username:t&&dM.ENCRYPT_PROXY_USERNAME_AND_PSW&&window.isSecureContext?t.toString():dy.username,password:t&&dM.ENCRYPT_PROXY_USERNAME_AND_PSW&&window.isSecureContext?await uT(t.toString()):dy.password})))}function hL(e){let{candidateType:t,relayProtocol:i,type:r,address:n,port:o,protocol:s}=e;return"local-candidate"===r?{candidateType:t,relayProtocol:i,protocol:s}:{candidateType:t,relayProtocol:i,address:n,port:o,protocol:s}}function hk(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 hM(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?hk(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):hk(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}function hU(e){return window.TextEncoder?(new TextEncoder).encode(e).length:e.length}function hx(e){return new sG(t=>{window.setTimeout(t,e)})}function hV(){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)+hV(e-i.length,"")}function hF(){return hV(32,"").toUpperCase()}let hj=()=>{};function hB(e){return new sG((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=aQ()?"canplay":"playing";n.addEventListener(o,()=>{let e=n.videoWidth,i=n.videoHeight;!e&&az()||(r=!0,n.srcObject=null,n.remove(),t([e,i]))}),n.srcObject=new MediaStream([e]),n.play().catch(hj),setTimeout(()=>{r||(n.srcObject=null,n.remove(),t([n.videoWidth,n.videoHeight]))},4e3)})}function hG(e){return sG.all(e.map(e=>e.then(e=>{throw e},e=>e))).then(e=>{throw e},e=>e)}function hW(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?sG.reject(new du(o.UNEXPECTED_ERROR,"can not emit promise")):new sG((i,n)=>{e.emit(t,...r,i,n)})}function hH(e,t){if(0===e.getListeners(t).length)return sG.resolve();for(var i=arguments.length,r=Array(i>2?i-2:0),n=2;n<i;n++)r[n-2]=arguments[n];return hW(e,t,...r)}function hK(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 hY(e,t,...r)}function hY(e,t){let i=null,r=null;for(var n=arguments.length,s=Array(n>2?n-2:0),a=2;a<n;a++)s[a-2]=arguments[a];if(e.emit(t,...s,e=>{i=e},e=>{r=e}),null!==r)throw r;if(null===i)throw new du(o.UNEXPECTED_ERROR,"handler is not sync");return i}function hq(e,t){let i=e.indexOf(t);-1!==i&&e.splice(i,1)}function hJ(e){let t=[];return e.forEach(e=>{-1===t.indexOf(e)&&t.push(e)}),t}function hX(e){sG.resolve().then(e)}function hz(e){return JSON.parse(JSON.stringify(e))}let hQ={};function hZ(e,t){hQ[t]||(hQ[t]=!0,e())}function h$(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 h0(e){let t="";for(let i=0;i<e.length;i+=1)t+=String.fromCharCode(e[i]);return window.btoa(t)}let h1=new class{constructor(){cc(this,"fnMap",new Map)}throttleByKey(e,t,i,r){for(var n=arguments.length,o=Array(n>4?n-4:0),s=4;s<n;s++)o[s-4]=arguments[s];if(this.fnMap.has(t)){let n=this.fnMap.get(t);if(n.threshold!==i){n.fn(...n.args),clearTimeout(n.timer);let s=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:s,args:o,skipFn:r})}else n.skipFn&&n.skipFn(...n.args),this.fnMap.set(t,hM(hM({},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})}}},h2=h1.throttleByKey.bind(h1),h3=async e=>{let{fragementLength:t,referenceList:i,asyncMapHandler:r,allFailedhandler:n,promisesCollector:o}=e,s=0,a,c=0,d=async()=>{let e=(()=>{let e=s*t;return i.slice(e,e+t).map(r)})();o&&o.push(...e);try{a=await hG(e)}catch(e){if(c+=t,s++,!(c>=i.length))return void await d();n(e)}
1e.forEach(e=>e.cancel())};return await d(),a};function h4(e){return"object"==typeof e&&null!==e&&!(e instanceof RegExp)}let h5={[f.ACCESS_POINT]:{[g.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[g.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[g.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[g.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[g.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[g.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[g.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[g.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voice service available",retry:!0},[g.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[g.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[g.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[g.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[g.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[g.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[g.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[g.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[g.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[g.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[f.UNILBS]:{[T.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[T.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[T.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[T.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[T.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[T.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[T.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[T.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[T.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[T.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[T.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[T.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1}},[f.STRING_UID_ALLOCATOR]:{[S.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[S.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[S.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function h6(e){let t=h5[Math.floor(e/1e4)];if(!t)return{desc:"unkonw error",retry:!1};let i=t[e%1e4];if(!i){if(Math.floor(e/1e4)===f.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:"unkonw error",retry:!1}}return i}let h8={[R.K_TIMESTAMP_EXPIRED]:{desc:"K_TIMESTAMP_EXPIRED",action:"failed"},[R.K_CHANNEL_PERMISSION_INVALID]:{desc:"K_CHANNEL_PERMISSION_INVALID",action:"failed"},[R.K_CERTIFICATE_INVALID]:{desc:"K_CERTIFICATE_INVALID",action:"failed"},[R.K_CHANNEL_NAME_EMPTY]:{desc:"K_CHANNEL_NAME_EMPTY",action:"failed"},[R.K_CHANNEL_NOT_FOUND]:{desc:"K_CHANNEL_NOT_FOUND",action:"failed"},[R.K_TICKET_INVALID]:{desc:"K_TICKET_INVALID",action:"failed"},[R.K_CHANNEL_CONFLICTED]:{desc:"K_CHANNEL_CONFLICTED",action:"failed"},[R.K_SERVICE_NOT_READY]:{desc:"K_SERVICE_NOT_READY",action:"tryNext"},[R.K_SERVICE_TOO_HEAVY]:{desc:"K_SERVICE_TOO_HEAVY",action:"tryNext"},[R.K_UID_BANNED]:{desc:"K_UID_BANNED",action:"failed"},[R.K_IP_BANNED]:{desc:"K_IP_BANNED",action:"failed"},[R.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[R.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[R.WARN_NO_AVAILABLE_CHANNEL]:{desc:"WARN_NO_AVAILABLE_CHANNEL",action:"failed"},[R.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:"WARN_LOOKUP_CHANNEL_TIMEOUT",action:"tryNext"},[R.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:"WARN_LOOKUP_CHANNEL_REJECTED",action:"failed"},[R.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:"WARN_OPEN_CHANNEL_TIMEOUT",action:"tryNext"},[R.WARN_OPEN_CHANNEL_REJECTED]:{desc:"WARN_OPEN_CHANNEL_REJECTED",action:"failed"},[R.WARN_REQUEST_DEFERRED]:{desc:"WARN_REQUEST_DEFERRED",action:"failed"},[R.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:"ERR_DYNAMIC_KEY_TIMEOUT",action:"failed"},[R.ERR_NO_AUTHORIZED]:{desc:"ERR_NO_AUTHORIZED",action:"failed"},[R.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:"ERR_VOM_SERVICE_UNAVAILABLE",action:"tryNext"},[R.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:"ERR_NO_CHANNEL_AVAILABLE_CODE",action:"failed"},[R.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:"ERR_MASTER_VOCS_UNAVAILABLE",action:"tryNext"},[R.ERR_INTERNAL_ERROR]:{desc:"ERR_INTERNAL_ERROR",action:"tryNext"},[R.ERR_NO_ACTIVE_STATUS]:{desc:"ERR_NO_ACTIVE_STATUS",action:"failed"},[R.ERR_INVALID_UID]:{desc:"ERR_INVALID_UID",action:"failed"},[R.ERR_DYNAMIC_KEY_EXPIRED]:{desc:"ERR_DYNAMIC_KEY_EXPIRED",action:"failed"},[R.ERR_STATIC_USE_DYANMIC_KE]:{desc:"ERR_STATIC_USE_DYANMIC_KE",action:"failed"},[R.ERR_DYNAMIC_USE_STATIC_KE]:{desc:"ERR_DYNAMIC_USE_STATIC_KE",action:"failed"},[R.ERR_NO_VOCS_AVAILABLE]:{desc:"ERR_NO_VOCS_AVAILABLE",action:"tryNext"},[R.ERR_NO_VOS_AVAILABLE]:{desc:"ERR_NO_VOS_AVAILABLE",action:"tryNext"},[R.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:"ERR_JOIN_CHANNEL_TIMEOUT",action:"tryNext"},[R.ERR_JOIN_BY_MULTI_IP]:{desc:"ERR_JOIN_BY_MULTI_IP",action:"recover"},[R.ERR_NOT_JOINED]:{desc:"ERR_NOT_JOINED",action:"failed"},[R.ERR_REPEAT_JOIN_REQUEST]:{desc:"ERR_REPEAT_JOIN_REQUEST",action:"quit"},[R.ERR_REPEAT_JOIN_CHANNEL]:{desc:"ERR_REPEAT_JOIN_CHANNEL",action:"quit"},[R.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[R.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[R.ERR_INVALID_STRINGUID]:{desc:"ERR_INVALID_STRINGUID",action:"failed"},[R.ERR_TOO_MANY_USERS]:{desc:"ERR_TOO_MANY_USERS",action:"tryNext"},[R.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[R.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[R.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",action:"success"},[R.ERR_PUBLISH_REQUEST_INVALID]:{desc:"ERR_PUBLISH_REQUEST_INVALID",action:"failed"},[R.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:"ERR_SUBSCRIBE_REQUEST_INVALID",action:"failed"},[R.ERR_NOT_SUPPORTED_MESSAGE]:{desc:"ERR_NOT_SUPPORTED_MESSAGE",action:"failed"},[R.ERR_ILLEAGAL_PLUGIN]:{desc:"ERR_ILLEAGAL_PLUGIN",action:"failed"},[R.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:"ILLEGAL_CLIENT_ROLE_LEVEL",action:"failed"},[R.ERR_REJOIN_TOKEN_INVALID]:{desc:"ERR_REJOIN_TOKEN_INVALID",action:"failed"},[R.ERR_REJOIN_USER_NOT_JOINED]:{desc:"ERR_REJOIN_NOT_JOINED",action:"failed"},[R.ERR_INVALID_OPTIONAL_INFO]:{desc:"ERR_INVALID_OPTIONAL_INFO",action:"quit"},[R.ERR_TEST_RECOVER]:{desc:"ERR_TEST_RECOVER",action:"recover"},[R.ERR_TEST_TRYNEXT]:{desc:"ERR_TEST_TRYNEXT",action:"recover"},[R.ERR_TEST_RETRY]:{desc:"ERR_TEST_RETRY",action:"recover"},[R.ILLEGAL_AES_PASSWORD]:{desc:"ERR_TEST_RETRY",action:"failed"},[R.ERR_TOO_MANY_BROADCASTERS]:{desc:"ERR_TOO_MANY_BROADCASTERS",action:"failed"},[R.ERR_TOO_MANY_SUBSCRIBERS]:{desc:"ERR_TOO_MANY_SUBSCRIBERS",action:"failed"},[R.ERR_LICENSE_ILLEGAL]:{desc:"ERR_LICENSE_ILLEGAL",action:"quit"},[R.ERR_LICENSE_MISSING]:{desc:"ERR_LICENSE_MISSING",action:"quit"},[R.ERR_LICENSE_EXPIRED]:{desc:"ERR_LICENSE_EXPIRED",action:"quit"},[R.ERR_LICENSE_MINUTES_EXCEEDED]:{desc:"ERR_LICENSE_MINUTES_EXCEEDED",action:"quit"},[R.ERR_LICENSE_PERIOD_INVALID]:{desc:"ERR_LICENSE_PERIOD_INVALID",action:"quit"},[R.ERR_LICENSE_MULTIPLE_SDK_SERVICE]:{desc:"ERR_LICENSE_MULTIPLE_SDK_SERVICE",action:"quit"}};function h7(e){return h8[e]||{desc:"UNKNOW_ERROR_".concat(e),action:"failed"}}function h9(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 pe extends dd{get url(){return this.websocket?this.websocket.url:null}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){["tryNext","recover"].includes(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(L.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(L.CONNECTED):"closed"===this._state?this.emit(L.CLOSED):"failed"===this._state&&this.emit(L.FAILED))}resetReconnectCount(e){dg.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=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?arguments[4]:void 0;super(),cc(this,"connectionID",0),cc(this,"currentURLIndex",0),cc(this,"urls",void 0),cc(this,"_reconnectMode","tryNext"),cc(this,"reconnectReason",void 0),cc(this,"_initMutex",new uO("websocket")),cc(this,"name",void 0),cc(this,"_state","closed"),cc(this,"reconnectInterrupter",void 0),cc(this,"websocket",void 0),cc(this,"retryConfig",void 0),cc(this,"reconnectCount",0),cc(this,"forceCloseTimeout",5e3),cc(this,"onlineReconnectListener",void 0),cc(this,"useCompress",void 0),cc(this,"tryDoubleDomain",!1),cc(this,"wsInflateLength",0),cc(this,"wsDeflateLength",0),cc(this,"closeEstablishingWs",()=>{}),cc(this,"store",void 0),cc(this,"joinChannelServiceRecordIndex",void 0),this.store=n,this.name=e,this.retryConfig=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?h9(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):h9(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}({},t),this.useCompress=i,this.tryDoubleDomain=r;let{timeout:o,timeoutFactor:s}=t,a=Math.max(300,Math.floor(3*o/5)),c=Math.max(1.2,Math.floor(8*s)/10);ec.ONLINE&&(this.retryConfig.timeout=a,this.retryConfig.timeoutFactor=c),up.on(ed.NETWORK_STATE_CHANGE,(e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===ec.ONLINE?(this.retryConfig.timeout=a,this.retryConfig.timeoutFactor=c):(this.retryConfig.timeout=o,this.retryConfig.timeoutFactor=s))})}getConnection(){return this.websocket||void 0}init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;this.forceCloseTimeout=t;let i=(t,i)=>{this.urls=e;let r=this.urls[this.currentURLIndex];this.state="connecting",this.createWebSocketConnection(r).then(t).catch(i),this.once(L.CLOSED,()=>i(new du(o.WS_DISCONNECT))),this.once(L.CONNECTED,()=>t())};return this._initMutex.lock().then(e=>new sG((e,t)=>{i(e,t)}).then(()=>{e()}).catch(()=>{e()}))}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.state=e?"failed":"closed",this.closeEstablishingWs&&this.closeEstablishingWs()}reconnect(e,t){var i;if(!this.websocket)return void dg.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),dg.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.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),r&&r.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 du(o.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new du(o.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,t){return this.connectionID+=1,this.connectionID,this.joinChannelServiceRecordIndex=void 0,new sG((i,r)=>{var n;let s=e=>{var t;null==(t=this.store)||t.signalChannelOpen(),dg.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),i()},a=async e=>{if(dg.debug("[".concat(this.name,"] websocket close ").concat(this.websocket&&this.websocket.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 t=hK(this,L.WILL_RECONNECT,this.reconnectMode)||this.reconnectMode,n=await this.reconnectWithAction(t);
1if("closed"===this.state)return void dg.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!n)return r(new du(o.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),void this.close(!0);i()}else r(new du(o.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close()},c=e=>{this.emit(L.ON_MESSAGE,e)};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),dM.GATEWAY_WSS_ADDRESS&&this.name.startsWith("gateway")&&(e=dM.GATEWAY_WSS_ADDRESS),dg.debug("[".concat(this.name,"] start connect, url: ").concat(e));let d=null==(n=this.store)?void 0:n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});this.chooseBestWebsocketConnection(e,!!t,d).then(e=>{var t;this.websocket=e,s&&s(e.url),e.onclose=a,e.onmessage=c,null==(t=this.store)||t.recordJoinChannelService({endTs:Date.now(),status:"success"},d),this.joinChannelServiceRecordIndex=d}).catch(e=>{var t;if(null==(t=this.store)||t.recordJoinChannelService({endTs:Date.now(),status:e instanceof du&&e.code===o.WS_ABORT?"aborted":"error",errors:[e]},d),"closed"!==this.state){if(e instanceof du&&e.code===o.WS_ERR){let t=new du(o.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return dg.error("[".concat(this.name,"]").concat(t)),void r(t)}a&&a(e)}else r(new du(o.WS_DISCONNECT,"websocket 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.urls||"closed"===this.state)return!1;this.onlineReconnectListener||up.networkState!==ec.OFFLINE||(this.onlineReconnectListener=up.onlineWaiter&&up.onlineWaiter.then(()=>{this.onlineReconnectListener=void 0}));let i=!0;if(this.reconnectInterrupter=()=>{i=!1},t){let t=dp(this.reconnectCount,this.retryConfig);dg.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await sG.race([hx(t),this.onlineReconnectListener||new sG(()=>{})])}if("closed"===this.state||!i)return!1;this.reconnectCount+=1;let r=async(e,t)=>{this.emit(L.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e){let t=this.urls[this.currentURLIndex];this.emit(L.RECONNECT_WAITTING_FINISH,e),await r(t,e)}else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return await this.reconnectWithAction("recover",!1);dg.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex));let t=this.urls[this.currentURLIndex];this.emit(L.RECONNECT_WAITTING_FINISH,e),await r(t,e)}else if("recover"===e){dg.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.emit(L.RECONNECT_WAITTING_FINISH,e),this.urls=await hW(this,L.REQUEST_NEW_URLS),this.currentURLIndex=0;let t=this.urls[this.currentURLIndex];await r(t,e)}return!0}catch(i){var n;return dg.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&&i.data.desc.includes("dynamic key expired")?(this.emit(L.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):await this.reconnectWithAction(e,t)}}async chooseBestWebsocketConnection(e,t,i){return new sG((r,n)=>{var s,a;let c=!1,d=[];this.closeEstablishingWs=()=>{dg.debug("[choose-best-ws] close establishing websockets"),d.forEach(e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()}),n(new du(o.WS_ABORT,"choose best websocket aborted"))};let l=dM.GATEWAY_DOMAINS,u=e.indexOf("?h="),h=l.find(t=>-1!==u?e.includes(t,u):e.includes(t));dg.debug("[choose-best-ws] currentDomain: ",h,", domains: ",l);let p=!this.tryDoubleDomain||t||!h;if(!p&&h){let t=Date.now();try{l.forEach(t=>{let i=-1===u?e.replace(h,t):e.substr(0,u)+e.substr(u).replace(h,t),r=new WebSocket(i);r.binaryType="arraybuffer",d.push(r),dg.debug("[choose-best-ws] ws is connecting:",r.url)})}catch(e){for(dg.debug("[choose-best-ws] ws create failed, fallback to single url"),d.forEach(e=>e.close());d.length;)d.pop();p=!0}null==(s=this.store)||s.recordJoinChannelService({urls:d.map(e=>e.url),service:"gateway"}
1,i),d.forEach(e=>{e.onopen=()=>{if(c)return;let i=Date.now()-t;dg.debug("[choose-best-ws] ws open cost ".concat(i,"ms")),d.filter(t=>t!==e).forEach(e=>{dg.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()}),c=!0,r(e)},e.onclose=e=>{!c&&(d.find(e=>e.readyState!==WebSocket.CLOSED&&e.readyState!==WebSocket.CLOSING)||(dg.debug("[choose-best-ws] all websocket is closed"),c=!0,n(e)))},e.onmessage=t=>{dg.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}}),hx(this.forceCloseTimeout).then(()=>{d.forEach(e=>{e.readyState!==WebSocket.OPEN&&e.close()})})}if(p){let t;dg.debug("[choose-best-ws] use single url: ",e),null==(a=this.store)||a.recordJoinChannelService({urls:[e],service:"gateway"},i);try{t=new WebSocket(e),d.push(t),t.binaryType="arraybuffer"}catch(t){let e=new du(o.WS_ERR,"init websocket failed! Error: ".concat(t.toString()));return dg.error("[".concat(this.name,"]").concat(e)),void n(e)}t.onopen=()=>{r(t)},t.onclose=e=>{n(e)},t.onmessage=e=>{dg.debug("[choose-best-ws]".concat(t.url," onmessage: ").concat(e.data))},hx(this.forceCloseTimeout).then(()=>{t&&t.readyState!==WebSocket.OPEN&&t.close()})}}).then(e=>(this.closeEstablishingWs=void 0,e)).catch(e=>{throw this.closeEstablishingWs=void 0,e})}}class pt{constructor(e){cc(this,"input",[]),cc(this,"size",void 0),this.size=e}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:rs(e=this.input).call(e,(e,t)=>e+t)/this.input.length}}class pi extends dd{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===A.CONNECTED?this.emit(O.WS_CONNECTED):e===A.RECONNECTING?this.emit(O.WS_RECONNECTING,this._websocketReconnectReason):e===A.CLOSED&&this.emit(O.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()}constructor(e,t){super(),cc(this,"_disconnectedReason",void 0),cc(this,"_websocketReconnectReason",void 0),cc(this,"_connectionState",A.CLOSED),cc(this,"reconnectToken",void 0),cc(this,"websocket",void 0),cc(this,"openConnectionTime",void 0),cc(this,"clientId",void 0),cc(this,"lastMsgTime",Date.now()),cc(this,"uploadCache",[]),cc(this,"uploadCacheInterval",void 0),cc(this,"rttRolling",new pt(5)),cc(this,"pingpongTimer",void 0),cc(this,"wsInflateDataTimer",void 0),cc(this,"pingpongTimeoutCount",0),cc(this,"joinResponse",void 0),cc(this,"multiIpOption",void 0),cc(this,"initError",void 0),cc(this,"spec",void 0),cc(this,"store",void 0),cc(this,"onWebsocketMessage",e=>{if(e.data instanceof ArrayBuffer)return void this.emit(O.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===w.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===w.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(C.UID_BANNED);break;case 15:this.close(C.IP_BANNED);break;case 16:this.close(C.CHANNEL_BANNED)}if(t._type===w.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case R.ERR_LICENSE_MISSING:this.close(C.LICENSE_MISSING);break;case R.ERR_LICENSE_EXPIRED:this.close(C.LICENSE_EXPIRED);break;case R.ERR_LICENSE_MINUTES_EXCEEDED:this.close(C.LICENSE_MINUTES_EXCEEDED);break;case R.ERR_LICENSE_PERIOD_INVALID:this.close(C.LICENSE_PERIOD_INVALID);break;case R.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(C.LICENSE_MULTIPLE_SDK_SERVICE);break;case R.ERR_LICENSE_ILLEGAL:this.close(C.LICENSE_ILLEGAL);break;default:this.close()}}}),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new pe("gateway-".concat(this.clientId),this.spec.retryConfig,!0,!0,t),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===A.CONNECTED&&this.reconnect("retry",y.OFFLINE)})}async request(e,t,i,r){let n=hV(6,""),s=this.websocket.connectionID,a=()=>new sG((t,i)=>{if(this.connectionState===A.CONNECTED)return t();let r=()=>{this.off(O.WS_CLOSED,n),t()},n=()=>{this.off(O.WS_CONNECTED,r),i(new du(o.WS_ABORT))};this.once(O.WS_CONNECTED,r),this.once(O.WS_CLOSED,n),e!==b.PUBLISH&&e!==b.SUBSCRIBE&&e!==b.UNSUBSCRIBE&&e!==b.UNPUBLISH&&e!==b.CONTROL&&e!==b.RESTART_ICE||this.once(O.DISCONNECT_P2P,()=>{i(new du(o.DISCONNECT_P2P))}),e!==b.PUBLISH&&e!==b.RESTART_ICE||this.once(O.ABORT_P2P_EXECUTION,()=>{i(new du(o.DISCONNECT_P2P))})});if(this.connectionState!==A.CONNECTING&&this.connectionState!==A.RECONNECTING||e===b.JOIN||e===b.REJOIN||await a(),this.websocket.sendMessage({_id:n,_type:e,_message:t},!0),r)return;let c=new sG((i,r)=>{let a=!1,c=(r,n)=>{a=!0,i({isSuccess:"success"===r,message:n||{}}),this.off(O.WS_CLOSED,d),this.off(O.WS_RECONNECTING,d),this.emit
1(O.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(n),c);let d=()=>{r(new du(o.WS_ABORT,"type: ".concat(e))),this.off(O.WS_CLOSED,d),this.off(O.WS_RECONNECTING,d),this.off("res-@".concat(n),c)};this.once(O.WS_CLOSED,d),this.once(O.WS_RECONNECTING,d),hx(dM.SIGNAL_REQUEST_TIMEOUT).then(()=>{this.websocket.connectionID!==s||a||(dg.warning("ws request timeout, type: ".concat(e)),this.emit(O.REQUEST_TIMEOUT,e,t))})}),d=null;try{d=await c}catch(r){if(this.connectionState===A.CLOSED||e===b.LEAVE)throw new du(o.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?r.throw():e===b.JOIN||e===b.REJOIN?null:(await a(),await this.request(e,t))}if(d.isSuccess)return d.message;let l=Number(d.message.error_code||d.message.code),u=h7(l),h=new du(o.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message});return"success"===u.action?d.message:(dg.warning("[".concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(u.desc,", action: ").concat(u.action)),l===R.ERR_TOO_MANY_BROADCASTERS?((e===b.JOIN||e===b.REJOIN)&&(this.initError=h,this.close()),h.throw()):"failed"===u.action?h.throw():"quit"===u.action?(this.initError=h,this.close(),h.throw()):(l===R.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,dg.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",y.MULTI_IP)):this.reconnect(u.action,y.SERVER_ERROR),e===b.JOIN||e===b.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new sG(i=>{let r=n=>{(!t||t(n))&&(this.off(e,r),i(n))};this.on(e,r)})}upload(e,t){let i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(t){let e=dM.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!==A.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)},dM.UPLOAD_CACHE_INTERVAL||2e3))}}send(e,t){this.websocket.sendMessage({_type:e,_message:t})}init(e,t){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new sG((i,r)=>{this.once(O.WS_CONNECTED,()=>i(this.joinResponse)),this.once(O.WS_CLOSED,()=>r(this.initError||new du(o.WS_ABORT))),this.connectionState=A.CONNECTING,this.websocket.init(e).catch(r),this.wsInflateDataTimer&&window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=window.setInterval(()=>{this.handleWsInflateData()},2e4),setTimeout(()=>{t&&void 0===this.openConnectionTime&&(dg.debug("[".concat(this.clientId,"] init websocket timeout while join with fallback to proxy")),r(new du(o.INIT_WEBSOCKET_TIMEOUT)))},dM.JOIN_WITH_FALLBACK_PROXY_PENDING_DURATION)})}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||C.LEAVE,this.connectionState=A.CLOSED,dg.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close(),e===C.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new pe("gateway-".concat(this.clientId),this.spec.retryConfig,!0,!0,this.store),this.handleWebsocketEvents())}async join(){if(!this.joinResponse){this.emit(O.ABORT_P2P_EXECUTION);let e=await hW(this,O.REQUEST_JOIN_INFO),t=await this.request(b.JOIN,e);if(!t)return this.emit(O.REPORT_JOIN_GATEWAY,o.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(O.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=A.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new du(o.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");let e=hY(this,O.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;let t=await this.request(b.REJOIN,e);return!!t&&(this.connectionState=A.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEac
1h(e=>{this.emit(w.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(w.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(w.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(w.MUTE_AUDIO,{uid:e.uid}):this.emit(w.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(w.MUTE_VIDEO,{uid:e.uid}):this.emit(w.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(w.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(w.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(w.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(w.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(w.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)}handleNotification(e){dg.debug("[".concat(this.clientId,"] receive notification: "),e);let t=h7(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(C.UID_BANNED),void this.close()):void this.reconnect(t.action,y.SERVER_ERROR);dg.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=dM.PING_PONG_TIME_OUT,t=Date.now();this.pingpongTimeoutCount>=e&&(dg.warning("PINGPONG Timeout. Last Socket Message: ".concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>dM.WEBSOCKET_TIMEOUT_MIN)?this.reconnect("retry",y.TIMEOUT):this.request(b.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;let e=Date.now()-t;this.rttRolling.add(e),dM.REPORT_STATS&&this.send(b.PING_BACK,{pingpongElapse:e})}).catch(e=>{})}handleWsInflateData(){let{wsInflateLength:e,wsDeflateLength:t}=this.websocket.getWsInflateData();0!==e&&0!==t&&this.upload(N.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(L.RECONNECT_WAITTING_FINISH,e=>{this.emit(O.WS_RECONNECT_WAITTING_FINISH,e)}),this.websocket.on(L.RECONNECT_CREATE_CONNECTION,e=>{this.emit(O.WS_RECONNECT_CREATE_CONNECTION,e)}),this.websocket.on(L.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(L.CLOSED,()=>{this.connectionState=A.CLOSED}),this.websocket.on(L.FAILED,()=>{this._disconnectedReason=C.NETWORK_ERROR,this.connectionState=A.CLOSED}),this.websocket.on(L.RECONNECTING,e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===A.CONNECTED?this.connectionState=A.RECONNECTING:this.connectionState=A.CONNECTING}),this.websocket.on(L.WILL_RECONNECT,(e,t)=>{if(hY(this,O.IS_P2P_DISCONNECTED)&&"retry"===e)return dg.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit(O.NEED_RENEW_SESSION),this.emit(O.DISCONNECT_P2P),t("tryNext");"retry"!==e&&(dg.debug("".concat(this.clientId," websockt will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0,this.emit(O.NEED_RENEW_SESSION),this.emit(O.DISCONNECT_P2P)),t(e)}),this.websocket.on(L.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch(e=>{dg.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",y.SERVER_ERROR)}):this.join().catch(e=>{if(this.emit(O.REPORT_JOIN_GATEWAY,e.message||e.code,this.url||""),e instanceof du&&e.code===o.UNEXPECTED_RESPONSE&&e.data.code===R.ERR_NO_AUTHORIZED)return dg.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",y.SERVER_ERROR);dg.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",y.SERVER_ERROR):(this.initError=e,this.close())})}),this.websocket.on(L.REQUEST_NEW_URLS,(e,t)=>{hW(this,O.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)}),this.websocket.on(L.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(w.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})}}function pr(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 pn extends dd{get url(){return this._url?this._url:null}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){["tryNext","recover"].includes(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(em.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(em.CONNECTED):"closed"===this._state?this.emit(em.CLOSED):"failed"===this._state&&this.emit(em.FAILED))}constructor(e,t,i,r){super(),cc(this,"connectionID",0),cc(this,"currentURLIndex",0),cc(this,"reconnectReason",void 0),cc(this,"_reconnectMode","tryNext"),cc(this,"_initMutex",void 0),cc(this,"_name",void 0),cc(this,"_state","closed"),cc(this,"_reconnectInterrupter",void 0),cc(this,"_url",void 0),cc(this,"_retryConfig",void 0),cc(this,"_reconnectCount",0),cc(this,"_forceCloseTimeout",5e3),cc(this,"_onlineReconnectListener",void 0),cc(this,"_closeEstablishingTransmitter",()=>{}),cc(this,"_store",void 0),cc(this,"_joinChannelServiceRecordIndex",void 0),cc(this,"_transmitter",void 0),cc(this,"_useCompress",void 0),cc(this,"_inflateLength",0),cc(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]:{};t%2?pr(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):pr(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}({},t),this._useCompress=i}resetReconnectCount(e){dg.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 dg.warning("[".concat(this._name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),dg.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}}function po(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),s=Number(!i);return BigInt(r*s+n*o)<<BigInt(32)|BigInt(r*o+n*s)}function ps(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))}(Ei=eS||(eS={}))[Ei.Default=0]="Default",Ei[Ei.Ack=1]="Ack";class pa{constructor(e,t,i){cc(this,"version",1),cc(this,"initialRTO",void 0),cc(this,"maxBatchAckCount",void 0),cc(this,"maxRTO",void 0),cc(this,"initialRTT",void 0),cc(this,"ID",void 0),cc(this,"rtt",void 0),cc(this,"packetNumber",1),cc(this,"rtoRatioMap",new Map),cc(this,"timeoutMap",new Map),cc(this,"unorderedPacketQueue",[]),cc(this,"batchAckPacketQueue",[]),cc(this,"lastOrderedPacketNumber",0),cc(this,"batchAckTimer",void 0),cc(this,"sendImpl",void 0),cc(this,"receiveImpl",void 0),this.sendImpl=e,this.receiveImpl=t,this.ID=hV(7,"transmitter-"),this.initialRTO=void 0!==(null==i?void 0:i.initialRTO)?i.initialRTO:dM.TRANSMITTER_INITIAL_RTO,this.initialRTT=void 0!==(null==i?void 0:i.initialRTT)?i.initialRTT:dM.TRANSMITTER_INITIAL_RTT,this.rtt=void 0!==(null==i?void 0:i.initialRTT)?i.initialRTT:dM.TRANSMITTER_INITIAL_RTT,this.maxBatchAckCount=void 0!==(null==i?void 0:i.maxBatchAckCount)?i.maxBatchAckCount:dM.TRANSMITTER_MAX_BATCH_ACK_COUNT,this.maxRTO=void 0!==(null==i?void 0:i.maxRTO)?i.maxRTO:dM.TRANSMITTER_MAX_RTO}packetize(e,t){return{type:eS.Default,version:this.version,packetNumber:t,payload:e}}serialize(e){switch(e.type){case eS.Default:{let t,i=new ArrayBuffer((t="string"==typeof e.payload?(ne
1w 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),ps(r,7,BigInt(e.sendTs)),new Uint8Array(r.buffer).set(t,15),i}case eS.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),ps(i,8,BigInt(e.ackSendTs)),t}}}deserialize(e){let t=new DataView(e),i=t.getUint16(0),r=t.getUint8(2);switch(r){case eS.Default:{let n=t.getUint32(3),o=po(t,7),s=e.slice(15),a=(new TextDecoder).decode(s);return{version:i,type:r,packetNumber:n,sendTs:Number(o),payload:a}}case eS.Ack:{let e=t.getUint32(3);return{version:i,type:r,maxAckPacketNumber:e,shift:t.getUint8(7),ackSendTs:Number(po(t,8))}}default:throw dg.error("[".concat(this.ID,"] Unrecognized packet type ").concat(r)),Error("Unrecognized packet type ".concat(r))}}sendMessage(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===eS.Default?this.ack(t):t.type===eS.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(()=>{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:eS.Ack,version:this.version};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:eS.Ack,version:this.version};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:eS.Ack,version:this.version};this.sendPacket(e),this.batchAckPacketQueue=[]}sendPacket(e){e.type===eS.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)}}}class pc extends pn{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3?arguments[3]:void 0),cc(this,"_initMutex",void 0),cc(this,"_reconnectInterrupter",void 0),cc(this,"_url",void 0),cc(this,"_transmitter",void 0),cc(this,"_addresses",void 0),cc(this,"_reliableTransmission",void 0),this._initMutex=new uO("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);ec.ONLINE&&(this._retryConfig.timeout=n,this._retryConfig.timeoutFactor=o),up.on(ed.NETWORK_STATE_CHANGE,(e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===ec.ONLINE?(this._retryConfig.timeout=n,this._retryConfig.timeoutFactor=o):(this._retryConfig.timeout=i,this._retryConfig.timeoutFactor=r))})}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||dM.FINGERPRINT);let r=this._addresses[this.currentURLIndex];this.state="connecting",this.createTransmitterConnection(r).then(t).cat
1ch(i),this.once(em.CLOSED,()=>i(new du(o.WS_DISCONNECT))),this.once(em.CONNECTED,()=>t())};return this._initMutex.lock().then(e=>new sG((e,t)=>{i(e,t)}).then(()=>{e()}).catch(()=>{e()}))}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this._transmitter||!this._reliableTransmission)throw new du(o.WS_ABORT,"datachannel is not ready");try{t||(e=JSON.stringify(e)),this._reliableTransmission.sendMessage(e)}catch(e){throw new du(o.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 sG((t,i)=>{var r;let n=()=>{dg.debug("[".concat(this._name,"] datachannel opened:"),this._url),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),t()},s=async e=>{var r;if(null==(r=this._closeEstablishingTransmitter)||r.call(this),dg.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=hK(this,em.WILL_RECONNECT,this.reconnectMode)||this.reconnectMode,n=await this.reconnectWithAction(r);if("closed"===this.state)return void dg.debug("[".concat(this.connectionID,"] dc is closed, no need to reconnect"));if(!n)return i(new du(o.WS_DISCONNECT,"datachannel reconnect failed: ".concat(e.code))),void this.close(!0);t()}else i(new du(o.WS_DISCONNECT,"datachannel close: ".concat(e.code))),this.close()},a=e=>{var t;null==(t=this._reliableTransmission)||t.onData(e.data)};this._transmitter&&(this._transmitter.onclose=null,this._transmitter.close()),this._reliableTransmission&&(this._reliableTransmission.close(),this._reliableTransmission=void 0),dg.debug("[".concat(this._name,"] start connect, address: ").concat(JSON.stringify(e)));let c=null==(r=this._store)?void 0:r.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"}),d=Date.now();hW(this,em.TO_CONNECT_DATACHANNEL,e).then(e=>{var t,i;if(!e)throw Error("transmissonInfo not exist yet");let{transmitter:r,close:o}=e;this._transmitter=r,null==(t=this._store)||t.signalChannelOpen();let l=Date.now()-d;dg.debug("[choose dc] dc open cost ".concat(l,"ms")),this._reliableTransmission=new pa(e=>{var t;this._transmitter&&"open"===this._transmitter.readyState&&(null==(t=this._transmitter)||t.send(e))},e=>{"string"==typeof e&&this.emit(em.ON_MESSAGE,e)}),this._closeEstablishingTransmitter=()=>{var e;null==(e=this._reliableTransmission)||e.close(),this._reliableTransmission=void 0,o()},n&&n(),r.onclose=s,r.onmessage=a,null==(i=this._store)||i.recordJoinChannelService({endTs:Date.now(),status:"success"},c),this._joinChannelServiceRecordIndex=c}).catch(e=>{var t;if(null==(t=this._store)||t.recordJoinChannelService({endTs:Date.now(),status:e instanceof du&&e.code===o.WS_ABORT?"aborted":"error",errors:[e]},c),"closed"!==this.state){if(e instanceof du&&e.code===o.WS_ERR){let t=new du(o.WS_ERR,"init datachannel failed! Error: ".concat(e.toString()));return dg.error("[".concat(this._name,"]").concat(t)),void i(t)}s&&s(e)}else i(new du(o.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||up.networkState!==ec.OFFLINE||(this._onlineReconnectListener=up.onlineWaiter&&up.onlineWaiter.then(()=>{this._onlineReconnectListener=void 0}));let i=!0;if(this._reconnectInterrupter=()=>{i=!1},t){let t=dp(this._reconnectCount,this._retryConfig);dg.debug("[".concat(this._name,"] wait ").concat(t,"ms to reconnect datachannel, mode: ").concat(e)),await sG.race([hx(t),this._onlineReconnectListener||new sG(()=>{})])}if("closed"===this.state||!i)return!1;this._reconnectCount+=1;let r=async(e,t)=>
1{this.emit(em.RECONNECT_CREATE_CONNECTION,t),await this.createTransmitterConnection(e)};try{if("retry"===e){let t=this._addresses[this.currentURLIndex];this.emit(em.RECONNECT_WAITTING_FINISH,e),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||dM.FINGERPRINT){this.currentURLIndex=e;break}this.currentURLIndex+=1}if(this.currentURLIndex>=this._addresses.length)return dg.debug("[".concat(this._name,"] the available addresses are exhausted, change to recover")),await this.reconnectWithAction("recover",!1);dg.debug("[".concat(this._name,"] datachannel url length: ").concat(this._addresses.length," current index: ").concat(this.currentURLIndex));let t=this._addresses[this.currentURLIndex];this.emit(em.RECONNECT_WAITTING_FINISH,e),await r(t,e)}else"recover"===e&&(dg.debug("[".concat(this._name,"] start to failback to websocket")),this.resetReconnectCount("recover mode"),this.emit(em.RECONNECT_WAITTING_FINISH,e),this.emit(em.FAILBACK));return!0}catch(i){var n;return dg.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&&i.data.desc.includes("dynamic key expired")?(this.emit(em.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):await this.reconnectWithAction(e,t)}}}class pd extends dd{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===A.CONNECTED?this.emit(O.WS_CONNECTED):e===A.RECONNECTING?this.emit(O.WS_RECONNECTING,this._websocketReconnectReason):e===A.CLOSED&&this.emit(O.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()}constructor(e,t){super(),cc(this,"_disconnectedReason",void 0),cc(this,"_websocketReconnectReason",void 0),cc(this,"_connectionState",A.CLOSED),cc(this,"reconnectToken",void 0),cc(this,"websocket",void 0),cc(this,"openConnectionTime",void 0),cc(this,"clientId",void 0),cc(this,"lastMsgTime",Date.now()),cc(this,"uploadCache",[]),cc(this,"uploadCacheInterval",void 0),cc(this,"rttRolling",new pt(5)),cc(this,"pingpongTimer",void 0),cc(this,"inflateDataTimer",void 0),cc(this,"pingpongTimeoutCount",0),cc(this,"joinResponse",void 0),cc(this,"multiIpOption",void 0),cc(this,"initError",void 0),cc(this,"spec",void 0),cc(this,"store",void 0),cc(this,"onWebsocketMessage",e=>{if(e instanceof ArrayBuffer)return void this.emit(O.ON_BINARY_DATA,e);let t=JSON.parse(e);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")&&(this.emit(t._type,t._message),t._type===w.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===w.ON_USER_BANNED))switch(t._message.error_code){case 14:this.close(C.UID_BANNED);break;case 15:this.close(C.IP_BANNED);break;case 16:this.close(C.CHANNEL_BANNED)}}),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new pc("gateway-".concat(this.clientId),this.spec.retryConfig,!0,t),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===A.CONNECTED&&this.reconnect("retry",eE.OFFLINE)})}async request(e,t,i,r){let n=hV(6,""),s=this.websocket.connectionID,a=()=>new sG((t,i)=>{if(this.connectionState===A.CONNECTED)return t();let r=()=>{this.off(O.WS_CLOSED,n),t()},n=()=>{this.off(O.WS_CONNECTED,r),i(new du(o.WS_ABORT))};this.once(O.WS_CONNECTED,r),this.once(O.WS_CLOSED,n),e!==b.PUBLISH&&e!==b.SUBSCRIBE&&e!==b.UNSUBSCRIBE&&e!==b.UNPUBLISH&&e!==b.CONTROL&&e!==b.RESTART_ICE||this.once(O.DISCONNECT_P2P,()=>{i(new du(o.DISCONNECT_P2P))}),e!==b.PUBLISH&&e!==b.RESTART_ICE||this.once(O.ABORT_P2P_EXECUTION,()=>{i(new du(o.DISCONNECT_P2P))})});if(this.connectionState!==A.CONNECTING&&this.connectionState!==A.RECONNECTING||e===b.JOIN||e===b.REJOIN||await a(),e===b.LEAVE&&(this.websocket.unbindDcCloseEventListener(),r=!0),this.websocket.sendMessage({_id:n,_type:e,_message:t},!0,!1),r)return;let c=new sG((i,r)=>{let a=!1,c=(r,n)=>{a=!0,i({isSuccess:"success"===r,message:n||{}}),this.off(O.WS_CLOSED,d),this.off(O.WS_RECONNECTING,d),this.emit
1(O.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(n),c);let d=()=>{r(new du(o.WS_ABORT,"type: ".concat(e))),this.off(O.WS_CLOSED,d),this.off(O.WS_RECONNECTING,d),this.off("res-@".concat(n),c)};this.once(O.WS_CLOSED,d),this.once(O.WS_RECONNECTING,d),hx(dM.SIGNAL_REQUEST_TIMEOUT).then(()=>{this.websocket.connectionID!==s||a||(dg.warning("dc request timeout, type: ".concat(e)),this.emit(O.REQUEST_TIMEOUT,e,t))})}),d=null;try{d=await c}catch(r){if(this.connectionState===A.CLOSED||e===b.LEAVE)throw new du(o.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?r.throw():e===b.JOIN||e===b.REJOIN?null:(await a(),await this.request(e,t))}if(d.isSuccess)return d.message;let l=Number(d.message.error_code||d.message.code),u=h7(l),h=new du(o.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message});return"success"===u.action?d.message:(dg.warning("[".concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(u.desc,", action: ").concat(u.action)),l===R.ERR_TOO_MANY_BROADCASTERS?((e===b.JOIN||e===b.REJOIN)&&(this.initError=h,this.close()),h.throw()):"failed"===u.action?h.throw():"quit"===u.action?(this.initError=h,this.close(),h.throw()):(l===R.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,dg.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",eE.MULTI_IP)):this.reconnect(u.action,eE.SERVER_ERROR),e===b.JOIN||e===b.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new sG(i=>{let r=n=>{(!t||t(n))&&(this.off(e,r),i(n))};this.on(e,r)})}upload(e,t){let i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(t){let e=dM.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!==A.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)},dM.UPLOAD_CACHE_INTERVAL||2e3))}}send(e,t){this.websocket.sendMessage({_type:e,_message:t})}init(e,t){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new sG((i,r)=>{this.once(O.WS_CONNECTED,()=>i(this.joinResponse)),this.once(O.WS_CLOSED,()=>r(this.initError||new du(o.WS_ABORT))),this.connectionState=A.CONNECTING,this.websocket.init(e).catch(r),this.websocket.once(em.FAILBACK,()=>{void 0===this.openConnectionTime&&r(new du(o.INIT_DATACHANNEL_TIMEOUT))}),this.inflateDataTimer&&window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=window.setInterval(()=>{this.handleInflateData()},2e4),setTimeout(()=>{t&&void 0===this.openConnectionTime&&(dg.debug("[".concat(this.clientId,"] init datachannel timeout while join with failback to websocket")),r(new du(o.INIT_DATACHANNEL_TIMEOUT)))},dM.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._disconnectedReason=e||C.LEAVE,this.connectionState=A.CLOSED,dg.debug("[".concat(this.clientId,"] ")+"will close datachannel in signal"),this.websocket.close(),e===C.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new pc("gateway-".concat(this.clientId),this.spec.retryConfig,!0,this.store),this.handleWebsocketEvents())}async join(){if(!this.joinResponse){this.emit(O.ABORT_P2P_EXECUTION);let e=await hW(this,O.DATACHANNEL_CONNECTING),t=await this.request(b.JOIN,e);if(!t)return this.emit(O.REPORT_JOIN_GATEWAY,o.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(O.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=A.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new du(o.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");let e=hY(this,O.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;let t=await this.request(b.REJOIN,e);return!!t&&(this.connectionState=A.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEac
1h(e=>{this.emit(w.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(w.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(w.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(w.MUTE_AUDIO,{uid:e.uid}):this.emit(w.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(w.MUTE_VIDEO,{uid:e.uid}):this.emit(w.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(w.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(w.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(w.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(w.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(w.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)}handleNotification(e){dg.debug("[".concat(this.clientId,"] receive notification: "),e);let t=h7(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(C.UID_BANNED),void this.close()):void this.reconnect(t.action,eE.SERVER_ERROR);dg.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=dM.PING_PONG_TIME_OUT,t=Date.now();this.pingpongTimeoutCount>=e&&(dg.warning("PINGPONG Timeout. Last Socket Message: ".concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>dM.WEBSOCKET_TIMEOUT_MIN)?this.reconnect("retry",eE.TIMEOUT):this.request(b.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;let e=Date.now()-t;this.rttRolling.add(e),dM.REPORT_STATS&&this.send(b.PING_BACK,{pingpongElapse:e})}).catch(e=>{})}handleInflateData(){let{inflateLength:e,deflateLength:t}=this.websocket.getInflateData();0!==e&&0!==t&&this.upload(N.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(em.RECONNECT_WAITTING_FINISH,e=>{this.emit(O.WS_RECONNECT_WAITTING_FINISH,e)}),this.websocket.on(em.RECONNECT_CREATE_CONNECTION,e=>{this.emit(O.WS_RECONNECT_CREATE_CONNECTION,e)}),this.websocket.on(em.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(em.CLOSED,()=>{this.connectionState=A.CLOSED}),this.websocket.on(em.FAILED,()=>{this._disconnectedReason=C.NETWORK_ERROR,this.connectionState=A.CLOSED}),this.websocket.on(em.RECONNECTING,e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===A.CONNECTED?this.connectionState=A.RECONNECTING:this.connectionState=A.CONNECTING}),this.websocket.on(em.WILL_RECONNECT,(e,t)=>{if(hY(this,O.IS_P2P_DISCONNECTED)&&"retry"===e)return dg.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit(O.NEED_RENEW_SESSION),this.emit(O.DISCONNECT_P2P),t("tryNext");"retry"!==e&&(dg.debug("".concat(this.clientId," websockt will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0,this.emit(O.NEED_RENEW_SESSION),this.emit(O.DISCONNECT_P2P)),t(e)}),this.websocket.on(em.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch(e=>{dg.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",eE.SERVER_ERROR)}):this.join().catch(e=>{if(this.emit(O.REPORT_JOIN_GATEWAY,e.message||e.code,this.url||""),e instanceof du&&e.code===o.UNEXPECTED_RESPONSE&&e.data.code===R.ERR_NO_AUTHORIZED)return dg.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",eE.SERVER_ERROR);dg.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",eE.SERVER_ERROR):(this.initError=e,this.close())})}),this.websocket.on(em.REQUEST_NEW_URLS,(e,t)=>{hW(this,O.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)}),this.websocket.on(em.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(w.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}),this.websocket.on(em.TO_CONNECT_DATACHANNEL,async(e,t,i)=>
1hW(this,O.DATACHANNEL_PRECONNECT,e).then(t).catch(i)),this.websocket.on(em.FAILBACK,()=>{void 0!==this.openConnectionTime&&this.emit(O.DATACHANNEL_FAILBACK)})}}function pl(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 pu(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?pl(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):pl(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let ph=new Map;class pp extends dd{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(K.CONNECTION_STATE_CHANGE,e,t,this._disconnectedReason):this.emit(K.CONNECTION_STATE_CHANGE,e,t)}get joinGatewayStartTime(){return this._joinGatewayStartTime}set joinGatewayStartTime(e){dg.debug("[".concat(this.store.clientId,"] set joinGatewayStartTime at ").concat(e)),this._joinGatewayStartTime=e}constructor(e,t){super(),cc(this,"store",void 0),cc(this,"joinInfo",void 0),cc(this,"key",void 0),cc(this,"signal",void 0),cc(this,"role",void 0),cc(this,"inChannelInfo",{joinAt:null,duration:0}),cc(this,"spec",void 0),cc(this,"_state","DISCONNECTED"),cc(this,"_statsCollector",void 0),cc(this,"_disconnectedReason",void 0),cc(this,"isSignalRecover",!1),cc(this,"hasChangeBGPAddress",!1),cc(this,"trafficStatsInterval",void 0),cc(this,"networkQualityInterval",void 0),cc(this,"_joinGatewayStartTime",0),cc(this,"_signalTimeout",!1),cc(this,"_clientRoleOptions",void 0),cc(this,"_isProactiveJoin",!1),this.store=e,this.spec=t,this.signal=this.store.useDataChannel?new pd(pu(pu({},t),{},{retryConfig:t.websocketRetryConfig}),e):new pi(pu(pu({},t),{},{retryConfig:t.websocketRetryConfig}),e),this._statsCollector=t.statsCollector,this.role=t.role||"audience",this._clientRoleOptions=t.clientRoleOptions,this.handleSignalEvents()}async join(e,t,i){if(this.signal instanceof pd){let t=!1;"disabled"!==e.cloudProxyServer?(dg.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?(dg.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)||dM.FINGERPRINT||(dg.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=ph.get(e.cname);if(n||(n=new Map,ph.set(e.cname,n)),this._isProactiveJoin=!0,n.has(e.uid)){let t=new du(o.UID_CONFLICT);throw uC.joinGateway(e.sid,{lts:r,succ:!1,ec:t.message,addr:null,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!e.proxyServer,signalChannel:this.signal instanceof pd?"1":"0"}),this._isProactiveJoin=!1,t}n.set(e.uid,!0),this.joinInfo=e,this.key=t;let s=0;this.joinGatewayStartTime=r;let a=e.proxyServer;try{let t;if(dg.debug("[".concat(this.store.clientId,"] use ").concat(this.signal instanceof pd?"datachannel":"websocket"," join uid ").concat(s)),this.signal instanceof pd)t=await this.signal.init(e.apResponse.addresses,i);else{let r=e.proxyServer,n=r?e.gatewayAddrs.map(e=>{let t=e.address.split(":");return"wss://".concat(r,"/ws/?h=").concat(t[0],"&p=").concat(t[1])}):e.gatewayAddrs.map(e=>"wss://".concat(e.address));t=await this.signal.init(n,i)}s=t.uid,dg.debug("[".concat(this.store.clientId,"] ").concat(this.signal instanceof pd?"datachannel":"websocket"," join uid ").concat(s," cost ").concat(Date.now()-this.joinGatewayStartTime))}
1catch(t){if(t&&t.code===o.INIT_WEBSOCKET_TIMEOUT)throw dg.warning("[".concat(this.store.clientId,"] User join failed"),t.toString()),t;if(t&&t.code===o.INIT_DATACHANNEL_TIMEOUT)throw dg.warning("[".concat(this.store.clientId,"] User join datachannel failed"),t.toString()),this.resetSignal(),t;throw dg.error("[".concat(this.store.clientId,"] User join failed"),t.toString()),uC.joinGateway(e.sid,{lts:r,succ:!1,ec:t.message,addr:this.signal.url,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!a,signalChannel:this.signal instanceof pd?"1":"0"}),this._isProactiveJoin=!1,n.delete(e.uid),this.signal.close(),t}return this.state="CONNECTED",this.inChannelInfo.joinAt=Date.now(),dg.debug("[".concat(this.store.clientId,"] Connected to gateway server")),this.trafficStatsInterval=window.setInterval(()=>{this.updateTrafficStats().catch(e=>{dg.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(K.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6}):this._signalTimeout?this.emit(K.NETWORK_QUALITY,{downlinkNetworkQuality:5,uplinkNetworkQuality:5}):"CONNECTED"===this.state&&this._statsCollector.trafficStats?this.emit(K.NETWORK_QUALITY,{uplinkNetworkQuality:hw(this._statsCollector.trafficStats.B_unq),downlinkNetworkQuality:hw(this._statsCollector.trafficStats.B_dnq)}):this.emit(K.NETWORK_QUALITY,{uplinkNetworkQuality:0,downlinkNetworkQuality:0})},2e3),this.store.joinGatewayEnd(),s}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!==C.FALLBACK&&(this.state="DISCONNECTING");try{var i;e||this.signal.connectionState!==A.CONNECTED||await (i=this.signal.request(b.LEAVE,void 0,!0),3e3==1/0?i:sG.race([i,function(e){let t=new du(o.TIMEOUT,"timeout");return new sG((e,i)=>{window.setTimeout(()=>i(t),3e3)})}(3e3)]))}catch(e){dg.warning("[".concat(this.store.clientId,"] leave request failed, ignore"),e)}this.signal.close(t),t!==C.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}}async publish(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new du(o.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:dM.PUB_EXTEND,twcc:!!dM.PUBLISH_TWCC};try{return(await this.signal.request(b.PUBLISH,r,!0))._message}catch(r){if(i&&r.data&&r.data.code===R.ERR_PUBLISH_REQUEST_INVALID)return dg.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 unpublish(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new du(o.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await this.signal.request(b.UNPUBLISH,{stream_id:t,ortc:e},!0)}catch(e){dg.warning("unpublish warning: ",e)}}async subscribe(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new du(o.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:!!dM.SUBSCRIBE_TWCC,extend:dM.SUB_EXTEND,ssrcId:t.ssrcId};try{return(await this.signal.request(b.SUBSCRIBE,r,!0))._message}catch(r){if(i&&r.data&&r.data.code===R.ERR_SUBSCRIBE_REQUEST_INVALID)return dg.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}}async subscribeAll(e,t){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new du(o.INVALID_OPERATION,"can not massSubscribe when connection state is ".concat(this.state));let i={p2p_id:this.store.p2pId,users:e,dtx:!1};try{return await this.signal.request(b.SUBSCRIBE_STREAMS,i,!0)}catch(i){if(t&&i.data&&i.data.code===R.ERR_SUBSCRIBE_REQUEST_INVALID)return dg.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(b.SET_VIDEO_PROFILE,t);dg.debug("[".concat(this.store.clientId,"] encoder config is not complete, do not report to gateway"))}async unsubscribe(e,t){try{await this.signal.request(b.UNSUBSCRIBE,{p2p_id:this.store.p2pId,ortc:e,stream_id:t},!0)}catch(e){dg.warning("unsubscribe warning: ",e)}}async massUnsubscribe(e){try{await this.signal.request(b.UNSUBSCRIBE_STREAMS,e,!0)}catch(e){dg.warning("unsubscribeAll warning: ",e)}}async reconnectPC(e){let{iceParameters:t,dtlsParameters:i,rtpCapabilities:r}=e;return{gatewayEstablishParams:await this.signal.request(b.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(b.GATEWAY_INFO)}renewToken(e){return this.signal.request(b.RENEW_TOKEN,e)}async setClientRole(e,t){let i;if(t&&(this._clientRoleOptions=Object.assign({},t)),"CONNECTED"!==this.state)return void(this.role=e);i="audience"===e?this._clientRoleOptions&&this._clientRoleOptions.level?this._clientRoleOptions.level:2:0,await this.signal.request(b.SET_CLIENT_ROLE,{role:e,level:i,client_ts:Date.now()}),this.role=e}async setRemoteVideoStreamType(e,t){await this.signal.request(b.SWITCH_VIDEO_STREAM,{stream_id:e,stream_type:t})}async setDefaultRemoteVideoStreamType(e){await this.signal.request(b.DEFAULT_VIDEO_STREAM,{stream_type:e})}async setStreamFallbackOption(e,t){await this.signal.request(b.SET_FALLBACK_OPTION,{stream_id:e,fallback_type:t})}async pickSVCLayer(e,t){await this.signal.request(b.PICK_SVC_LAYER,{stream_id:e,spatial_layer:t.spatialL
1ayer,temporal_layer:t.temporalLayer})}getInChannelInfo(){return this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt),pu({},this.inChannelInfo)}async getGatewayVersion(){return(await this.signal.request(b.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=ph.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)}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:dy.username,password:dy.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(pu(pu({},dy),{},{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(b.TRAFFIC_STATS,void 0,!0);e.timestamp=Date.now(),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&&hX(()=>{this.emit(K.STREAM_TYPE_CHANGE,e.peer_uid,e.B_st)})}),this._statsCollector.updateTrafficStats(e)}getJoinMessage(e){if(!this.joinInfo||!this.key)throw new du(o.UNEXPECTED_ERROR,"can not generate join message, no join info");let t=Object.assign({},this.joinInfo.apResponse),i=dM.REPORT_APP_SCENARIO;if("string"!=typeof i)try{i=JSON.stringify(i)}catch(e){i=void 0}i&&i.length>128&&(i=void 0);let r=pu({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:dI,browser:navigator.userAgent,process_id:dM.PROCESS_ID,mode:this.spec.mode,codec:this.spec.codec,role:this.role,has_changed_gateway:this.hasChangeBGPAddress,ap_response:t,extend:dM.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:i,attributes:{userAttributes:{enablePublishedUserList:dM.ENABLE_PUBLISHED_USER_LIST,maxSubscription:dM.MAX_SUBSCRIPTION,subscribeAudioFilterTopN:"number"==typeof dM.SUBSCRIBE_AUDIO_FILTER_TOPN?dM.SUBSCRIBE_AUDIO_FILTER_TOPN:void 0,enablePublishAudioFilter:"boolean"==typeof dM.ENABLE_PUBLISH_AUDIO_FILTER?dM.ENABLE_PUBLISH_AUDIO_FILTER:void 0,enableUserLicenseCheck:"boolean"==typeof dM.ENABLE_USER_LICENSE_CHECK?dM.ENABLE_USER_LICENSE_CHECK:void 0}},join_ts:this.joinGatewayStartTime},e);return this.joinInfo.stringUid&&(r.string_uid=this.joinInfo.stringUid),this.joinInfo.aesmode&&this.joinInfo.aespassword&&(r.aes_mode=this.joinInfo.aesmode,dM.ENCRYPT_AES?(r.aes_secret=this.joinInfo.aespassword,r.aes_encrypt=!0):r.aes_secret=this.joinInfo.aespassword,this.joinInfo.aessalt&&(r.aes_salt=this.joinInfo.aessalt)),t.addresses[this.signal.websocket.currentURLIndex]&&(r.ap_response.ticket=t.addresses[this.signal.websocket.currentURLIndex].ticket,delete t.addresses),void 0!==this.joinInfo.defaultVideoStream&&(r.default_video_stream=this.joinInfo.defaultVideoStream),r}getRejoinMessage(){if(!this.joinInfo)throw new du(o.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(O.WS_RECONNECT_WAITTING_FINISH,e=>{["tryNext","recover"].includes(e)&&this.joinInfo&&uC.adjustSessionStartTime(this.joinInfo.sid)}),this.signal.on(O.WS_RECONNECT_CREATE_CONNECTION,e=>{this.joinGatewayStartTime=Date.now()}),this.signal.on(O.WS_RECONNECTING,e=>{this.joinInfo&&uC.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:e||y.NETWORK_E
1RROR}),this.joinInfo&&(this.state="RECONNECTING",uC.sessionInit(this.joinInfo.sid,{lts:(new Date).getTime(),extend:this.isSignalRecover?{recover:!0}:{rejoin:!0},cname:this.joinInfo.cname,appid:this.joinInfo.appId,mode:this.spec.mode}),this.isSignalRecover=!1,this.joinGatewayStartTime=Date.now())}),this.signal.on(O.WS_CLOSED,e=>{let t;switch(e){case C.LEAVE:t=y.LEAVE;break;case C.UID_BANNED:case C.IP_BANNED:case C.CHANNEL_BANNED:case C.SERVER_ERROR:t=y.SERVER_ERROR;break;case C.FALLBACK:t=y.FALLBACK;break;case C.LICENSE_MISSING:case C.LICENSE_EXPIRED:case C.LICENSE_MINUTES_EXCEEDED:case C.LICENSE_PERIOD_INVALID:case C.LICENSE_MULTIPLE_SDK_SERVICE:case C.LICENSE_ILLEGAL:t=e;break;default:t=y.NETWORK_ERROR}dg.debug("[signal] websocket closed, reason: ".concat(t||"undefined -> "+y.NETWORK_ERROR)),this.joinInfo&&uC.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:e===C.LEAVE?1:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:t}),this._disconnectedReason=e,e!==C.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}),this.signal.on(O.WS_CONNECTED,()=>{if(this.updateTurnConfigFromSignal(),this.state="CONNECTED",this.joinInfo&&("audience"===this.role&&this._clientRoleOptions&&this._clientRoleOptions.level&&(dg.debug("[".concat(this.store.clientId,"] patch to send set client role, role: ").concat(this.role,", mode: ").concat(this.spec.mode,", level: ").concat(this._clientRoleOptions&&this._clientRoleOptions.level)),this.setClientRole(this.role,this._clientRoleOptions)),uC.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,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!this.joinInfo.proxyServer,signalChannel:this.signal instanceof pd?"1":"0"}),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 dg.error("[".concat(this.store.clientId,"] set local access point after joined failed: ").concat(e));dk("EVENT_REPORT_DOMAIN",e[1]),dk("EVENT_REPORT_BACKUP_DOMAIN",e[1]),dk("LOG_UPLOAD_SERVER","".concat(e[1],":6444"))}}),this.signal.on(w.ON_UPLINK_STATS,e=>{this._statsCollector.updateUplinkStats(e)}),this.signal.on(O.REQUEST_RECOVER,(e,t,i)=>{if(!this.joinInfo)return i(new du(o.UNEXPECTED_ERROR,"gateway: can not recover, no join info"));e&&(this.joinInfo.multiIP=e,this.hasChangeBGPAddress=!0),this.isSignalRecover=!0,hW(this,K.REQUEST_NEW_GATEWAY_LIST).then(t).catch(i)}),this.signal.on(O.REQUEST_JOIN_INFO,async e=>{var t;this.updateTurnConfigFromSignal();let{iceParameters:i,dtlsParameters:r,rtpCapabilities:n}=await hW(this,K.REQUEST_P2P_CONNECTION_PARAMS,{turnServer:null==(t=this.joinInfo)?void 0:t.turnServer});e(this.getJoinMessage({ortc:{iceParameters:i,dtlsParameters:r,rtpCapabilities:n,version:"2"}}))}),this.signal.on(O.REQUEST_REJOIN_INFO,e=>{e(this.getRejoinMessage())}),this.signal.on(O.REPORT_JOIN_GATEWAY,(e,t)=>{this.joinInfo&&(uC.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!1,ec:e,addr:t,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!this.joinInfo.proxyServer,signalChannel:this.signal instanceof pd?"1":"0"}),this._isProactiveJoin=!1)}),this.signal.on(O.IS_P2P_DISCONNECTED,e=>{e(hY(this,K.IS_P2P_DISCONNECTED))}),this.signal.on(O.DISCONNECT_P2P,()=>{this.emit(K.DISCONNECT_P2P)}),this.signal.on(O.NEED_RENEW_SESSION,()=>{this.emit(K.NEED_RENEW_SESSION)}),this.signal.on(O.REQUEST_SUCCESS,()=>{this._signalTimeout=!1}),this.signal.on(O.REQUEST_TIMEOUT,()=>{this._signalTimeout=!0}),this.signal.on(O.JOIN_RESPONSE,e=>{let t=this.getCurrentGatewayAddress();this.emit(K.JOIN_RESPONSE,e,t)}),this.signal.on(O.DATACHANNEL_PRECONNECT,async(e,t,i)=>{this.updateTurnConfigFromSignal();let r=this.getCurrentGatewayAddress();return hW(this,K.DATACHANNEL_PRECONNECT,e,r).then(t).catch(i)}),this.signal.on(O.DATACHANNEL_CONNECTING,async e=>{let{iceParameters:t,dtlsParameters:i,rtpCapabilities:r}=await hW(this,K.REQUEST_DC_CONNECTION_PARAMS);e(this.getJoinMessage({ortc:{iceParameters:t,dtlsParameters:i,rtpCapabilities:r,version:"2"}}))}),this.signal.on(O.DATACHANNEL_FAILBACK,()=>{dg.warning("[".concat(this.store.clientId,"] User join datachannel failed")),this.reset(),this.resetSignal(),this.emit
1(K.DATACHANNEL_FAILBACK)})}async tryUnsubBeforeResub(e,t){try{await this.signal.request(b.UNSUBSCRIBE,{p2p_id:this.store.p2pId,stream_id:e,ortc:[t]},!0)}catch(e){throw dg.warning("unsubscribe warning",e),e}}async tryUnpubBeforeRepub(e,t){try{await this.signal.request(b.UNPUBLISH,{stream_id:e,ortc:t},!0)}catch(e){throw dg.warning("unpublish 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(b.UNSUBSCRIBE_STREAMS,t,!0)}catch(e){throw dg.warning("massUnsubscribe warning",e),e}}async muteLocal(e,t){let i={action:e.find(e=>e.stream_type===H.Audio)?"mute_local_audio":"mute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(b.CONTROL,i,!0,!0)}catch(e){throw dg.warning("gateway unmuteLocal warning: ",e),e}}async unmuteLocal(e,t){let i={action:e.find(e=>e.stream_type===H.Audio)?"unmute_local_audio":"unmute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(b.CONTROL,i,!0,!0)}catch(e){throw dg.warning("gateway muteLocal warning: ",e),e}}uploadStats(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(b.RESTART_ICE,t,!0)}catch(e){throw dg.warning("P2PChannel.restartICE warning: ",e),e}}reconnect(){"CONNECTED"===this.state&&this.signal.reconnect(void 0,y.P2P_FAILED)}getCurrentGatewayAddress(){var e;if(!dM.GATEWAY_WSS_ADDRESS)return null!=(e=this.joinInfo)&&e.gatewayAddrs?this.joinInfo.gatewayAddrs[this.signal.currentURLIndex]:void 0}async setPublishAudioFilterEnabled(e){await this.signal.request(b.SET_PARAMETER,{enablePublishAudioFilter:e})}resetSignal(){this.signal&&(this.signal.removeAllListeners(),this.signal.close(C.FALLBACK)),this.store.useDataChannel=!1,this.signal=new pi(pu(pu({},this.spec),{},{retryConfig:this.spec.websocketRetryConfig}),this.store),this.handleSignalEvents(),this.emit(K.RESET_SIGNAL,q.websocket)}}!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 tm&&tm];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 s(e,t){if(t)e:{var i=o;e=e.split(".");for(var r=0;r<e.length-1;r++){var s=e[r];if(!(s in i))break e;i=i[s]}(t=t(r=i[e=e[e.length-1]]))!=r&&null!=t&&n(i,e,{configurable:!0,writable:!0,value:t})}}function a(t){var i="undefined"!=typeof Symbol&&Symbol.iterator&&t[Symbol.iterator];return i?i.call(t):{next:e(t)}}if(s("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)}}),s("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 s=o[i[r]];"function"==typeof s&&"function"!=typeof s.prototype[t]&&n(s.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 u(e){if(e.m)throw TypeError("Generator is already running");e.m=!0}function h(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 u(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 u(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 u(this.g),this.g.j?_(this,this.g.j.throw,e,this.g.o):(this.g.s(e),E(this))},s("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])},T=function(e){return e.replace(/\r?\n|\r/g,"\r\n")},g=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.")},I="object"==typeof globalThis?globalThis:"object"==typeof window?window:"object"==typeof self?self:this,C=I.FormData,v=I.XMLHttpRequest&&I.XMLHttpRequest.prototype.send,y=I.Request&&I.fetch,A=I.navigator&&I.navigator.sendBeacon,O=I.Element&&I.Element.prototype,b=I.Symbol&&Symbol.toStringTag;b&&(Blob.prototype[b]||(Blob.prototype[b]="Blob"),"File"in I&&!File.prototype[b]&&(File.prototype[b]="File"));try{new File([],"")}catch(e){I.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]"}}}),b&&Object.defineProperty(e,b,{value:"File"}),e}}var N=function(e){return e.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22")},w=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?T(e.value):e.value,t.append(e.name,i))})};if((i=w.prototype).append=function(e,t,i){R(arguments,2),this.i.push(g(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=h(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=a(this),r=i.next();!r.done;r=i.next()){var n=a(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=a(r)).next()),3!=e.h)return i.done?void(e.h=0):h(e,a(i.value).next().value);i=t.next(),e.h=2})},i.set=function(e,t,i){R(arguments,2);var r=[],n=g(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=a(n)).next()),3!=e.h)return i.done?void(e.h=0):((r=a(i.value)).next(),h(e,r.next().value));i=t.next(),e.h=2})},w.prototype._asNative=function(){for(var e=new C,t=a(this),i=t.next();!i.done;i=t.next()){var r=a(i.value);i=r.next().value,r=r.next().value,e.append(i,r)}return e},w.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+N(T(r))+'"\r\n\r\n'+T(e)+"\r\n"):t.push(i+N(T(r))+'"; filename="'+N(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})},w.prototype[Symbol.iterator]=function(){return this.entries()},w.prototype.toString=function(){return"[object FormData]"},O&&!O.matches&&(O.matches=O.matchesSelector||O.mozMatchesSelector||O.msMatchesSelector||O.oMatchesSelector||O.webkitMatchesSelector||function(e){for(var t=(e=(this.document||this.ownerDocument).querySelectorAll(e)).length;0<=--t&&e.item(t)!==this;);return -1<t}),b&&(w.prototype[b]="FormData"),v){var D=I.XMLHttpRequest.prototype.setRequestHeader;I.XMLHttpRequest.prototype.setRequestHeader=function(e,t){D.call(this,e,t),"content-type"===e.toLowerCase()&&(this.B=!0)},I.XMLHttpRequest.prototype.send=function(e){e instanceof w&&(e=e._blob(),this.B||this.setRequestHeader("Content-Type",e.type)),v.call(this,e)}}y&&(I.fetch=function(e,t){return t&&t.body&&t.body instanceof w&&(t.body=t.body._blob()),y.call(this,e,t)}),A&&(I.navigator.sendBeacon=function(e,t){return t instanceof w&&(t=t._asNative()),A.call(this,e,t)}),I.FormData=w}}();let p_=()=>{let e=dM.AREAS;return 0===e.length&&e.push(ee.GLOBAL),rs(e).call(e,(e,t,i)=>{let r=pE(t);return r?0===i?r:"".concat(e,",").concat(r):e},"")},pE=e=>e===ee.OVERSEA?"".concat(et.ASIA,",").concat(et.EUROPE,",").concat(et.AFRICA,",").concat(et.NORTH_AMERICA,",").concat(et.SOUTH_AMERICA,",").concat(et.OCEANIA):et[e],pm=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=lk[e],r=Object.keys(i);r&&r.map(e=>{"CODE"!==e&&(t[e]=t[e].concat(i[e]))})}),t},pf={GLOBAL:{ASIA:[ee.CHINA,ee.JAPAN,ee.INDIA,ee.KOREA,ee.HKMC],EUROPE:[],NORTH_AMERICA:[ee.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}},pS=Object.keys(pf[ee.GLOBAL]),pT=[ee.CHINA,ee.NORTH_AMERICA,ee.EUROPE,ee.ASIA,ee.JAPAN,ee.INDIA,ee.OCEANIA,ee.SOUTH_AMERICA,ee.AFRICA,ee.KOREA,ee.HKMC,ee.US],pg=function(e,t){let i=[];if(e.includes(ee.GLOBAL)){let r=[ee.GLOBAL,ee.OVERSEA],n=Object.keys(lk);if(t===ee.GLOBAL)throw new du(o.INVALID_PARAMS,"GLOBAL is an invalid excludedArea value");if(t===ee.CHINA)i=[ee.OVERSEA];else if(pS.includes(t)){let e=pf[ee.GLOBAL][t]||[],o=[...r,t,...e];i=n.filter(e=>!o.includes(e))}else{let o;if(o=!1,pS.forEach(e=>{pf[ee.GLOBAL][e].includes(t)&&(o=!0)}),o){let e,o=[...r,(pS.forEach(i=>{pf[ee.GLOBAL][i].includes(t)&&(e=i)}),e),t];i=n.filter(e=>!o.includes(e))}else i=e}i=function(e){let t=[];return pT.forEach(i=>{e.includes(i)&&t.push(i)}),t.concat(e.filter(e=>!pT.includes(e)))}(i)}else i=e;return i};function pR(e){if(!e&&dM.AREAS.includes(ee.EXTENSIONS))return dg.debug("update area from ap : reset"),void pI(dv,!0);if(!dM.AREAS.includes(ee.GLOBAL)||!e)return;let t=lk.EXTENSIONS;t&&(t={CODE:pE(ee.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")]},dg.debug("update area from ap success: ".concat(e,",config is "),t),dk("AREAS",[ee.EXTENSIONS],!0),Ob
1ject.keys(t).map(e=>{"LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e?dk(e,t[e][0]):dk(e,t[e])}))}function pI(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=uC.reportApiInvoke(null,{name:p.SET_AREA,options:e,tag:_.TRACER});try{let r=[];if("string"==typeof e&&(r=[e]),Array.isArray(e)&&(e.forEach(e=>{if(!lL.includes(e))throw new du(o.INVALID_PARAMS,"invalid area code")}),r=e),"[object Object]"===Object.prototype.toString.call(e)){let{areaCode:t,excludedArea:i}=e;if(!t)throw new du(o.INVALID_PARAMS,"area code is needed");let n=t;"string"==typeof t&&(n=[t]),r=i?pg(n,i):n}if(!t){if(dU.AREAS){let e=new du(o.PROHIBITED_OPERATION,"setArea is prohibited because of config-distribute");return i.onError(e),void dg.warning("setArea is prohibited because of config-distribute")}if(r.includes(ee.GLOBAL)&&dM.AREAS===ee.EXTENSIONS){let e=new du(o.PROHIBITED_OPERATION,"setArea is prohibited because of ap extensions");return i.onError(e),void dg.warning("setArea is prohibited because of ap extensions")}}dk("AREAS",r,t);let n=pm(r);Object.keys(n).map(e=>{"LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e?dk(e,n[e][0]):dk(e,n[e])}),dg.debug("set area success:",r.join(","))}catch(e){throw i.onError(e),e}i.onSuccess()}function pC(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 pv(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?pC(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):pC(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let py=1,pA=1;function pO(e,t,i,r){let n,{url:s,areaCode:a}=e,c=Date.now(),[d,l]=pP(t,a,[ef.CHOOSE_SERVER]),u=up.networkState;return d_(async()=>{u&&up.networkState===ec.OFFLINE&&up.onlineWaiter&&await sG.race([up.onlineWaiter,hx(r&&r.maxRetryTimeout||dh.maxRetryTimeout)]),u=up.networkState;let{data:e,headers:o}=await uu(s,{data:d,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);n="1"===o.http3?1:-1,uC.reportResourceTiming(s,t.sid),pN(e,s,t,c,[ef.CHOOSE_SERVER],n);let a=hD(e,ef.CHOOSE_SERVER);return pw(a),hA(a,s)},e=>(e&&uC.joinChooseServer(t.sid,{lts:c,succ:!0,csAddr:s,opid:l,serverList:e.gatewayAddrs.map(e=>e.address),ec:null,cid:e.cid.toString(),uid:e.uid.toString(),csIp:e.csIp,unilbsServerIds:[ef.CHOOSE_SERVER].toString(),isHttp3:n}),!1),e=>e.code!==o.OPERATION_ABORTED&&(e.code===o.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(uC.joinChooseServer(t.sid,{lts:c,succ:!1,csAddr:s,serverList:null,opid:l,ec:e.code,csIp:e.data&&e.data.csIp,unilbsServerIds:[ef.CHOOSE_SERVER].toString(),extend:JSON.stringify({networkState:u}),isHttp3:n}),dg.warning("[".concat(t.clientId,"] Choose server network error, retry"),e),!0)),r)}function pb(e,t,i,r){let n,s,{url:a,areaCode:c,serviceIds:d}=e,l=Date.now(),[u,h]=pP(t,c,d);return d_(async()=>{n&&up.networkState===ec.OFFLINE&&up.onlineWaiter&&await sG.race([up.onlineWaiter,hx(r&&r.maxRetryTimeout||dh.maxRetryTimeout)]),n=up.networkState;let{data:e,headers:o}=await uu(a,{data:u,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);s="1"===o.http3?1:-1,uC.reportResourceTiming(a,t.sid),pN(e,a,t,l,d,s);let c=hD(e,ef.CHOOSE_SERVER),h=hD(e,"proxy5"===t.cloudProxyServer?ef.CLOUD_PROXY_5:"proxy3"===t.cloudProxyServer||"proxy4"===t.cloudProxyServer?ef.CLOUD_PROXY:ef.CLOUD_PROXY_FALLBACK);return pw(c),{gatewayInfo:hA(c,a),proxyInfo:h,url:a}},e=>(e.gatewayInfo&&uC.joinChooseServer(t.sid,{lts:l,succ:!0,csAddr:a,serverList:e.gatewayInfo.gatewayAddrs.map(e=>e.address),ec:null,opid:h,cid:e.gatewayInfo.cid.toString(),uid:e.gatewayInfo.uid.toString(),csIp:e.gatewayInfo.csIp,unilbsServerIds:d.toString(),isHttp3:s}),e.proxyInfo&&uC.joinWebProxyAP(t.sid,{lts:l,sucess:1,apServerAddr:a,turnServerAddrList:e.proxyInfo.addresses.map(e=>e.ip).join(","),errorCode:null,eventType:t.cloudProxyServer,unilbsServerIds:d.toString()}),!1),e=>e.code!==o.OPERATION_ABORTED&&(e.code===o.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(uC.joinWebProxyAP(t.sid,{lts:l,sucess:0,apServerAddr:a,turnServerAddrList:null,errorCode:e.code,eventType:t.cloudProxyServer,unilbsServerIds:d.toString(),extend:JSON.stringify({networkState:n})}),dg.warning("[".concat(t.clientId,"] multi unilbs network error, retry"),e),!0)),r)}let pN=(e,t,i,r,n,s)=>{let a=[],c=o=>{4096===o.flag?uC.joinChooseServer(i.sid,{lts:r,succ:!1,csAddr:t,opid:e.opid,serverList:null,ec:o.error.message,csIp:o.error.data&&o.error.data.csIp,unilbsServerIds:n.toString(),isHttp3:s}
1):1048576!==o.flag&&4194304!==o.flag&&4194310!==o.flag||uC.joinWebProxyAP(i.sid,{lts:r,sucess:0,apServerAddr:t,turnServerAddrList:null,errorCode:o.error.code,eventType:i.cloudProxyServer,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)dg.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 du(o.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:!0,csIp:e.detail[502]}),flag:t.buffer.flag};a.push(i),c(i)}if(0!==i){let r=h6(i),n={error:new du(o.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?dg.warning(n.error.toString()):a.push(n),c(n)}}),a.length)throw dg.warning("[".concat(i.clientId,"] multi unilbs ").concat(t," failed, ").concat(a.map(e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message,", retry: ").concat(e.error.data.retry)).join(" | "))),new du(o.CAN_NOT_GET_GATEWAY_SERVER,a.map(e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message)).join(" | "),{retry:!!a.find(e=>e.error.data.retry),csIp:e.detail[502],desc:[...new Set(a.map(e=>{var t,i;return null==e||null==(t=e.error)||null==(i=t.data)?void 0:i.desc}).filter(e=>!!e))]})},pw=e=>{var t,i,r,n,s;if(e.addresses&&0===e.addresses.length&&0===e.code)throw new du(o.CAN_NOT_GET_GATEWAY_SERVER,"void gateway address",{retry:!0,csIp:e.detail&&e.detail[502]});if(null!=(t=e.detail)&&t[23]&&"string"==typeof(null==(i=e.detail)?void 0:i[23])?pR(e.detail[23].toLowerCase()):pR(),null!=(r=e.detail)&&r[19]&&"string"==typeof(null==(n=e.detail)?void 0:n[19])){let t=e.detail[19],i=null==t?void 0:t.split(";");for(let t=0;t<i.length;t++){let r=ab(s=i[t]).call(s);e.addresses[t]&&i&&(e.addresses[t].fingerprint=r)}}if(dM.GATEWAY_ADDRESS&&dM.GATEWAY_ADDRESS.length>0){dg.debug("assign gateway address to",dM.GATEWAY_ADDRESS);let t=dM.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:n}});e.addresses=t}},pD=(e,t)=>{if(e.response_body&&e.response_body.length){let t=e.response_body[0];if(0!==t.buffer.code){let e=h6(t.buffer.code);throw new du(o.UPDATE_TICKET_FAILED,"[".concat(t.buffer.code,"]: ").concat(e.desc),{retry:e.retry})}return t.buffer.ticket}throw dg.debug("update ticket request received ap response without response body:",t),new du(o.UPDATE_TICKET_FAILED,"cannot find response body from ap response",{retry:!1})},pP=(e,t,i)=>{let r=Math.floor(1e12*Math.random()),n={appid:e.appId,client_ts:Date.now(),opid:r,sid:e.sid,request_bodies:[{uri:22,buffer:{cname:e.cname,detail:{6:e.stringUid,11:t,12:dM.USE_NEW_TOKEN?"1":void 0,22:t},key:e.token,service_ids:i,uid:e.uid||0}}]};n.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 o=new FormData;return o.append("request",JSON.stringify(n)),[o,r]},pL=(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]},pk=0;async function pM(e,t,i,r){let n=async function(e,t,i,r){let n=null,o=[],s=async()=>{let n=dM.WEBCS_DOMAIN.slice(0,dM.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:p_()})),s=r.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:n.map(e=>e.url)}),a=await h3({fragementLength:dM.FRAGEMENT_LENGTH,referenceList:n,asyncMapHandler:r=>(dg.debug("[".concat(e.clientId,"] Connect to choose_server:"),r.url),pO(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),a},a=async()=>
1{if(await hx(1e3),null!==n)return n;let s=dM.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:p_()})),a=r.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:s.map(e=>e.url)}),c=await h3({fragementLength:dM.FRAGEMENT_LENGTH,referenceList:s,asyncMapHandler:r=>(dg.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),r.url),pO(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),c};try{return n=await hG([s(),a()]),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 pU(e,t,i,r,n){let o=e.cloudProxyServer;if("disabled"===o){if(!r)return;if(e.useLocalAccessPoint)return await pM(e,t,i,n);if(dM.JOIN_WITH_FALLBACK_MEDIA_PROXY){let{gatewayInfo:r,proxyInfo:o}=await pF(e,t,i,n);return e.turnServer&&"auto"!==e.turnServer.mode||(e.turnServer={mode:"manual",servers:o.map(e=>({turnServerURL:e.address,tcpport:e.tcpport||dy.tcpport,udpport:e.udpport||dy.udpport,username:e.username||dy.username,password:e.password||dy.password,forceturn:!1,security:!0}))}),{gatewayInfo:r}}return await pM(e,t,i,n)}let{proxyInfo:s,gatewayInfo:a}=await pF(e,t,i,n);return e.turnServer={mode:"manual",servers:s.map(e=>({turnServerURL:e.address,tcpport:"proxy3"===o?void 0:e.tcpport?e.tcpport:dy.tcpport,udpport:"proxy4"===o?void 0:e.udpport?e.udpport:dy.udpport,username:e.username||dy.username,password:e.password||dy.password,forceturn:"proxy4"!==o,security:"proxy5"===o}))},dg.debug("[".concat(e.clientId,"] set proxy server: ").concat(e.proxyServer,", mode: ").concat(o)),{gatewayInfo:a}}async function px(e,t,i,r,n){let s=dM.ACCOUNT_REGISTER.slice(0,dM.AJAX_REQUEST_CONCURRENT),a=[];a=t.proxyServer?s.map(e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1")):s.map(e=>"https://".concat(e,"/api/v1"));let c=null==n?void 0:n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"stringUID",urls:a});try{let s=await async function(e,t,i,r,n){let s=Date.now(),a={sid:i.sid,opid:10,appid:i.appId,string_uid:t},c=e[0],d=await d_(()=>uu(c+"".concat(-1===c.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 dg.error("Invalid Uint Uid ".concat(t," => ").concat(i.uid),i),uC.reqUserAccount(a.sid,{lts:s,success:!1,serverAddr:c,stringUid:a.string_uid,uid:i.uid,errorCode:o.INVALID_UINT_UID_FROM_STRING_UID,extend:a}),new du(o.INVALID_UINT_UID_FROM_STRING_UID);return uC.reqUserAccount(a.sid,{lts:s,success:!0,serverAddr:c,stringUid:a.string_uid,uid:i.uid,errorCode:null,extend:a}),!1}let n=h6(i.code);return n.retry&&(c=e[(r+1)%e.length]),uC.reqUserAccount(a.sid,{lts:s,success:!1,serverAddr:c,stringUid:a.string_uid,uid:i.uid,errorCode:n.desc,extend:a}),n.retry},(t,i)=>t.code!==o.OPERATION_ABORTED&&(uC.reqUserAccount(a.sid,{lts:s,success:!1,serverAddr:c,stringUid:a.string_uid,uid:null,errorCode:t.code,extend:a}),c=e[(i+1)%e.length],!0),n);if(0!==d.code){let e=h6(d.code);throw new du(o.UNEXPECTED_RESPONSE,e.desc)}return d}(a,e,t,i,r);return null==n||n.recordJoinChannelService({status:"success",endTs:Date.now()},c),s.uid}catch(e){throw null==n||n.recordJoinChannelService({status:"error",endTs:Date.now(),errors:[e]},c),e}}async function pV(e,t,i){let r=dM.CDS_AP.slice(0,dM.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=aY(),s={flag:64,cipher_method:0,features:{device:n.name,system:n.os,system_general:navigator.userAgent,vendor:t.appId,version:dI,cname:t.cname,sid:t.sid,session_id:t.sid,detail:"",proxyServer:t.proxyServer}};return d_(()=>uu(e,{data:s,timeout:1e3,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":54}}),void 0,e=>e.code!==o.OPERATION_ABORTED,r)})(r,e,t,i)),n=null,s=null,a={};try{n=await hG(r)}catch(e){if(e.code===o.OPERATION_ABORTED)throw e;s=e}
1if(r.forEach(e=>e.cancel()),uC.reportApiInvoke(e.sid,{name:p.REQUEST_CONFIG_DISTRIBUTE,options:{error:s,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=ab(i=e.slice(4)).call(i),o=JSON.parse(t[e])[1];r[n]=o}),r}(n)}catch(e){}return a}async function pF(e,t,i,r){let n,s,a,c=dM.PROXY_SERVER_TYPE3,d=(e,t,i)=>{let r=i||c;return Array.isArray(r)&&(r=t%2==0?c[1]:c[0]),"https://".concat(r,"/ap/?url=").concat(e)},l=null,u=[],h=async()=>{let n=dM.WEBCS_DOMAIN.slice(0,dM.AJAX_REQUEST_CONCURRENT).map((t,i)=>({url:"disabled"===e.cloudProxyServer&&e.proxyServer?d("".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"):d("".concat(t,"/api/v2/transpond/webrtc?v=2"),i),areaCode:p_(),serviceIds:[ef.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?ef.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?ef.CLOUD_PROXY:ef.CLOUD_PROXY_FALLBACK]})),o=r.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:n.map(e=>e.url)}),s=await h3({fragementLength:dM.FRAGEMENT_LENGTH,referenceList:n,asyncMapHandler:r=>(dg.debug("[".concat(e.clientId,"] Connect to choose_server:"),r.url),pb(r,e,t,i)),allFailedhandler:e=>{throw r.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},o),e[0]},promisesCollector:u});return r.recordJoinChannelService({endTs:Date.now(),status:"success"},o),s},p=async()=>{if(await hx(1e3),null!==l)return l;let n=dM.WEBCS_DOMAIN_BACKUP_LIST.map((t,i)=>({url:"disabled"===e.cloudProxyServer&&e.proxyServer?d("".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"):d("".concat(t,"/api/v2/transpond/webrtc?v=2"),i),areaCode:p_(),serviceIds:[ef.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?ef.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?ef.CLOUD_PROXY:ef.CLOUD_PROXY_FALLBACK]})),o=r.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:n.map(e=>e.url)}),s=await h3({fragementLength:dM.FRAGEMENT_LENGTH,referenceList:n,asyncMapHandler:r=>(dg.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),r.url),pb(r,e,t,i)),allFailedhandler:e=>{throw r.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},o),e[0]},promisesCollector:u});return r.recordJoinChannelService({endTs:Date.now(),status:"success"},o),s};try{({gatewayInfo:n,proxyInfo:s,url:a}=await hG([h(),p()]))}catch(e){throw e[0]}if(u.length&&u.forEach(e=>e.cancel&&"function"==typeof e.cancel&&e.cancel()),!n||!s)throw new du(o.UNEXPECTED_ERROR,"missing gateway or proxy response").print();if(e.apUrl=a,"disabled"!==e.cloudProxyServer&&Array.isArray(c)&&a){let t=/^https?:\/\/(.+?)(\/.*)?$/.exec(a)[1];c.includes(t)&&(e.proxyServer=t,dg.setProxyServer(t),uC.setProxyServer(t))}return l={gatewayInfo:n,proxyInfo:await hP(s,n.uid)}}async function pj(e,t,i,r){let n=dM.UAP_AP.slice(0,dM.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){py+=1;let s={service_name:t,json_body:JSON.stringify({sid:i.sid,command:"convergeAllocateEdge",uid:"666",appId:i.appId,ts:Math.floor(Date.now()/1e3),seq:py,requestId:py,version:dI,cname:i.cname})},a,c,d=e[0];return d_(async()=>{a=Date.now();let e=await uu(d,{data:s,cancelToken:r,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"}});if(c=Date.now()-a,0!==e.code){let t=new du(o.UNEXPECTED_RESPONSE,"live streaming ap error, code"+e.code,{retry:!0,responseTime:c});throw dg.error(t.toString()),t}let i=JSON.parse(e.json_body);if(200!==i.code){let e=new du(o.UNEXPECTED_RESPONSE,"live streaming app center error, code: ".concat(i.code,", reason: ").concat(i.reason),{code:i.code,responseTime:c});throw dg.error(e.toString()),e}if(!i.servers||0===i.servers.length){let e=new du(o.UNEXPECTED_RESPONSE,"live streaming app center empty server",{c
1ode:i.code,responseTime:c});throw dg.error(e.toString()),e}let n={addressList:i.servers.map(e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(dM.WORKER_DOMAIN,":").concat(e.wss,"?serviceName=").concat(encodeURIComponent(t))),workerToken:i.workerToken,vid:i.vid};return dM.LIVE_STREAMING_ADDRESS&&(n.addressList=dM.LIVE_STREAMING_ADDRESS instanceof Array?dM.LIVE_STREAMING_ADDRESS:[dM.LIVE_STREAMING_ADDRESS]),pv(pv({},n),{},{responseTime:c})},(r,n)=>(uC.apworkerEvent(i.sid,{success:!0,sc:200,serviceName:t,responseDetail:JSON.stringify(r.addressList),firstSuccess:0===n,responseTime:c,serverIp:e[n%e.length]}),!1),(r,n)=>(uC.apworkerEvent(i.sid,{success:!1,sc:r.data&&r.data.code||200,serviceName:t,responseTime:c,serverIp:e[n%e.length]}),!!(r.code!==o.OPERATION_ABORTED&&r.code!==o.UNEXPECTED_RESPONSE||r.data&&r.data.retry)&&(d=e[(n+1)%e.length],!0)),n)}(n,e,t,i,r)}async function pB(e,t,i){let r=dM.UAP_AP.slice(0,dM.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:dI,cname:t.cname,uid:t.uid.toString(),requestId:pA,seq:pA};pA+=1;let s={service_name:"tele_channel",json_body:JSON.stringify(n)};return d_(async()=>{let t=await uu(e,{data:s,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":61}});if(0!==t.code){let e=new du(o.UNEXPECTED_RESPONSE,"cross channel ap error, code"+t.code,{retry:!0});throw dg.error(e.toString()),e}let r=JSON.parse(t.json_body);if(200!==r.code){let e=new du(o.UNEXPECTED_RESPONSE,"cross channel app center error, code: ".concat(r.code,", reason: ").concat(r.reason));throw dg.error(e.toString()),e}if(!r.servers||0===r.servers.length){let e=new du(o.UNEXPECTED_RESPONSE,"cross channel app center empty server");throw dg.error(e.toString()),e}return{vid:r.vid,workerToken:r.workerToken,addressList:(dM.CHANNEL_MEDIA_RELAY_SERVERS||r.servers).map(e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(dM.WORKER_DOMAIN,":").concat(e.wss))}},void 0,e=>!!(e.code!==o.OPERATION_ABORTED&&e.code!==o.UNEXPECTED_RESPONSE||e.data&&e.data.retry),r)})(r,e,t,i));try{let e=await hG(r);return r.forEach(e=>e.cancel()),e}catch(e){throw e[0]}}async function pG(e,t,i){let r=null,n=[],s=async s=>{let a=dM[s?"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 s&&(await hx(1e3),null!==r)?r:await h3({fragementLength:dM.FRAGEMENT_LENGTH,referenceList:a,asyncMapHandler:r=>(dg.debug("[".concat(e.clientId,"] update ticket, Connect to ").concat(s?"backup":""," choose_server:"),r),function(e,t,i,r){let[n]=pL(t,[ef.CHOOSE_SERVER]),s=up.networkState;return d_(async()=>(s&&up.networkState===ec.OFFLINE&&up.onlineWaiter&&await sG.race([up.onlineWaiter,hx(r&&r.maxRetryTimeout||dh.maxRetryTimeout)]),s=up.networkState,pD(await uu(e,{data:n,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0),e)),()=>!1,e=>e.code!==o.OPERATION_ABORTED&&(e.code===o.UPDATE_TICKET_FAILED?e.data.retry:(dg.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 hG([s(!1),s(!0)]),n.length&&n.forEach(e=>e.cancel&&"function"==typeof e.cancel&&e.cancel()),r}catch(e){throw e[0]}}function pW(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 pH(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?pW(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):pW(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}class pK extends dd{constructor(){super(),cc(this,"configs",void 0),cc(this,"joinInfo",void 0),cc(this,"cancelToken",void 0),cc(this,"retryConfig",{timeout:3e3,timeoutFactor:1.5,maxRetryCount:1,maxRetryTimeout:1e4}),cc(this,"interval",void 0),cc(this,"mutex",new uO("config-distribute")),cc(this,"mutableParamsRead",!1)}startGetConfigDistribute(e,t){this.joinInfo=e,this.cancelToken=t,this.interval&&this.stopGetConfigDistribute(),dM.ENABLE_CONFIG_DISTRIBUTE&&
1(this.updateConfigDistribute(),this.interval=window.setInterval(()=>{this.updateConfigDistribute()},dM.CONFIG_DISTRIBUTE_INTERVAL))}stopGetConfigDistribute(){this.interval&&clearInterval(this.interval),this.interval=void 0,this.joinInfo=void 0,this.cancelToken=void 0}async awaitConfigDistributeComplete(){this.mutex.isLocked&&(await this.mutex.lock())()}async updateConfigDistribute(){let e;if(this.mutableParamsRead||(this.mutableParamsRead=!0,uC.reportApiInvoke(null,{options:void 0,name:p.LOAD_CONFIG_FROM_LOCALSTORAGE,tag:_.TRACER}).onSuccess(JSON.stringify(dU))),!this.joinInfo||!this.cancelToken||!this.retryConfig)return void dg.debug("[config-distribute] get config distribute interrupted have no joininfo");let t=await this.mutex.lock();try{e=await pV(this.joinInfo,this.cancelToken,this.retryConfig),dg.debug("[config-distribute] get config distribute",JSON.stringify(e)),e.limit_bitrate&&this.handleBitrateLimit(e.limit_bitrate),this.cacheGlobalParameterConfig(e),this.configs=e}catch(t){let e=new du(o.NETWORK_RESPONSE_ERROR,t);dg.warning("[config-distribute] ".concat(e.toString()))}finally{t()}}getBitrateLimit(){return this.configs?this.configs.limit_bitrate:void 0}handleBitrateLimit(e){e&&e.uplink&&e.id&&void 0!==e.uplink.max_bitrate&&void 0!==e.uplink.min_bitrate&&(this.configs&&this.configs.limit_bitrate?this.configs&&this.configs.limit_bitrate&&this.configs.limit_bitrate.id!==e.id&&this.emit(ei.UPDATE_BITRATE_LIMIT,e):this.emit(ei.UPDATE_BITRATE_LIMIT,e))}getLowStreamConfigDistribute(){return this.configs&&this.configs.limit_bitrate&&pH({},this.configs.limit_bitrate.low_stream_uplink)}cacheGlobalParameterConfig(e){var t;let i=lr(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];if("number"==typeof e[t].__priority){let n=e[t].__priority,o=i[r-1];if("number"==typeof e[o].__priority){if(!(n>e[o].__priority))continue;i[r]=i[r-1],i[r-1]=t}else i[r]=i[r-1],i[r-1]=t}}let r={};i.forEach(t=>{let i=e[t],n=i.__expires;
1Object.keys(i).forEach(e=>{"__priority"===e||"__expires"===e||Object.prototype.hasOwnProperty.call(r,e)||(r[e]=pH({value:i[e]},n&&{expires:n}))})});try{let e=JSON.stringify(r),t=window.btoa(e);window.localStorage.setItem("websdk_ng_global_parameter",t),dg.debug("Caching global parameters ".concat(e))}catch(e){dg.error("Error caching global parameters:",e.message)}}}function pY(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 pq(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?pY(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):pY(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}class pJ extends dd{constructor(e,t,i,r){super(),cc(this,"spec",void 0),cc(this,"token",void 0),cc(this,"websocket",void 0),cc(this,"pingpongTimer",void 0),cc(this,"reconnectMode","retry"),cc(this,"serviceMode",void 0),cc(this,"reqId",0),cc(this,"commandReqId",0),cc(this,"handleWebSocketOpen",()=>{this.reconnectMode="retry",this.startPingPong()}),cc(this,"handleWebSocketMessage",e=>{if(!e.data)return;let t=JSON.parse(e.data);t.requestId?this.emit("@".concat(t.requestId,"-").concat(t.sid),t):this.serviceMode===k.INJECT?this.emit(U.INJECT_STREAM_STATUS,t):(uC.workerEvent(this.spec.sid,{actionType:"status",serverCode:t.code,workerType:this.serviceMode===k.TRANSCODE?1:2}),this.emit(U.PUBLISH_STREAM_STATUS,t))}),this.spec=t,this.token=e,this.serviceMode=r,this.websocket=new pe("live-streaming",i),this.websocket.on(L.CONNECTED,this.handleWebSocketOpen),this.websocket.on(L.ON_MESSAGE,this.handleWebSocketMessage),this.websocket.on(L.REQUEST_NEW_URLS,(e,t)=>{hW(this,U.REQUEST_NEW_ADDRESS).then(e).catch(t)}),this.websocket.on(L.RECONNECTING,()=>{this.websocket.reconnectMode=this.reconnectMode})}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,s=this.reqId;if(!s||!this.websocket)throw new du(o.UNEXPECTED_ERROR);let a=pq({command:e,sdkVersion:"4.17.2"===dI?"0.0.1":dI,seq:s,requestId:s,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 du(o.WS_DISCONNECT);let c=()=>new sG((e,t)=>{this.websocket.once(L.CLOSED,()=>t(new du(o.WS_ABORT))),this.websocket.once(L.CONNECTED,e)});"connected"!==this.websocket.state&&await c(),a.clientRequest&&(a.clientRequest.workerToken=this.token);let d=new sG((e,t)=>{let i=()=>{t(new du(o.WS_ABORT))};this.websocket.once(L.RECONNECTING,i),this.websocket.once(L.CLOSED,i),this.once("@".concat(s,"-").concat(this.spec.sid),t=>{e(t)})});r&&uC.workerEvent(this.spec.sid,pq(pq({},r),{},{requestId:n,actionType:"request",payload:JSON.stringify(t.clientRequest),serverCode:0,code:0}));let l=Date.now();this.websocket.sendMessage(a);let u=null;try{u=await d}catch(r){if("closed"===this.websocket.state)throw r;return await c(),await this.request(e,t,i)}return r&&uC.workerEvent(this.spec.sid,pq(pq({},r),{},{requestId:n,actionType:"response",payload:JSON.stringify(u.serverResponse),serverCode:u.code,success:200===u.code,responseTime:Date.now()-l})),200!==u.code&&this.handleResponseError(u),u}tryNextAddress(){this.reconnectMode="tryNext",this.websocket.reconnect("tryNext")}close(){let e="4.17.2"===dI?"0.0.1":dI;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 V.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void dg.warning("live stream response already exists stream");case V.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case V.LIVE_STREAM_RESPONSE_BAD_STREAM:case V.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return new du(o.LIVE_STREAMING_INVALID_ARGUMENT,"",{code:e.code}).throw();case V.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if("UnpublishStream"
1===e.serverResponse.command||"UninjectStream"===e.serverResponse.command)return;throw new du(o.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case V.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new du(o.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:e.code}).throw();case V.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{let t=new du(o.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(U.WARNING,t,e.serverResponse.url)}case V.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:{let t=new du(o.LIVE_STREAMING_WARN_FREQUENT_REQUEST);return this.emit(U.WARNING,t,e.serverResponse.url)}case V.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new du(o.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case V.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new du(o.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:e.code}).throw();case V.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{let t=new du(o.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT);return this.emit(U.WARNING,t,e.serverResponse.url)}case V.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return new du(o.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code}).throw();case V.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new du(o.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream resource limit",{retry:!0,changeAddress:!0});case V.LIVE_STREAM_RESPONSE_WORKER_LOST:case V.LIVE_STREAM_RESPONSE_WORKER_QUIT:if("UnpublishStream"===e.serverResponse.command||"UninjectStream"===e.serverResponse.command)return;throw new du(o.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case V.ERROR_FAIL_SEND_MESSAGE:if("UnpublishStream"===e.serverResponse.command||"UninjectStream"===e.serverResponse.command)return;if("UpdateTranscoding"===e.serverResponse.command||"ControlStream"===e.serverResponse.command)return new du(o.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:e.code}).throw();throw new du(o.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case V.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case V.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case V.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case V.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return new du(o.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(hj)},6e3)}}function pX(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 pz(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?pX(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):pX(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}class pQ extends dd{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:dh,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:dh;super(),cc(this,"onLiveStreamWarning",void 0),cc(this,"onLiveStreamError",void 0),cc(this,"onInjectStatusChange",void 0),cc(this,"spec",void 0),cc(this,"retryTimeout",1e4),cc(this,"connection",void 0),cc(this,"httpRetryConfig",void 0),cc(this,"wsRetryConfig",void 0),cc(this,"streamingTasks",new Map),cc(this,"isStartingStreamingTask",!1),cc(this,"taskMutex",new uO("live-streaming")),cc(this,"cancelToken",da.CancelToken.source()),cc(this,"transcodingConfig",void 0),cc(this,"injectConfig",pz({},lw)),cc(this,"injectLoopTimes",0),cc(this,"uapResponse",void 0),cc(this,"lastTaskId",1),cc(this,"statusError",new Map),this.spec=e,this.httpRetryConfig=i,this.wsRetryConfig=t}async setTranscodingConfig(e){var t;let i=pz(pz({},lN),e);66!==i.videoCodecProfile&&77!==i.videoCodecProfile&&100!==i.videoCodecProfile&&(dg.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=>pz(pz(pz({},lA),e),{},{zOrder:e.zOrder?e.zOrder+1:1}))),lh(i.width)||ls(i.width,"config.width",0,1e4),lh(i.height)||ls(i.height,"config.height",0,1e4),lh(i.videoBitrate)||ls(i.videoBitrate,"config.videoBitrate",1,1e6),lh(i.videoFrameRate)||ls(i.videoFrameRate,"config.videoFrameRate"),lh(i.lowLatency)||ln(i.lowLatency,"config.lowLatency"),lh(i.audioSampleRate)||lo(i.audioSampleRate,"config.audioSampleRate",[32e3,44100,48e3]),lh(i.audioBitrate)||ls(i.audioBitrate,"config.audio
1Bitrate",1,128),lh(i.audioChannels)||lo(i.audioChannels,"config.audioChannels",[1,2,3,4,5]),lh(i.videoGop)||ls(i.videoGop,"config.videoGop"),lh(i.videoCodecProfile)||lo(i.videoCodecProfile,"config.videoCodecProfile",[66,77,100]),lh(i.userCount)||ls(i.userCount,"config.userCount",0,17),lh(i.backgroundColor)||ls(i.backgroundColor,"config.backgroundColor",0,0xffffff),lh(i.userConfigExtraInfo)||lc(i.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1),i.transcodingUsers&&!lh(i.transcodingUsers)&&(ld(i.transcodingUsers,"config.transcodingUsers"),i.transcodingUsers.forEach((e,t)=>{lu(e.uid),lh(e.x)||ls(e.x,"transcodingUser[".concat(t,"].x"),0,1e4),lh(e.y)||ls(e.y,"transcodingUser[".concat(t,"].y"),0,1e4),lh(e.width)||ls(e.width,"transcodingUser[".concat(t,"].width"),0,1e4),lh(e.height)||ls(e.height,"transcodingUser[".concat(t,"].height"),0,1e4),lh(e.zOrder)||ls(e.zOrder-1,"transcodingUser[".concat(t,"].zOrder"),0,100),lh(e.alpha)||ls(e.alpha,"transcodingUser[".concat(t,"].alpha"),0,1,!1)})),lh(i.watermark)||lb(i.watermark,"watermark"),lh(i.backgroundImage)||lb(i.backgroundImage,"backgroundImage"),i.images&&!lh(i.images)&&(ld(i.images,"config.images"),i.images.forEach((e,t)=>{lb(e,"images[".concat(t,"]"))}));let r=[];i.images&&r.push(...i.images.map(e=>pz(pz(pz({},lO),e),{},{zOrder:255}))),i.backgroundImage&&(r.push(pz(pz(pz({},lO),i.backgroundImage),{},{zOrder:0})),delete i.backgroundImage),i.watermark&&(r.push(pz(pz(pz({},lO),i.watermark),{},{zOrder:255})),delete i.watermark),i.images=r,i.transcodingUsers&&(i.userConfigs=i.transcodingUsers.map(e=>pz({},e)),i.userCount=i.transcodingUsers.length,delete i.transcodingUsers);let n=(i.userConfigs||[]).map(e=>"number"==typeof e.uid?sG.resolve(e.uid):px(e.uid,this.spec,this.cancelToken.token,this.httpRetryConfig));if((await sG.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(u8(t=this.streamingTasks).call(t)).map(e=>e.taskId).join("#")});dg.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=>{dg.warning("[".concat(this.spec.clientId,"] live streaming receive error"),e.toString(),"try to republish",t.url),this.startLiveStreamingTask(t.url,t.mode,e).then(()=>{dg.debug("[".concat(this.spec.clientId,"] live streaming republish ").concat(t.url," success"))}).catch(e=>{dg.error("[".concat(this.spec.clientId,"] live streaming republish failed"),t.url,e.toString()),this.onLiveStreamError&&this.onLiveStreamError(t.url,e)})})}}setInjectStreamConfig(e,t){this.injectConfig=Object.assign({},this.injectConfig,e),this.injectLoopTimes=t}async startLiveStreamingTask(e,t,i){var r;if(Array.from(u8(r=this.streamingTasks).call(r)).find(e=>e.mode===k.INJECT)&&t===k.INJECT)return new du(o.LIVE_STREAMING_TASK_CONFLICT,"inject stream over limit").throw();if(!this.transcodingConfig&&t===k.TRANSCODE)throw new du(o.INVALID_OPERATION,"[LiveStreaming] no transcoding config found, can not start transcoding streaming task");let n={command:"PublishStream",ts:Date.now(),url:e,uid:this.spec.uid.toString(),autoDestroyTime:100,acceptImageTimeout:!0};dg.debug("[".concat(this.spec.clientId,"] start live streaming ").concat(e,", mode: ").concat(t));let s=await this.taskMutex.lock();if(!this.connection&&i)return void s();if(this.streamingTasks.get(e)&&!i)return s(),new du(o.LIVE_STREAMING_TASK_CONFLICT).throw();try{this.connection||(this.connection=await this.connect(t))}catch(e){throw s(),e}switch(t){case k.TRANSCODE:n.transcodingConfig=pz({},this.transcodingConfig);break;case k.RAW:break;case k.INJECT:n={cname:this.spec.cname,command:"InjectStream",sid:this.spec.sid,transcodingConfig:this.injectConfig,ts:Date.now(),url:e,loopTimes:this.injectLoopTimes}}this.uapResponse&&this.uapResponse.vid&&(n.vid=this.uapResponse.vid
1),this.isStartingStreamingTask=!0;let a=this.lastTaskId++;try{let r=new sG((t,r)=>{hx(this.retryTimeout).then(()=>{if(i)return r(i);let t=this.statusError.get(e);return t?(this.statusError.delete(e),r(t)):void 0})}),o=await sG.race([this.connection.request("request",{clientRequest:n},!0,{url:e,command:"PublishStream",workerType:t===k.TRANSCODE?1:2,requestByUser:!i,tid:a.toString()}),r]);this.isStartingStreamingTask=!1,dg.debug("[".concat(this.spec.clientId,"] live streaming started, code: ").concat(o.code)),this.streamingTasks.set(e,{clientRequest:n,mode:t,url:e,taskId:a}),s()}catch(r){if(s(),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 sG((t,i)=>{let r=this.streamingTasks.get(e);if(!r||!this.connection)return new du(o.UNEXPECTED_ERROR,"can not find streaming task to stop").throw();let n=r.mode;r.abortTask=()=>{dg.debug("[".concat(this.spec.clientId,"] stop live streaming success(worker exception)")),this.streamingTasks.delete(e),t()},this.connection.request("request",{clientRequest:{command:n===k.INJECT?"UninjectStream":"UnpublishStream",url:r.url}},!1,{url:e,command:"UnPublishStream",workerType:n===k.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then(i=>{dg.debug("[".concat(this.spec.clientId,"] stop live streaming success, code: ").concat(i.code)),this.streamingTasks.delete(e),0===this.streamingTasks.size&&n!==k.INJECT&&(this.connection&&this.connection.close(),this.connection=void 0),t(),n===k.INJECT&&this.onInjectStatusChange&&this.onInjectStatusChange(M.INJECT_STREAM_STATUS_STOP_SUCCESS,this.spec.uid,e)}).catch(i)})}async controlInjectStream(e,t,i,r){let n=this.streamingTasks.get(e);if(!n||!this.connection||n.mode!==k.INJECT)throw new du(o.INVALID_OPERATION,"can not find inject stream task to control");return(await this.connection.request("request",{clientRequest:{command:"ControlStream",url:e,control:t,audioVolume:i,position:r}})).serverResponse}resetAllTask(){var e;let t=Array.from(u8(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=new Map,this.cancelToken=da.CancelToken.source(),this.uapResponse=void 0,this.connection&&this.connection.close(),this.connection=void 0}async connect(e){if(this.connection)throw new du(o.UNEXPECTED_ERROR,"live streaming connection has already connected");let t=await hW(this,x.REQUEST_WORKER_MANAGER_LIST,e);return this.uapResponse=t,this.connection=new pJ(t.workerToken,this.spec,this.wsRetryConfig,e),this.connection.on(U.WARNING,(e,t)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e)),this.connection.on(U.PUBLISH_STREAM_STATUS,e=>this.handlePublishStreamServer(e)),this.connection.on(U.INJECT_STREAM_STATUS,e=>this.handleInjectStreamServerStatus(e)),this.connection.on(U.REQUEST_NEW_ADDRESS,(t,i)=>{if(!this.connection)return i(new du(o.UNEXPECTED_ERROR,"can not get new live streaming address list"));hW(this,x.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 V.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case V.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case V.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case V.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:{let r=new du(o.LIVE_STREAMING_CDN_ERROR,"",{code:e.code});if(i)return dg.error(r.toString()),this.onLiveStreamError&&this.onLiveStreamError(t,r);if(!this.isStartingStreamingTask)return;this.statusError.set(t,r)}case V.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{let e=new du(o.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,r);return this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e)}case V.LIVE_STREAM_RESPONSE_WORKER_LOST:case V.LIVE_STREAM_RESPONSE_WORKER_QUIT:var n;if(!this.connection)return;for(let t of(this.connection.tryNextAddress(),Array.from(u8(n=this.streamingTasks).call(n))))t.abortTask?t.abortTask():(dg.warning("[".concat(this.spec.clientId,"] publish stream status code"),e.code,"try to republish",t.url),this.startLiveStreamingTask(t.url,t.mode,new du(o.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code})).then(()=>{dg.debug("[".concat(this.spec.clientId,"] republish live stream success"),t.url)}).catch(e=>{dg.error(e.toString()),this.onLiveStreamError&&this.onLiveStreamError(t.url,e)}));return}}handleInjectStreamServerStatus(e){let t=Number(e.uid),i=e.serverStatus&&e.serverStatus.url;switch(e.code){case 200:return void(this.onInjectStatusChange&&this.onInjectStatusChange(M.INJECT_STREAM_STATUS_START_SUCCESS,t,i));case 451:return this.onInjectStatusChange&&this.onInjectStatusChange(M.INJECT_STREAM_STATUS_START_ALREADY_EXISTS,t,i),void this.streamingTasks.delete(i);case 453:return this.onInjectStatusChange&&this.onInjectStatusChange(M.INJECT_STREAM_STATUS_START_UNAUTHORIZED,t,i),void this.streamingTasks.delete(i);case 470:return this.onInjectStatusChange&&this.onInjectStatusChange(M.INJECT_STREAM_STATUS_BROKEN,t,i),void this.streamingTasks.delete(i);case 499:return this.onInjectStatusChange&&this.onInjectStatusChange(M.INJECT_STREAM_STATUS_START_TIMEOUT,t,i),void this.streamingTasks.delete(i);default:return void dg.debug("inject stream server status",e)}}hasUrl(e){return this.streamingTasks.has(e)}}class pZ{constructor(){cc(this,"destChannelMediaInfos",new Map),cc(this,"srcChannelMediaInfo",void 0)}setSrcChannelInfo(e){lD(e),this.srcChannelMediaInfo=e}addDestChannelInfo(e){lD(e),this.destChannelMediaInfos.set(e.channelName,e)}removeDestChannelInfo(e){ll(e),this.destChannelMediaInfos.delete(e)}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo}getDestChannelMediaInfo(){return this.destChannelMediaInfos}}function p$(e){if(!(e instanceof pZ))return new du(o.INVALID_PARAMS,"Config should be instance of [ChannelMediaRelayConfiguration]").throw();let t=e.getSrcChannelMediaInfo(),i=e.getDestChannelMediaInfo();return t?0===i.size?new du(o.INVALID_PARAMS,"destChannelMediaInfo should not be empty").throw():void 0:new du(o.INVALID_PARAMS,"srcChannelMediaInfo should not be empty").throw()}class p0 extends dd{constructor(e,t,i){super(),cc(this,"ws",void 0),cc(this,"requestId",1),cc(this,"heartBeatTimer",void 0),cc(this,"joinInfo",void 0),cc(this,"clientId",void 0),cc(this,"onOpen",()=>
1{this.emit("open"),this.startHeartBeatCheck()}),cc(this,"onClose",e=>{this.emit("close"),this.dispose()}),cc(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 pe("cross-channel-".concat(this.clientId),i),this.ws.on(L.RECONNECTING,()=>{this.ws.reconnectMode="retry",this.emit("reconnecting")}),this.ws.on(L.CONNECTED,this.onOpen),this.ws.on(L.ON_MESSAGE,this.onMessage),this.ws.on(L.CLOSED,this.onClose)}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 sG((t,i)=>{let r=window.setTimeout(()=>{i(new du(o.TIMEOUT,"wait status timeout, status: ".concat(e)))},5e3);this.once(e,n=>{window.clearTimeout(r),n.state&&0!==n.state?i(new du(o.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(e))):t(void 0)}),this.once("dispose",()=>{window.clearTimeout(r),i(new du(o.WS_ABORT))})})}async request(e){if("closed"===this.ws.state)throw new du(o.WS_DISCONNECT);"connected"!==this.ws.state&&await new sG((e,t)=>{this.ws.once(L.CLOSED,()=>t(new du(o.WS_ABORT))),this.ws.once(L.CONNECTED,e)});let t=this.sendMessage(e),i=new sG((e,i)=>{let r=()=>{i(new du(o.WS_ABORT))};this.ws.once(L.RECONNECTING,r),this.ws.once(L.CLOSED,r),this.once("req_".concat(t),e),hx(3e3).then(()=>{this.removeAllListeners("req_".concat(t)),this.ws.off(L.RECONNECTING,r),this.ws.off(L.CLOSED,r),i(new du(o.TIMEOUT,"cross channel ws request timeout"))})}),r=await i;if(!r||200!==r.code)throw new du(o.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(JSON.stringify(r)));return r}async connect(e){this.ws.removeAllListeners(L.REQUEST_NEW_URLS),this.ws.on(L.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}}class p1 extends dd{set state(e){e!==this._state&&(e!==G.RELAY_STATE_FAILURE&&(this.errorCode=W.RELAY_OK),this.emit("state",e,this.errorCode),this._state=e)}get state(){return this._state}constructor(e,t,i,r){super(),cc(this,"joinInfo",void 0),cc(this,"sid",void 0),cc(this,"clientId",void 0),cc(this,"cancelToken",da.CancelToken.source()),cc(this,"workerToken",void 0),cc(this,"requestId",0),cc(this,"signal",void 0),cc(this,"prevChannelMediaConfig",void 0),cc(this,"httpRetryConfig",void 0),cc(this,"_state",G.RELAY_STATE_IDLE),cc(this,"errorCode",W.RELAY_OK),cc(this,"onStatus",e=>{dg.debug("[".concat(this.clientId,"] ChannelMediaStatus: ").concat(JSON.stringify(e))),e&&e.command&&("onAudioPacketReceived"===e.command&&this.emit("event",B.PACKET_RECEIVED_AUDIO_FROM_SRC),"onVideoPacketReceived"===e.command&&this.emit("event",B.PACKET_RECEIVED_VIDEO_FROM_SRC),"onSrcTokenPrivilegeDidExpire"===e.command&&(this.errorCode=W.SRC_TOKEN_EXPIRED,this.state=G.RELAY_STATE_FAILURE),"onDestTokenPrivilegeDidExpire"===e.command&&(this.errorCode=W.DEST_TOKEN_EXPIRED,this.state=G.RELAY_STATE_FAILURE))}),cc(this,"onReconnect",async()=>{dg.debug("[".concat(this.clientId,"] ChannelMediaSocket disconnect, reconnecting")),this.emit("event",B.NETWORK_DISCONNECTED),this.state=G.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch(e=>{this.state!==G.RELAY_STATE_IDLE&&(dg.error("auto restart channel media relay failed",e.toString()),this.errorCode=W.SERVER_CONNECTION_LOST,this.state=G.RELAY_STATE_FAILURE)})}),this.joinInfo=e,this.clientId=t,this.sid=hF(),this.signal=new p0(this.joinInfo,this.clientId,i),this.httpRetryConfig=r}async startChannelMediaRelay(e){if(this.state!==G.RELAY_STATE_IDLE)throw new du(o.INVALID_OPERATION);this.state=G.RELAY_STATE_CONNECTING,await this.connect(),dg.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 du(o.CROSS_CHANNEL_FAILED_JOIN_SRC);if(e.data&&e.data.serverResponse&&"SetDestChannelStatus"===e.serverResponse.command)throw new du(o.CROSS_CHANNEL_FAILED_JOIN_DEST);if(e.data&&e.data.serverResponse&&"StartPacketTransfer"===e.serverResponse.command)throw new du(o.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST);throw e}this.prevChannelMediaConfig=e}async updateChannelMediaRelay(e){if(this.state!==G.RELAY_STATE_RUNNING)throw new du(o.INVALID_OPERATION);await this.sendUpdateMessage(e),this.prevChannelMediaConfig=e}async stopChannelMediaRelay(){await this.sendStopRelayMessage(),dg.debug("[".concat(this.clientId,"] stopChannelMediaRelay: send stop message success")),this.state=G.RELAY_STATE_IDLE,this.dispose()}dispose(){dg.debug("[".concat(this.clientId,"] disposeChannelMediaRelay")),this.cancelToken.cancel(),this.cancelToken=da.CancelToken.source(),this.state=G.RELAY_STATE_IDLE,this.emit
1("dispose"),this.signal.dispose(),this.prevChannelMediaConfig=void 0}async connect(){let e=await pB(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=e.workerToken,await this.signal.connect(e.addressList),this.emit("event",B.NETWORK_CONNECTED),this.signal.on("status",this.onStatus),this.signal.on("reconnecting",this.onReconnect)}async sendStartRelayMessage(e){let t=this.genMessage(j.StopPacketTransfer);await this.signal.request(t),await this.signal.waitStatus("Normal Quit"),dg.debug("[".concat(this.clientId,"] startChannelMediaRelay: StopPacketTransfer success"));let i=this.genMessage(j.SetSdkProfile,e);await this.signal.request(i),dg.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));let r=this.genMessage(j.SetSourceChannel,e);await this.signal.request(r),await this.signal.waitStatus("SetSourceChannelStatus"),this.emit("event",B.PACKET_JOINED_SRC_CHANNEL),dg.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));let n=this.genMessage(j.SetSourceUserId,e);await this.signal.request(n),dg.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));let o=this.genMessage(j.SetDestChannel,e);await this.signal.request(o),await this.signal.waitStatus("SetDestChannelStatus"),this.emit("event",B.PACKET_JOINED_DEST_CHANNEL),dg.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetDestChannel success"));let s=this.genMessage(j.StartPacketTransfer,e);await this.signal.request(s),this.emit("event",B.PACKET_SENT_TO_DEST_CHANNEL),this.state=G.RELAY_STATE_RUNNING,dg.debug("[".concat(this.clientId,"] startChannelMediaRelay: StartPacketTransfer success"))}async sendUpdateMessage(e){let t=this.genMessage(j.UpdateDestChannel,e);await this.signal.request(t),this.emit("event",B.PACKET_UPDATE_DEST_CHANNEL),dg.debug("[".concat(this.clientId,"] sendUpdateMessage: UpdateDestChannel success"))}async sendStopRelayMessage(){let e=this.genMessage(j.StopPacketTransfer);await this.signal.request(e),dg.debug("[".concat(this.clientId,"] sendStopRelayMessage: StopPacketTransfer success"))}genMessage(e,t){let i=[],r=[],n=[];this.requestId+=1;let s={appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sdkVersion:dI,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};"4.17.2"===s.sdkVersion&&(s.sdkVersion="0.0.1");let a=null,c=null;switch(e){case j.SetSdkProfile:return s.clientRequest={command:"SetSdkProfile",type:"multi_channel"},s;case j.SetSourceChannel:if(!(c=t&&t.getSrcChannelMediaInfo()))throw new du(o.UNEXPECTED_ERROR,"can not find source config");return s.clientRequest={command:"SetSourceChannel",uid:"0",channelName:c.channelName,token:c.token||this.joinInfo.appId},s;case j.SetSourceUserId:if(!(c=t&&t.getSrcChannelMediaInfo()))throw new du(o.UNEXPECTED_ERROR,"can not find source config");return s.clientRequest={command:"SetSourceUserId",uid:c.uid+""},s;case j.SetDestChannel:if(!(a=t&&t.getDestChannelMediaInfo()))throw new du(o.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)}),s.clientRequest={command:"SetDestChannel",channelName:i,uid:r,token:n},s;case j.StartPacketTransfer:return s.clientRequest={command:"StartPacketTransfer"},s;case j.Reconnect:return s.clientRequest={command:"Reconnect"},s;case j.StopPacketTransfer:return s.clientRequest={command:"StopPacketTransfer"},s;case j.UpdateDestChannel:if(!(a=t&&t.getDestChannelMediaInfo()))throw new du(o.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)}),s.clientRequest={command:"UpdateDestChannel",channelName:i,uid:r,token:n},s}return s}}let p2=e=>{let t=document.createElement("canvas");return t.width=2,t.height=2,new sG((i,r)=>{t.toBlob(async e=>{(t.remove(),e)?i({buffer:await p3(e),width:t.width,height:t.height}):r(new du(o.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))},e,1)})},p3=async e=>new Uint8Array(await e.arrayBuffer());function p4(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 p5(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
1t%2?p4(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):p4(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}class p6{get videoElementStatus(){return this._videoElementStatus}set videoElementStatus(e){e!==this._videoElementStatus&&(dg.debug("[".concat(this.trackId,"] video-element-status change ").concat(this._videoElementStatus," => ").concat(e)),this._videoElementStatus=e)}constructor(e){cc(this,"trackId",void 0),cc(this,"config",void 0),cc(this,"onFirstVideoFrameDecoded",void 0),cc(this,"freezeTimeCounterList",[]),cc(this,"renderFreezeAccTime",0),cc(this,"timeUpdatedCount",0),cc(this,"freezeTime",0),cc(this,"playbackTime",0),cc(this,"lastTimeUpdatedTime",0),cc(this,"autoplayFailed",!1),cc(this,"videoTrack",void 0),cc(this,"videoElement",void 0),cc(this,"cacheVideoElement",void 0),cc(this,"videoElementCheckInterval",void 0),cc(this,"_videoElementStatus",c.NONE),cc(this,"isGettingVideoDimensions",!1),cc(this,"startGetVideoDimensions",()=>{let e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return dg.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(e,500)};this.isGettingVideoDimensions||e()}),cc(this,"autoResumeAfterInterruption",()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&"running"===uL.curState&&(a6()?(dg.debug("[track-".concat(this.trackId,"] video element paused, auto resume for iOS 15.2")),this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):a5()?(dg.debug("[track-".concat(this.trackId,"] video element paused, auto resume for iOS 15.1")),this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):a4()&&(dg.debug("[track-".concat(this.trackId,"] video element paused, auto resume for iOS 15.0")),this.videoElement.pause(),this.videoElement.play()))}),cc(this,"handleVideoEvents",e=>{switch(e.type){case"play":case"playing":this.startGetVideoDimensions(),this.videoElementStatus=c.PLAYING;break;case"loadeddata":if(this.onFirstVideoFrameDecoded&&this.onFirstVideoFrameDecoded(),this.cacheVideoElement){try{this.cacheVideoElement.remove()}catch(e){}this.cacheVideoElement=void 0}break;case"canplay":this.videoElementStatus=c.CANPLAY;break;case"stalled":this.videoElementStatus=c.STALLED;break;case"suspend":this.videoElementStatus=c.SUSPEND;break;case"pause":this.videoElementStatus=c.PAUSED,aQ()||a8()||aX()&&this.autoplayFailed||!this.videoTrack||"live"!==this.videoTrack.readyState||(dg.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=c.WAITING;break;case"abort":this.videoElementStatus=c.ABORT;break;case"ended":this.videoElementStatus=c.ENDED;break;case"emptied":this.videoElementStatus=c.EMPTIED;break;case"error":{this.videoElementStatus=c.ERROR;let e=this.videoElement.error;e&&dg.error("[".concat(this.trackId,"] media error, code: ").concat(e.code,", message: ").concat(e.message));break}case"timeupdate":{let e=performance.now();if(this.timeUpdatedCount+=1,this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);let t=e-this.lastTimeUpdatedTime,i=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,hI.lastVisibleTime<hI.lastHiddenTime||i<hI.lastHiddenTime||i<hI.lastVisibleTime)return;for(t>dM.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)}}}}),cc(this,"autoResumeAfterInterruptionOnIOS15",()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&(a6()?(dg.debug("[track-".concat(this.trackId,"] video element paused, auto resume for iOS 15.2")),this.videoElement.srcObject=null,this.videoElement.srcObject=ne
1w MediaStream([this.videoTrack]),this.videoElement.play()):a5()?(dg.debug("[track-".concat(this.trackId,"] video element paused, auto resume for iOS 15.1")),this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):a4()&&(dg.debug("[track-".concat(this.trackId,"] video element paused, auto resume for iOS 15.0")),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"),uL.on(uy.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),uL.on(uy.IOS_15_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15)}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&&uC.autoplayFailed(e,"video",t.message,this.trackId),"NotAllowedError"===t.name?(dg.warning("detected video element autoplay failed",t),this.autoplayFailed=!0,this.handleAutoPlayFailed()):dg.warning("[".concat(this.trackId,"] play warning: "),t)});let i=aY();if(("Safari"===i.name&&15===Number(i.version)||a3())&&t&&t.then&&t.catch){let e=()=>{this.config.mirror&&(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 dg.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 sG((r,n)=>{i.toBlob(async e=>{(i.remove(),e)?r({buffer:await p3(e),width:i.width,height:i.height}):n(new du(o.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))},e,t<0?.1:t>1?1:t)})):await p2(e)}destroy(){uL.off(uy.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),uL.off(uy.IOS_15_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15),this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[]}initVideoElement(){if(this.videoElementStatus=c.INIT,!this.videoElementCheckInterval&&(p8.forEach(e=>{this.videoElement.addEventListener(e,this.handleVideoEvents)}),this.videoElementCheckInterval=window.setInterval(()=>{var e;(e=this.videoElement)!==document.body&&document.body.contains(e)||(this.videoElementStatus=c.DESTROYED)},1e3),dM.ENABLE_VIDEO_FRAME_CALLBACK)){var e,t;let i,r=(e,t)=>{var n,o;if(this.videoElementStatus===c.PLAYING){if(i){let e=t.presentationTime-i.presentationTime;e>dM.VIDEO_FREEZE_DURATION&&hI.lastVisibleTime>=hI.lastHiddenTime&&i.timestamp>hI.lastVisibleTime&&i.timestamp>hI.lastHiddenTime&&(this.renderFreezeAccTime+=e)}i=p5(p5({},t),{},{timestamp:e})}dM.ENABLE_VIDEO_FRAME_CALLBACK&&(null==(n=(o=this.videoElement).requestVideoFrameCallback)||n.call(o,r))};null==(e=(t=this.videoElement).requestVideoFrameCallback)||e.call(t,r)}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),ct()&&(this.videoElement.poster="noposter");let i=aY();("Safari"===i.name&&15===Number(i.version)||a3()||!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,az()&&this.videoElement.load()):(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,az()&&this.videoElement.load());let r=this.videoElement.play();void 0!==r&&r.catch(e=>{dg.debug("[".concat(this.trackId,"] playback interrupted"),e.toString())})}
1resetVideoElement(){p8.forEach(e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents)}),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.videoElementStatus=c.NONE}handleAutoPlayFailed(){let e=t=>{t.preventDefault(),this.videoElement.play().then(()=>{dg.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))}).catch(e=>{dg.error(e)}),this.autoplayFailed=!1,ci()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};ci()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),um()}}let p8=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];class p7 extends p6{constructor(e){super(e),cc(this,"container",void 0),cc(this,"slot",void 0),this.slot=e.element,this.updateConfig(e)}updateConfig(e){this.config=e,this.trackId=e.trackId;let t=e.element;t!==this.slot&&(this.destroy(),this.slot=t),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 p2(e)}destroy(){if(super.destroy(),this.videoElement.remove(),this.videoElement=document.createElement("video"),this.container){try{this.container.remove(),this.slot.removeChild(this.container)}catch(e){}this.container=void 0}}createElements(){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",dM.KEEP_LAST_FRAME&&this.resetVideoElement(),this.mountedVideoElement()):this.unmountedVideoElement(),this.slot.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}}function p9(e){let i={};e.facingMode&&(i.facingMode=e.facingMode),e.cameraId&&(i.deviceId={exact:e.cameraId});let r=dN(e.encoderConfig);return i.width=r.width,i.height=r.height,!a9()&&r.frameRate&&(i.frameRate=r.frameRate),aY().name===t.EDGE&&"object"==typeof i.frameRate&&(i.frameRate.max=60),az()&&(i.frameRate={ideal:30,max:30}),i}function _e(e){let t={};if(a9()||(void 0!==e.AGC&&(t.autoGainControl=e.AGC),void 0!==e.AEC&&(t.echoCancellation=e.AEC),void 0!==e.ANS&&(t.noiseSuppression=e.ANS,aJ()&&e.ANS&&(t.googHighpassFilter=e.ANS))),e.encoderConfig){let i=dL(e.encoderConfig);t.channelCount=i.stereo?2:1,t.sampleRate=i.sampleRate,t.sampleSize=i.sampleSize}return e.microphoneId&&(t.deviceId={exact:e.microphoneId}),ct()&&(t.sampleRate=void 0),t}(Er=EK||(EK={})).COVERED="COVERED",Er.POSITION="POSITION",Er.SIZE="SIZE",Er.STYLE="STYLE",(En=EY||(EY={})).UNMOUNTED="UNMOUNTED",En.INVALID_HTML_ELEMENT="INVALID_HTML_ELEMENT";var _t,_i,_r,_n,_o,_s,_a,_c,_d,_l,_u,_h,_p,__,_E,_m,_f,_S,_T,_g,_R,_I,_C,_v,_y,_A,_O,_b,_N,_w,_D,_P,_L,_k,_M,_U,_x,_V,_F,_j,_B,_G,_W,_H,_K,_Y,_q,_J,_X,_z,_Q,_Z,_$,_0,_1,_2,_3,_4,_5,_6,_8,_7,_9,Ee,Et,Ei,Er,En,Eo,Es,Ea,Ec,Ed,El,Eu,Eh,Ep,E_,EE,Em,Ef,ES,ET,Eg,ER,EI,EC,Ev,Ey,EA,EO,Eb,EN,Ew,ED,EP,EL,Ek,EM,EU,Ex,EV,EF,Ej,EB,EG,EW,EH,EK,EY,Eq,EJ,EX,Ez,EQ,EZ,E$,E0,E1,E2,E3,E4,E5,E6,E8,E7,E9,me,mt,mi,mr,mn,mo,ms,ma,mc,md,ml,mu,mh,mp,m_,mE,mm,mf=new class{constructor(){cc(this,"_clientSize",null),cc(this,"getClientWidth",()=>document.documentElement?document.documentElement.clientWidth:document.body.clientWidth),cc(this,"getClientHeight",()=>document.documentElement?document.documentElement.clientHeight:document.body.clientHeight),cc(this,"getStyle",e=>window.getComputedStyle(e,null)),cc(this,"checkCssVisibleProperty",e=>{let t=!0,{display:i,visibility:r,opacity:n,filter:o}=this.getStyle(e);return("none"===i||["hidden","collapse"].includes(r)||.1>Number(n))&&(t=!1),!!t&&(o&&o.split(" ").filter(e=>["brightness","blur","opacity"].includes(e.split("(")[0])).map(e=>{let[t,i]=e.split(/\(|\)/);return[t,Number(i.match(/^[0-9\.]+/))]}
1).forEach(e=>{let[i,r]=e;switch(i){case"brightness":(r<.1||r>3)&&(t=!1);break;case"blur":r>3&&(t=!1);break;case"opacity":r<.1&&(t=!1)}}),t)}),cc(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}),cc(this,"checkActualCssVisibleIncludeInherit",e=>this.checkPropertyUpToAllParentNodes(e,this.checkCssVisibleProperty)),cc(this,"getSizeAboutClient",e=>{let{width:t,height:i,left:r,right:n,top:o,bottom:s}=e.getBoundingClientRect(),a=this.getClientWidth(),c=this.getClientHeight();return{width:t,height:i,left:r,right:n,top:o,bottom:s,clientWidth:a,clientHeight:c,clientMin:Math.min(a,c)}}),cc(this,"checkActualSize",()=>{let{width:e,height:t,clientMin:i}=this._clientSize;return this.checkSizeIsVisible(e,t,i)}),cc(this,"elementFromPoint",(e,t)=>document.elementFromPoint?document.elementFromPoint(e,t):null),cc(this,"checkCoverForAPoint",(e,t,i)=>{let r=this.elementFromPoint(e,t);return null!==r&&r!==i}),cc(this,"getPointPositionList",()=>{let{width:e,height:t,left:i,top:r}=this._clientSize,n=e/6,o=t/6,s=[];for(let e=0;e<5;e++)for(let t=0;t<5;t++){let a=(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;s.push({x:a,y:c})}return[...s]}),cc(this,"checkElementCover",e=>this.getPointPositionList().map(t=>this.checkCoverForAPoint(t.x,t.y,e)).filter(e=>!!e).length>6),cc(this,"checkSizeIsVisible",(e,t,i)=>(e>50||i/e<=10)&&(t>50||i/t<=10)),cc(this,"checkSizeOfPartInClient",()=>{let e,t,i,{left:r,right:n,top:o,bottom:s,clientHeight:a,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<a))return!1;i=o}if(s<0)return!1;let l=t-e,u=(s<a?s:a)-i;return this.checkSizeIsVisible(l,u,d)}),cc(this,"returnHiddenResult",e=>(this._clientSize=null,{visible:!1,reason:e})),cc(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(EK.COVERED);{let e=this.checkActualSize(),t=this.checkSizeOfPartInClient();return e&&!t?this.returnHiddenResult(EK.POSITION):e?(this._clientSize=null,{visible:!0}):this.returnHiddenResult(EK.SIZE)}}return this.returnHiddenResult(EK.STYLE)}return this.returnHiddenResult(EY.UNMOUNTED)}return this.returnHiddenResult(EY.INVALID_HTML_ELEMENT)}),cc(this,"checkElementIsMountedOnDom",e=>this.checkPropertyUpToAllParentNodes(e,e=>"HTML"!==e.nodeName.toUpperCase()?null!==e.parentElement:!!document.documentElement))}};function mS(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 mT(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?mS(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):mS(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let mg=(Eq=uI({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),EJ=u3(),EX=uI({argsMap:e=>[e.getTrackId()]}),Ez=ub("LocalVideoTrack","_enabledMutex"),EQ=uI({argsMap:(e,t)=>[e.getTrackId(),t]}),EZ=u3(),E$=ub("LocalVideoTrack","_enabledMutex"),E0=uI({argsMap:(e,t)=>[e.getTrackId(),t]}),E1=u3(),E2=uI({argsMap:(e,t)=>[e.getTrackId(),t]}),E3=u3(),E4=u3(),E5=uI({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),E6=u3(),E8=u3(),E7=u3(),E9=u3(),me=u3(),mt=u3(),mi=u3(),mr=uI({argsMap:(e,t)=>[e.getTrackId(),t.name]}),mn=uI({argsMap:e=>[e.getTrackId()]}),mo=uI({argsMap:e=>[e.getTrackId()]}),ms=uI({argsMap:(e,t,i)=>[e.getTrackId(),t.label,i]}),ui((ma=class e extends uN{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==c.PLAYING)}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}get __className__(){return"LocalVideoTrack"}constructor(e,t,i,r,n,o){if(super(e,n),cc(this,"trackMediaType","video"),cc(this,"_player",void 0),cc(this,"_videoVisibleTimer",null),cc(this,"_previousVideoVisibleStatus",void 0),cc(this,"_clearPreviousVideoVisibleStatus",()=>this._previousVideoVisibleStatus=void 0),cc(this,"_encoderConfig",void 0),cc(this,"_scalabiltyMode",{numSpatialL
1ayers:1,numTemporalLayers:1}),cc(this,"_optimizationMode",void 0),cc(this,"_videoHeight",void 0),cc(this,"_videoWidth",void 0),cc(this,"_forceBitrateLimit",void 0),cc(this,"_enabled",!0),cc(this,"processorDestination",void 0),cc(this,"_processorContext",void 0),aX()){let{width:t,height:i}=e.getSettings();this._videoWidth=t,this._videoHeight=i}else this.updateMediaStreamTrackResolution();this._encoderConfig=t,this._scalabiltyMode=i,this._optimizationMode=r,this._hints=o||[],-1===this._hints.indexOf(X.SCREEN_TRACK)&&this.updateBitrateFromProfile(),t&&-1!==this._hints.indexOf(X.CUSTOM_TRACK)&&this.setEncoderConfiguration(t),this.processorContext=new ht(this.getTrackId(),"local"),this.processorDestination=new he(this.processorContext),this.bindProcessorDestinationEvents()}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:(dg.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}dg.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));let i=mT(mT(mT({},this._getDefaultPlayerConfig()),t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new p6(i):this._player=new p7(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.emit(Z.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}},dM.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,dg.debug("[".concat(this.getTrackId(),"] stop video playback")))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(dg.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){this._originMediaStreamTrack.enabled=!1;try{await hH(this,J.NEED_DISABLE_TRACK,this)}catch(e){throw dg.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}return t||(this._enabled=!1),void dg.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}this._originMediaStreamTrack.enabled=!0;try{await hH(this,J.NEED_ENABLE_TRACK,this)}catch(e){throw dg.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}dg.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,dg.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await hH(this,J.NEED_MUTE_TRACK,this):await hH(this,J.NEED_UNMUTE_TRACK,this))}async setEncoderConfiguration(e,t){if(!this._enabled)throw new du(o.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if(e=dN(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),e.width||e.height||e.frameRate){let t=p9({encoderConfig:e});(aX()||aQ()||a8())&&(t.deviceId=void 0),dg.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 du(o.UNEXPECTED_ERROR,t.toString());throw dg.error("[".concat(this.getTrackId(),"] applyConstraints error"),e.toString()),e}}this._encoderConfig=e,-1===this._hints.indexOf(X.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await hH(this,J.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw()}}getStats(){return hZ(()=>{dg.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")},"localVideoTrackGetStatsWarning"),hK(this,J.GET_STATS)||mT({},lI)}async setBeautyEffect(e){dg.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 p2(e)}clone(t,i,r,n){return new e(this._mediaStreamTrack.clone(),t,i,r,n)}async setBitrateLimit(e){if(dg.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);try{await hH(this,J.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw()}}}async setOptimizationMode(e){if("motion"!==e&&"detail"!==e&&"balanced"!==e)return void dg.error(o.INVALID_PARAMS,"optimization mode must be motion, detail or balanced");let t=this._optimizationMode;try{this._optimizationMode=e,await hH(this,J.SET_OPTIMIZATION_MODE,this)}catch(e){throw this._optimizationMode=t,dg.error("[".concat(this.getTrackId(),"] set optimization mode failed"),e.toString()),e}dg.info("[".concat(this.getTrackId(),"] set optimization mode success (").concat(e,")"))}
1setScalabiltyMode(e){if(1===e.numSpatialLayers&&1!==e.numTemporalLayers)return dg.error(o.INVALID_PARAMS,"scalability mode currently not supported, no SVC."),void(this._scalabiltyMode={numSpatialLayers:1,numTemporalLayers:1});this._scalabiltyMode=e,dg.info("[".concat(this.getTrackId(),"] set scalability mode success (").concat(e,")"))}updateMediaStreamTrackResolution(){hB(this._originMediaStreamTrack).then(e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t}).catch(hj)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:"contain"}}updateBitrateFromProfile(){if(!this._encoderConfig)return;let{width:e,height:t,frameRate:i}=this.getMediaStreamTrackSettings();if(!e||!t||!i)return;let[r,n]=function(e,t,i){let r,n=dM.BITRATE_ADAPTER_TYPE,o=200*Math.pow(i/15,.6)*Math.pow(e*t/640/360,.75);if("STANDARD_BITRATE"===n)r=4*o;else{if("COMPATIABLE_BITRATE"!==n)return;r=2*o}return[Math.floor(r),Math.floor(o)]}(e,t,i)||[void 0,void 0];this._encoderConfig.bitrateMin||this._encoderConfig.bitrateMax||(this._encoderConfig.bitrateMin=n,this._encoderConfig.bitrateMax=r,dg.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(e,", h: ").concat(t,", fps: ").concat(i,"] => [brMax: ").concat(r,", brMin: ").concat(n,"]")))}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=mf.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;let e=uC.reportApiInvoke(null,{tag:_.TRACER,name:p.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 du(o.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}async renewMediaStreamTrack(e){}pipe(e){if(this.processor===e)return e;if(e._source)throw new du(o.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()}async replaceTrack(e,t){if(!(e instanceof MediaStreamTrack))throw new du(o.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if("video"!==e.kind)throw new du(o.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(e,t,!0),this.updateMediaStreamTrackResolution()}bindProcessorDestinationEvents(){this.processorDestination.on(el.ON_TRACK,async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),await hH(this,J.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await hH(this,J.NEED_REPLACE_TRACK,this))})}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(el.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(eu.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(eu.REQUEST_CONSTRAINTS)}}).prototype,"play",[Eq,EJ],Object.getOwnPropertyDescriptor(ma.prototype,"play"),ma.prototype),ui(ma.prototype,"stop",[EX],Object.getOwnPropertyDescriptor(ma.prototype,"stop"),ma.prototype),ui(ma.prototype,"setEnabled",[Ez,EQ,EZ],Object.getOwnPropertyDescriptor(ma.prototype,"setEnabled"),ma.prototype),ui(ma.prototype,"setMuted",[E$,E0,E1],Object.getOwnPropertyDescriptor(ma.prototype,"setMuted"),ma.prototype),ui(ma.prototype,"setEncoderConfiguration",[E2,E3],Object.getOwnPropertyDescriptor(ma.prototype,"setEncoderConfiguration"),ma.prototype),ui(ma.prototype,"getStats",[E4],Object.getOwnPropertyDescriptor(ma.prototype,"getStats"),ma.prototype),ui(ma.prototype,"setBeautyEffect",[E5,E6],Object.getOwnPropertyDescriptor(ma.prototype,"setBeautyEffect"),ma.prototype),ui(ma.prototype,"getCurrentFrameData",[E8],Object.getOwnPropertyDescriptor(ma.prototype,"getCurrentFrameData"),ma.prototype),ui(ma.prototype,"getCurrentFrameImage",[E7],Object.getOwnPropertyDescriptor(ma.prototype,"getCurrentFrameImage"),ma.prototype),ui(ma.prototype,"setBitrateLimit",[E9],Object.getOwnPropertyDescriptor(ma.prototype,"setBitrateLimit"),ma.prototype),ui(ma.prototype,"setOptimizationMode",[me],Object.getOwnPropertyDescriptor(ma.prototype,"setOptimizationMode"),ma.prototype),ui(ma.prototype,"setScalabiltyMode",[mt],Object.getOwnPropertyDescriptor(ma.prototype,"setScalabiltyMode"),ma.prototype),ui(ma.prototype,"updateMediaStreamTrackResolution",[mi],Object.getOwnPropertyDescriptor(ma.prototype,"updateMediaStreamTrackResolution"),ma.prototype),ui(ma.prototype,"pipe",[mr],Object.getOwnPropertyDescriptor(ma.prototype,"pipe"),ma.prototype),ui(ma.prototype,"unpipe",[mn],Object.getOwnPropertyDescriptor(ma.prototype,"unpipe"),ma.prototype),ui(ma.prototype,"close",[mo],Object.getOwnPropertyDescriptor(ma.prototype,"close"),ma.prototype),ui(ma.prototype,"replaceTrack",[ms],Object.getOwnPropertyDescriptor(ma.prototype,"replaceTrack"),ma.prototype),ma),mR=(mc=uI({argsMap:(e,t)=>[e.getTrackId(),t]}),md=u3(),ml=ub("CameraVideoTrack","_enabledMutex"),mu=uI({argsMap:(e,t)=>[e.getTrackId(),t]}),mh=u3(),mp=uI({argsMap:(e,t)=>[e.getTrackId(),t]}),m_=u3(),mE=uI({argsMap:e=>[e.getTrackId()]}),ui((mm=class extends mg{get __className__(){return"CameraVideoTrack"}constructor(e,t,i,r,n,o){super(e,dN(t.encoderConfig),r,n,o),cc(this,"_config",void 0),cc(this,"_originalConstraints",void 0),cc(this,"_constraints",void 0),cc(this,"_enabled",!0),cc(this,"_deviceName","default"),cc(this,"tryResumeVideoForIOS15WeChat",async()=>{a3()&&!a6()&&a7()&&this._enabled&&!this._isClosed&&(dg.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=dN(this._config.encoderConfig),uL.on(uy.IOS_15_INTERRUPTION_END,this.tryResumeVideoForIOS15WeChat),uL.on(uy.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15WeChat),this.bindProcessorContextEvents()}async setDevice(e){if(dg.info("[".concat(this.getTrackId(),"] set device to ").concat(e)),this._enabled)try{let t=await u0.getDeviceById(e),i={};i.video=mT({},this._constraints),i.video.deviceId={exact:e},i.video.facingMode=void 0,this._originMediaStreamTrack.stop();let r=null;try{r=await uz(i,this.getTrackId())}catch(e){throw dg.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),r=await uz({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 dg.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{let t=await u0.getDeviceById(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw dg.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}dg.info("[".concat(this.getTrackId(),"] setDevice success"))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(dg.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{let e=await uz({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1)}await hH(this,J.NEED_ENABLE_TRACK,this)}catch(e){throw dg.error("[".concat(this.getTrackId(),"] setEnabled true error"),e.toString()),e}this.updateMediaStreamTrackResolution(),dg.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 hH(this,J.NEED_DISABLE_TRACK,this)}catch(e){throw dg.error("[".concat(this.getTrackId(),"] setEnabled to fal
1se error"),e.toString()),e}dg.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new du(o.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");e=dN(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);let i=hz(this._config);i.encoderConfig=e;let r=p9(i);(aX()||aQ()||a8())&&(r.deviceId=void 0),dg.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 du(o.UNEXPECTED_ERROR,t.toString());throw dg.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(X.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await hH(this,J.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw()}}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((aQ()||a8())&&this._enabled&&!this._isClosed&&uL.duringInterruption){let e=async()=>{uL.off(uy.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(dg.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};uL.on(uy.IOS_INTERRUPTION_END,e)}else dg.debug("[".concat(this.getTrackId(),"] track ended")),this.emit(Z.TRACK_ENDED)}async renewMediaStreamTrack(e){let t=e||this._constraints,i=u0.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId={exact:i}),this._enabled){let e=await uz({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),uL.off(uy.IOS_15_INTERRUPTION_END,this.tryResumeVideoForIOS15WeChat),uL.off(uy.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15WeChat)}bindProcessorContextEvents(){this.processorContext.on(eu.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(eu.REQUEST_CONSTRAINTS,async e=>{e(this._originMediaStreamTrack.getSettings())})}}).prototype,"setDevice",[mc,md],Object.getOwnPropertyDescriptor(mm.prototype,"setDevice"),mm.prototype),ui(mm.prototype,"setEnabled",[ml,mu,mh],Object.getOwnPropertyDescriptor(mm.prototype,"setEnabled"),mm.prototype),ui(mm.prototype,"setEncoderConfiguration",[mp,m_],Object.getOwnPropertyDescriptor(mm.prototype,"setEncoderConfiguration"),mm.prototype),ui(mm.prototype,"close",[mE],Object.getOwnPropertyDescriptor(mm.prototype,"close"),mm.prototype),mm);class mI{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)return this._audioTrack}get videoTrack(){if(this.hasVideo)return this._videoTrack}constructor(e,t){cc(this,"uid",void 0),cc(this,"_uintid",void 0),cc(this,"_trust_in_room_",!0),cc(this,"_trust_audio_enabled_state_",!0),cc(this,"_trust_video_enabled_state_",!0),cc(this,"_trust_audio_mute_state_",!0),cc(this,"_trust_video_mute_state_",!0),cc(this,"_audio_muted_",!1),cc(this,"_video_muted_",!1),cc(this,"_audio_enabled_",!0),cc(this,"_video_enabled_",!0),cc(this,"_audio_added_",!1),cc(this,"_video_added_",!1),cc(this,"_trust_video_stream_added_state_",!0),cc(this,"_trust_audio_stream_added_state_",!0),cc(this,"_audioTrack",void 0),cc(this,"_videoTrack",void 0),cc(this,"_audioSSRC",void 0),cc(this,"_videoSSRC",void 0),cc(this,"_audioOrtc",void 0),cc(this,"_videoOrtc",void 0),cc(this,"_cname",void 0),cc(this,"_rtxSsrcId",void 0),this.uid=e,this._uintid=t}}i1({target:"Promise",stat:!0},{try:function(e){var t=o6.f(this),i=o9(e);return(i.error?t.reject:t.resolve)(i.value),t.promise}});var mC=iy("isConcatSpreadable"),mv="Maximum allowed index exceeded",my=tA.TypeError,mA=t6>=51||!tf(function(){var e=[];return e[mC]=!1,e.concat()[0]!==e}),mO=l4("concat"),mb=function(e){if(!tQ(e))return!1;var t=e[mC];return void 0!==t?!!t:lx(e)};i1({target:"Array",proto:!0,forced:!mA||!mO},{concat:function(e){var t,i,r,n,o,s=ip(this),a=lB(s,0),c=0;for(t=-1,r=arguments.length;t<r;t++)if(mb(o=-1===t?s:arguments[t])){if(c+(n=i6(o))>0x1fffffffffffff)throw my(mv);for(i=0;i<n;i++,c++)i in o&&dK(a,c,o[i])}else{if(c>=0x1fffffffffffff)throw my(mv);dK(a,c++,o)}return a.length=c,a}});var mN={},mw=rb.f,mD="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];mN.f=function(e){return mD&&"Window"==tH(e)?function(e){try{return mw(e)}catch(e){return dJ(mD)}}(e):mw(tz(e))};var mP={};mP.f=iy;var mL=iH.f,mk=function(e){var t=tZ.Symbol||(tZ.Symbol={});iE(t,e)||mL(t,e,{value:mP.f(e)})},mM=ic.exports,mU=lH.forEach,mx=rS("hidden"),mV="Symbol",mF=iy("toPrimitive"),mj=nj(mV),mB=Object.prototype,mG=tA.Symbol,mW=mG&&mG.prototype,mH=tA.TypeError,mK=tA.QObject,mY=t0("JSON","stringify"),mq=tP.f,mJ=iH.f,mX=mN.f,mz=tU.f,mQ=tC([].push),mZ=mM("symbols"),m$=mM("op-symbol
1s"),m0=mM("string-to-symbol-registry"),m1=mM("symbol-to-string-registry"),m2=mM("wks"),m3=!mK||!mK.prototype||!mK.prototype.findChild,m4=tL&&tf(function(){return 7!=rZ(mJ({},"a",{get:function(){return mJ(this,"a",{value:7}).a}})).a})?function(e,t,i){var r=mq(mB,t);r&&delete mB[t],mJ(e,t,i),r&&e!==mB&&mJ(mB,t,r)}:mJ,m5=function(e,t){var i=mZ[e]=rZ(mW);return nF(i,{type:mV,tag:e,description:t}),tL||(i.description=t),i},m6=function(e,t,i){e===mB&&m6(m$,t,i),iJ(e);var r=iw(t);return iJ(i),iE(mZ,r)?(i.enumerable?(iE(e,mx)&&e[mx][r]&&(e[mx][r]=!1),i=rZ(i,{enumerable:tB(0,!1)})):(iE(e,mx)||mJ(e,mx,tB(1,{})),e[mx][r]=!0),m4(e,r,i)):mJ(e,r,i)},m8=function(e,t){iJ(e);var i=tz(t);return mU(rH(i).concat(ft(i)),function(t){tL&&!tM(m7,i,t)||m6(e,t,i[t])}),e},m7=function(e){var t=iw(e),i=tM(mz,this,t);return!(this===mB&&iE(mZ,t)&&!iE(m$,t))&&(!(i||!iE(this,t)||!iE(mZ,t)||iE(this,mx)&&this[mx][t])||i)},m9=function(e,t){var i=tz(e),r=iw(t);if(i!==mB||!iE(mZ,r)||iE(m$,r)){var n=mq(i,r);return!n||!iE(mZ,r)||iE(i,mx)&&i[mx][r]||(n.enumerable=!0),n}},fe=function(e){var t=mX(tz(e)),i=[];return mU(t,function(e){iE(mZ,e)||iE(rk,e)||mQ(i,e)}),i},ft=function(e){var t=e===mB,i=mX(t?m$:tz(e)),r=[];return mU(i,function(e){iE(mZ,e)&&(!t||iE(mB,e))&&mQ(r,mZ[e])}),r};if(t8||(nK(mW=(mG=function(){if(tv(mW,this))throw mH("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?nh(arguments[0]):void 0,t=ig(e),i=function(e){this===mB&&tM(i,m$,e),iE(this,mx)&&iE(this[mx],t)&&(this[mx][t]=!1),m4(this,t,tB(1,e))};return tL&&m3&&m4(mB,t,{configurable:!0,set:i}),m5(t,e)}).prototype,"toString",function(){return mj(this).tag}),nK(mG,"withoutSetter",function(e){return m5(ig(e),e)}),tU.f=m7,iH.f=m6,rW.f=m8,tP.f=m9,rb.f=mN.f=fe,rj.f=ft,mP.f=function(e){return m5(iy(e),e)},tL&&mJ(mW,"description",{configurable:!0,get:function(){return mj(this).description}})),i1({global:!0,wrap:!0,forced:!t8,sham:!t8},{Symbol:mG}),mU(rH(m2),function(e){mk(e)}),i1({target:mV,stat:!0,forced:!t8},{for:function(e){var t=nh(e);if(iE(m0,t))return m0[t];var i=mG(t);return m0[t]=i,m1[i]=t,i},keyFor:function(e){if(!ie(e))throw mH(e+" is not a symbol");if(iE(m1,e))return m1[e]},useSetter:function(){m3=!0},useSimple:function(){m3=!1}}),i1({target:"Object",stat:!0,forced:!t8,sham:!tL},{create:function(e,t){return void 0===t?rZ(e):m8(rZ(e),t)},defineProperty:m6,defineProperties:m8,getOwnPropertyDescriptor:m9}),i1({target:"Object",stat:!0,forced:!t8},{getOwnPropertyNames:fe,getOwnPropertySymbols:ft}),i1({target:"Object",stat:!0,forced:tf(function(){rj.f(1)})},{getOwnPropertySymbols:function(e){return rj.f(ip(e))}}),mY&&i1({target:"JSON",stat:!0,forced:!t8||tf(function(){var e=mG();return"[null]"!=mY([e])||"{}"!=mY({a:e})||"{}"!=mY(Object(e))})},{stringify:function(e,t,i){var r=oy(arguments),n=t;if((tQ(t)||void 0!==e)&&!ie(e))return lx(t)||(t=function(e,t){if(tD(n)&&(t=tM(n,this,e,t)),!ie(t))return t}),r[1]=t,tw(mY,null,r)}}),!mW[mF]){var fi=mW.valueOf;nK(mW,mF,function(e){return tM(fi,this)})}n$(mG,mV),rk[mx]=!0,mk("asyncIterator"),mk("hasInstance"),mk("isConcatSpreadable"),mk("iterator"),mk("match"),mk("matchAll"),mk("replace"),mk("search"),mk("species"),mk("split"),mk("toPrimitive"),mk("toStringTag"),mk("unscopables"),n$(tA.JSON,"JSON",!0);var fr=tZ.Symbol;mk("asyncDispose"),mk("dispose"),mk("matcher"),mk("metadata"),mk("observable"),mk("patternMatch"),mk("replaceAll");var fn=mP.f("asyncIterator");function fo(e){this.wrapped=e}function fs(e){var t,i;function r(t,i){try{var o=e[t](i),s=o.value,a=s instanceof fo;sG.resolve(a?s.wrapped:s).then(function(e){a?r("return"===t?"return":"next",e):n(o.done?"return":"normal",e)},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 sG(function(o,s){var a={key:e,arg:n,resolve:o,reject:s,next:null};i?i=i.next=a:(t=i=a,r(e,n))})},"function"!=typeof e.return&&(this.return=void 0)}function fa(e){return function(){return new fs(e.apply(this,arguments))}}function fc(e){return new fo(e)}fs.prototype["function"==typeof fr&&fn||"@@asyncIterator"]=function(){return this},fs.prototype.next=function(e){return this._invoke("next",e)},fs.prototype.throw=function(e){return this._invoke("throw",e)},fs.prototype.return=function(e){return this._invoke("return",e)};var fd=mP.f("iterator");function fl(e,t){var i={},r=!1;function n(i,n){return r=!0,{done:!1,value:t(n=new sG(function(t){t(e[i](n))}))}}return i[void 0!==fr&&fd||"@@iterator"]=function(){return this},i.next=function(e){return r?(r=!1,e):n("next",e)},"function"==typeof e.throw&&(i.throw=function(e){if(r)throw r=!1,e;return n("throw",e)}
1),"function"==typeof e.return&&(i.return=function(e){return r?(r=!1,e):n("return",e)}),i}var fu={exports:{}};function fh(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?fh(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):fh(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}function f_(e,t,i,r,n,o,s){let a=[],c=[],d=[],l=[],u=!1,h=!1;if(fu.exports.parse(e).mediaDescriptions.forEach(e=>{s&&s!==e.attributes.direction||("video"!==e.media.mediaType||u||(c=e.attributes.payloads,l=e.attributes.extmaps,u=!0),"audio"!==e.media.mediaType||h||(a=e.attributes.payloads,d=e.attributes.extmaps,h=!0))}),!l||0===c.length)throw Error("Cannot get video capabilities from SDP.");if(!d||0===a.length)throw Error("Cannot get audio capabilities from SDP.");return c.forEach(e=>{var t;null!=(t=e.rtpMap)&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate))}),a.forEach(e=>{var t;null!=(t=e.rtpMap)&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate))}),t&&(a=a.filter(e=>{var t;return"rtx"!==(null==(t=e.rtpMap)?void 0:t.encodingName.toLowerCase())}),c=c.filter(e=>{var t;return"rtx"!==(null==(t=e.rtpMap)?void 0:t.encodingName.toLowerCase())})),i&&(c=c.filter(e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null==(t=e.rtpMap)?void 0:t.encodingName)||"")})),r&&(a=a.filter(e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null==(t=e.rtpMap)?void 0:t.encodingName)||"")})),n&&(null==n?void 0:n.length)>0&&(a=a.filter(e=>{var t;return n.includes((null==(t=e.rtpMap)?void 0:t.encodingName.toLowerCase())||"")})),o&&(null==o?void 0:o.length)>0&&(c=c.filter(e=>{var t;return o.includes((null==(t=e.rtpMap)?void 0:t.encodingName.toLowerCase())||"")})),{audioCodecs:a,videoCodecs:c,audioExtensions:d,videoExtensions:l}}function fE(e){let t,i,r=fu.exports.parse(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 fm(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 ff(e,t){let i,r,{cname:n}=e;t&&t.ip&&"number"==typeof t.port?(i=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:t.ip,port:t.port.toString(),type:"host",extension:{}}],dg.debug("Using remote candidate from AP ".concat(t.ip,":").concat(t.port)),t.ip6&&(i.push({foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:t.ip6,port:t.port.toString(),type:"host",extension:{}}),dg.debug("Using IPV6 remote candidate from AP ".concat(t.ip6,":").concat(t.port)))):i=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:{}}));let o={fingerprints:e.dtlsParameters.fingerprints.map(e=>({hashFunction:e.algorithm,fingerprint:e.fingerprint}))},s={iceUfrag:e.iceParameters.iceUfrag,icePwd:e.iceParameters.icePwd};
1switch(e.dtlsParameters.role){case"server":r="passive";break;case"client":r="active";break;case"auto":r="actpass"}return{dtlsParameters:o,iceParameters:s,candidates:i,rtpCapabilities:fO(e.rtpCapabilities),setup:r,cname:n}}function fS(e,t,i){let r=[],n=[];return e.forEach(e=>{let{ssrcId:o,rtx:s}=e,a=hV(8,"track-"),c={ssrcId:o,attributes:fp({label:a,mslabel:i=i||hV(10,""),msid:"".concat(i," ").concat(a)},t&&{cname:t})};if(r.push(c),void 0!==s){let e={ssrcId:s,attributes:fp({label:a,mslabel:i,msid:"".concat(i," ").concat(a)},t&&{cname:t})};r.push(e),n.push({semantic:"FID",ssrcIds:[o,s]})}}),e.length>1&&n.push({semantic:"SIM",ssrcIds:e.map(e=>{let{ssrcId:t}=e;return t})}),{ssrcs:r,ssrcGroups:n}}function fT(e,t){t instanceof hh&&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:{}}),e.fmtp.parameters.minptime="10",e.fmtp.parameters.useinbandfec="1";let n=t._encoderConfig;n&&"pcmu"!==r&&"pcma"!==r&&"g722"!==r&&(n.bitrate&&!az()&&(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"))})}function fg(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 fR(e,t){if(!(t instanceof mg&&t._encoderConfig&&-1===t._hints.indexOf(X.SCREEN_TRACK)))return;let i=t._encoderConfig;lU.supportMinBitrate&&i.bitrateMin&&e.attributes.payloads.forEach(e=>{var t;["h264","vp8","vp9","av1"].includes((null==(t=e.rtpMap)?void 0:t.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-min-bitrate"]="".concat(i.bitrateMin))}),lU.supportMinBitrate&&!t._hints.includes(X.LOW_STREAM)&&i.bitrateMax&&e.attributes.payloads.forEach(e=>{var t;["h264","vp8","vp9","av1"].includes((null==(t=e.rtpMap)?void 0:t.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-start-bitrate"]="".concat(dM.X_GOOGLE_START_BITRATE||Math.floor(i.bitrateMax)))})}function fI(i){if("video"!==i.media.mediaType)return;let r=aY();if(r.name!==t.SAFARI&&r.os!==e.IOS)return;let n=i.attributes.extmaps.findIndex(e=>/video-orientation/g.test(e.extensionName));-1!==n&&i.attributes.extmaps.splice(n,1)}function fC(e,t,i){let r,n;if(t){var o,s;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=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.extensionName);t&&(e.attributes.extmaps.find(e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.extensionName)||e.attributes.extmaps.push({entry:t.entry,extensionName:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"}),(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=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===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=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.extensionName);t&&(e.attributes.extmaps.find(e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.extensionName)||e.attributes.extmaps.push({entry:t.entry,extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"}),(s=n,e.attributes.payloads.filter(e=>!!s.find(t=>t.payloadType===e.payloadType&&!!t.rtcpFeedbacks.find(e=>
1"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=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.extensionName);-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach(e=>{let t=e.rtcpFeedbacks.findIndex(e=>"goog-remb"===e.type);-1!==t&&e.rtcpFeedbacks.splice(t,1)})}}}function fv(e,t,i){if(az()||"video"!==e.media.mediaType||!(t instanceof mg)||"vp9"!==i&&"vp8"!==i||"vp8"===i&&!dM.SIMULCAST||void 0===t._scalabiltyMode||t._scalabiltyMode.numSpatialLayers<=1)return;let r="vp8"===i?2:t._scalabiltyMode.numSpatialLayers,n=e.attributes.ssrcs[0],o=e.attributes.ssrcGroups.find(e=>"FID"===e.semantic&&e.ssrcIds[0]===n.ssrcId),s={semantic:"SIM",ssrcIds:[n.ssrcId]};for(let t=1;t<r;t++)e.attributes.ssrcs.push({ssrcId:n.ssrcId+t,attributes:hz(n.attributes)}),s.ssrcIds.push(n.ssrcId+t),o&&(e.attributes.ssrcs.push({ssrcId:o.ssrcIds[1]+t,attributes:hz(n.attributes)}),e.attributes.ssrcGroups.push({semantic:"FID",ssrcIds:[n.ssrcId+t,o.ssrcIds[1]+t]}));e.attributes.ssrcGroups.unshift(s)}async function fy(e,t,i,r,n){let o=new RTCPeerConnection;o.addTransceiver("video",{direction:"sendonly"}),o.addTransceiver("audio",{direction:"sendonly"}),o.addTransceiver("video",{direction:"recvonly"}),o.addTransceiver("audio",{direction:"recvonly"});let s=(await o.createOffer()).sdp,a=f_(s,e,t,i,r,n,"sendonly"),c=f_(s,e,t,i,r,n,"recvonly"),d={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},l={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},u={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(fA(a,c,"videoExtensions",d,l,u),fA(a,c,"videoCodecs",d,l,u),fA(a,c,"audioExtensions",d,l,u),fA(a,c,"audioCodecs",d,l,u),dM.RAISE_H264_BASELINE_PRIORITY){let e=u.videoCodecs.findIndex(e=>{var t,i;return"h264"===(null==(t=e.rtpMap)?void 0:t.encodingName.toLocaleLowerCase())&&"42001f"===(null==(i=e.fmtp)?void 0:i.parameters["profile-level-id"])});if(-1!==e){let t=u.videoCodecs.findIndex(e=>{var t;return"h264"===(null==(t=e.rtpMap)?void 0:t.encodingName.toLocaleLowerCase())});if(t<e){dg.debug("raising H264 baseline profile priority");let i=u.videoCodecs[e];u.videoCodecs.splice(e,1),u.videoCodecs.splice(t,0,i)}-1!==t&&(l.videoCodecs=l.videoCodecs.filter(e=>{var t,i;return"h264"!==(null==(t=e.rtpMap)?void 0:t.encodingName.toLocaleLowerCase())||"42001f"===(null==(i=e.fmtp)?void 0:i.parameters["profile-level-id"])})),-1!==t&&dM.FILTER_SEND_H264_BASELINE&&(d.videoCodecs=d.videoCodecs.filter(e=>{var t,i;return"h264"!==(null==(t=e.rtpMap)?void 0:t.encodingName.toLocaleLowerCase())||"42001f"===(null==(i=e.fmtp)?void 0:i.parameters["profile-level-id"])}))}}try{o.close()}catch(e){}return{send:d,recv:l,sendrecv:u}}function fA(e,t,i,r,n,o){if("videoExtensions"===i||"audioExtensions"===i){let s=[];return e[i].forEach(e=>{t[i].some((t,i)=>{if(e.entry===t.entry&&e.extensionName===t.extensionName)return s.push(i),!0})?o[i].push(e):r[i].push(e)}),void t[i].forEach((e,t)=>{-1===s.indexOf(t)&&n[i].push(e)})}if("videoCodecs"===i||"audioCodecs"===i){let s=[];return e[i].forEach(e=>{t[i].some((t,i)=>{if(e.payloadType===t.payloadType&&JSON.stringify(e)===JSON.stringify(t))return s.push(i),!0})?o[i].push(e):r[i].push(e)}),void t[i].forEach((e,t)=>{-1===s.indexOf(t)&&n[i].push(e)})}}function fO(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=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=o,{send:t,recv:i}}function fb(e){"audio"===e.media.mediaType&&e.attributes.payloads.filter(e=>{var t;return"opus"===(null==(t=e.rtpMap)?void 0:t.encodingName.toLowerCase())}
1).forEach(e=>{e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1"})}fu.exports=(()=>{var e={8:(e,t,i)=>{var r;let n;i.r(t),i.d(t,{Parser:()=>R,Printer:()=>A,parse:()=>w,print:()=>D});let o="".concat("\r").concat("\n");function s(e){return e>="0"&&e<="9"}function a(e){return e>="!"&&e<="~"}function c(e){return a(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 u(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function h(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 u(e)||s(e)||"+"===e||"/"===e}function E(e){return s(e)||u(e)||"+"===e||"/"===e||"-"===e||"_"===e}function m(e){return u(e)||s(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){T(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 T(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 g{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&&s(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(;s(e[i])||u(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;s(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&&s(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);s(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,s),h(e[i])?i+1:i}consumeRepeatInterval(e,t){if(!l(e[t]))throw Error("Invalid repeat interval");for(t+=1;s(e[t]);)t+=1;return h(e[t])&&(t+=1),t}consumePort(e,t){return this.consumeOneOrMore(e,t,s)}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 g{constructor(){super(),T(this,"records",[]),T(this,"currentLine",0)}parse(e){let t=this.probeEOL(e);this.records=e.split(t).filter(e=>!!e.trim()).map(this.parseLine),this.currentLine=0;let i=this.parseVersion(),r=this.parseOrigin(),n=this.parseSessionName(),o=this.parseInformation(),s=this.parseUri(),a=this.parseEmail(),c=this.parsePhone(),d=this.parseConnection(),l=this.parseBandWidth(),u=this.parseTimeFields(),h=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:s,emails:a,phones:c,connection:d,bandwidths:l,timeFields:u,key:h,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 C;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 v(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,s);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,s));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,s);this.consumeSpaceForRecord(e);let r=this.extractOneOrMore(e,s);this.consumeSpaceForRecord(e);let o=this.extractOneOrMore(e,d);this.consumeSpaceForRecord(e);let a=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:a,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(),s=this.parseMediaAttributes(t);e.push({media:t,information:i,connections:r,bandwidths:n,key:o,attributes:s})}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,...i){let r=t.call(this,e.value,e.cur,...i),n=e.value.slice(e.cur,r);return e.cur=r,n}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}}class I extends g{constructor(...e){super(...e),T(this,"attributes",void 0),T(this,"digested",!1)}extractOneOrMore(e,t,i){let r=this.consumeOneOrMore(e.attValue,e._cur,t),n=e.attValue.slice(e._cur,r),[o,s]=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 s&&n.length>s)throw Error("error in length, should be less or equal than ".concat(s," 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,...i){if(!e.attValue)throw Error("Nothing to extract from attValue.");let r=t.call(this,e.attValue,e._cur,...i),n=e.attValue.slice(e._cur,r);return e._cur=r,n}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,s);"/"===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}}class C extends I{constructor(...e){super(...e),T(this,"attributes",{unrecognized:[],groups:[],extmaps:[],fingerprints:[],identities:[]})}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}}class v extends I{constructor(e){super(),T(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:[]}}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,s,[1,5]);this.consumeAttributeSpace(e);let r=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);let n=this.extractOneOrMore(e,s,[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,a)}this.attributes.candidates.push(d)}parseRemoteCandidate(e){let t=[];for(;;){let i=this.extractOneOrMore(e,s,[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,s)};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,s);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=t.trim();let n="string"==typeof i?i.trim():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=>u(e)||s(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,s,[1,5])}parseMaxMessageSize(e){this.attributes.maxMessageSize=this.extractOneOrMore(e,s,[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})}}function y(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{constructor(){y(this,"eol",o)}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 b(this.eol).print(e)}printMediaAttributes(e){return new N(this.eol).print(e)}}class O{constructor(e){y(this,"eol",void 0),this.eol=e}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("")}}class b extends O{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 N extends O{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 w(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)})();class fN{constructor(e){cc(this,"sessionDesc",void 0),cc(this,"localCapabilities",void 0),cc(this,"rtpCapabilities",void 0),cc(this,"candidates",void 0),cc(this,"iceParameters",void 0),cc(this,"dtlsParameters",void 0),cc(this,"setup",void 0),cc(this,"currentMidIndex",void 0),cc(this,"cname",void 0);let{remoteIceParameters:t,remoteDtlsParameters:i,candidates:r,remoteRTPCapabilities:n,remoteSetup:o,localCapabilities:s,sdkCodec:a,cname:c}=e=hz(e),d=fu.exports.parse("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.iceParameters=t,this.dtlsParameters=i,this.setup=o,this.localCapabilities=s,this.cname=c;for(let e=0;e<d.mediaDescriptions.length;e++){let s=d.mediaDescriptions[e];if(s.attributes.iceUfrag=t.iceUfrag,s.attributes.icePwd=t.icePwd,s.attributes.fingerprints=i.fingerprints,s.attributes.candidates=r,s.attributes.setup=o,"video"===s.media.mediaType){s.media.fmts=n.videoCodecs.map(e=>e.payloadType.toString(10));let e=n.videoCodecs.filter(e=>{var t;return null==(t=e.rtpMap)?void 0:t.encodingName.toLowerCase().includes(a)});if(0===e.length)throw Error("Codec ".concat(a," not supported by remote SDP."));s.attributes.payloads=e,s.attributes.extmaps=n.videoExtensions}"audio"===s.media.mediaType&&(s.media.fmts=n.audioCodecs.map(e=>e.payloadType.toString(10)),s.attributes.payloads=n.audioCodecs,s.attributes.extmaps=n.audioExtensions),d.mediaDescriptions[e]=this.mungMediaDesc(s)}this.sessionDesc=d,this.currentMidIndex=d.mediaDescriptions.length-1}toString(){return fu.exports.print(this.sessionDesc)}send(e,t,i){let{ssrcs:r,ssrcGroups:n}=fS(t,this.cname),o=this.sessionDesc.mediaDescriptions.find(t=>e===en.VIDEO?"video"===t.media.mediaType:"audio"===t.media.mediaType),s=r[0].attributes.label,a=r[0].attributes.mslabel;return o.attributes.ssrcs=o.attributes.ssrcs.concat(r),o.attributes.ssrcGroups=o.attributes.ssrcGroups.concat(n),{id:s,mslabel:a}}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=>{e.includes(t.attributes.label||"")?n.push(t):i.push(t)}),t.attributes.ssrcGroups.forEach(e=>{n.map(e=>e.ssrcId).includes(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){}restartICE(e){e=hz(e),this.iceParameters=e,this.sessionDesc.mediaDescriptions.forEach(t=>
1{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=hz(e);return fT(i,t),fR(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===en.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=hz(e);return fg(t),function(e){let t=e.attributes.extmaps.find(e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.extensionName);t&&e.attributes.extmaps.splice(e.attributes.extmaps.indexOf(t),1),e.attributes.payloads.forEach(e=>{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]}}function fw(e){if(Array.isArray(e))return e.map(e=>e);if(!fD(e))return e;let t={};for(let i in e)fD(e[i])||Array.isArray(e[i])?t[i]=fw(e[i]):t[i]=e[i];return t}function fD(e){return!("object"!=typeof e||Array.isArray(e)||!e)}class fP{constructor(e){cc(this,"input",[]),cc(this,"size",void 0),this.size=e}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}}let fL={address:"unknown",candidateType:"unknown",id:"unknown",port:0,priority:0,protocol:"unknown",type:"unknown"},fk={timestamp:0,bitrate:{actualEncoded:0,transmit:0},sendPacketLossRate:0,recvPacketLossRate:0,videoRecv:[],videoSend:[],audioRecv:[],audioSend:[],selectedCandidatePair:{id:"unknown",localCandidate:fL,remoteCandidate:fL}},fM={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},fU={firsCount:0,nacksCount:0,plisCount:0,frameCount:0,bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,qpSumPerFrame:0},fx={bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0},fV={jitterBufferMs:0,jitterMs:0,bytes:0,packetsLost:0,packetLostRate:0,packets:0,ssrc:0,receivedFrames:0,droppedFrames:0,concealedSamples:0};class fF{constructor(e,t){cc(this,"onFirstVideoReceived",void 0),cc(this,"onFirstVideoDecoded",void 0),cc(this,"onFirstAudioReceived",void 0),cc(this,"onFirstVideoDecodedTimeout",void 0),cc(this,"onFirstAudioDecoded",void 0),cc(this,"onSelectedLocalCandidateChanged",void 0),cc(this,"onSelectedRemoteCandidateChanged",void 0),cc(this,"videoIsReady",!1),cc(this,"videoIsReady2",{}),cc(this,"pc",void 0),cc(this,"options",void 0),cc(this,"intervalTimer",void 0),cc(this,"stats",fw(fk)),cc(this,"isFirstVideoReceived",{}),cc(this,"isFirstVideoDecoded",{}),cc(this,"isFirstAudioReceived",{}),cc(this,"isFirstAudioDecoded",{}),cc(this,"isFirstVideoDecodedTimeout",{}),cc(this,"lossRateWindowStats",[]),this.pc=e,this.options=t,this.intervalTimer=window.setInterval(async()=>{this.updateStats()},this.options.updateInterval)}getStats(){return this.stats}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 s of["videoSend","audioSend","videoRecv","audioRecv"])e[s].forEach((e,a)=>{if(!this.lossRateWindowStats[t-1][s][a]||!this.lossRateWindowStats[0][s][a])return;let c=this.lossRateWindowStats[t-1][s][a].packets-this.lossRateWindowStats[0][s][a].packets,d=this.lossRateWindowStats[t-1][s][a].packetsLost-this.lossRateWindowStats[0][s][a].packetsLost;
1"videoSend"===s||"audioSend"===s?(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)}}function fj(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 fB extends fF{constructor(){super(...arguments),cc(this,"_stats",fk),cc(this,"lastDecodeVideoReceiverStats",new Map)}async updateStats(){let e=await this._getStats(),t=this.statsResponsesToObjects(e);this._stats=fw(fk);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)}processSSRCStats(e){e.forEach(e=>{let t=e.id.includes("send");switch("".concat(e.mediaType,"_").concat(t?"send":"recv")){case"video_send":{let t=fw(fU);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.pl
1isCount=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=fw(fM),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:function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?fj(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):fj(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}({},t),lts:Date.now()}),this._stats.videoRecv.push(t);break}case"audio_recv":{let t=fw(fV);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=fw(fx);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 sG((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}}function fG(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 fW(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?fG(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):fG(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}class fH extends fF{constructor(){super(...arguments),cc(this,"_stats",fk),cc(this,"report",void 0),cc(this,"lastDecodeVideoReceiverStats",new Map),cc(this,"lastVideoFramesRecv",new Map),cc(this,"lastVideoFramesSent",new Map),cc(this,"lastVideoFramesDecode",new Map),cc(this,"lastVideoJBDelay",new Map),cc(this,"lastAudioJBDelay",new Map),cc(this,"mediaBytesSent",new Map),cc(this,"mediaBytesRetransmit",new Map),cc(this,"mediaBytesTargetEncode",new Map),cc(this,"lastEncoderMs",new Map)}async updateStats(){this.report=await this.pc.getStats(),this._stats=fw(fk),this.report.forEach(e=>{switch(e.type){case aH.OUTBOUND:"audio"===e.mediaType?this.processAudioOutboundStats(e):"video"===e.mediaType&&this.processVideoOutboundStats(e);break;case aH.INBOUND:"audio"===e.mediaType?this.processAudioInboundStats(e):"video"===e.mediaType&&this.processVideoInboundStats(e);break;case aH.TRANSPORT:{let t=this.report.get(e.selectedCandidatePairId);t&&this.processCandidatePairStats(t);break}case aH.CANDIDATE_PAIR:e.selected&&this.processCandidatePairStats(e)}}),this.updateSendBitrate(),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats}processCandidatePairStats(e){if(this._stats.sendBandwidth=e.availableOutgoingBitrate||0,e.currentRoundTripTime&&(this._stats.rtt=1e3*e.currentRoundTripTime),this._stats.videoSend.forEach(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===aH.LOCAL_CANDIDATE&&(t=this._stats.selectedCandidatePair.localCandidate),e.type===aH.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===aH.LOCAL_CANDIDATE&&this.stats.selectedCandidatePair.localCandidate.id!==t.id&&this.onSelectedLocalCandidateChanged&&this.onSelectedLocalCandidateChanged(fW({},t),fW({},this.stats.selectedCandidatePair.localCandidate)),e.type===aH.REMOTE_CANDIDATE&&this.stats.selectedCandidatePair.remoteCandidate.id!==t.id&&this.onSelectedRemoteCandidateChanged&&this.onSelectedRemoteCandidateChanged(fW({},t),fW({},this.stats.selectedCandidatePair.remoteCandidate)))}processAudioInboundStats(e){let t=this._stats.audioRecv.find(t=>t.ssrc===e.ssrc);
1t||(t=fw(fV),this._stats.audioRecv.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsReceived,t.packetsLost=e.packetsLost,t.bytes=e.bytesReceived,t.jitterMs=1e3*e.jitter,this.processAudioTrackReceiverStats(e,e.trackId,t),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)}processVideoInboundStats(e){let t=this._stats.videoRecv.find(t=>t.ssrc===e.ssrc);t||(t=fw(fM),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.totalInterFrameDelay=e.totalInterFrameDelay,t.totalSquaredInterFrameDelay=e.totalSquaredInterFrameDelay;let i=this.lastDecodeVideoReceiverStats.get(t.ssrc),r=this.lastVideoFramesDecode.get(t.ssrc),n=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,o=n-i.lts;t.framesDecodeFreezeTime=r.framesDecodeFreezeTime,t.framesDecodeInterval=r.framesDecodeInterval,this.isFirstVideoDecoded[t.ssrc]||!(o>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=o,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))}r&&n-r.lts>=800?(t.decodeFrameRate=Math.round((t.framesDecodeCount-r.count)/((n-r.lts)/1e3)),this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:n,rate:t.decodeFrameRate})):r?t.decodeFrameRate=r.rate:this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:n,rate:0}),e.totalDecodeTime&&(t.decodeMs=1e3*e.totalDecodeTime),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:fW({},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=fw(fU),this._stats.videoSend.push(t));let i=this.mediaBytesSent.get(e.ssrc);if(i)i.add(e.bytesSent);else{let t=new fP(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 fP(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 fP(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,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,aH.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t)}}processAudioOutboundStats(e){let t=this._stats.audioSend.find(t=>t.ssrc===e.ssrc);if(t||(t=fw(fx),this._stats.audioSend.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsSent,t.bytes=e.bytesSent,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,aH.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t)}}findRemoteStatsId(e,t){var i;let r=Array.from(u8(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;let s=t?this.report.get(t):void 0,a=null!=(r=null==s?void 0:s.framesSent)?r:e.framesSent,c=null!=(n=null==s?void 0:s.frameWidth)?n:e.frameWidth,d=null!=(o=null==s?void 0:s.frameHeight)?o:e.frameHeight;if("number"!=typeof a)return;0!==a||"number"==typeof c&&"number"==typeof d||(c=0,d=0);let l=0,u=Date.now(),h=this.lastVideoFramesSent.get(i.ssrc);h&&u-h.lts>=800?(l=Math.round((a-h.count)/((u-h.lts)/1e3)),this.lastVideoFramesSent.set(i.ssrc,{count:a,lts:u,rate:l})):h?l=h.rate:this.lastVideoFramesSent.set(i.ssrc,{count:a,lts:u,rate:0}),i.sentFrame={width:c,height:d,frameRate:Math.max(0,l)}}processVideoTrackReceiverStats(e,t,i){var r,n,o,s,a;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,u=null!=(o=null==c?void 0:c.frameHeight)?o:e.frameHeight,h=null!=(s=null==c?void 0:c.jitterBufferDelay)?s:e.jitterBufferDelay,p=null!=(a=null==c?void 0:c.jitterBufferEmittedCount)?a: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:u||0,frameRate:r||0},i.decodedFrame={width:l||0,height:u||0,frameRate:i.decodeFrameRate||0},i.outputFrame={width:l||0,height:u||0,frameRate:i.decodeFrameRate||0}}if(h&&p){let e=this.lastVideoJBDelay.get(i.ssrc);this.lastVideoJBDelay.set(i.ssrc,{jitterBufferDelay:h,jitterBufferEmittedCount:p}),e||(e={jitterBufferDelay:0,jitterBufferEmittedCount:0});let t=1e3*(h-e.jitterBufferDelay)/(p-e.jitterBufferEmittedCount);i.jitterBufferMs=t,i.currentDelayMs=Math.round(t)}}processAudioTrackSenderStats(e,t,i){var r,n,o,s;let a=t?this.report.get(t):void 0,c=null!=(r=null!=(n=null==a?void 0:a.echoReturnLoss)?n:e.echoReturnLoss)?r:0,d=null!=(o=null!=(s=null==a?void 0:a.echoReturnLossEnhancement)?s:e.echoReturnLossEnhancement)?o:0;i.aecReturnLoss=c,i.aecReturnLossEnhancement=d}processAudioTrackReceiverStats(e,t,i){var r,n,o,s,a,c,d;let l=t?this.report.get(t):void 0,u=null!=(r=null==l?void 0:l.removedSamplesForAcceleration)?r:e.removedSamplesForAcceleration,h=null!=(n=null==l?void 0:l.totalSamplesReceived)?n:e.totalSamplesReceived,p=null!=(o=null==l?void 0:l.jitterBufferDelay)?o:e.jitterBufferDelay,_=null!=(s=null==l?void 0:l.jitterBufferEmittedCount)?s:e.jitterBufferEmittedCount,E=null!=(a=null==l?void 0:l.audioLevel)?a:null==e?void 0:e.audioLevel,m=null!=(c=null==l?void 0:l.totalSamplesDuration)?c:null==e?void 0:e.totalSamplesDuration,f=null!=(d=null==l?void 0:l.concealedSamples)?d:e.concealedSamples;if(u&&h&&(i.accelerateRate=u/h),p&&_){let e=this.lastAudioJBDelay.get(i.ssrc);this.lastAudioJBDelay.set(i.ssrc,{jitterBufferDelay:p,jitterBufferEmittedCount:_}),e||(e={jitterBufferDelay:0,jitterBufferEmittedCount:0}),i.jitterBufferMs=Math.round(1e3*(p-e.jitterBufferDelay)/(_-e.jitterBufferEmittedCount))}i.outputLevel=E;let S=1920;m&&h&&(S=h/m/50,i.receivedFrames=Math.round(h/S)),f&&(i.droppedFrames=Math.round(f/S))}processRemoteInboundStats(e,t){let i=this.report.get(e);i&&(t.packetsLost=i.packetsLost,i.roundTripTime&&(t.rttMs=1e3*i.roundTripTime))}getCodecFromCodecStats(e){let t=this.report.get(e);if(!t)return"";let i=t.mimeType.match(/\/(.*)$/);
1return 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))}}class fK extends fF{updateStats(){return sG.resolve()}}function fY(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 fB(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:r,firstVideoDecodedTimeout:n}):new fH(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:r,firstVideoDecodedTimeout:n}):window.RTCStatsReport&&e.getStats()instanceof sG?new fH(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:r,firstVideoDecodedTimeout:n}):new fK(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:r,firstVideoDecodedTimeout:n})}function fq(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 fJ(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?fq(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):fq(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let fX=(ui((eR=class e extends lM{get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}constructor(t,i){super(t,i),cc(this,"store",void 0),cc(this,"peerConnection",void 0),cc(this,"remoteSDP",void 0),cc(this,"initialOffer",void 0),cc(this,"statsFilter",void 0),cc(this,"useRTX",!1),cc(this,"localCapabilities",void 0),cc(this,"localCandidateCount",0),cc(this,"allCandidatesReceived",!1),cc(this,"establishPromise",void 0),cc(this,"mutex",new uO("P2PConnection-mutex")),this.store=i,this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.statsFilter=fY(this.peerConnection,void 0,void 0,az()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}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=fE(e.sdp),i=f_(e.sdp,!this.useRTX,dM.FILTER_VIDEO_FEC,dM.FILTER_AUDIO_FEC,["opus"]);return this.localCapabilities=i,this.initialOffer=e,fJ(fJ({},t),{},{rtpCapabilities:{send:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},recv:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},sendrecv:i},offerSDP:e.sdp})}catch(e){throw new du(o.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e,t,i,r,n,s){try{if(!this.initialOffer)throw Error("Cannot establish P2PConnection without initial offer.");this.remoteSDP=new fN({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:r.send,remoteSetup:n,localCapabilities:this.localCapabilities,sdkCodec:this.store.codec,cname:s});let o=this.remoteSDP.toString();await this.peerConnection.setLocalDescription(this.initialOffer),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new du(o.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}send(e,t){var i=this;return fa(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()),s=fu.exports.parse(o.sdp),a=e.map(e=>{let t=e._mediaStreamTrack,r=s.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 a}
1catch(e){throw n.forEach(e=>{aX()&&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:a[t],id:i}})}catch(e){throw new du(o.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=>{aX()&&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 du(o.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 sG((t,r)=>{let o=setTimeout(()=>{r(Error("Cannot receive track, id: ".concat(i)))},1e4),s=r=>{let a=aY();if(("Safari"===a.name&&11===Number(a.version)||aQ())&&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",s),clearTimeout(o),void t(n)}if(r.track.id===i)return this.peerConnection.removeEventListener("track",s),clearTimeout(o),void t(r.track)};this.peerConnection.addEventListener("track",s)}),s=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:s});let a=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(a),{track:await o,id:i}}catch(e){throw new du(o.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 du(o.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(aX()&&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 du(o.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(aX()&&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 du(o.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(){var e=this;return fa(function*(){let t=yield fc(e.mutex.lock("From P2PConnection.restartICE"));try{let t=yield fc(e.peerConnection.createOffer({iceRestart:!0}));if(!t.sdp)throw Error("Cannot restartICE because restart offer SDP does not exist.");let i=fE(t.sdp),{remoteIceParameters:r}=yield i.iceParameters;if(!e.remoteSDP)throw Error("Cannot restartICE before remoteSDP created.");e.remoteSDP.restartICE(r);let n=e.remoteSDP.toString();yield fc(e.peerConnection.setLocalDescription(t)),yield fc(e.peerConnection.setRemoteDescription({type:"answer",sdp:n}))}catch(e){dg.warning("restart ICE failed, abort operation",e)}finally{t()}})()}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 du(o.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)}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,dg.debug("[pc-".concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,dg.debug("[pc-".concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))},dM.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&&(lS(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),dM.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 applySendEncodings(e,t){try{if(!lU.supportSetRtpSenderParameters||e.length!==t.length)return;for(let r=0;r<e.length;r++){var i;let n=e[r],o=t[r];if(!o)continue;let s={},a={};if(o instanceof mg)switch(o._optimizationMode){case"motion":s.degradationPreference="maintain-framerate";break;case"detail":s.degradationPreference="maintain-resolution";break;default:s.degradationPreference="balanced"}if(dM.DSCP_TYPE&&ce()){let e=dM.DSCP_TYPE;["very-low","low","medium","high"].includes(e)&&(a.networkPriority=e)}let c=n.getParameters(),d=null==(i=c.encodings)?void 0:i[0];d&&Object.assign(d,a),Object.assign(c,s),await n.setParameters(c)}}catch(e){dg.debug("Apply RTPSendEncodings failed.")}}mungSendOfferSDP(e,t){let i=fu.exports.parse(e);return t.forEach((e,t)=>{let r=e._mediaStreamTrack,n=i.mediaDescriptions.find(e=>e.attributes.mid===r.kind);n&&fT(n,e)}),fu.exports.print(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 sG((e,t)=>{let i=setTimeout(()=>{t(Error("Cannot receive track, id: ".concat(r)))},1e4),s=t=>{let a=aY();if("Safari"===a.name&&11===Number(a.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",s),clearTimeout(i),void e({track:n,id:r})}if(t.track.id===r)return this.peerConnection.removeEventListener("track",s),clearTimeout(i),void e({track:t.track,id:r})};this.peerConnection.addEventListener("track",s)})}),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 sG.all(t)}catch(e){throw new du(o.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}
1setConfiguration(t){if(lU.supportPCSetConfiguration){let i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}}}).prototype,"connect",[fz],Object.getOwnPropertyDescriptor(eR.prototype,"connect"),eR.prototype),ui(eR.prototype,"stopSending",[fz],Object.getOwnPropertyDescriptor(eR.prototype,"stopSending"),eR.prototype),ui(eR.prototype,"receive",[fz],Object.getOwnPropertyDescriptor(eR.prototype,"receive"),eR.prototype),ui(eR.prototype,"stopReceiving",[fz],Object.getOwnPropertyDescriptor(eR.prototype,"stopReceiving"),eR.prototype),ui(eR.prototype,"muteRemote",[fz],Object.getOwnPropertyDescriptor(eR.prototype,"muteRemote"),eR.prototype),ui(eR.prototype,"unmuteRemote",[fz],Object.getOwnPropertyDescriptor(eR.prototype,"unmuteRemote"),eR.prototype),ui(eR.prototype,"muteLocal",[fz],Object.getOwnPropertyDescriptor(eR.prototype,"muteLocal"),eR.prototype),ui(eR.prototype,"unmuteLocal",[fz],Object.getOwnPropertyDescriptor(eR.prototype,"unmuteLocal"),eR.prototype),ui(eR.prototype,"close",[fz],Object.getOwnPropertyDescriptor(eR.prototype,"close"),eR.prototype),ui(eR.prototype,"updateEncoderConfig",[fz],Object.getOwnPropertyDescriptor(eR.prototype,"updateEncoderConfig"),eR.prototype),ui(eR.prototype,"updateSendParameters",[fz],Object.getOwnPropertyDescriptor(eR.prototype,"updateSendParameters"),eR.prototype),ui(eR.prototype,"replaceTrack",[fz],Object.getOwnPropertyDescriptor(eR.prototype,"replaceTrack"),eR.prototype),ui(eR.prototype,"getRemoteSSRC",[fz],Object.getOwnPropertyDescriptor(eR.prototype,"getRemoteSSRC"),eR.prototype),eR);function fz(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),s=0;s<n;s++)o[s]=arguments[s];return await r.apply(this,o)}finally{i()}},i}class fQ{get localCapabilities(){return hz(this._localCapabilities)}get rtpCapabilities(){return hz(this._rtpCapabilities)}get candidates(){return hz(this._candidates)}get iceParameters(){return hz(this._iceParameters)}get dtlsParameters(){return hz(this._dtlsParameters)}constructor(e){cc(this,"sessionDesc",void 0),cc(this,"_localCapabilities",void 0),cc(this,"_rtpCapabilities",void 0),cc(this,"_candidates",void 0),cc(this,"_iceParameters",void 0),cc(this,"_dtlsParameters",void 0),cc(this,"setup",void 0),cc(this,"currentMidIndex",void 0),cc(this,"cname",void 0),cc(this,"firefoxSsrcMidMap",new Map);let{remoteIceParameters:t,remoteDtlsParameters:i,candidates:r,remoteRTPCapabilities:n,remoteSetup:o,localCapabilities:s,cname:a}=e=hz(e),c=fu.exports.parse("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\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=n,this._candidates=r,this._iceParameters=t,this._dtlsParameters=i,this._localCapabilities=s,this.setup=o,this.cname=a;let d=this.rtpCapabilities.send;for(let e of c.mediaDescriptions){if(e.attributes.iceUfrag=t.iceUfrag,e.attributes.icePwd=t.icePwd,e.attributes.fingerprints=i.fingerprints,e.attributes.candidates=r,e.attributes.setup=o,"video"===e.media.mediaType&&(e.media.fmts=d.videoCodecs.map(e=>e.payloadType.toString(10)),e.attributes.payloads=d.videoCodecs,e.attributes.extmaps=d.videoExtensions,dM.PRELOAD_MEDIA_COUNT>0)){let{ssrcs:t,ssrcGroups:i}=fS([{ssrcId:4e4,rtx:dM.USE_RTX?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}if("audio"===e.media.mediaType&&(e.media.fmts=d.audioCodecs.map(e=>e.payloadType.toString(10)),e.attributes.payloads=d.audioCodecs,e.attributes.extmaps=d.audioExtensions,fb(e),dM.PRELOAD_MEDIA_COUNT>0)){let{ssrcs:t,ssrcGroups:i}=fS([{ssrcId:2e4}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}}this.sessionDesc=c,this.currentMidIndex=c.mediaDescriptions.length-1}preloadRemoteMedia(){let e=dM.PRELOAD_MEDIA_COUNT;this.rtpCapabilities;let t=this.candidates,i=this.dtlsParameters,r=this.iceParameters,n=this.rtpCapabilities.send;for(let o=1;o<e;o++){let e=2*o+2e4,s=2*o+4e4,{ssrcs:a,ssrcGroups:c}=fS([{ssrcId:e}],this.cname),{ssrcs:d,ssrcGroups:l}=fS([{ssrcId:s,rtx:dM.USE_RTX?s+1:void 0}],this.cname);this.sessionDesc.mediaDescriptions.push({media:{mediaType:"video",port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:n.videoCodecs.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:r.iceUfrag,icePwd:r.icePwd,unrecognized:[],candidates:t,extmaps:n.videoExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:d,ssrcGroups:l,rtcpFeedbackWildcards:[],payloads:n.videoCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(2*o)}}),this.sessionDesc.mediaDescriptions.push({media:{mediaType:"audio",port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:n.audioCodecs.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:r.iceUfrag,icePwd:r.icePwd,unrecognized:[],candidates:t,extmaps:n.audioExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:a,ssrcGroups:c,rtcpFeedbackWildcards:[],payloads:n.audioCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(2*o+1)}}),this.currentMidIndex+=2}this.updateBundleMids()}toString(){return fu.exports.print(this.sessionDesc)}send(e,t,i,r){let{ssrcs:n,ssrcGroups:o}=fS(t,this.cname,dM.SYNC_GROUP?i:void 0),s=this.findPreloadMediaDesc(n);if(s){if(az()&&this.firefoxSsrcMidMap.set(n[0].ssrcId,s.attributes.mid),r&&(r.twcc||r.remb)){let e=this.sessionDesc.mediaDescriptions.indexOf(s);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(s,r),{mid:s.attributes.mid,needExchangeSDP:!0}}return{mid:s.attributes.mid,needExchangeSDP:!1}}{let t,i=this.findAvailableMediaIndex(e,n);return -1===i||1===i&&(aX()||a1())||a2()?(t=this.createOrRecycleSendMedia(e,n,o,"sendonly",r),this.updateBundleMids()):((t=hz(this.sessionDesc.mediaDescriptions[i])).attributes.direction="sendonly",t.attributes.ssrcs=n,t.attributes.ssrcGroups=o,this.sessionDesc.mediaDescriptions[i]=this.mungSendMediaDesc(t,r)),az()&&this.firefoxSsrcMidMap.set(n[0].ssrcId,t.attributes.mid),{mid:t.attributes.mid,needExchangeSDP:!0}}}batchSend(e){let t=e.map(e=>{let{kind:t,ssrcMsg:i,mslabel:r}=e;return this.send(t,i,r)}),i=[],r=!1;
1return 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||az()||a2()?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=>e.includes(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=>e.includes(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()}restartICE(e){e=hz(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(az()){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})}createOrRecycleRecvMedia(e,t,i,r,n,o){let s=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,c=this.localCapabilities.send,d=[];if(s===en.VIDEO){var l,u;if(dM.H264_PROFILE_LEVEL_ID&&"h264"===r&&(d=a.videoCodecs.filter(e=>{var t,i;return((null==(t=e.rtpMap)?void 0:t.encodingName.toLowerCase())||"").includes(r)&&(null==e||null==(i=e.fmtp)?void 0:i.parameters["profile-level-id"])===dM.H264_PROFILE_LEVEL_ID})),!d||0===(null==(l=d)?void 0:l.length)){let e=c.videoCodecs.filter(e=>{var t;return((null==(t=e.rtpMap)?void 0:t.encodingName.toLowerCase())||"").includes(r)});0!==e.length&&(d=a.videoCodecs.filter(t=>e.some(e=>e.payloadType===t.payloadType)))}if(dM.USE_RTX){let e=d.map(e=>e.payloadType.toString());d=[...d,...a.videoCodecs.filter(t=>{var i,r;return"rtx"===(null==(i=t.rtpMap)?void 0:i.encodingName)&&e.includes((null==(r=t.fmtp)?void 0:r.parameters.apt)||"")})]}0===d.length&&(dg.warning("codec ".concat(r," not included in rtpCapabilities, fallback to default payloads: ").concat(null==(u=a.videoCodecs[0].rtpMap)?void 0:u.encodingName)),d=a.videoCodecs)}else 0===(d=a.audioCodecs.filter(e=>{var t;return((null==(t=e.rtpMap)?void 0:t.encodingName.toLowerCase())||"").includes(n)})).length&&(dg.warning("codec ".concat(n," not included in rtpCapabilities, fallback to opus")),d=a.audioCodecs.filter(e=>{var t;return((null==(t=e.rtpMap)?void 0:t.encodingName.toLowerCase())||"").includes("opus")}));let h=s===en.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;let p="".concat(this.currentMidIndex),_={media:{mediaType:s,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:d.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:h,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:d,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(p)}};_=this.mungRecvMediaDsec(_,e,o);let E=this.findFirstClosedMedia(s);if(E){let e=this.sessionDesc.mediaDescriptions.indexOf(E);this.sessionDesc.mediaDescriptions[e]=_}else this.sessionDesc.mediaDescriptions.push(_);return _}createOrRecycleSendMedia(e,t,i,r,n){let o=this.rtpCapabilities.send,s=e===en.VIDEO?o.videoCodecs:o.audioCodecs,a=e===en.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: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:a,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(c)}};d=this.mungSendMediaDesc(d,n);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}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=hz(e);return fg(r),fT(r,t),fR(r,t),fI(r),fC(r,i,this.localCapabilities.send),r}mungSendMediaDesc(e,t){let i=hz(e);return fC(i,t,this.localCapabilities.recv),fb(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=>az()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port)}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find(t=>{var i,r;return(null==(i=t.attributes)||null==(r=i.ssrcs[0])?void 0:r.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}}function fZ(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 f$(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
1t%2?fZ(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):fZ(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let f0=(ui((eI=class e extends lM{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}constructor(t,i){super(t,i),cc(this,"store",void 0),cc(this,"peerConnection",void 0),cc(this,"remoteSDP",void 0),cc(this,"initialOffer",void 0),cc(this,"transportEventReceiver",void 0),cc(this,"statsFilter",void 0),cc(this,"useRTX",dM.USE_RTX),cc(this,"localCapabilities",void 0),cc(this,"localCandidateCount",0),cc(this,"allCandidatesReceived",!1),cc(this,"establishPromise",void 0),cc(this,"mutex",new uO("P2PConnection-mutex")),this.store=i,this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.statsFilter=fY(this.peerConnection,void 0,void 0,az()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}async establish(){try{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});let e=await this.peerConnection.createOffer();if(!e.sdp)throw Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");let t=fE(e.sdp),i=await fy(!this.useRTX,dM.FILTER_VIDEO_FEC,dM.FILTER_AUDIO_FEC);return this.localCapabilities=fO(i),this.initialOffer=e,f$(f$({},t),{},{rtpCapabilities:i,offerSDP:e.sdp})}catch(e){throw new du(o.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e,t,i,r,n,s){try{if(!this.initialOffer)throw Error("Cannot establish P2PConnection without initial offer.");this.remoteSDP=new fQ({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:r,remoteSetup:n,localCapabilities:this.localCapabilities,cname:s});let o=this.remoteSDP.toString(),a=fu.exports.parse(this.initialOffer.sdp),c=a.mediaDescriptions.find(e=>"audio"===e.media.mediaType);c&&fb(c);let d=fu.exports.print(a),l=this.logSDPExchange(d||"","offer","local","connect");await this.peerConnection.setLocalDescription({type:"offer",sdp:d}),null==l||l(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o});let u=this.peerConnection.getTransceivers()[0];if(null!=u&&u.receiver&&this.tryBindTransportEvents(u.receiver),dM.PRELOAD_MEDIA_COUNT>0){this.remoteSDP.preloadRemoteMedia();let e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});let t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t)}}catch(e){throw new du(o.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}send(e,t,i){var r=this;return fa(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=[];e.forEach(e=>{let t=r.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});o.push(t)}),az()&&!0===dM.SIMULCAST&&(yield fc(r.applySimulcastForFirefox(o,e)));let s=yield fc(r.peerConnection.createOffer()),a=r.remoteSDP.predictReceivingMids(e.length),c=r.mungSendOfferSDP(s.sdp,e,a),d=fu.exports.parse(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 fm(t,r.useRTX)});try{n=yield l}catch(s){n=[],r.remoteSDP.receive(e,t,i,n);let o=r.remoteSDP.toString();throw yield fc(r.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield fc(r.peerConnection.setRemoteDescription({type:"answer",sdp:o})),yield fc(r.stopSending(a,!0)),s}r.remoteSDP.receive(e,t,i,n);let u=r.remoteSDP.toString(),h=r.logSDPExchange(c,"offer","local","send");return yield fc(r.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield fc(r.applySimulcastEncodings(o,e)),yield fc(r.applySendEncodings(o,e)),null==h||h(u),yield fc(r.peerConnection.setRemoteDescription({type:"answer",sdp:u})),o.map((e,t)=>{let i=a[t];return{localSSRC:l[t],id:i,transceiver:e}})}catch(e){throw e instanceof du?e:new du(o.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-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;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 du(o.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.peerConnection.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}),dg.debug("[P2PConnection] receive ".concat(e," by exchanging SDP."))}else dg.debug("[P2PConnection] receive ".concat(e," no need to exchange SDP."));let s=this.peerConnection.getTransceivers().find(e=>e.mid===n);if(!s)throw Error("Cannot get transceiver after setLocalDescription.");return{track:s.receiver.track,id:n}}catch(e){throw new du(o.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);if(i){let e=this.remoteSDP.toString(),t=this.logSDPExchange(e,"offer","remote","receive");await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});let i=await this.peerConnection.createAnswer();null==t||t(i.sdp||""),await this.peerConnection.setLocalDescription(i),dg.debug("[P2PConnection] batchReceive by exchanging SDP.")}else dg.debug("[P2PConnection] batchReceive no need to exchange SDP.");return 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}})}catch(e){throw new du(o.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.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 du(o.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 du(o.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 du(o.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 du(o.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);let n=this.remoteSDP.toString();null==r||r(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new du(o.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(){var e=this;return fa(function*(){let t=yield fc(e.mutex.lock("From P2PConnection.restartICE"));try{let t=yield fc(e.peerConnection.createOffer({iceRestart:!0}));if(!t.sdp)throw Error("Cannot restartICE because restart offer SDP does not exist.");let i=fE(t.sdp),{remoteIceParameters:r}=yield i.iceParameters;if(!e.remoteSDP)throw Error("Cannot restartICE before remoteSDP created.");e.remoteSDP.restartICE(r);let n=e.remoteSDP.toString(),o=e.logSDPExchange(t.sdp||"","offer","local","restartICE");yield fc(e.peerConnection.setLocalDescription(t)),null==o||o(n),yield fc(e.peerConnection.setRemoteDescription({type:"answer",sdp:n}))}catch(e){dg.warning("restart ICE failed, abort operation",e)}finally{t()}})()}close(){var e;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()}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 du(o.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)?az()||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)}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,dg.debug("[pc-".concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,dg.debug("[pc-".concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))},dM.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:[]};return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(lS(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),dM.USE_TURN_SERVER_OF_GATEWAY&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),dM.FORCE_TURN_TCP?i.iceTransportPolicy="relay":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(hy(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!dM.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}tryBindTransportEvents(e){e.transport&&(this.transportEventReceiver=e,e.transport.onstatechange=()=>{var t,i;null!=(t=e.transport)&&t.state&&(null==(i=this.onDTLSTransportStateChange)||i.call(this,e.transport.state))},e.transport.onerror=e=>{var t;null==(t=this.onDTLSTransportError)||t.call(this,e.error)},e.transport.iceTransport&&(e.transport.iceTransport.onstatechange=()=>{var t,i;let r=null==(t=e.transport)?void 0:t.iceTransport.state;r&&(null==(i=this.onICETransportStateChange)||i.call(this,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 applySendEncodings(e,t){try{if(!lU.supportSetRtpSenderParameters||e.length!==t.length)return;for(let c=0;c<e.length;c++){let d=e[c],l=t[c];if(l&&l instanceof mg){var i,r,n,o,s,a;if(this.isVP8Simulcast(l))continue;let e={},t={};switch(l._optimizationMode){case"motion":e.degradationPreference="maintain-framerate";break;case"detail":e.degradationPreference="maintain-resolution";break;default:e.degradationPreference="balanced"}if(null!=(i=l._encoderConfig)&&i.bitrateMax&&(t.maxBitrate=1e3*(null==(n=l._encoderConfig)?void 0:n.bitrateMax)),l._hints.includes(X.LOW_STREAM)&&(null!=(o=l._encoderConfig)&&o.frameRate&&(t.maxFramerate=hO(l._encoderConfig.frameRate)),null!=(s=l._encoderConfig)&&s.scaleResolutionDownBy&&(null==(a=l._encoderConfig)?void 0:a.scaleResolutionDownBy)>1&&(t.scaleResolutionDownBy=l._encoderConfig.scaleResolutionDownBy)),dM.DSCP_TYPE&&ce()){let e=dM.DSCP_TYPE;["very-low","low","medium","high"].includes(e)&&(t.networkPriority=e)}let c=d.sender.getParameters(),u=null==(r=c.encodings)?void 0:r[0];az()&&!u&&(e.encodings=[t]),u&&Object.assign(u,t),Object.assign(c,e),await d.sender.setParameters(c)}}}catch(e){dg.debug("Apply RTPSendEncodings failed.")}}mungSendOfferSDP(e,t,i){let r=fu.exports.parse(e);return t.forEach((e,t)=>{let n=i[t],o=r.mediaDescriptions.find(e=>e.attributes.mid===n);o&&(fT(o,e),fv(o,e,this.store.codec))}),fu.exports.print(r)}mungReceiveAnswerSDP(e,t,i){let r=fu.exports.parse(e),n=r.mediaDescriptions.find(e=>e.attributes.mid===t);return n&&i===en.AUDIO&&"audio"===n.media.mediaType&&fb(n),fu.exports.print(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;let a=e[s],c=t[s];if(c instanceof mg&&!c._hints.includes(X.LOW_STREAM)&&null!=(i=c._encoderConfig)&&i.bitrateMax&&(null==(r=c._encoderConfig)?void 0:r.bitrateMax)>
1200&&null!=(n=c._scalabiltyMode)&&n.numSpatialLayers&&(null==(o=c._scalabiltyMode)?void 0:o.numSpatialLayers)>1&&"vp8"===this.store.codec){let e={},t={high:1e3*(c._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=a.sender.getParameters();await a.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!az()&&e.length===t.length)for(let i=0;i<e.length;i++){let r=t[i];if(r instanceof mg&&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 s=t.sender.getParameters();await t.sender.setParameters(Object.assign(s,n))}}}isVP8Simulcast(e){var t,i,r,n;return!!(e instanceof mg&&dM.SIMULCAST&&"vp8"===this.store.codec&&!e._hints.includes(X.LOW_STREAM)&&null!=(t=e._encoderConfig)&&t.bitrateMax&&(null==(i=e._encoderConfig)?void 0:i.bitrateMax)>200&&null!=(r=e._scalabiltyMode)&&r.numSpatialLayers&&(null==(n=e._scalabiltyMode)?void 0:n.numSpatialLayers)>1)}logSDPExchange(e,t,i,r){if(dM.SDP_LOGGING)return dg.upload("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 null==t?void 0:t[0].ssrcId}
1setConfiguration(t){if(lU.supportPCSetConfiguration){let i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}}}).prototype,"connect",[f1],Object.getOwnPropertyDescriptor(eI.prototype,"connect"),eI.prototype),ui(eI.prototype,"receive",[f1],Object.getOwnPropertyDescriptor(eI.prototype,"receive"),eI.prototype),ui(eI.prototype,"batchReceive",[f1],Object.getOwnPropertyDescriptor(eI.prototype,"batchReceive"),eI.prototype),ui(eI.prototype,"stopReceiving",[f1],Object.getOwnPropertyDescriptor(eI.prototype,"stopReceiving"),eI.prototype),ui(eI.prototype,"muteRemote",[f1],Object.getOwnPropertyDescriptor(eI.prototype,"muteRemote"),eI.prototype),ui(eI.prototype,"unmuteRemote",[f1],Object.getOwnPropertyDescriptor(eI.prototype,"unmuteRemote"),eI.prototype),ui(eI.prototype,"muteLocal",[f1],Object.getOwnPropertyDescriptor(eI.prototype,"muteLocal"),eI.prototype),ui(eI.prototype,"unmuteLocal",[f1],Object.getOwnPropertyDescriptor(eI.prototype,"unmuteLocal"),eI.prototype),ui(eI.prototype,"close",[f1],Object.getOwnPropertyDescriptor(eI.prototype,"close"),eI.prototype),ui(eI.prototype,"updateEncoderConfig",[f1],Object.getOwnPropertyDescriptor(eI.prototype,"updateEncoderConfig"),eI.prototype),ui(eI.prototype,"updateSendParameters",[f1],Object.getOwnPropertyDescriptor(eI.prototype,"updateSendParameters"),eI.prototype),ui(eI.prototype,"replaceTrack",[f1],Object.getOwnPropertyDescriptor(eI.prototype,"replaceTrack"),eI.prototype),ui(eI.prototype,"getRemoteSSRC",[f1],Object.getOwnPropertyDescriptor(eI.prototype,"getRemoteSSRC"),eI.prototype),eI);function f1(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),s=0;s<n;s++)o[s]=arguments[s];return await r.apply(this,o)}finally{i()}},i}function f2(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=hO(t.width),r.height=hO(t.height);let n=hO(t.framerate||15);document.body.append(i),document.body.append(r);let s=e._mediaStreamTrack;i.srcObject=new MediaStream([s]),i.play();let a=r.getContext("2d");if(!a)throw new du(o.UNEXPECTED_ERROR,"can not get canvas context");let c=r.captureStream(lU.supportRequestFrame?0:n).getVideoTracks()[0],d=ux(()=>(()=>{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&&(dg.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),c.requestFrame&&c.requestFrame(),s!==e._mediaStreamTrack&&(s=e._mediaStreamTrack,i.srcObject=new MediaStream([s]))})(),n),l=c.stop;return c.stop=()=>{l.call(c),d(),i&&(i.remove(),i=null),r&&(r.width=0,r.remove(),r=null),dg.debug("clean low stream renderer")},c}function f3(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 f4(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?f3(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):f3(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}class f5 extends uv{getUserId(){return this._userId}constructor(e,t,i,r){super(e,"track-".concat(e.kind,"-").concat(t,"-").concat(r.clientId,"_").concat(hV(5,""))),cc(this,"_userId",void 0),cc(this,"_uintId",void 0),cc(this,"_isDestroyed",!1),cc(this,"store",void 0),cc(this,"processor",void 0),cc(this,"processorContext",void 0),this._userId=t,this._uintId=i,this.store=r}_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,dg.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}let f6=(eC=uI({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),ev=uI({argsMap:e=>[e.getTrackId()]}),ey=uI({argsMap:(e,t)=>[e.getTrackId(),t.name]}),eA=uI({argsMap:e=>[e.getTrackId()]}),ui((eO=class extends f5{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==c.PLAYING)}get __className__(){return"RemoteVideoTrack"}constructor(e,t,i,r){super(e,t,i,r),cc(this,"_videoVisibleTimer",null),cc(this,"_previousVideoVisibleStatus",void 0),cc(this,"_clearPreviousVideoVisibleStatus",()=>this._previousVideoVisibleStatus=void 0),cc(this,"trackMediaType","video"),cc(this,"_videoWidth",void 0),cc(this,"_videoHeight",void 0),cc(this,"_player",void 0),cc(this,"processorDestination",void 0),cc(this,"processorContext",void 0),this.updateMediaStreamTrackResolution(),this.processorContext=new ht(this.getTrackId(),"remote"),this.processorDestination=new he(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){return hZ(()=>
1{dg.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")},"remoteVideoTrackGetStatsWarning"),hK(this,J.GET_STATS)||f4({},ly)}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:(dg.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}dg.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));let i=f4(f4({fit:"cover"},t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new p6(i):this._player=new p7(i),this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.emit($.FIRST_FRAME_DECODED)}),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.emit($.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}},dM.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,dg.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){hB(this._originMediaStreamTrack).then(e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t}).catch(hj)}_updatePlayerSource(){dg.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=mf.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;let e=uC.reportApiInvoke(null,{tag:_.TRACER,name:p.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 du(o.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}pipe(e){if(this.processor===e)return e;if(e._source)throw new du(o.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(el.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(el.ON_TRACK)}_destroy(){super._destroy(),this.unbindProcessorDestinationEvents()}}).prototype,"play",[eC],Object.getOwnPropertyDescriptor(eO.prototype,"play"),eO.prototype),ui(eO.prototype,"stop",[ev],Object.getOwnPropertyDescriptor(eO.prototype,"stop"),eO.prototype),ui(eO.prototype,"pipe",[ey],Object.getOwnPropertyDescriptor(eO.prototype,"pipe"),eO.prototype),ui(eO.prototype,"unpipe",[eA],Object.getOwnPropertyDescriptor(eO.prototype,"unpipe"),eO.prototype),eO),f8=(eb=uI({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}
1),eN=uI({argsMap:(e,t)=>[e.getTrackId(),t]}),ew=uI({argsMap:e=>[e.getTrackId()]}),eD=uI({argsMap:e=>[e.getTrackId()]}),eP=uI({argsMap:(e,t)=>[e.getTrackId(),t.name]}),eL=uI({argsMap:e=>[e.getTrackId()]}),ui((ek=class extends f5{get isPlaying(){return this._useAudioElement?u2.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}constructor(e,t,i,r){super(e,t,i,r),cc(this,"trackMediaType","audio"),cc(this,"_source",void 0),cc(this,"_useAudioElement",!0),cc(this,"_volume",100),cc(this,"processorContext",void 0),cc(this,"processorDestination",void 0),cc(this,"_played",!1),cc(this,"_bypassWebAudio",!1),dM.DISABLE_WEBAUDIO?(this._source=new hn,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new uj(e,!0),dM.REMOTE_AUDIO_TRACK_USES_WEB_AUDIO&&(this._useAudioElement=!1)),this._source.once(P.RECEIVE_TRACK_BUFFER,()=>{this.emit($.FIRST_FRAME_DECODED)}),this.processorContext=new hr(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new hi(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(P.UPDATE_SOURCE,()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})})}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(P.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(P.ON_AUDIO_BUFFER),this._source.on(P.ON_AUDIO_BUFFER,t=>e(t))}setVolume(e){this._volume=e,this._useAudioElement?u2.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement)throw new du(o.NOT_SUPPORTED,"your browser does not support setting the audio output device");await u2.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getStats(){return hZ(()=>{dg.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")},"remoteAudioTrackGetStatsWarning"),hK(this,J.GET_STATS)||f4({},lC)}play(){dg.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement?(dg.debug("[".concat(this.getTrackId(),"] use audio element to play")),u2.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):this._source.play()}stop(){dg.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?u2.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];dg.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&u2.updateTrack(this.getTrackId(),this._mediaStreamTrack)}pipe(e){if(this._bypassWebAudio)throw new du(o.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new du(o.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 du(o.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(el.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())}),this.processorDestination.on(el.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(el.ON_TRACK),this.processorDestination.removeAllListeners(el.ON_NODE)}}).prototype,"setVolume",[eb],Object.getOwnPropertyDescriptor(ek.prototype,"setVolume"),ek.prototype),ui(ek.prototype,"setPlaybackDevice",[eN],Object.getOwnPropertyDescriptor(ek.prototype,"setPlaybackDevice"),ek.prototype),ui(ek.prototype,"play",[ew],Object.getOwnPropertyDescriptor(ek.prototype,"play"),ek.prototype),ui(ek.prototype,"stop",[eD],Object.getOwnPropertyDescriptor(ek.prototype,"stop"),ek.prototype),ui(ek.prototype,"pipe",[eP],Object.getOwnPropertyDescriptor(ek.prototype,"pipe"),ek.prototype),ui(ek.prototype,"unpipe",[eL],Object.getOwnPropertyDescriptor(ek.prototype,"unpipe"),ek.prototype),ek);function f7(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 f9(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
1t%2?f7(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):f7(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}class Se extends dd{constructor(){super(),cc(this,"uplinkStatsUploadInterval",void 0),cc(this,"uplinkStatsUploadSlowInterval",void 0),cc(this,"uplinkRelatedStatsUploadInterval",void 0),cc(this,"uplinkDenoiserStatsUploadInterval",void 0),cc(this,"transportStatsUploadInterval",void 0),cc(this,"uplinkExtensionStatsUploadInterval",void 0),cc(this,"downlinkExtensionStatsUploadInterval",void 0),cc(this,"extensionUsageStatsUploadInterval",void 0),cc(this,"downlinkStatsUploadInterval",void 0),cc(this,"downlinkStatsUploadSlowInterval",void 0),cc(this,"downlinkRelatedStatsUploadInterval",void 0),cc(this,"lastStats",void 0),cc(this,"uploadUnplinkStarted",!1),cc(this,"uploadDownlinkStarted",!1),cc(this,"uploadTransportStarted",!1),cc(this,"uploadExtensionUsageStarted",!1),cc(this,"requestStats",void 0),cc(this,"requestLocalMedia",void 0),cc(this,"requestRemoteMedia",void 0),cc(this,"requestAllTracks",void 0),cc(this,"requestVideoIsReady",void 0),cc(this,"requestUpload",void 0)}startUploadTransportStats(){this.uploadTransportStarted||(this.uploadTransportStarted=!0,this.transportStatsUploadInterval&&window.clearInterval(this.transportStatsUploadInterval),this.transportStatsUploadInterval=window.setInterval(()=>{var e;let t=null==(e=this.requestStats)?void 0:e.call(this);t&&this.uploadTransportStats(t)},1e3))}startUploadExtensionUsageStats(){if(this.uploadExtensionUsageStarted)return;this.uploadExtensionUsageStarted=!0,this.extensionUsageStatsUploadInterval&&window.clearInterval(this.extensionUsageStatsUploadInterval);let e=new Map;this.extensionUsageStatsUploadInterval=window.setInterval(async()=>{var t,i,r;let n=Date.now(),o={connectionInterval:dM.EXTENSION_USAGE_UPLOAD_INTERVAL/1e3,details:[],lts:n},s=[];for(let e of(null==(t=this.requestAllTracks)?void 0:t.call(this))||[])!e.muted&&e.enabled&&(s=s.concat(await e.getProcessorUsage()));for(let[e,t]of(null==(i=this.requestRemoteMedia)?void 0:i.call(this))||[])t.has(en.VIDEO)&&e.videoTrack&&(s=s.concat(await e.videoTrack.getProcessorUsage())),t.has(en.AUDIO)&&e.audioTrack&&(s=s.concat(await e.audioTrack.getProcessorUsage()));if(0===s.length)return;o.details=function(e,t){let i={};for(let{id:s,value:a,level:c,direction:d}of e){var r,n,o;let e=null!=(r=t.get(s))?r:0,l=2===a?e+dM.EXTENSION_USAGE_UPLOAD_INTERVAL/1e3:e;t.set(s,l),i[s]?(2===a&&(i[s].value=a),c>i[s].level&&(i[s].level=c),"remote"===d&&(i[s].remoteUidCount+=1),i[s].totalTs=null!=(n=t.get(s))?n:0):i[s]={value:a,level:c,remoteUidCount:+("local"!==d),totalTs:null!=(o=t.get(s))?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}})}(s,e);let a=Date.now(),c=a>n?a:n+1;null==(r=this.requestUpload)||r.call(this,N.EXTENSION_USAGE_STATS,{usageStats:o,sendTs:c})},dM.EXTENSION_USAGE_UPLOAD_INTERVAL)}startUploadUplinkStats(){this.uploadUnplinkStarted||(this.uploadUnplinkStarted=!0,this.uplinkStatsUploadInterval&&window.clearInterval(this.uplinkStatsUploadInterval),this.uplinkStatsUploadInterval=window.setInterval(()=>{var e;let t=null==(e=this.requestStats)?void 0:e.call(this);t&&(this.uploadUplinkStats(t),this.lastStats=t)},3e3),this.uplinkStatsUploadSlowInterval&&window.clearInterval(this.uplinkStatsUploadSlowInterval),this.uplinkStatsUploadSlowInterval=window.setInterval(()=>{var e;let t=null==(e=this.requestStats)?void 0:e.call(this);t&&this.uploadSlowUplinkStats(t)},6e4),this.uplinkRelatedStatsUploadInterval&&window.clearInterval(this.uplinkRelatedStatsUploadInterval),this.uplinkRelatedStatsUploadInterval=window.setInterval(()=>{var e;let t=null==(e=this.requestStats)?void 0:e.call(this);t&&this.uploadRelatedUplinkStats(t,this.lastStats),this.lastStats=t},1e3),this.uplinkDenoiserStatsUploadInterval&&window.clearInterval(this.uplinkDenoiserStatsUploadInterval),this.uplinkDenoiserStatsUploadInterval=window.setInterval(()=>{var e;let t=null==(e=this.requestAllTracks)?void 0:e.call(this);t&&this.uploadDenoiserStats(t)},2e3),this.uplinkExtensionStatsUploadInterval&&window.clearInterval(this.uplinkExtensionStatsUploadInterval),this.uplinkExtensionStatsUploadInterval=window.setInterval(()=>{var e;let t=null==(e=this.requestAllTracks)?void 0:e.call(this);t&&this.uploadExtensionStats(t)},2e3))}uploadTransportStats(e){hX(()=>{var t;null==(t=this.requestUpload)||t.call(this,N.TRANSPORT_STATS,function(e){let t={connectionType:100,googRtt:e.rtt};
1if("relay"===e.selectedCandidatePair.localCandidate.candidateType){let i=e.selectedCandidatePair.localCandidate.relayProtocol;"udp"===i&&(t.connectionType=101),"tcp"===i&&(t.connectionType=103),"tls"===i&&(t.connectionType=104)}return t}(e))})}uploadUplinkStats(e){var t;((null==(t=this.requestLocalMedia)?void 0:t.call(this))||[]).forEach(t=>{let[i,{track:r,ssrcs:n}]=t;switch(i){case eo.LocalVideoLowTrack:case eo.LocalVideoTrack:{let t=function(e,t,i){var r;let n=t.videoSend.find(t=>t.ssrc===e);if(!n)return null;let o={id:hV(10,""),timestamp:new Date(t.timestamp).toISOString(),mediaType:"video",type:"ssrc",ssrc:n.ssrc.toString()};switch(o.A_vstd=i._originMediaStreamTrack&&!i._originMediaStreamTrack.enabled||i._mediaStreamTrack&&!i._mediaStreamTrack.enabled?"1":"0",n.sentFrame&&(o.A_fhs=n.sentFrame.height.toString(),o.A_frs=n.sentFrame.frameRate.toString(),o.A_fws=n.sentFrame.width.toString()),n.adaptionChangeReason){case"none":o.A_ac="0";break;case"cpu":o.A_ac="1";break;case"bandwidth":o.A_ac="2";break;case"other":o.A_ac="3"}return o.A_lvps=l_[i._player?i._player.videoElementStatus:"uninit"].toString(),o.A_nr=null==(r=n.nacksCount)?void 0:r.toString(),n.avgEncodeMs&&(o.A_aem=n.avgEncodeMs.toFixed(0).toString()),o}(n[0].ssrcId,e,r),o=i===eo.LocalVideoTrack?hN(n[0].ssrcId,e,r):null;t&&hX(()=>{var e;return null==(e=this.requestUpload)?void 0:e.call(this,N.PUBLISH_STATS,{stream_type:i===eo.LocalVideoLowTrack?"low":"high",stats:f9(f9({},t),o)})});let s=function(e){let t={id:"bweforvideo",timestamp:new Date(e.timestamp).toISOString(),type:"VideoBwe"};return e.bitrate.retransmit&&(t.A_rb=e.bitrate.retransmit.toString()),e.bitrate.targetEncoded&&(t.A_teb=e.bitrate.targetEncoded.toString()),t.A_aeb=e.bitrate.actualEncoded.toString(),t.A_tb=e.bitrate.transmit.toString(),void 0!==e.sendBandwidth&&(t.A_asb=e.sendBandwidth.toString()),t}(e);s&&setTimeout(()=>{var e;return null==(e=this.requestUpload)?void 0:e.call(this,N.PUBLISH_STATS,{stream_type:i===eo.LocalVideoLowTrack?"low":"high",stats:s})},1e3);break}case eo.LocalAudioTrack:{let t=function(e,t,i){let r=t.audioSend.find(t=>t.ssrc===e);if(!r)return null;let n={id:hV(10,""),timestamp:new Date(t.timestamp).toISOString(),mediaType:"audio",type:"ssrc",ssrc:r.ssrc.toString()};return n.A_astd=i._originMediaStreamTrack.enabled&&i._mediaStreamTrack.enabled?"0":"1",r.inputLevel?n.A_ail=Math.round(100*r.inputLevel).toString():n.A_ail=Math.round(100*i._source.getAccurateVolumeLevel()).toString(),n.A_apil=Math.round(100*i._source.getAccurateVolumeLevel()).toString(),r.aecReturnLoss&&(n.A_ecrl=Math.round(r.aecReturnLoss).toString()),r.aecReturnLossEnhancement&&(n.A_ecrle=Math.round(r.aecReturnLossEnhancement).toString()),n}(n[0].ssrcId,e,r);t&&hX(()=>{var e;return null==(e=this.requestUpload)?void 0:e.call(this,N.PUBLISH_STATS,{stream_type:"high",stats:t})})}}})}uploadSlowUplinkStats(e){var t;((null==(t=this.requestLocalMedia)?void 0:t.call(this))||[]).filter(e=>{let[t]=e;return t===eo.LocalVideoLowTrack||t===eo.LocalVideoTrack}).forEach(t=>{let[i,{ssrcs:r}]=t,n=hN(r[0].ssrcId,e);n&&hX(()=>{var e;return null==(e=this.requestUpload)?void 0:e.call(this,N.PUBLISH_STATS,{stream_type:i===eo.LocalVideoLowTrack?"low":"high",stats:n})})})}uploadRelatedUplinkStats(e,t){var i;((null==(i=this.requestLocalMedia)?void 0:i.call(this))||[]).filter(e=>{let[t]=e;return t===eo.LocalVideoLowTrack||t===eo.LocalVideoTrack}).forEach(t=>{let[i,{ssrcs:r}]=t,n=function(e,t){let i=t.videoSend.find(t=>t.ssrc===e);return i?{mediaType:"video",isVideoMute:!1,frameRateInput:i.inputFrame&&i.inputFrame.frameRate.toString(),frameRateSent:i.sentFrame&&i.sentFrame.frameRate.toString(),googRtt:i.rttMs.toString(),qpSumPerFrame:Math.floor(i.qpSumPerFrame).toString()}:null}(r[0].ssrcId,e);n&&hX(()=>{var e;null==(e=this.requestUpload)||e.call(this,N.PUBLISH_RELATED_STATS,{stream_type:i===eo.LocalVideoLowTrack?"low":"high",stats:n})})})}uploadDenoiserStats(e){for(let n=0;n<e.length;n++){let o=e[n];if(o instanceof hp){var t,i,r;let e=null==(t=(i=o._external).getDenoiserStats)?void 0:t.call(i);return void(e&&(null==(r=this.requestUpload)||r.call(this,N.DENOISER_STATS,e)))}}}uploadExtensionStats(e){for(let t=0;t<e.length;
1t++)e[t].getProcessorStats().forEach(e=>{var t;null==(t=this.requestUpload)||t.call(this,e.type,e.stats)})}stopUploadUplinkStats(){this.uploadUnplinkStarted&&(this.uploadUnplinkStarted=!1,this.uplinkStatsUploadInterval&&window.clearInterval(this.uplinkStatsUploadInterval),this.uplinkRelatedStatsUploadInterval&&window.clearInterval(this.uplinkRelatedStatsUploadInterval),this.uplinkDenoiserStatsUploadInterval&&window.clearInterval(this.uplinkDenoiserStatsUploadInterval),this.uplinkStatsUploadInterval=void 0,this.uplinkRelatedStatsUploadInterval=void 0,this.uplinkDenoiserStatsUploadInterval=void 0)}startUploadDownlinkStats(){let e;if(this.uploadDownlinkStarted)return;this.uploadDownlinkStarted=!0,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval);let t=!1;this.downlinkStatsUploadInterval=window.setInterval(()=>{var i;let r=null==(i=this.requestStats)?void 0:i.call(this);r&&(this.uploadDownlinkStats(r,t,e),e=r),t=!t},3e3),this.downlinkStatsUploadSlowInterval&&window.clearInterval(this.downlinkStatsUploadSlowInterval),this.downlinkStatsUploadSlowInterval=window.setInterval(()=>{var e;let t=null==(e=this.requestStats)?void 0:e.call(this);t&&this.uploadSlowDownlinkStats(t)},6e4),this.downlinkRelatedStatsUploadInterval&&window.clearInterval(this.downlinkRelatedStatsUploadInterval),this.downlinkRelatedStatsUploadInterval=window.setInterval(()=>{var e;let t=null==(e=this.requestStats)?void 0:e.call(this);t&&(this.uploadRelatedDownlinkStats(t,this.lastStats),this.lastStats=t)},1e3),this.downlinkExtensionStatsUploadInterval&&window.clearInterval(this.downlinkExtensionStatsUploadInterval),this.downlinkExtensionStatsUploadInterval=window.setInterval(()=>{var e;let t=null==(e=this.requestRemoteMedia)?void 0:e.call(this);t&&this.uploadDownlinkExtensionStats(t)},2e3)}uploadDownlinkStats(e,t,i){var r;((null==(r=this.requestRemoteMedia)?void 0:r.call(this))||[]).forEach(r=>{let[n,o]=r;if(o.has(en.VIDEO)&&n.videoTrack){let r=n.videoTrack?function(e,t,i,r,n){var o,s;let a=t.videoRecv.find(t=>t.ssrc===e);if(!a)return null;let c={id:hV(10,""),timestamp:new Date(t.timestamp).toISOString(),mediaType:"video",type:"ssrc",ssrc:a.ssrc.toString()};if(c.bytesReceived=a.bytes.toString(),c.packetsLost=a.packetsLost.toString(),c.packetsReceived=a.packets.toString(),a.framesRateFirefox&&(c.A_frr=a.framesRateFirefox.toString()),a.receivedFrame?(c.A_frr=a.receivedFrame.frameRate.toString(),c.A_fhr=a.receivedFrame.height.toString(),c.A_fwr=a.receivedFrame.width.toString()):(c.A_fhr=null==(o=r._videoHeight)?void 0:o.toString(),c.A_fwr=null==(s=r._videoWidth)?void 0:s.toString()),c.A_frd=a.decodeFrameRate.toString(),a.outputFrame&&(c.A_fro=a.outputFrame.frameRate.toString()),void 0!==a.jitterBufferMs&&(c.A_jbm=Math.floor(a.jitterBufferMs).toString()),void 0!==a.currentDelayMs&&(c.A_cdm=Math.floor(a.currentDelayMs).toString()),c.A_fs=a.firsCount.toString(),c.A_ns=a.nacksCount.toString(),c.A_ps=a.plisCount.toString(),r&&(c.A_vrtd=r._originMediaStreamTrack.enabled&&r._mediaStreamTrack.enabled?"0":"1"),r._player&&r._player.freezeTimeCounterList.length>0&&(c.A_vrft=Math.round(r._player.freezeTimeCounterList.splice(0,1)[0]).toString()),n&&r._player&&"visible"===hI.visibility){let e=Math.min(6e3,r._player.renderFreezeAccTime);c.A_vrrft=Math.round(e).toString(),r._player.renderFreezeAccTime=Math.max(0,r._player.renderFreezeAccTime-e)}if(c.A_rvps=l_[r._player?r._player.videoElementStatus:"uninit"].toString(),i){let t=i.videoRecv.find(t=>t.ssrc===e);if(t&&void 0!==a.totalInterFrameDelay&&void 0!==a.totalSquaredInterFrameDelay&&void 0!==t.totalInterFrameDelay&&void 0!==t.totalSquaredInterFrameDelay){let e=a.totalInterFrameDelay-t.totalInterFrameDelay,i=a.totalSquaredInterFrameDelay-t.totalSquaredInterFrameDelay,r=a.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)&&(c.A_ifdsd=o.toString())}}return c}(n._videoSSRC,e,i,n.videoTrack,t):void 0;r&&hX(()=>{var e;return null==(e=this.requestUpload)?void 0:e.call(this,N.SUBSCRIBE_STATS,{stream_id:n.uid,stats:r})})}if(o.has(en.AUDIO)&&n.audioTrack){let t=n.audioTrack?function(e,t,i,r){let n=t.audioRecv.find(t=>t.ssrc===e);if(!n)return null;let o={id:hV(10,""),timestamp:new Date(t.timestamp).toISOString(),mediaType:"audio",type:"ssrc",ssrc:n.ssrc.toString()};if(o.bytesReceived=n.bytes.toString(),o.packetsLost=n.packetsLost.toString(),o.packetsReceived=n.packets.toString(),n.outputLevel?o.A_aol=Math.round(100*n.outputLevel).toString():o.A_aol=Math.round(100*r._source.getAccurateVolumeLevel()).toString(),o.A_apol=Math.round(100*r._source.getAccurateVolumeLevel()).toString(),r&&(o.A_artd=r._originMediaStreamTrack.enabled&&r._mediaStreamTrack.enabled?"0":"1"),o.A_jr=n.jitterMs.toString(),o.A_jbm=Math.floor(n.jitterBufferMs).toString(),o.A_cdm=Math.floor(n.jitterBufferMs).toString(),o.A_raps=l_[u2.getPlayerState(r.getTrackId())].toString(),i){let t=i.audioRecv.find(t=>t.ssrc===e);if(t){let e=n.concealedSamples-t.concealedSamples;e>0&&(o.A_cs=Math.round(e).toString())}}return o}(n._audioSSRC,e,i,n.audioTrack):void 0;t&&hX(()=>{var e;return null==(e=this.requestUpload)?void 0:e.call(this,N.SUBSCRIBE_STATS,{stream_id:n.uid,stats:t})})}})}uploadSlowDownlinkStats(e){}uploadRelatedDownlinkStats(e,t){var i;((null==(i=this.requestRemoteMedia)?void 0:i.call(this))||[]).forEac
1h(i=>{let[r,n]=i;if(n.has(en.VIDEO)&&r.videoTrack){var o;let i=!0===(r._videoSSRC&&(null==(o=this.requestVideoIsReady)?void 0:o.call(this,r._videoSSRC))||!1),n=function(e,t,i,r,n,o){let s=i.videoRecv.find(t=>t.ssrc===e),a=n?n.videoRecv.find(t=>t.ssrc===e):void 0;if(!s)return null;let c=hR.isRemoteVideoFreeze(o,s,a)&&t,d={mediaType:"video",isVideoMute:!1,peerId:r,frameRateReceived:s.receivedFrame&&s.receivedFrame.frameRate.toString(),frameRateDecoded:s.decodedFrame&&s.decodedFrame.frameRate.toString(),isFreeze:c,bytesReceived:s.bytes.toString(),packetsReceived:s.packets.toString(),packetsLost:s.packetsLost.toString(),qpSumPerFrame:Math.floor(s.qpSumPerFrame).toString()};return s.framesRateFirefox&&(d.frameRateDecoded=s.framesRateFirefox.toString(),d.frameRateReceived=s.framesRateFirefox.toString()),d}(r._videoSSRC,i,e,r.uid,t,r.videoTrack);n&&hX(()=>{var e;null==(e=this.requestUpload)||e.call(this,N.SUBSCRIBE_RELATED_STATS,{stream_id:r.uid,stats:n})})}if(n.has(en.AUDIO)&&r.audioTrack){let t=function(e,t,i,r){let n=t.audioRecv.find(t=>t.ssrc===e);if(!n)return null;let o=hR.isRemoteAudioFreeze(r);return{mediaType:"audio",isAudioMute:!1,peerId:i,googJitterReceived:n.jitterMs.toString(),isFreeze:o,bytesReceived:n.bytes.toString(),packetsReceived:n.packets.toString(),packetsLost:n.packetsLost.toString(),frameReceived:n.receivedFrames.toString(),frameDropped:n.droppedFrames.toString()}}(r._audioSSRC,e,r.uid,r.audioTrack);t&&hX(()=>{var e;null==(e=this.requestUpload)||e.call(this,N.SUBSCRIBE_RELATED_STATS,{stream_id:r.uid,stats:t})})}})}stopUploadDownlinkStats(){this.uploadDownlinkStarted&&(this.uploadDownlinkStarted=!1,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval),this.downlinkRelatedStatsUploadInterval&&window.clearInterval(this.downlinkRelatedStatsUploadInterval),this.downlinkStatsUploadInterval=void 0,this.downlinkRelatedStatsUploadInterval=void 0)}stopUploadTransportStats(){this.uploadTransportStarted&&(this.uploadTransportStarted=!1,this.transportStatsUploadInterval&&window.clearInterval(this.transportStatsUploadInterval),this.transportStatsUploadInterval=void 0)}stopUploadExtensionUsageStats(){this.uploadExtensionUsageStarted&&(this.uploadExtensionUsageStarted=!1,this.extensionUsageStatsUploadInterval&&window.clearInterval(this.extensionUsageStatsUploadInterval),this.extensionUsageStatsUploadInterval=void 0)}uploadDownlinkExtensionStats(e){e.forEach(e=>{let[t,i]=e;i.has(en.VIDEO)&&t.videoTrack&&t.videoTrack.getProcessorStats().forEac
1h(e=>{var t;null==(t=this.requestUpload)||t.call(this,e.type,e.stats)}),i.has(en.AUDIO)&&t.audioTrack&&t.audioTrack.getProcessorStats().forEach(e=>{var t;null==(t=this.requestUpload)||t.call(this,e.type,e.stats)})})}}let St="v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0\na=msid-semantic: WMS\na=ice-lite\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\nc=IN IP4 127.0.0.1\na=mid:0\n";class Si{get localCapabilities(){return hz(this._localCapabilities)}get rtpCapabilities(){return hz(this._rtpCapabilities)}get candidates(){return hz(this._candidates)}get iceParameters(){return hz(this._iceParameters)}get dtlsParameters(){return hz(this._dtlsParameters)}constructor(e){cc(this,"sessionDesc",void 0),cc(this,"_localCapabilities",void 0),cc(this,"_rtpCapabilities",void 0),cc(this,"_candidates",void 0),cc(this,"_iceParameters",void 0),cc(this,"_dtlsParameters",void 0),cc(this,"setup",void 0),cc(this,"currentMidIndex",void 0),cc(this,"cname",void 0),cc(this,"firefoxSsrcMidMap",new Map);let{remoteIceParameters:t,remoteDtlsParameters:i,candidates:r,remoteRTPCapabilities:n,remoteSetup:o,localCapabilities:s,cname:a}=e=hz(e),c=fu.exports.parse(St);this._rtpCapabilities=n,this._candidates=r,this._iceParameters=t,this._dtlsParameters=i,this._localCapabilities=s,this.setup=o,this.cname=a;let d=this.rtpCapabilities.send;for(let e of c.mediaDescriptions){if(e.attributes.iceUfrag=t.iceUfrag,e.attributes.icePwd=t.icePwd,e.attributes.fingerprints=i.fingerprints,e.attributes.candidates=r,e.attributes.setup=o,"application"===e.media.mediaType&&(e.attributes.sctpPort="5000"),"video"===e.media.mediaType&&(e.media.fmts=d.videoCodecs.map(e=>e.payloadType.toString(10)),e.attributes.payloads=d.videoCodecs,e.attributes.extmaps=d.videoExtensions,dM.PRELOAD_MEDIA_COUNT>0)){let{ssrcs:t,ssrcGroups:i}=fS([{ssrcId:4e4,rtx:dM.USE_RTX?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}if("audio"===e.media.mediaType&&(e.media.fmts=d.audioCodecs.map(e=>e.payloadType.toString(10)),e.attributes.payloads=d.audioCodecs,e.attributes.extmaps=d.audioExtensions,fb(e),dM.PRELOAD_MEDIA_COUNT>0)){let{ssrcs:t,ssrcGroups:i}=fS([{ssrcId:2e4}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}}this.sessionDesc=c,this.currentMidIndex=c.mediaDescriptions.length-1}updateRemoteRTPCapabilities(e){let t=fu.exports.parse(St);this._rtpCapabilities=e;let i=this.rtpCapabilities.send;for(let e of t.mediaDescriptions){if(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&&(e.media.fmts=i.videoCodecs.map(e=>e.payloadType.toString(10)),e.attributes.payloads=i.videoCodecs,e.attributes.extmaps=i.videoExtensions,dM.PRELOAD_MEDIA_COUNT>0)){let{ssrcs:t,ssrcGroups:i}=fS([{ssrcId:4e4,rtx:dM.USE_RTX?40001:void 0}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}if("audio"===e.media.mediaType&&(e.media.fmts=i.audioCodecs.map(e=>e.payloadType.toString(10)),e.attributes.payloads=i.audioCodecs,e.attributes.extmaps=i.audioExtensions,dM.PRELOAD_MEDIA_COUNT>0)){let{ssrcs:t,ssrcGroups:i}=fS([{ssrcId:2e4}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}}this.sessionDesc=t,this.currentMidIndex=t.mediaDescriptions.length-1}preloadRemoteMedia(e){this.rtpCapabilities;let t=this.candidates,i=this.dtlsParameters,r=this.iceParameters,n=this.rtpCapabilities.send;for(let o=1;o<e;o++){let e=2*o+2e4,s=2*o+4e4,{ssrcs:a,ssrcGroups:c}=fS([{ssrcId:e}],this.cname),{ssrcs:d,ssrcGroups:l}=fS([{ssrcId:s,rtx:dM.USE_RTX?s+1:void 0}],this.cname);this.sessionDesc.mediaDescriptions.push({media:{mediaType:"video",port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:n.videoCodecs.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:r.iceUfrag,icePwd:r.icePwd,unrecognized:[],candidates:t,extmaps:n.videoExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:d,ssrcGroups:l,rtcpFeedbackWildcards:[],payloads:n.videoCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(2*o-1)}}),this.sessionDesc.mediaDescriptions.push({media:{mediaType:"audio",port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:n.audioCodecs.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:r.iceUfrag,icePwd:r.icePwd,unrecognized:[],candidates:t,extmaps:n.audioExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:a,ssrcGroups:c,rtcpFeedbackWildcards:[],payloads:n.audioCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(2*o)}}),this.currentMidIndex+=2}this.updateBundleMids()}toString(){return fu.exports.print(this.sessionDesc)}send(e,t,i,r){let{ssrcs:n,ssrcGroups:o}=fS(t,this.cname,dM.SYNC_GROUP?i:void 0),s=this.findPreloadMediaDesc(n);if(s){if(az()&&this.firefoxSsrcMidMap.set(n[0].ssrcId,s.attributes.mid),r&&(r.twcc||r.remb)){let e=this.sessionDesc.mediaDescriptions.indexOf(s);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(s,r),{mid:s.attributes.mid,needExchangeSDP:!0}}return{mid:s.attributes.mid,needExchangeSDP:!1}}{let t,i=this.findAvailableMediaIndex(e,n);return -1===i||aX()||aQ()||a1()?(t=this.createOrRecycleSendMedia(e,n,o,"sendonly",r),this.updateBundleMids()):((t=hz(this.sessionDesc.mediaDescriptions[i])).attributes.direction="sendonly",t.attributes.ssrcs=n,t.attributes.ssrcGroups=o,this.sessionDesc.mediaDescriptions[i]=this.mungSendMediaDesc(t,r)),az()&&this.firefoxSsrcMidMap.set(n[0].ssrcId,t.attributes.mid),{mid:t.attributes.mid,needExchangeSDP:!0}}}batchSend(e){let t=e.map(e=>{let{kind:t,ssrcMsg:i,mslabel:r}=e;return this.send(t,i,r)}),i=[],r=!1;
1return 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||az()||aX()||aQ()?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=>e.includes(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=>e.includes(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()}restartICE(e){e=hz(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(az()){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})}createOrRecycleRecvMedia(e,t,i,r,n,o){let s=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,c=this.localCapabilities.send,d=[];if(s===en.VIDEO){var l,u;if(dM.H264_PROFILE_LEVEL_ID&&"h264"===r&&(d=a.videoCodecs.filter(e=>{var t,i;return((null==(t=e.rtpMap)?void 0:t.encodingName.toLowerCase())||"").includes(r)&&(null==e||null==(i=e.fmtp)?void 0:i.parameters["profile-level-id"])===dM.H264_PROFILE_LEVEL_ID})),!d||0===(null==(l=d)?void 0:l.length)){let e=c.videoCodecs.filter(e=>{var t;return((null==(t=e.rtpMap)?void 0:t.encodingName.toLowerCase())||"").includes(r)});0!==e.length&&(d=a.videoCodecs.filter(t=>e.some(e=>e.payloadType===t.payloadType)))}if(dM.USE_RTX){let e=d.map(e=>e.payloadType.toString());d=[...d,...a.videoCodecs.filter(t=>{var i,r;return"rtx"===(null==(i=t.rtpMap)?void 0:i.encodingName)&&e.includes((null==(r=t.fmtp)?void 0:r.parameters.apt)||"")})]}0===d.length&&(dg.warning("codec ".concat(r," not included in rtpCapabilities, fallback to default payloads: ").concat(null==(u=a.videoCodecs[0].rtpMap)?void 0:u.encodingName)),d=a.videoCodecs)}else 0===(d=a.audioCodecs.filter(e=>{var t;return((null==(t=e.rtpMap)?void 0:t.encodingName.toLowerCase())||"").includes(n)})).length&&(dg.warning("codec ".concat(n," not included in rtpCapabilities, fallback to opus")),d=a.audioCodecs.filter(e=>{var t;return((null==(t=e.rtpMap)?void 0:t.encodingName.toLowerCase())||"").includes("opus")}));let h=s===en.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;let p="".concat(this.currentMidIndex),_={media:{mediaType:s,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:d.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:h,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:d,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(p)}};_=this.mungRecvMediaDsec(_,e,o);let E=this.findFirstClosedMedia(s);if(E){let e=this.sessionDesc.mediaDescriptions.indexOf(E);this.sessionDesc.mediaDescriptions[e]=_}else this.sessionDesc.mediaDescriptions.push(_);return _}createOrRecycleSendMedia(e,t,i,r,n){let o=this.rtpCapabilities.send,s=e===en.VIDEO?o.videoCodecs:o.audioCodecs,a=e===en.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: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:a,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(c)}};d=this.mungSendMediaDesc(d,n);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}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=hz(e);return fg(r),fT(r,t),fR(r,t),fI(r),fC(r,i,this.localCapabilities.send),r}mungSendMediaDesc(e,t){let i=hz(e);return fC(i,t,this.localCapabilities.recv),fb(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=>az()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port)}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find(t=>{var i,r;return(null==(i=t.attributes)||null==(r=i.ssrcs[0])?void 0:r.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}}function Sr(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 Sn(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
1t%2?Sr(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Sr(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let So=(ui((eM=class e extends lM{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}constructor(e,t,i){super(e,t),cc(this,"store",void 0),cc(this,"peerConnection",void 0),cc(this,"remoteSDP",void 0),cc(this,"initialOffer",void 0),cc(this,"transportEventReceiver",void 0),cc(this,"statsFilter",void 0),cc(this,"useRTX",dM.USE_RTX),cc(this,"localCapabilities",void 0),cc(this,"localCandidateCount",0),cc(this,"allCandidatesReceived",!1),cc(this,"establishPromise",void 0),cc(this,"mutex",new uO("NVExtentionsConnection-mutex")),cc(this,"rtcMedia",void 0),this.store=t,this.peerConnection=i,this.statsFilter=fY(this.peerConnection,void 0,void 0,az()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}async establish(e){try{let e=await this.peerConnection.createOffer();if(!e.sdp)throw Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");let t=fE(e.sdp),i=await fy(!this.useRTX,dM.FILTER_VIDEO_FEC,dM.FILTER_AUDIO_FEC);return this.localCapabilities=i,this.initialOffer=e,Sn(Sn({},t),{},{rtpCapabilities:i,offerSDP:e.sdp})}catch(e){throw new du(o.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e,t,i,r,n,s){try{if(!this.initialOffer)throw Error("Cannot establish NVConnection without initial offer.");this.remoteSDP=new Si({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:r,remoteSetup:n,localCapabilities:fO(this.localCapabilities),cname:s});let o=this.remoteSDP.toString(),a=fu.exports.parse(this.initialOffer.sdp),c=a.mediaDescriptions.find(e=>"audio"===e.media.mediaType);c&&fb(c);let d=fu.exports.print(a),l=this.logSDPExchange(d||"","offer","local","connect");await this.peerConnection.setLocalDescription({type:"offer",sdp:d}),null==l||l(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new du(o.EXCHANGE_SDP_FAILED,"NV.connect failed; ".concat(e.toString()))}}async updateRemoteConnect(e){var t,i,r;null==(t=this.remoteSDP)||t.updateRemoteRTPCapabilities(e),null==(i=this.remoteSDP)||i.preloadRemoteMedia(2);let n=null==(r=this.remoteSDP)?void 0:r.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:n});let o=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(o),dg.debug("[NVExtentionsConnection] updateRemoteRTPCapabilities by exchanging SDP.")}send(e,t,i){var r=this;return fa(function*(){let n=yield fc(r.mutex.lock("From NVExtentionsConnection.send"));try{let n;if(!r.remoteSDP)throw Error("Cannot call NVExtentionsConnection.send before remote SDP created");let o=[];e.forEach(e=>{let t=r.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});o.push(t)}),az()&&!0===dM.SIMULCAST&&(yield fc(r.applySimulcastForFirefox(o,e)));let s=yield fc(r.peerConnection.createOffer()),a=r.remoteSDP.predictReceivingMids(e.length),c=r.mungSendOfferSDP(s.sdp,e,a),d=fu.exports.parse(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 fm(t,r.useRTX)});try{n=yield l}catch(s){n=[],r.remoteSDP.receive(e,t,i,n);let o=r.remoteSDP.toString();throw yield fc(r.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield fc(r.peerConnection.setRemoteDescription({type:"answer",sdp:o})),yield fc(r.stopSending(a,!0)),s}r.remoteSDP.receive(e,t,i,n);let u=r.remoteSDP.toString(),h=r.logSDPExchange(c,"offer","local","send");return yield fc(r.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield fc(r.applySimulcastEncodings(o,e)),yield fc(r.applySendEncodings(o,e)),null==h||h(u),yield fc(r.peerConnection.setRemoteDescription({type:"answer",sdp:u})),o.map((e,t)=>{let i=a[t];return{localSSRC:l[t],id:i,transceiver:e}})}catch(e){throw e instanceof du?e:new du(o.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.send failed; ".concat(e.toString()))}finally{n()}})()}async stopSending(e,t){let i=t?void 0:await this.mutex.lock("From NVExtentionsConnection.stopSending");try{if(!this.remoteSDP)throw Error("Cannot call NVExtentionsConnection.stopSending before remote SDP created");let t=this.peerConnection.getTransceivers().filter(t=>
1-1!==e.indexOf(t.mid));if(t.length!==e.length)throw Error("Transceivers' length doesn't match mids' length when trying to call NVExtentionsConnection.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.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new du(o.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.stopSending failed; ".concat(e.toString()))}finally{i&&i()}}async receive(e,t,i,r){try{if(!this.remoteSDP)throw Error("Cannot call NVExtentionsConnection.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.peerConnection.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}),dg.debug("[NVExtentionsConnection] receive ".concat(e," by exchanging SDP."))}else dg.debug("[NVExtentionsConnection] receive ".concat(e," no need to exchange SDP."));let s=this.peerConnection.getTransceivers().find(e=>e.mid===n);if(!s)throw Error("Cannot get transceiver after setLocalDescription.");return{track:s.receiver.track,id:n}}catch(e){throw new du(o.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.receive failed; ".concat(e.toString()))}}async batchReceive(e){try{if(!this.remoteSDP)throw Error("Cannot call NVExtentionsConnection.batchReceive before remoteSDP created.");let{mids:t,needExchangeSDP:i}=this.remoteSDP.batchSend(e);if(i){let e=this.remoteSDP.toString(),t=this.logSDPExchange(e,"offer","remote","receive");await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});let i=await this.peerConnection.createAnswer();null==t||t(i.sdp||""),await this.peerConnection.setLocalDescription(i),dg.debug("[NVExtentionsConnection] batchReceive by exchanging SDP.")}else dg.debug("[NVExtentionsConnection] batchReceive no need to exchange SDP.");return 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}})}catch(e){throw new du(o.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw Error("Cannot call NVExtentionsConnection.stopReceiving before remote SDP created.");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 du(o.EXCHANGE_SDP_FAILED,"NVExtentionsConnection stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){try{if(!this.remoteSDP)throw Error("Cannot call NVExtentionsConnection.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 du(o.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.muteRemote failed; ".concat(e.toString()))}}async unmuteRemote(e){try{if(!this.remoteSDP)throw Error("Cannot call NVExtentionsConnection.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 du(o.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.unmuteRemote failed; ".concat(e.toString()))}}async muteLocal(e){try{if(!this.remoteSDP)throw Error("Cannot call NVExtentionsConnection.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 du(o.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw Error("Cannot call NVExtentionsConnection.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);let n=this.remoteSDP.toString();null==r||r(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new du(o.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(){var e=this;return fa(function*(){let t=yield fc(e.mutex.lock("From NVExtentionsConnection.restartICE"));try{let t=yield fc(e.peerConnection.createOffer({iceRestart:!0}));if(!t.sdp)throw Error("Cannot restartICE because restart offer SDP does not exist.");let i=fE(t.sdp),{remoteIceParameters:r}=yield i.iceParameters;if(!e.remoteSDP)throw Error("Cannot restartICE before remoteSDP created.");e.remoteSDP.restartICE(r);let n=e.remoteSDP.toString(),o=e.logSDPExchange(t.sdp||"","offer","local","restartICE");yield fc(e.peerConnection.setLocalDescription(t)),null==o||o(n),yield fc(e.peerConnection.setRemoteDescription({type:"answer",sdp:n}))}catch(e){dg.warning("restart ICE failed, abort operation",e)}finally{t()}})()}close(){var e;null==(e=this.onConnectionStateChange)||e.call(this,"closed"),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=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 NVExtentionsConnection.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 du(o.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)?az()||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)}getP2PConnectionParams(){var e;if(null==(e=this.peerConnection.currentLocalDescription)||!e.sdp||!this.localCapabilities)throw Error();return Sn(Sn({},fE(this.peerConnection.currentLocalDescription.sdp)),{},{rtpCapabilities:this.localCapabilities})}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,dg.debug("[pc-".concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,dg.debug("[pc-".concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))},dM.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:[]};return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(lS(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),dM.USE_TURN_SERVER_OF_GATEWAY&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),dM.FORCE_TURN_TCP?i.iceTransportPolicy="relay":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(hy(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!dM.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}async applySendEncodings(e,t){try{if(!lU.supportSetRtpSenderParameters||e.length!==t.length)return;for(let c=0;c<e.length;c++){let d=e[c],l=t[c];if(l&&l instanceof mg){var i,r,n,o,s,a;if(this.isVP8Simulcast(l))continue;let e={},t={};switch(l._optimizationMode){case"motion":e.degradationPreference="maintain-framerate";break;case"detail":e.degradationPreference="maintain-resolution";break;default:e.degradationPreference="balanced"}if(null!=(i=l._encoderConfig)&&i.bitrateMax&&(t.maxBitrate=1e3*(null==(n=l._encoderConfig)?void 0:n.bitrateMax)),l._hints.includes(X.LOW_STREAM)&&(null!=(o=l._encoderConfig)&&o.frameRate&&(t.maxFramerate=hO(l._encoderConfig.frameRate)),null!=(s=l._encoderConfig)&&s.scaleResolutionDownBy&&(null==(a=l._encoderConfig)?void 0:a.scaleResolutionDownBy)>1&&(t.scaleResolutionDownBy=l._encoderConfig.scaleResolutionDownBy)),dM.DSCP_TYPE&&ce()){let e=dM.DSCP_TYPE;["very-low","low","medium","high"].includes(e)&&(t.networkPriority=e)}let c=d.sender.getParameters(),u=null==(r=c.encodings)?void 0:r[0];az()&&!u&&(e.encodings=[t]),u&&Object.assign(u,t),Object.assign(c,e),await d.sender.setParameters(c)}}}catch(e){dg.debug("Apply RTPSendEncodings failed.")}}mungSendOfferSDP(e,t,i){let r=fu.exports.parse(e);return t.forEach((e,t)=>{let n=i[t],o=r.mediaDescriptions.find(e=>e.attributes.mid===n);o&&(fT(o,e),fv(o,e,this.store.codec))}),fu.exports.print(r)}mungReceiveAnswerSDP(e,t,i){let r=fu.exports.parse(e),n=r.mediaDescriptions.find(e=>e.attributes.mid===t);return n&&i===en.AUDIO&&"audio"===n.media.mediaType&&fb(n),fu.exports.print(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;let a=e[s],c=t[s];if(c instanceof mg&&!c._hints.includes(X.LOW_STREAM)&&null!=(i=c._encoderConfig)&&i.bitrateMax&&(null==(r=c._encoderConfig)?void 0:r.bitrateMax)>200&&null!=(n=c._scalabiltyMode)&&n.numSpatialLayers&&(null==(o=c._scalabiltyMode)?void 0:o.numSpatialLayers)>1&&"vp8"===this.store.codec){let e={},t={high:1e3*(c._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=a.sender.getParameters();await a.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!az()&&e.length===t.length)for(let i=0;i<e.length;i++){let r=t[i];if(r instanceof mg&&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 s=t.sender.getParameters();await t.sender.setParameters(Object.assign(s,n))}}}isVP8Simulcast(e){var t,i,r,n;return!!(e instanceof mg&&dM.SIMULCAST&&"vp8"===this.store.codec&&
1!e._hints.includes(X.LOW_STREAM)&&null!=(t=e._encoderConfig)&&t.bitrateMax&&(null==(i=e._encoderConfig)?void 0:i.bitrateMax)>200&&null!=(r=e._scalabiltyMode)&&r.numSpatialLayers&&(null==(n=e._scalabiltyMode)?void 0:n.numSpatialLayers)>1)}logSDPExchange(e,t,i,r){if(dM.SDP_LOGGING)return dg.upload("exchanging ".concat(i," ").concat(t," SDP during NVExtentionsConnection.").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 null==t?void 0:t[0].ssrcId}setConfiguration(t){if(lU.supportPCSetConfiguration){let i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}}}).prototype,"connect",[Ss],Object.getOwnPropertyDescriptor(eM.prototype,"connect"),eM.prototype),ui(eM.prototype,"updateRemoteConnect",[Ss],Object.getOwnPropertyDescriptor(eM.prototype,"updateRemoteConnect"),eM.prototype),ui(eM.prototype,"receive",[Ss],Object.getOwnPropertyDescriptor(eM.prototype,"receive"),eM.prototype),ui(eM.prototype,"batchReceive",[Ss],Object.getOwnPropertyDescriptor(eM.prototype,"batchReceive"),eM.prototype),ui(eM.prototype,"stopReceiving",[Ss],Object.getOwnPropertyDescriptor(eM.prototype,"stopReceiving"),eM.prototype),ui(eM.prototype,"muteRemote",[Ss],Object.getOwnPropertyDescriptor(eM.prototype,"muteRemote"),eM.prototype),ui(eM.prototype,"unmuteRemote",[Ss],Object.getOwnPropertyDescriptor(eM.prototype,"unmuteRemote"),eM.prototype),ui(eM.prototype,"muteLocal",[Ss],Object.getOwnPropertyDescriptor(eM.prototype,"muteLocal"),eM.prototype),ui(eM.prototype,"unmuteLocal",[Ss],Object.getOwnPropertyDescriptor(eM.prototype,"unmuteLocal"),eM.prototype),ui(eM.prototype,"close",[Ss],Object.getOwnPropertyDescriptor(eM.prototype,"close"),eM.prototype),ui(eM.prototype,"updateEncoderConfig",[Ss],Object.getOwnPropertyDescriptor(eM.prototype,"updateEncoderConfig"),eM.prototype),ui(eM.prototype,"updateSendParameters",[Ss],Object.getOwnPropertyDescriptor(eM.prototype,"updateSendParameters"),eM.prototype),ui(eM.prototype,"replaceTrack",[Ss],Object.getOwnPropertyDescriptor(eM.prototype,"replaceTrack"),eM.prototype),ui(eM.prototype,"getRemoteSSRC",[Ss],Object.getOwnPropertyDescriptor(eM.prototype,"getRemoteSSRC"),eM.prototype),eM);function Ss(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 NVExtentionsConnection.".concat(t));try{for(var n=arguments.length,o=Array(n),s=0;s<n;s++)o[s]=arguments[s];return await r.apply(this,o)}finally{i()}},i}function Sa(e){var t,i,r,n=2;for("undefined"!=typeof Symbol&&(i=fn,r=Symbol.iterator);n--;){if(i&&null!=(t=e[i]))return t.call(e);if(r&&null!=(t=e[r]))return new Sc(t.call(e));i="@@asyncIterator",r="@@iterator"}throw TypeError("Object is not async iterable")}function Sc(e){function t(e){if(Object(e)!==e)return sG.reject(TypeError(e+" is not an object."));var t=e.done;return sG.resolve(e.value).then(function(e){return{value:e,done:t}})}return(Sc=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?sG.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?sG.reject(e):t(i.apply(this.s,arguments))}},new Sc(e)}let Sd=(ui((eU=class e extends lM{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}constructor(t,i){super(t,i),cc(this,"store",void 0),cc(this,"peerConnection",void 0),cc(this,"cname",void 0),cc(this,"mutex",new uO("DataChannelConnection-mutex")),cc(this,"dataChannel",void 0),cc(this,"_p2pConnection",void 0),cc(this,"establishPromise",void 0),cc(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 So(t,i,this.peerConnection),this.bindPCEvents(),this.establishPromise=this._p2pConnection.establishPromise}async establish(){var e;let t=null==(e=this._nvMedia)?void 0:e.getLocalRtpCapabilities();return await this._p2pConnection.establish(t)}getP2PConnectionParams(){return this._p2pConnection.getP2PConnectionParams()}async connect(e,t,i,r,n,s){return this.cname=s,await this._p2pConnection.connect(e,t,i,r,n,s),await new sG((e,t)=>{let r=setTimeout(()=>{this.closeSignal(),t(new du(o.DATACHANNEL_CONNECTION_TIMEOUT,"Datachannel connection timed out, candidates: ".concat(JSON.stringify(i))))},2e3);this.dataChannel.onopen=()=>{if("open"===this.dataChannel.readyState)return clearTimeout(r),void e()},this.dataChannel.onerror=e=>{this.closeSignal(),t(e)}}),{transmitter:this.dataChannel,close:this.closeSignal.bind(this)}}send(e,t,i){var r=this;return fa(function*(){let n=yield fc(r.mutex.lock("From DataChannelConnection.send"));try{return yield*fl(Sa(r._p2pConnection.send(e,t,i)),fc)}finally{n()}})()}async stopSending(e,t){return this._p2pConnection.stopSending(e,t)}async receive(e,t,i,r){return this._nvMedia?(dg.debug("[DataChannelConnection] receive ".concat(e," by DataChannel.")),await this._nvMedia.reveiveByRTCMedia(e,t,this.cname)):(dg.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(){var e=this;return fa(function*(){return yield*fl(Sa(e._p2pConnection.restartICE()),fc)})()}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;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(dM.SDP_LOGGING)return dg.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&&(lS(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),dM.USE_TURN_SERVER_OF_GATEWAY&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),dM.FORCE_TURN_TCP?i.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach(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(hy(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!dM.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.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)}}
1).prototype,"connect",[Sl],Object.getOwnPropertyDescriptor(eU.prototype,"connect"),eU.prototype),ui(eU.prototype,"receive",[Sl],Object.getOwnPropertyDescriptor(eU.prototype,"receive"),eU.prototype),ui(eU.prototype,"stopReceiving",[Sl],Object.getOwnPropertyDescriptor(eU.prototype,"stopReceiving"),eU.prototype),ui(eU.prototype,"muteRemote",[Sl],Object.getOwnPropertyDescriptor(eU.prototype,"muteRemote"),eU.prototype),ui(eU.prototype,"unmuteRemote",[Sl],Object.getOwnPropertyDescriptor(eU.prototype,"unmuteRemote"),eU.prototype),ui(eU.prototype,"muteLocal",[Sl],Object.getOwnPropertyDescriptor(eU.prototype,"muteLocal"),eU.prototype),ui(eU.prototype,"unmuteLocal",[Sl],Object.getOwnPropertyDescriptor(eU.prototype,"unmuteLocal"),eU.prototype),ui(eU.prototype,"close",[Sl],Object.getOwnPropertyDescriptor(eU.prototype,"close"),eU.prototype),ui(eU.prototype,"updateEncoderConfig",[Sl],Object.getOwnPropertyDescriptor(eU.prototype,"updateEncoderConfig"),eU.prototype),ui(eU.prototype,"updateSendParameters",[Sl],Object.getOwnPropertyDescriptor(eU.prototype,"updateSendParameters"),eU.prototype),ui(eU.prototype,"replaceTrack",[Sl],Object.getOwnPropertyDescriptor(eU.prototype,"replaceTrack"),eU.prototype),ui(eU.prototype,"getRemoteSSRC",[Sl],Object.getOwnPropertyDescriptor(eU.prototype,"getRemoteSSRC"),eU.prototype),eU);function Sl(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),s=0;s<n;s++)o[s]=arguments[s];return await r.apply(this,o)}finally{i()}},i}function Su(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 Sh(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Su(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Su(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}function Sp(e){var t,i,r,n=2;for("undefined"!=typeof Symbol&&(i=fn,r=Symbol.iterator);n--;){if(i&&null!=(t=e[i]))return t.call(e);if(r&&null!=(t=e[r]))return new S_(t.call(e));i="@@asyncIterator",r="@@iterator"}throw TypeError("Object is not async iterable")}function S_(e){function t(e){if(Object(e)!==e)return sG.reject(TypeError(e+" is not an object."));var t=e.done;return sG.resolve(e.value).then(function(e){return{value:e,done:t}})}return(S_=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?sG.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?sG.reject(e):t(i.apply(this.s,arguments))}},new S_(e)}let SE=(ui((ex=class extends dd{get state(){return this._state}set state(e){let t=this._state;this._state=e,this.emit(ea.StateChange,t,this._state)}constructor(e,t){super(),cc(this,"store",void 0),cc(this,"statsUploader",void 0),cc(this,"connection",void 0),cc(this,"localTrackMap",new Map),cc(this,"remoteUserMap",new Map),cc(this,"pendingLocalTracks",[]),cc(this,"pendingRemoteTracks",[]),cc(this,"statsCollector",void 0),cc(this,"isPlanB",!1),cc(this,"shouldForwardP2PCreation",void 0),cc(this,"iceFailedCount",0),cc(this,"dtlsFailedCount",0),cc(this,"mutex",new uO("P2PChannel-mutex")),cc(this,"_state",es.Disconnected),cc(this,"handleMuteLocalTrack",async(e,t,i)=>{let r=await this.mutex.lock("Locking from P2PChannel.handleMuteLocalTrack");try{if(!this.connection||this.state!==es.Connected)return void i(new du(o.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]);n&&n[1].track._originMediaStreamTrack.stop(),await this.connection.muteLocal(r.map(e=>{let[,{id:t}]=e;return t}));let s=this.createMuteMessage(r);await hH(this,ea.RequestMuteLocal,s),t()}catch(e){i(e)}finally{r()}}),cc(this,"handleUnmuteLocalTrack",async(e,t,i)=>{let r=await this.mutex.lock("Locking from P2PChannel.handleUnmuteLocalTrack");try{if(!this.connection||this.state!==es.Connected)return void i(new du(o.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(t.track._originMediaStreamTrack.stop(),lU.supportDualStreamEncoding){let i=e._mediaStreamTrack.clone();t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}else{let i=f2(e,hY(this,ea.RequestLowStreamParameter));t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}await new sG((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)})}await this.connection.unmuteLocal(r.map(e=>{let[,{id:t}]=e;return t}));let s=this.createUnmuteMessage(r);await hH(this,ea.RequestUnmuteLocal,s),t()}catch(e){i(e)}finally{r()}}),cc(this,"handleUpdateVideoEncoder",async(e,t,i)=>{let r=await this.mutex.lock("Locking from P2PChannel.handleSetVideoEncoder");try{let i=this.localTrackMap.get(eo.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==es.Connected)return void t();let{id:r,track:n}=i;await this.connection.updateSendParameters(r,n),await this.connection.updateEncoderConfig(r,n),this.emit
1(ea.UpdateVideoEncoder,n),t()}catch(e){i(e)}finally{r()}}),cc(this,"handleSetOptimizationMode",async(e,t,i)=>{let r=await this.mutex.lock("Locking from P2PChannel.handleSetOptimizationMode");try{let i=this.localTrackMap.get(eo.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==es.Connected)return;let{id:r,track:n}=i;await this.connection.updateSendParameters(r,n),t()}catch(e){i(e)}finally{r()}}),cc(this,"handleReplaceTrack",async(e,t,i,r)=>{var n,o;let s;dg.debug("P2PChannel handleReplaceTrack for [track-id-".concat(e.getTrackId(),"]")),"boolean"==typeof r&&r||(s=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!==es.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]===eo.LocalVideoTrack&&lU.supportDualStreamEncoding){let t=this.localTrackMap.get(eo.LocalVideoLowTrack);if(t){let i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new sG((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)})}}t()}catch(e){i(e)}finally{null==(o=s)||o()}}),cc(this,"handleGetLocalVideoStats",e=>{e(this.statsCollector.getLocalVideoTrackStats())}),cc(this,"handleGetLocalAudioStats",e=>{e(this.statsCollector.getLocalAudioTrackStats())}),cc(this,"handleGetRemoteVideoStats",e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid]),cc(this,"handleGetRemoteAudioStats",e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid]),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new Se,this.bindStatsUploaderEvents(),this.isPlanB=!lU.supportUnifiedPlan||dM.CHROME_FORCE_PLAN_B&&ce(),this.shouldForwardP2PCreation=dM.FORWARD_P2P_CREATION&&lU.supportPCSetConfiguration,this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new Sd({},this.store):this.isPlanB?new fX({},this.store):new f0({},this.store),this.bindConnectionEvents(this.connection))}async startP2PConnection(e,t){if(this.state=es.New,this.shouldForwardP2PCreation||(this.connection=this.store.useDataChannel?new Sd(e,this.store):this.isPlanB?new fX(e,this.store):new f0(e,this.store),this.bindConnectionEvents(this.connection)),!this.connection)throw new du(o.UNEXPECTED_ERROR,"Cannot P2PChannel.startConnection before P2PConnection initialization .");return this.connection.setConfiguration(e),this.connection.establishPromise}async connect(e,t,i,r,n,s){if(!this.connection)throw new du(o.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");this.connection instanceof Sd?this.connection.updateRemoteConnect(r):(this.store.peerConnectionStart(),await this.connection.connect(e,t,i,r,n,s),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=es.Connected)}async preConnect(e,t,i,r,n,s){if(!this.connection)throw new du(o.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");this.store.peerConnectionStart();let a=await this.connection.connect(e,t,i,r,n,s);return this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=es.Connected,a}getEstablishParams(){if(this.connection instanceof Sd)return this.connection.getP2PConnectionParams();throw Error("Only DataChannelConnection needs to obtain establishParams")}publish(e,t,i){var r=this;return fa(function*(){let n=yield fc(r.mutex.lock("From P2PChannel.publish"));try{if(!r.connection||r.state!==es.Connected){if(r.state===es.Disconnected)throw new du(o.UNEXPECTED_ERROR,"PeerConnection already disconnected.");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,hS.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)));yield*fl(Sp(r.doPublish(r.connection,n)),fc)}finally{n()}})()}doPublish(e,t){var i=this;return fa(function*(){let r;
1t.forEach(e=>{let{track:t,type:r}=e,n=Date.now();i.store.publish(t.getTrackId(),r===eo.LocalAudioTrack?"audio":"video",n)}),i.bindLocalTrackEvents(t);let n=yield fc(e.send(t.map(e=>{let{track:t}=e;return t}),i.store.codec,i.store.audioCodec)),s=(yield fc(n.next())).value,a=i.createGatewayPublishMessage(t,s);try{r=yield a}catch(e){throw n.throw(e),(null==e?void 0:e.code)===o.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(a,r),d=(yield fc(n.next(c))).value;t.forEach(e=>{let{type:t}=e;i.statsCollector.addLocalStats(t)}),i.assignLocalTracks(t,d),i.statsUploader.startUploadUplinkStats(),t.forEach(e=>{let{track:t,type:r}=e,n=Date.now();i.store.publish(t.getTrackId(),r===eo.LocalAudioTrack?"audio":"video",void 0,n)})})()}publishLowStream(e){var t=this;return fa(function*(){if(!t.connection||t.state!==es.Connected)return;let i=yield fc(t.mutex.lock("Locking from P2PChannel.publishLowStream"));try{let i=t.localTrackMap.get(eo.LocalVideoTrack);if(!i)throw new du(o.UNEXPECTED_ERROR,"Could not find high stream");if(t.localTrackMap.has(eo.LocalVideoLowTrack))throw new du(o.UNEXPECTED_ERROR,"[".concat(t.store.clientId,"] Can't publish low stream when stream already publish"));let n=[{track:t.getLowVideoTrack(i.track,e),type:eo.LocalVideoLowTrack}];if(yield*fl(Sp(t.doPublish(t.connection,n)),fc),i.track.muted||!i.track.enabled){var r;let e=null==(r=t.localTrackMap.get(eo.LocalVideoLowTrack))?void 0:r.id;void 0!==e&&(yield fc(t.connection.muteLocal([e])))}}finally{i()}})()}async republish(){this.pendingLocalTracks.length>0&&(dg.debug("Emit P2PChannelEvents.RequestRePublish to republish tracks."),await hW(this,ea.RequestRePublish,this.pendingLocalTracks),this.emit(ea.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[])}async reSubscribe(e){for(let e=this.pendingRemoteTracks.length-1;e>=0;e--){let{user:t,kind:i}=this.pendingRemoteTracks[e];(i!==en.AUDIO||t._audio_added_&&t._audioSSRC)&&(i!==en.VIDEO||t._video_added_&&t._videoSSRC)||this.pendingRemoteTracks.splice(e,1)}if(e)await hW(this,ea.RequestReSubscribe,this.pendingRemoteTracks);else for(let{user:e,kind:t}of this.pendingRemoteTracks)await this.subscribe(e,t,t===en.VIDEO?e._videoSSRC:e._audioSSRC);this.pendingRemoteTracks.forEach(e=>{let{user:t}=e;this.emit(ea.MediaReconnectEnd,t.uid)}),this.pendingRemoteTracks=[]}async unpublish(e){if(!this.connection||this.state!==es.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 unpublishLowStream(){if(!this.connection||this.state!==es.Connected)return;let e=this.localTrackMap.get(eo.LocalVideoLowTrack);if(!e)return;e.track.close();let t=[[eo.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.stopUploadUplinkStats(),i}async subscribe(e,t,i,r,n){var s;let a,c;if(!this.connection||this.state!==es.Connected)throw new du(o.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");if(null!=(s=this.remoteUserMap.get(e))&&s.has(t))return;if(n){let i=n.find(e=>{let{stream_type:i}=e;return i===t});if(!i)throw new du(o.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);a=r.track,c=r.id}else{let n=await this.connection.receive(t,[{ssrcId:i,rtx:r}],String(e._uintid),void 0);a=n.track,c=n.id}t===en.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(a):(e._audioTrack=new f8(a,e.uid,e._uintid,this.store),dg.info("[".concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(a):(e._videoTrack=new f6(a,e.uid,e._uintid,this.store),dg.info("[".concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId()))),this.bindRemoteTrackEvents(e,e._videoTrack));let d=this.remoteUserMap.get(e);d?d.set(t,c):this.remoteUserMap.set(e,new Map([[t,c]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadDownlinkStats();let l=this.pendingRemoteTracks.findIndex(i=>{let{user:r,kind:n}=i;return r.uid===e.uid&&t===n});-1!==l&&(this.pendingRemoteTracks.splice(l,1),this.emit(ea.MediaReconnectEnd,e.uid))}async massSubscribe(e){return this.massSubscribeNoLock(e)}async massSubscribeNoLock(e){if(!this.connection||this.state!==es.Connected)throw new du(o.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=await this.connection.batchReceive(e.map(e=>{let{user:t,mediaType:i,ssrcId:r,rtxSsrcId:n}=e;return{kind:i,ssrcMsg:[{ssrcId:r,rtx:n}],mslabel:String(t._uintid)}}));e.forEach((e,i)=>{let{user:r,mediaType:n}=e,{track:o,id:s}=t[i];n===en.AUDIO?(r._audioTrack?r._audioTrack._updateOriginMediaStreamTrack(o):(r._audioTrack=new f8(o,r.uid,r._uintid,this.store),dg.info("[".concat(this.store.p2pId,"] create remote audio track: ").concat(r._audioTrack.getTrackId()))),this.bindRemoteTrackEvents(r,r._audioTrack)):(r._videoTrack?r._videoTrack._updateOriginMediaStreamTrack(o):(r._videoTrack=new f6(o,r.uid,r._uintid,this.store),dg.info("[".concat(this.store.p2pId,"] create remote video track: ").concat(r._videoTrack.getTrackId()))),this.bindRemoteTrackEvents(r,r._videoTrack));let a=this.remoteUserMap.get(r);a?a.set(n,s):this.remoteUserMap.set(r,new Map([[n,s]])),this.statsCollector.addRemoteStats(r.uid),this.statsUploader.startUploadDownlinkStats();let c=this.pendingRemoteTracks.findIndex(e=>{let{user:t,kind:i}=e;return t.uid===r.uid&&n===i});-1!==c&&(this.pendingRemoteTracks.splice(c,1),this.emit(ea.MediaReconnectEnd,r.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===es.Connected||i||r.forEach(t=>{var i,r;let{kind:n}=t;n===en.AUDIO?(null==(i=e._audioTrack)||i._destroy(),e._audioTrack=void 0):n===en.VIDEO&&(null==(r=e._videoTrack)||r._destroy(),e._videoTrack=void 0)}),!this.connection||this.state!==es.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.stopUploadDownlinkStats(),n.forEac
1h(e=>{var t,r,n;let[o,{kind:s}]=e;s===en.VIDEO&&o._videoSSRC&&(null==(t=this.connection)||t.setStatsRemoteVideoIsReady(o._videoSSRC,!1)),s===en.VIDEO?(this.unbindRemoteTrackEvents(o._videoTrack),i||(null==(r=o._videoTrack)||r._destroy(),o._videoTrack=void 0)):s===en.AUDIO&&(this.unbindRemoteTrackEvents(o._audioTrack),i||(null==(n=o._audioTrack)||n._destroy(),o._audioTrack=void 0))}),o}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!==es.Connected)return void t.forEach(e=>{var t,i;let{user:r,kind:n}=e;n===en.AUDIO?(null==(t=r._audioTrack)||t._destroy(),r._audioTrack=void 0):n===en.VIDEO&&(null==(i=r._videoTrack)||i._destroy(),r._videoTrack=void 0)});let i=rs(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.stopUploadDownlinkStats(),i.forEach(e=>{var t,i,r;let[n,{kind:o}]=e;o===en.VIDEO&&n._videoSSRC&&(null==(t=this.connection)||t.setStatsRemoteVideoIsReady(n._videoSSRC,!1)),o===en.VIDEO?(this.unbindRemoteTrackEvents(n._videoTrack),null==(i=n._videoTrack)||i._destroy(),n._videoTrack=void 0):o===en.AUDIO&&(this.unbindRemoteTrackEvents(n._audioTrack),null==(r=n._audioTrack)||r._destroy(),n._audioTrack=void 0)}),r}async muteRemote(e,t){if(!this.connection)return;let i=this.remoteUserMap.get(e);if(!i)return void dg.warning("P2PChannel.muteRemote has no remote user ".concat(e.uid,"."));if(!i.get(t))return void dg.warning("P2PChannel.muteRemote has no remote user ".concat(e.uid," media type ").concat(t,"."));let r=t===en.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 dg.warning("P2PChannel.unmuteRemote has no remote user ".concat(e.uid,"."));i.get(t)||dg.warning("P2PChannel.unmuteRemote has no remote user ".concat(e.uid," media type ").concat(t,"."))}getAllTracks(e){let t=this.localTrackMap.get(eo.LocalAudioTrack);if((null==t?void 0:t.track)instanceof hE){let i=t.track;return Array.from(this.localTrackMap.entries()).filter(e=>{let[t]=e;return t!==eo.LocalAudioTrack}).filter(t=>{let[i]=t;return!(e&&i===eo.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===eo.LocalVideoLowTrack)}).map(e=>{let[,{track:t}]=e;return t})}reportPublishEvent(e,t,i,r,n){if(e){let i=this.localTrackMap.get(eo.LocalAudioTrack),o=r?this.localTrackMap.get(eo.LocalVideoLowTrack):this.localTrackMap.get(eo.LocalVideoTrack);uC.publish(this.store.sessionId,{eventElapse:hS.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(X.SCREEN_TRACK)),audio:!!i,video:!!o,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:n})}else{var o;i||(i=[]);let s=i.find(e=>e instanceof hh),a=r?null==(o=this.localTrackMap.get(eo.LocalVideoTrack))?void 0:o.track:i.find(e=>e instanceof mg);uC.publish(this.store.sessionId,{eventElapse:hS.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==s?void 0:s.getTrackLabel(),videoName:null==a?void 0:a.getTrackLabel(),screenshare:-1!==(null==a?void 0:a._hints.indexOf(X.SCREEN_TRACK)),audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:n})}}reportSubscribeEvent(e,t,i,r){let n=r===en.VIDEO?i._videoSSRC:i._audioSSRC;n&&uC.subscribe(this.store.sessionId,{succ:e,ec:t,video:r===en.VIDEO,audio:r===en.AUDIO,peerid:i.uid,subscribeRequestid:r===en.VIDEO?i._videoSSRC:i._audioSSRC,p2pid:this.store.p2pId,eventElapse:hS.measureFromSubscribeStart(this.store.clientId,n)})}reset(){dg.debug("P2PChannel.reset"),this.mutex=new uO("P2PChannel-mutex"),this.connection&&(this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new Sd({},this.store):this.isPlanB?new fX({},this.store):new f0({},this.store),this.bindConnectionEvents(this.connection)),this.statsUploader.stopUploadUplinkStats(),this.statsUploader.stopUploadDownlinkStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.iceFailedCount=0,this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.state=es.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(eo.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){let e=this.localTrackMap.get(eo.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 mg||t&&t.track instanceof hh?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(us(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(eo.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=lr(e).call(e,(e,t)=>e.level-t.level)}async disconnectForReconnect(){this.connection&&(dg.debug("P2PChannel.disconnectForReconnect closing P2PConnection"),this.state=es.Reconnecting,dM.KEEP_LAST_FRAME&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEac
1h(e=>{var t,i,r,n;let[o]=e;null==(t=o._videoTrack)||null==(i=t._player)||null==(r=i.getVideoElement())||r.pause(),null==(n=o._videoTrack)||n._originMediaStreamTrack.stop()}),this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0,this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new Sd({},this.store):this.isPlanB?new fX({},this.store):new f0({},this.store),this.bindConnectionEvents(this.connection)),0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach(e=>{let[t,{track:i}]=e;switch(t){case eo.LocalVideoTrack:i._hints.includes(X.LOW_STREAM)?i.close():this.pendingLocalTracks.push(i);break;case eo.LocalAudioTrack:i instanceof hE?this.pendingLocalTracks=this.pendingLocalTracks.concat(i.trackList):this.pendingLocalTracks.push(i);case eo.LocalVideoLowTrack:}}),this.emit(ea.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(us(i).call(i)).forEach(e=>{this.setPendingRemoteMedia(t,e)}),this.emit(ea.MediaReconnectStart,t.uid)}),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),this.statsUploader.stopUploadUplinkStats(),this.statsUploader.stopUploadDownlinkStats(),this.statsUploader.stopUploadTransportStats(),dg.debug("P2PChannel disconnected, waiting to reconnect."))}hasPendingRemoteMedia(e,t){for(let i of this.pendingRemoteTracks){let{user:r,kind:n}=i;if((e instanceof mI?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(){var e=this;return fa(function*(){if(!e.connection||e.state!==es.Connected||e.connection instanceof Sd)return;let t=yield fc(e.mutex.lock("From P2PChannel.restartICE"));try{yield*fl(Sp(e.connection.restartICE()),fc)}finally{t()}})()}getUplinkNetworkQuality(){if(!this.connection)return 0;let e=this.connection.getStats(),t=this.localTrackMap.get(eo.LocalVideoTrack),i=this.localTrackMap.get(eo.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=hK(this,ea.NeedSignalRTT),s=r?r.rttMs:void 0,a=n?n.rttMs:void 0,c=s&&a?(s+a)/2:s||a,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,u=null==t?void 0:t.track;if(u&&u._encoderConfig&&-1===u._hints.indexOf(X.SCREEN_TRACK)){let t=u._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){let e=(1e3*t-i)/(1e3*t);return dB[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,s=e.audioRecv.find(e=>e.ssrc===n),a=e.videoRecv.find(e=>e.ssrc===o);if(!s&&!a)return void(t+=1);let c=hK(this,ea.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,u=s?s.jitterMs:void 0,h=e.recvPacketLossRate,p=.7*h*100/50+.3*l/1500;u&&(p=.6*h*100/50+.2*l/1500+.2*u/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 sG((t,i)=>{this.handleMuteLocalTrack(e,t,i)})}filterTobePublishedTracks(e,t,i){let r=[],n=this.getAllTracks();e=hJ(e=e.filter(e=>-1===n.indexOf(e)));let s=!1,a=!1;for(let n of e){if(n instanceof mg&&(this.localTrackMap.has(eo.LocalVideoTrack)||s?new du(o.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(r.push({track:n,type:eo.LocalVideoTrack}),s=!0),t)){let e=this.getLowVideoTrack(n,i);r.push({track:e,type:eo.LocalVideoLowTrack})}if(n instanceof hh){let e=this.localTrackMap.get(eo.LocalAudioTrack);if(e){if(!(e.track instanceof hE))throw new du(o.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 du(o.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===eo.LocalAudioTrack});if(!(e.track instanceof hE))throw new du(o.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 du(o.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(n)}else{if(!lU.webAudioMediaStreamDest||n instanceof hE||n._bypassWebAudio)r.push({track:n,type:eo.LocalAudioTrack});else{let e=new hE;e.addAudioTrack(n),r.push({track:e,type:eo.LocalAudioTrack})}a=!0}}}return r}filterTobeUnpublishedTracks(e){let t=[],i=this.getAllTracks();for(let r of e=hJ(e=e.filter(e=>-1!==i.indexOf(e)))){if(r instanceof hh){let e=this.localTrackMap.get(eo.LocalAudioTrack);if(!e)continue;e.track instanceof hE?(e.track.removeAudioTrack(r),this.unbindLocalAudioTrackEvents(r),
10===e.track.trackList.length&&(t.push([eo.LocalAudioTrack,e]),e.track.close())):t.push([eo.LocalAudioTrack,e])}if(r instanceof mg){let e=this.localTrackMap.get(eo.LocalVideoTrack);if(!e)continue;t.push([eo.LocalVideoTrack,e]);let i=this.localTrackMap.get(eo.LocalVideoLowTrack);i&&t.push([eo.LocalVideoLowTrack,i])}}return t}bindLocalTrackEvents(e){e.forEach(e=>{let{track:t,type:i}=e;switch(i){case eo.LocalVideoTrack:t.addListener(J.GET_STATS,this.handleGetLocalVideoStats),t.addListener(J.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(J.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(J.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(J.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.addListener(J.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(J.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(J.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case eo.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case eo.LocalVideoLowTrack:}})}bindLocalAudioTrackEvents(e,t){e instanceof hE?e.trackList.forEach(e=>{e.addListener(J.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(J.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(J.GET_STATS,this.handleGetLocalAudioStats),e.addListener(J.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(J.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)}):(e.addListener(J.GET_STATS,this.handleGetLocalAudioStats),e.addListener(J.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(J.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(J.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(J.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||e.addListener(J.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 eo.LocalVideoTrack:t.off(J.GET_STATS,this.handleGetLocalVideoStats),t.off(J.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(J.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(J.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(J.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.off(J.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(J.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(J.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case eo.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case eo.LocalVideoLowTrack:}})}unbindLocalAudioTrackEvents(e){e instanceof hE?e.trackList.forEach(e=>{e.off(J.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(J.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(J.GET_STATS,this.handleGetLocalAudioStats),e.off(J.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(J.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)}):(e.off(J.GET_STATS,this.handleGetLocalAudioStats),e.off(J.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(J.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(J.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(J.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(J.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof f6&&t.addListener(J.GET_STATS,t=>{t(this.handleGetRemoteVideoStats(e))}),t instanceof f8&&t.addListener(J.GET_STATS,t=>{t(this.handleGetRemoteAudioStats(e))})}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(J.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t,i]=e;i.has(en.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(en.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack)})}createGatewayPublishMessage(e,t){return e.map((e,i)=>{let r,n,{track:o,type:s}=e;switch(s){case eo.LocalAudioTrack:r=H.Audio,n={dtx:o instanceof hp&&o._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case eo.LocalVideoTrack:r=o._hints.includes(X.SCREEN_TRACK)?H.Screen:H.High,n=Sh(Sh({},hb(o)),{},{codec:this.store.codec});break;case eo.LocalVideoLowTrack:r=H.Low,n=Sh(Sh({},hb(o)),{},{codec:this.store.codec})}return{stream_type:r,attributes:n,ssrcs:t[i]}})}createGatewayUnpublishMessage(e){return e.map(e=>{let t,[i,{track:r,ssrcs:n,id:o}]=e;switch(i){case eo.LocalVideoTrack:t=r._hints.includes(X.SCREEN_TRACK)?H.Screen:H.High;break;case eo.LocalAudioTrack:t=H.Audio;break;case eo.LocalVideoLowTrack:t=H.Low}
1return{stream_type:t,ssrcs:n,mid:o}})}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(dg.info("[p2pId: ".concat(this.store.p2pId,"]: P2PConnection.onConnectionStateChange(").concat(t,")")),this.emit(ea.PeerConnectionStateChange,t),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),"disconnected"===t&&"disconnected"===e.iceConnectionState)return setTimeout(()=>{"disconnected"===e.iceConnectionState&&dM.ICE_RESTART&&"CONNECTED"===hK(this,ea.QueryClientConnectionState)&&this.emit(ea.RequestRestartICE)},800),void setTimeout(()=>{"disconnected"===e.peerConnectionState&&(dg.debug("P2PConnection disconnected timeout 4000ms, force reconnect"),setTimeout(()=>this.emit(ea.P2PLost),0),this.iceFailedCount+=1,this.requestReconnect())},4e3);"failed"===t&&(dg.debug("P2PConnection state failed, force reconnect"),setTimeout(()=>
1this.emit(ea.P2PLost),0),this.iceFailedCount+=1,await this.requestReconnect())},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),dg.info("[p2pId: ".concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),uC.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:_.TRACER}).onSuccess(),this.emit(ea.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{dg.info("[p2pId: ".concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{dg.info("[p2pId: ".concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{dg.info("[p2pId: ".concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},e.onFirstAudioDecoded=e=>{var t,i;let r=Array.from(us(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($.FIRST_FRAME_DECODED),uC.firstRemoteFrame(this.store.sessionId,d.FIRST_AUDIO_DECODE,l.FIRST_AUDIO_DECODE,{peer:r._uintid,subscribeElapse:hS.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;let i=Array.from(us(t=this.remoteUserMap).call(t)).find(t=>t._audioSSRC===e);i&&uC.firstRemoteFrame(this.store.sessionId,d.FIRST_AUDIO_RECEIVED,l.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:hS.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(us(t=this.remoteUserMap).call(t)).find(t=>t._videoSSRC===e);i&&uC.firstRemoteFrame(this.store.sessionId,d.FIRST_VIDEO_RECEIVED,l.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:hS.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(ea.ConnectionTypeChange,i),dg.info("[p2pId: ".concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(hL(t))," -> ").concat(JSON.stringify(hL(e)),")"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{dg.info("[p2pId: ".concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(hL(t))," -> ").concat(JSON.stringify(hL(e)),")"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)}}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}filterTobeMutedTracks(e){let t=[];if(-1===this.getAllTracks().indexOf(e))return t;let i=this.localTrackMap.get(eo.LocalAudioTrack);if(e instanceof hh&&(null==i?void 0:i.track)instanceof hE)return i.track.isActive||t.push([eo.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]===eo.LocalVideoTrack)){let e=this.localTrackMap.get(eo.LocalVideoLowTrack);e&&t.push([eo.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){let t=[],i=this.localTrackMap.get(eo.LocalAudioTrack);if(e instanceof hh&&(null==i?void 0:i.track)instanceof hE)return i.track.isActive&&t.push([eo.LocalAudioTrack,i]),t;let r=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i});if(r)if(r[0]===eo.LocalVideoTrack){t.push(r);let e=this.localTrackMap.get(eo.LocalVideoLowTrack);e&&t.push([eo.LocalVideoLowTrack,e])}else t.push(r);return t}createMuteMessage(e){return e.map(e=>{let t,[i,{track:r,ssrcs:n,id:o}]=e;switch(i){case eo.LocalAudioTrack:t=H.Audio;break;case eo.LocalVideoTrack:t=r._hints.includes(X.SCREEN_TRACK)?H.Screen:H.High;break;case eo.LocalVideoLowTrack:t=H.Low}
1return{stream_type:t,ssrcs:n,mid:o}})}createUnmuteMessage(e){return e.map(e=>{let t,[i,{track:r,ssrcs:n,id:o}]=e;switch(i){case eo.LocalAudioTrack:t=H.Audio;break;case eo.LocalVideoTrack:t=r._hints.includes(X.SCREEN_TRACK)?H.Screen:H.High;break;case eo.LocalVideoLowTrack:t=H.Low}return{stream_type:t,ssrcs:n,mid:o}})}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}createUnsubscribeMessage(e){let t=[];return e.forEach(e=>{let[i,{kind:r,id:n}]=e;switch(r){case en.VIDEO:return void(i._videoSSRC&&t.push({stream_type:en.VIDEO,ssrcId:i._videoSSRC}));case en.AUDIO:return void(i._audioSSRC&&t.push({stream_type:en.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===en.VIDEO?e|=Y.Video:e|=Y.Audio,t.set(i,e)}else r===en.VIDEO?t.set(i,Y.Video):t.set(i,Y.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(eo.LocalVideoTrack),i=this.localTrackMap.get(eo.LocalVideoLowTrack);t&&await t.track.setBitrateLimit(e.uplink),i&&e.low_stream_uplink&&await i.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0})}isP2PDisconnected(){return!this.connection||"connected"!==this.connection.peerConnectionState}mapPubResToRemoteConfig(e,t){return e.map((e,i)=>{var r;let{stream_type:n}=e;return null==(r=t.find(e=>{let{stream_type:t}=e;return n===t}))?void 0:r.attributes})}async tryToUnmuteAudio(e){for(let i=0;i<e.length;i++)if(e[i]instanceof hh){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 hH(this,ea.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(ea.RequestUploadStats,e,t),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 hx(dp(this.dtlsFailedCount,dh)),this.emit(ea.RequestReconnect)}async reconnectP2P(){let e=Array.from(this.localTrackMap.entries()),t=this.createGatewayUnpublishMessage(e);Array.from(this.remoteUserMap.entries()),t.length>0&&await hW(this,ea.RequestUnpublishForReconnectPC,t),this.disconnectForReconnect(),this.emit(ea.RequestReconnectPC)}canPublishLowStream(){return this.localTrackMap.has(eo.LocalVideoTrack)||this.pendingLocalTracks.some(e=>e instanceof mg)}throwIfTrackTypeNotMatch(e){if(e.filter(e=>e instanceof mg).length>1)throw new du(o.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter(e=>e instanceof hh).length>1&&(e.some(e=>e instanceof hh&&e._bypassWebAudio)||!lU.webAudioMediaStreamDest))throw new du(o.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 mg&&this.pendingLocalTracks.some(e=>e instanceof mg))throw new du(o.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof hh&&this.pendingLocalTracks.some(e=>e instanceof hh)&&(!lU.webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some(e=>e instanceof hh&&e._bypassWebAudio)))throw new du(o.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=lU.supportDualStreamEncoding,n=Sh(Sh({},{width:160,height:120,framerate:15,bitrate:50}),t);i=r?e._mediaStreamTrack.clone():f2(e,n);let o=hV(8,"track-low-"),s=new mg(i,Sh(Sh({},r&&{scaleResolutionDownBy:function(e,t){let i=t._videoWidth||t.getMediaStreamTrack(!0).getSettings().width;return i||dg.warning("cannot get original video track's width, default scale down 4 times for low stream"),i?i/hO(e.width):4}(n,e)}),{},{frameRate:n.framerate,bitrateMax:n.bitrate,bitrateMin:n.bitrate}),void 0,void 0,o);return s._hints.push(X.LOW_STREAM),e.addListener(J.NEED_CLOSE,()=>{s.close()}),s}async globalLock(){return this.mutex.lock("From P2PChannel.globalLock")}reportVideoFirstFrameDecoded(e,t,i,r){var n;let o=Array.from(us(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,s=n.subscribe.find(e=>e.userId===o.uid&&"video"===e.type);uC.firstRemoteVideoDecode(this.store.sessionId,d.FIRST_VIDEO_DECODE,l.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:i,subscribeElapse:hS.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==s?void 0:s.subscribeEnd)||0,subscriberStart:(null==s?void 0:s.subscribeStart)||0,videoAddNotify:(null==s?void 0:s.streamAdded)||0,state:+!!r})}}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}resetConnection(e){dg.debug("[P2PChannel] reset connection to ".concat(e)),this.state===es.Connected?(dg.debug("[P2PChannel] fallback to websocket but P2PChannel state still connected, disconnect first"),this.disconnectForReconnect()):(this.connection&&(this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=e===q.datachannel?new Sd({},this.store):this.isPlanB?new fX({},this.store):new f0({},this.store),this.bindConnectionEvents(this.connection)))}}).prototype,"startP2PConnection",[Sm],Object.getOwnPropertyDescriptor(ex.prototype,"startP2PConnection"),ex.prototype),ui(ex.prototype,"connect",[Sm],Object.getOwnPropertyDescriptor(ex.prototype,"connect"),ex.prototype),ui(ex.prototype,"preConnect",[Sm],Object.getOwnPropertyDescriptor(ex.prototype,"preConnect"),ex.prototype),ui(ex.prototype,"unpublish",[Sm],Object.getOwnPropertyDescriptor(ex.prototype,"unpublish"),ex.prototype),ui(ex.prototype,"unpublishLowStream",[Sm],Object.getOwnPropertyDescriptor(ex.prototype,"unpublishLowStream"),ex.prototype),ui(ex.prototype,"subscribe",[Sm],Object.getOwnPropertyDescriptor(ex.prototype,"subscribe"),ex.prototype),ui(ex.prototype,"massSubscribe",[Sm],Object.getOwnPropertyDescriptor(ex.prototype,"massSubscribe"),ex.prototype),ui(ex.prototype,"unsubscribe",[Sm],Object.getOwnPropertyDescriptor(ex.prototype,"unsubscribe"),ex.prototype),ui(ex.prototype,"massUnsubscribe",[Sm],Object.getOwnPropertyDescriptor(ex.prototype,"massUnsubscribe"),ex.prototype),ui(ex.prototype,"muteRemote",[Sm],Object.getOwnPropertyDescriptor(ex.prototype,"muteRemote"),ex.prototype),ui(ex.prototype,"unmuteRemote",[Sm],Object.getOwnPropertyDescriptor(ex.prototype,"unmuteRemote"),ex.prototype),ui(ex.prototype,"hasRemoteMediaWithLock",[Sm],Object.getOwnPropertyDescriptor(ex.prototype,"hasRemoteMediaWithLock"),ex.prototype),ui(ex.prototype,"disconnectForReconnect",[Sm],Object.getOwnPropertyDescriptor(ex.prototype,"disconnectForReconnect"),ex.prototype),ui(ex.prototype,"updateBitrateLimit",[Sm],Object.getOwnPropertyDescriptor(ex.prototype,"updateBitrateLimit"),ex.prototype),ui(ex.prototype,"remoteMediaSsrcChanged",[Sm],Object.getOwnPropertyDescriptor(ex.prototype,"remoteMediaSsrcChanged"),ex.prototype),ex);function Sm(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),s=0;s<n;s++)o[s]=arguments[s];return await r.apply(this,o)}finally{i()}},i}function Sf(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 SS(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
1t%2?Sf(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Sf(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}(eg=eV||(eV={})).SET_SESSION_ID="SET_SESSION_ID",eg.SET_P2P_ID="SET_P2P_id",eg.SET_DC_ID="SET_DC_id",eg.SET_UID="SET_UID",eg.SET_PUB_ID="SET_PUB_ID",eg.SET_CLOUD_PROXY_SERVER_MODE="SET_CLOUD_PROXY_SERVER_MODE",eg.KEY_METRIC_CLIENT_CREATED="KEY_METRIC_CLIENT_CREATED",eg.KEY_METRIC_JOIN_START="KEY_METRIC_JOIN_START",eg.AVOID_JOIN_START="AVOID_JOIN_START",eg.KEY_METRIC_JOIN_END="KEY_METRIC_JOIN_END",eg.KEY_METRIC_REQUEST_AP_START="KEY_METRIC_REQUEST_AP_START",eg.KEY_METRIC_REQUEST_AP_END="KEY_METRIC_REQUEST_AP_END",eg.KEY_METRIC_JOIN_GATEWAY_START="KEY_METRIC_JOIN_GATEWAY_START",eg.KEY_METRIC_JOIN_GATEWAY_END="KEY_METRIC_JOIN_GATEWAY_END",eg.KEY_METRIC_PEER_CONNECTION_START="KEY_METRIC_PEER_CONNECTION_START",eg.KEY_METRIC_PEER_CONNECTION_END="KEY_METRIC_PEER_CONNECTION_END",eg.KEY_METRIC_ICE_CONNECTION_END="KEY_METRIC_ICE_CONNECTION_END",eg.KEY_METRIC_SIGNAL_CHANNEL_OPEN="KEY_METRIC_SIGNAL_CHANNEL_OPEN",eg.KEY_METRIC_PUBLISH="KEY_METRIC_PUBLISH",eg.KEY_METRIC_SUBSCRIBE="KEY_METRIC_SUBSCRIBE",eg.RECORD_JOIN_CHANNEL_SERVICE="RECORD_JOIN_CHANNEL_SERVICE",eg.RESET_JOIN_CHANNEL_SERVICE_RECORDS="RESET_JOIN_CHANNEL_SERVICE_RECORDS",eg.RESET_KEY_METRICS="RESET_KEY_METRICS",eg.SET_USE_DATACHANNEL="SET_USE_DATACHANNEL";class ST{constructor(e,t,i,r){cc(this,"state",void 0),this.state={codec:e,audioCodec:t,mode:i,clientId:r,sessionId:null,p2pId:0,dcId:0,pubId:0,subId:0,avoidJoinStart:0,keyMetrics:{publish:[],subscribe:[]},joinChannelServiceRecords:[],cloudProxyServerMode:"disabled",useDataChannel:!1}}dispatch(e){this.state=function(e,t){switch(t.type){case eV.SET_SESSION_ID:return SS(SS({},e),{},{sessionId:t.sessionId});case eV.SET_P2P_ID:return SS(SS({},e),{},{p2pId:t.p2pId});case eV.SET_UID:return SS(SS({},e),{},{uid:t.uid});case eV.SET_PUB_ID:return SS(SS({},e),{},{pubId:t.pubId});case eV.KEY_METRIC_CLIENT_CREATED:return SS(SS({},e),{},{keyMetrics:SS(SS({},e.keyMetrics),{},{clientCreated:t.metric})});case eV.KEY_METRIC_JOIN_START:return SS(SS({},e),{},{keyMetrics:SS(SS({},e.keyMetrics),{},{joinStart:t.metric})});case eV.AVOID_JOIN_START:return SS(SS({},e),{},{avoidJoinStart:t.avoidJoinStart});case eV.KEY_METRIC_JOIN_END:return SS(SS({},e),{},{keyMetrics:SS(SS({},e.keyMetrics),{},{joinEnd:t.metric})});case eV.KEY_METRIC_REQUEST_AP_START:return SS(SS({},e),{},{keyMetrics:SS(SS({},e.keyMetrics),{},{requestAPStart:t.metric})});case eV.KEY_METRIC_REQUEST_AP_END:return SS(SS({},e),{},{keyMetrics:SS(SS({},e.keyMetrics),{},{requestAPEnd:t.metric})});case eV.KEY_METRIC_JOIN_GATEWAY_START:return SS(SS({},e),{},{keyMetrics:SS(SS({},e.keyMetrics),{},{joinGatewayStart:t.metric})});case eV.KEY_METRIC_JOIN_GATEWAY_END:return SS(SS({},e),{},{keyMetrics:SS(SS({},e.keyMetrics),{},{joinGatewayEnd:t.metric})});case eV.KEY_METRIC_PEER_CONNECTION_START:return SS(SS({},e),{},{keyMetrics:SS(SS({},e.keyMetrics),{},{peerConnectionStart:t.metric})});case eV.KEY_METRIC_PEER_CONNECTION_END:return SS(SS({},e),{},{keyMetrics:SS(SS({},e.keyMetrics),{},{peerConnectionEnd:t.metric})});case eV.KEY_METRIC_SIGNAL_CHANNEL_OPEN:return SS(SS({},e),{},{keyMetrics:SS(SS({},e.keyMetrics),{},{signalChannelOpen:t.metric})});case eV.KEY_METRIC_ICE_CONNECTION_END:return SS(SS({},e),{},{keyMetrics:SS(SS({},e.keyMetrics),{},{iceConnectionEnd:t.metric})});case eV.KEY_METRIC_PUBLISH:{let i=e.keyMetrics.publish,r=i.findIndex(e=>e.trackId===t.metric.trackId);return -1!==r?(i[r]=SS(SS({},i[r]),t.metric),SS(SS({},e),{},{keyMetrics:SS(SS({},e.keyMetrics),{},{publish:[...i]})})):SS(SS({},e),{},{keyMetrics:SS(SS({},e.keyMetrics),{},{publish:[...e.keyMetrics.publish,t.metric]})})}case eV.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]=SS(SS({},i[r]),t.metric),SS(SS({},e),{},{keyMetrics:SS(SS({},e.keyMetrics),{},{subscribe:[...i]})})):SS(SS({},e),{},{keyMetrics:SS(SS({},e.keyMetrics),{},{subscribe:[...e.keyMetrics.subscribe,t.metric]})})}case eV.SET_CLOUD_PROXY_SERVER_MODE:return e.cloudProxyServerMode=t.mode,e;case eV.RECORD_JOIN_CHANNEL_SERVICE:return"number"!=typeof t.index?e.joinChannelServiceRecords=[...e.joinChannelServiceRecords,t.record]:(e.joinChannelServiceRecords[t.index]=SS(SS({},e.joinChannelServiceRecords[t.index]),t.record),e.joinChannelServiceRecords=[...e.joinChannelServiceRecords]),e;case eV.RESET_JOIN_CHANNEL_SERVICE_RECORDS:return e.joinChannelServiceRecords=[],e;case eV.RESET_KEY_METRICS:return e.keyMetrics={publish:[],subscribe:[]},e;case eV.SET_USE_DATACHANNEL:return SS(SS({},e),{},{useDataChannel:t.val});default:return e}}(this.state,e)}set sessionId(e){this.dispatch({type:eV.SET_SESSION_ID,sessionId:e})}get sessionId(){return this.state.sessionId}get codec(){return this.state.codec}get audioCodec(){return this.state.audioCodec}get clientId(){return this.state.clientId}set p2pId(e){this.dispatch({type:eV.SET_P2P_ID,p2pId:e})}get p2pId(){return this.state.p2pId}set dcId(e){this.dispatch({type:eV.SET_DC_ID,dcId:e})}get dcId(){return this.state.dcId}set uid(e){this.dispatch({type:eV.SET_UID,uid:e})}get uid(){return this.state.uid}set pubId(e){this.dispatch({type:eV.SET_PUB_ID,pubId:e})}get pubId(){return this.state.pubId}set cloudProxyServerMode(e){this.dispatch({type:eV.SET_CLOUD_PROXY_SERVER_MODE,mode:e})}get cloudProxyServerMode(){return this.state.cloudProxyServerMode}
1set useDataChannel(e){this.dispatch({type:eV.SET_USE_DATACHANNEL,val:e})}get useDataChannel(){return this.state.useDataChannel}clientCreated(){this.dispatch({type:eV.KEY_METRIC_CLIENT_CREATED,metric:Date.now()})}joinStart(){this.dispatch({type:eV.KEY_METRIC_JOIN_START,metric:Date.now()})}joinEnd(){this.dispatch({type:eV.KEY_METRIC_JOIN_END,metric:Date.now()})}requestAPStart(){this.dispatch({type:eV.KEY_METRIC_REQUEST_AP_START,metric:Date.now()})}requestAPEnd(){this.dispatch({type:eV.KEY_METRIC_REQUEST_AP_END,metric:Date.now()})}joinGatewayStart(){this.dispatch({type:eV.KEY_METRIC_JOIN_GATEWAY_START,metric:Date.now()})}joinGatewayEnd(){this.dispatch({type:eV.KEY_METRIC_JOIN_GATEWAY_END,metric:Date.now()})}peerConnectionStart(){this.dispatch({type:eV.KEY_METRIC_PEER_CONNECTION_START,metric:Date.now()})}peerConnectionEnd(){this.dispatch({type:eV.KEY_METRIC_PEER_CONNECTION_END,metric:Date.now()})}signalChannelOpen(){this.dispatch({type:eV.KEY_METRIC_SIGNAL_CHANNEL_OPEN,metric:Date.now()})}iceConnectionEnd(){this.dispatch({type:eV.KEY_METRIC_ICE_CONNECTION_END,metric:Date.now()})}publish(e,t,i,r){this.dispatch({type:eV.KEY_METRIC_PUBLISH,metric:SS(SS({trackId:e,type:t},i&&{publishStart:i}),r&&{publishEnd:r})})}subscribe(e,t,i,r,n,o,s){this.dispatch({type:eV.KEY_METRIC_SUBSCRIBE,metric:SS(SS(SS(SS(SS({userId:e,type:t},i&&{subscribeStart:i}),r&&{subscribeEnd:r}),n&&{firstFrame:n}),o&&{streamAdded:o}),s&&{firstDecoded:s})})}massSubscribe(e,t,i,r){e.forEach(e=>{this.dispatch({type:eV.KEY_METRIC_SUBSCRIBE,metric:SS(SS(SS({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:eV.RECORD_JOIN_CHANNEL_SERVICE,record:SS(SS({},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:eV.RECORD_JOIN_CHANNEL_SERVICE,record:e,index:t}),t)}catch(e){return 0}}resetJoinChannelServiceRecords(){this.dispatch({type:eV.RESET_JOIN_CHANNEL_SERVICE_RECORDS})}resetKeyMetrics(){this.dispatch({type:eV.RESET_KEY_METRICS})}get joinChannelServiceRecords(){try{return this.state.joinChannelServiceRecords}catch(e){return[]}}get avoidJoinStart(){return this.state.avoidJoinStart}set avoidJoinStart(e){this.dispatch({type:eV.AVOID_JOIN_START,avoidJoinStart:e})}}let Sg=()=>"HTTPS"===(eT||eT||(eT=(window.location.protocol.split(":")[0]||"").toUpperCase())),SR=()=>void 0!==window.isSecureContext;function SI(e,t){switch(t){case 0:for(;128&Sk(e););break;case 2:Sb(e,SV(e));break;case 5:Sb(e,4);break;case 1:Sb(e,8);break;default:throw Error("Unimplemented type: "+t)}}new Uint8Array(new Float32Array(1).buffer);let SC=new Float64Array(1),Sv=new Uint8Array(SC.buffer);function Sy(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let SA=[];function SO(){let e=SA.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function Sb(e,t){if(e.offset+t>e.limit)throw Error("Skip past limit");e.offset+=t}function SN(e){return e.offset>=e.limit}function Sw(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 SD(e,t){let i=e.offset;if(i+t>e.limit)throw Error("Read past limit");return e.offset+=t,i}function SP(e,t){let i=SD(e,t),r=String.fromCharCode,n=e.bytes,o="";for(let e=0;e<t;e++){let s,a,c,d,l=n[e+i];0==(128&l)?o+=r(l):192==(224&l)?e+1>=t||128!=(192&(s=n[e+i+1]))||(d=(31&l)<<6|63&s)<128?o+="�":(o+=r(d),e++):224==(240&l)?e+2>=t||32896!=(49344&((s=n[e+i+1])|(a=n[e+i+2])<<8))||(d=(15&l)<<12|(63&s)<<6|63&a)<2048||d>=55296&&d<=57343?o+="�":(o+=r(d),e+=2):240==(248&l)?e+3>=t?o+="�":(s=n[e+i+1],8421504!=(0xc0c0c0&(s|(a=n[e+i+2])<<8|(c=n[e+i+3])<<16))||(d=(7&l)<<18|(63&s)<<12|(63&a)<<6|63&c)<65536||d>1114111?o+="�":(d-=65536,o+=r(55296+(d>>10),56320+(1023&d)),e+=3)):o+="�"}return o}function SL(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}SF(e,r);let n=Sw(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 Sk(e){return e.bytes[SD(e,1)]}function SM(e,t){let i=Sw(e,1);e.bytes[i]=t}function SU(e){let t=SD(e,8),i=e.bytes;return Sv[0]=i[t++],Sv[1]=i[t++],Sv[2]=i[t++],Sv[3]=i[t++],Sv[4]=i[t++],Sv[5]=i[t++],Sv[6]=i[t++],Sv[7]=i[t++],SC[0]}function Sx(e,t){let i=Sw(e,8),r=e.bytes;SC[0]=t,r[i++]=Sv[0],r[i++]=Sv[1],r[i++]=Sv[2],r[i++]=Sv[3],r[i++]=Sv[4],r[i++]=Sv[5],r[i++]=Sv[6],r[i++]=Sv[7]}function SV(e){let t,i=0,r=0;do t=Sk(e),i<32&&(r|=(127&t)<<i),i+=7;while(128&t);return r}function SF(e,t){for(t>>>=0;t>=128;)SM(e,127&t|128),t>>>=7;SM(e,t)}function Sj(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,s=Sw(e,o),a=e.bytes;switch(o){case 10:a[s+9]=n>>>7&1;case 9:a[s+8]=9!==o?128|n:127&n;case 8:a[s+7]=8!==o?r>>>21|128:r>>
1>21&127;case 7:a[s+6]=7!==o?r>>>14|128:r>>>14&127;case 6:a[s+5]=6!==o?r>>>7|128:r>>>7&127;case 5:a[s+4]=5!==o?128|r:127&r;case 4:a[s+3]=4!==o?i>>>21|128:i>>>21&127;case 3:a[s+2]=3!==o?i>>>14|128:i>>>14&127;case 2:a[s+1]=2!==o?i>>>7|128:i>>>7&127;case 1:a[s]=1!==o?128|i:127&i}}let SB=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)})(function(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,s){var a;return r((a=r(r(t,e),r(n,s)))<<o|a>>>32-o,i)}function o(e,t,i,r,o,s,a){return n(t&i|~t&r,e,t,o,s,a)}function s(e,t,i,r,o,s,a){return n(t&r|i&~r,e,t,o,s,a)}function a(e,t,i,r,o,s,a){return n(t^i^r,e,t,o,s,a)}function c(e,t,i,r,o,s,a){return n(i^(t|~r),e,t,o,s,a)}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,u,h,p,_,E=0x67452301,m=-0x10325477,f=-0x67452302,S=0x10325476;for(l=0;l<d.length;l+=16)u=E,h=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=s(E,m,f,S,d[l+1],5,-0x9e1da9e),S=s(S,E,m,f,d[l+6],9,-0x3fbf4cc0),f=s(f,S,E,m,d[l+11],14,0x265e5a51),m=s(m,f,S,E,d[l+0],20,-0x16493856),E=s(E,m,f,S,d[l+5],5,-0x29d0efa3),S=s(S,E,m,f,d[l+10],9,0x2441453),f=s(f,S,E,m,d[l+15],14,-0x275e197f),m=s(m,f,S,E,d[l+4],20,-0x182c0438),E=s(E,m,f,S,d[l+9],5,0x21e1cde6),S=s(S,E,m,f,d[l+14],9,-0x3cc8f82a),f=s(f,S,E,m,d[l+3],14,-0xb2af279),m=s(m,f,S,E,d[l+8],20,0x455a14ed),E=s(E,m,f,S,d[l+13],5,-0x561c16fb),S=s(S,E,m,f,d[l+2],9,-0x3105c08),f=s(f,S,E,m,d[l+7],14,0x676f02d9),m=s(m,f,S,E,d[l+12],20,-0x72d5b376),E=a(E,m,f,S,d[l+5],4,-378558),S=a(S,E,m,f,d[l+8],11,-0x788e097f),f=a(f,S,E,m,d[l+11],16,0x6d9d6122),m=a(m,f,S,E,d[l+14],23,-0x21ac7f4),E=a(E,m,f,S,d[l+1],4,-0x5b4115bc),S=a(S,E,m,f,d[l+4],11,0x4bdecfa9),f=a(f,S,E,m,d[l+7],16,-0x944b4a0),m=a(m,f,S,E,d[l+10],23,-0x41404390),E=a(E,m,f,S,d[l+13],4,0x289b7ec6),S=a(S,E,m,f,d[l+0],11,-0x155ed806),f=a(f,S,E,m,d[l+3],16,-0x2b10cf7b),m=a(m,f,S,E,d[l+6],23,0x4881d05),E=a(E,m,f,S,d[l+9],4,-0x262b2fc7),S=a(S,E,m,f,d[l+12],11,-0x1924661b),f=a(f,S,E,m,d[l+15],16,0x1fa27cf8),m=a(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,u),m=r(m,h),f=r(f,p),S=r(S,_);return i(E)+i(m)+i(f)+i(S)}(""+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))};function SG(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 SW=new Map([["moderation",1],["supervise",2]]);class SH extends dd{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;let t=this._connectionState;
1this._connectionState=e,this.emit(e_.CONNECTION_STATE_CHANGE,t,e)}get inspectType(){return this._inspectType}set inspectType(e){var t;this._inspectMode=rs(t=e.map(e=>SW.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(()=>{this.quality=this._quality/this.qualityRatio},6e4))}constructor(e){super(),cc(this,"name","AgoraRTCVideoContentInspect"),cc(this,"_connectionState",eh.CONNECTING),cc(this,"_innerConnectionState",void 0),cc(this,"sequence",0),cc(this,"inspectStartTime",void 0),cc(this,"workerManagerConnection",void 0),cc(this,"workerConnection",void 0),cc(this,"workerMessageLengthLimit",void 0),cc(this,"inspectIntervalMinimum",void 0),cc(this,"qualityRatio",void 0),cc(this,"_connectInfo",void 0),cc(this,"_cancelTokenSource",da.CancelToken.source()),cc(this,"_retryConfig",void 0),cc(this,"wmSequence",0),cc(this,"inspectInterval",void 0),cc(this,"inspectTimer",null),cc(this,"ossFilePrefix",void 0),cc(this,"extraInfo",void 0),cc(this,"_inspectType",void 0),cc(this,"_inspectMode",void 0),cc(this,"_quality",1),cc(this,"qualityTimer",null),cc(this,"_inspectId",void 0),cc(this,"_needWorkUrlOnly",!1),cc(this,"inspectImage",()=>{if(this.connectionState!==eh.CONNECTED)throw new du(o.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===eh.CONNECTED?this.requestToInspectImage():dg.debug("[".concat(this._inspectId,"] Inspect State is not connected , "),this.connectionState)},this.inspectInterval<this.inspectIntervalMinimum?this.inspectIntervalMinimum:this.inspectInterval),this.requestToInspectImage()}),this._inspectId=hV(5,"inspect-"),this.workerMessageLengthLimit=dM.VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT,this.inspectIntervalMinimum=dM.VIDEO_INSPECT_INTERVAL_MINIMUM,this.qualityRatio=dM.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 pe("worker-manager-"+this._inspectId,dh),this.on(e_.STATE_CHANGE,(e,t)=>{this._innerConnectionState=e,dg.debug("[".concat(this._inspectId,"] Inspect operation :").concat(ep[e]," ").concat(t||""))}),this.handleWorkerManagerEvents(),this.workerConnection=new pe("worker-"+this._inspectId,dh),this.handleWorkerEvents()}async init(e,t){this.emit(e_.STATE_CHANGE,ep.CONNECT_AP),this._connectInfo=e;let i=this._cancelTokenSource.token;return this._retryConfig=t,new sG((r,n)=>{this.on(e_.CONNECTION_STATE_CHANGE,(e,t)=>{t===eh.CONNECTED&&r()}),this.requestAP(e,i,t).then(e=>{this.connectWorkerManager(e)}).catch(e=>{n(e)})})}async requestAP(e,t,i){let r=dM.WEBCS_DOMAIN.map(e=>"https://".concat(e,"/api/v1")),n=await function(e,t,i,r){let{appId:n,areaCode:s,cname:a,sid:c,token:d,uid:l}=t,u="image_moderation_api",h={service_name:u,json_body:JSON.stringify({appId:n,areaCode:s,cname:a,command:"allocateEdge",requestId:++pk,seq:pk,sid:c,token:d,ts:Date.now(),uid:l+""})},p,_,E=e[0];return d_(async()=>{p=Date.now();let e=await uu(E,{data:h,cancelToken:i,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(_=Date.now()-p,0!==e.code){let t=new du(o.UNEXPECTED_RESPONSE,"image inspect ap error, code"+e.code,{retry:!0,responseTime:_});throw dg.error(t.toString()),t}let t=JSON.parse(e.json_body);if(200!==t.code){let e=new du(o.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:_});throw dg.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){let e=new du(o.UNEXPECTED_RESPONSE,"image inspect ap empty server",{code:t.code,responseTime:_});throw dg.error(e.toString()),e}let r=dM.VIDEO_INSPECT_WORKER_MANAGER_HOST,n=dM.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(r,":").concat(n||i)}).filter(e=>!!e),workerToken:t.workerToken,vid:t.vid,responseTime:_}},(t,i)=>(uC.apworkerEvent(c,{success:!0,sc:200,serviceName:u,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===i,responseTime:_,serverIp:e[i%e.length]}),!1),(t,i)=>(uC.apworkerEvent(c,{success:!1,sc:t.data&&t.data.code||200,serviceName:u,responseTime:_,serverIp:e[i%e.length]}),!!(t.code!==o.OPERATION_ABORTED&&t.code!==o.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(E=e[(i+1)%e.length],!0)),r)}(r,e,t,i);
1this.emit(e_.STATE_CHANGE,ep.AP_CONNECTED);let{addressList:s}=n;return this.wmSequence++,s}async connectWorkerManager(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._needWorkUrlOnly=t,this.emit(e_.STATE_CHANGE,ep.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(e,1e4)}async connectWorker(e){await this.workerConnection.init([e])}handleWorkerManagerEvents(){this.workerManagerConnection.on(L.CONNECTED,async()=>{this.emit(e_.STATE_CHANGE,ep.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.17.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(L.CLOSED,()=>{this._innerConnectionState<ep.GET_WORKER_MANAGER_RESPONSE&&dg.debug("[".concat(this._inspectId,"] Inspect worker manager is closed before connecting worker"))}),this.workerManagerConnection.on(L.FAILED,()=>{this._innerConnectionState<ep.GET_WORKER_MANAGER_RESPONSE&&dg.debug("[".concat(this._inspectId,"] Connecting inspect worker manager is failed before connecting worker"))}),this.workerManagerConnection.on(L.RECONNECTING,()=>{this._innerConnectionState<ep.GET_WORKER_MANAGER_RESPONSE&&dg.debug("[".concat(this._inspectId,"] Inspect worker manager is reconnecting before connecting worker"))}),this.workerManagerConnection.on(L.ON_MESSAGE,async e=>{this.emit(e_.STATE_CHANGE,ep.GET_WORKER_MANAGER_RESPONSE);let t=this.workerManagerConnection.url;this.workerManagerConnection.close();let i=JSON.parse(e.data);if(200!==i.code)throw dg.error("[".concat(this._inspectId,"] Unexpected code ").concat(i.code," from worker manager")),new du(o.UNEXPECTED_RESPONSE,"response code of worker is unexpected",i);if(!(i.serverResponse&&i.serverResponse.portWss&&t))throw dg.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(i))),new du(o.UNEXPECTED_RESPONSE,"response content of worker is unexpected",i);{let e=dM.VIDEO_INSPECT_WORKER_PORT||i.serverResponse.portWss,r=t.replace(/:\d+\/?$/,":".concat(e));this.emit(e_.STATE_CHANGE,ep.CONNECT_WORKER,r),this._needWorkUrlOnly?this.emit(e_.REQUEST_NEW_WORKER_URL,r):await this.connectWorker(r)}}),this.workerManagerConnection.on(L.WILL_RECONNECT,(e,t)=>{t(e)}),this.workerManagerConnection.on(L.REQUEST_NEW_URLS,(e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)})}handleWorkerEvents(){this.workerConnection.on(L.CONNECTED,async()=>{this.emit(e_.STATE_CHANGE,ep.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=eh.CONNECTED}),this.workerConnection.on(L.ON_MESSAGE,async e=>{if(e.data instanceof ArrayBuffer){var t,i;let r=function(e){let t={};e:for(;!SN(e);){let i=SV(e);switch(i>>>3){case 0:break e;case 1:t.code=SV(e);break;case 2:t.msg=SP(e,SV(e));break;case 3:{let i=function(e){let t=SV(e),i=e.limit;return e.limit=e.offset+t,i}(e);t.data=function(e){let t={};e:for(;!SN(e);){let i=SV(e);switch(i>>>3){case 0:break e;case 1:t.requestId=SP(e,SV(e));break;case 2:t.requestType=SV(e)>>>0;break;case 3:t.scorePorn=SU(e);break;case 4:t.scoreSexy=SU(e);break;case 5:t.scoreNeutral=SU(e);break;case 6:t.requestScene=SV(e)>>>0;break;case 7:t.scene=SV(e)>>>0;break;default:SI(e,7&i)}}return t}(e),e.limit=i;break}default:SI(e,7&i)}}return t}({bytes:t=new Uint8Array(e.data),offset:0,limit:t.length});if(dM.SHOW_VIDEO_INSPECT_WORKER_MESSAGE&&dg.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(e_.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=rs(i=Object.keys(e)).call(i,(t,i)=>e[t]>e[i]?t:i,"porn"),n=Object.keys(e).find(e=>e===t);
1this.emit(e_.INSPECT_RESULT,n)}else this.emit(e_.INSPECT_RESULT,void 0,new du(o.UNEXPECTED_RESPONSE,r.code+"","There is an unexpected data on message"))}else this.emit(e_.INSPECT_RESULT,void 0,new du(o.UNEXPECTED_RESPONSE,r.code+"",r.msg))}else dg.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit(e_.INSPECT_RESULT,void 0,new du(o.UNEXPECTED_RESPONSE,"invalid worker message type"))}),this.workerConnection.on(L.CLOSED,()=>{this.connectionState=eh.CLOSED}),this.workerConnection.on(L.FAILED,()=>{this.connectionState=eh.CLOSED}),this.workerConnection.on(L.RECONNECTING,()=>{this.connectionState=this.connectionState===eh.CONNECTED?eh.RECONNECTING:eh.CONNECTING}),this.workerConnection.on(L.WILL_RECONNECT,(e,t)=>{"recover"===e&&t(e),t("tryNext")}),this.workerConnection.on(L.REQUEST_NEW_URLS,(e,t)=>{this.workerManagerConnection.close(),this.once(e_.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)})})}static intToLong(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}async requestToInspectImage(){this.sequence++;let e=hK(this,e_.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(e_.INSPECT_RESULT,void 0,new du(o.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(e_.INSPECT_RESULT,void 0,new du(o.INVALID_OPERATION,"Only the track being published can be inspected"))}async generateRequestData(e,t){let i,r,n,{appId:o,cname:s,cid:a,vid:c,sid:d,uid:l}=t,u=Date.now(),h=await e.getCurrentFrameImage("image/jpeg",this.quality),p=await (async(e,t,i)=>await SB(e.buffer,t,i))(h,o,s),_=this.sequence+"-"+a+"-"+l+"-"+u+"-"+hV(12,""),E={appId:o,cid:a,cname:s,deviceId:"",elapse:SH.intToLong(Number(u-this.inspectStartTime)),fileSize:p.byteLength,jpgEncryption:2,height:h.height,width:h.width,jpg:p,networkType:6,osType:7,requestId:_,sdkVersion:"4.17.2",sequence:this.sequence,sid:d,timestamp:SH.intToLong(u),uid:l,vid:c,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};void 0===this.extraInfo&&delete E.callbackData,void 0===this.ossFilePrefix&&delete E.ossFilePrefix;let m=(function(e,t){let i,r=e.appId;void 0!==r&&(SF(t,10),SL(t,r));let n=e.cid;void 0!==n&&(SF(t,16),SF(t,n));let o=e.cname;void 0!==o&&(SF(t,26),SL(t,o));let s=e.deviceId;void 0!==s&&(SF(t,34),SL(t,s));let a=e.elapse;void 0!==a&&(SF(t,40),Sj(t,a));let c=e.fileSize;void 0!==c&&(SF(t,48),Sj(t,Sy(c)));let d=e.height;void 0!==d&&(SF(t,56),Sj(t,Sy(d)));let l=e.jpg;void 0!==l&&(SF(t,66),SF(t,l.length),i=Sw(t,l.length),t.bytes.set(l,i));let u=e.networkType;void 0!==u&&(SF(t,72),Sj(t,Sy(u)));let h=e.osType;void 0!==h&&(SF(t,80),Sj(t,Sy(h)));let p=e.requestId;void 0!==p&&(SF(t,90),SL(t,p));let _=e.sdkVersion;void 0!==_&&(SF(t,98),SL(t,_));let E=e.sequence;void 0!==E&&(SF(t,104),Sj(t,Sy(E)));let m=e.sid;void 0!==m&&(SF(t,114),SL(t,m));let f=e.timestamp;void 0!==f&&(SF(t,120),Sj(t,f));let S=e.uid;void 0!==S&&(SF(t,128),SF(t,S));let T=e.vid;void 0!==T&&(SF(t,136),SF(t,T));let g=e.width;void 0!==g&&(SF(t,144),Sj(t,Sy(g)));let R=e.service;void 0!==R&&(SF(t,152),SF(t,R));let I=e.callbackData;void 0!==I&&(SF(t,162),SL(t,I));let C=e.jpgEncryption;void 0!==C&&(SF(t,168),SF(t,C));let v=e.requestType;void 0!==v&&(SF(t,176),SF(t,v));let y=e.scorePorn;void 0!==y&&(SF(t,185),Sx(t,y));let A=e.scoreSexy;void 0!==A&&(SF(t,193),Sx(t,A));let O=e.scoreNeutral;void 0!==O&&(SF(t,201),Sx(t,O));let b=e.scene;void 0!==b&&(SF(t,208),SF(t,b));let N=e.ossFilePrefix;void 0!==N&&(SF(t,218),SL(t,N));let w=e.serviceVendor;if(void 0!==w)for(let e of w){var D;SF(t,226);let i=SO();(function(e,t){let i=e.service;void 0!==i&&(SF(t,8),SF(t,i));let r=e.vendor;void 0!==r&&(SF(t,16),SF(t,r));let n=e.token;void 0!==n&&(SF(t,26),SL(t,n));let o=e.callbackUrl;void 0!==o&&(SF(t,34),SL(t,o))})(e,i),SF(t,i.limit),function(e,t){let i=Sw(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,SA.push(D)}}(E,i=SO()),r=i.bytes,n=i.limit,r.length===n?r:r.subarray(0,n));if(m.byteLength<this.workerMessageLengthLimit){if(dM.SHOW_VIDEO_INSPECT_WORKER_MESSAGE){let e=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
1t%2?SG(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):SG(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}({},E);delete e.jpg,dg.debug("[".concat(this._inspectId,"] Request message for worker of inspect content "),JSON.stringify(e))}return m}{let t=this.quality*this.qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:o,cname:s,cid:a,vid:c,sid:d,uid:l})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=da.CancelToken.source(),this.workerManagerConnection&&this.workerManagerConnection.close(),this.workerConnection&&this.workerConnection.close(),this.inspectTimer&&window.clearInterval(this.inspectTimer),this.inspectTimer=null,this.connectionState=eh.CLOSED,this.emit(e_.STATE_CHANGE,ep.CLOSED)}}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 SY(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){cc(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 Sq=(eF=uI(),ej=uI({argsMap:(e,t)=>(Array.isArray(t)||(t=[t]),t.map(e=>e?Object(e).toString():"null"))}),eB=uI({argsMap:(e,t)=>(t||(t=[]),Array.isArray(t)||(t=[t]),t.map(e=>e.getTrackId()))}),eG=uI({argsMap:(e,t,i)=>[t.uid,i]}),eW=uI({argsMap:(e,t)=>t.map(e=>{let{user:t,mediaType:i}=e;return[null==t?void 0:t.uid,i]})}),eH=uI({argsMap:(e,t,i)=>[t.uid,i]}),eK=uI({argsMap:(e,t)=>t.map(e=>{let{user:t,mediaType:i}=e;return{uid:null==t?void 0:t.uid,mediaType:i}})}),eY=uI(),eq=uI(),eJ=uI(),eX=uI(),ez=uI(),eQ=uI(),eZ=uI(),e$=uI(),e0=uI(),e1=uI(),e2=uI(),e3=uI(),e4=uI(),e5=uI(),e6=uI({argsMap:(e,t)=>[t]}),e8=uI(),e7=uI(),e9=uI(),te=uI(),tt=uI(),ti=uI(),tr=uI(),tn=uI(),to=uI(),ts=uI(),ta=uI({argsMap:(e,t)=>(Array.isArray(t)||(t=[t]),[JSON.stringify(t)])}),tc=uI(),td=uI(),tl=uI(),tu=uI({reportResult:!0}),th=uI(),ui((tp=class extends dd{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 isStringUID(){return!!this._joinInfo&&!!this._joinInfo.stringUid}get __className__(){return"Client"}constructor(e){let t;if(super(),cc(this,"store",void 0),cc(this,"_uid",void 0),cc(this,"_channelName",void 0),cc(this,"_uintUid",void 0),cc(this,"_users",[]),cc(this,"_codec",void 0),cc(this,"_mode",void 0),cc(this,"_config",void 0),cc(this,"_clientId",void 0),cc(this,"_appId",void 0),cc(this,"_sessionId",null),cc(this,"_key",void 0),cc(this,"_joinInfo",void 0),cc(this,"_gateway",void 0),cc(this,"_statsCollector",void 0),cc(this,"_configDistribute",void 0),cc(this,"_leaveMutex",new uO("client-leave")),cc(this,"_publishMutex",new uO("client-publish")),cc(this,"_renewTokenMutex",new uO("client-renewtoken")),cc(this,"_subscribeMutex",new uO("client-subscribe")),cc(this,"_encryptionMode","none"),cc(this,"_encryptionSecret",null),cc(this,"_encryptionSalt",null),cc(this,"_proxyServer",void 0),cc(this,"_turnServer",{servers:[],mode:"auto"}),cc(this,"_cloudProxyServerMode","disabled"),cc(this,"_isDualStreamEnabled",!1),cc(this,"_defaultStreamFallbackType",void 0),cc(this,"_lowStreamParameter",void 0),cc(this,"_streamFallbackTypeCacheMap",new Map),cc(this,"_remoteStreamTypeCacheMap",new Map),cc(this,"_axiosCancelSource",da.CancelToken.source()),cc(this,"_audioVolumeIndicationInterval",void 0),cc(this,"_networkQualityInterval",void 0),cc(this,"_userOfflineTimeout",void 0),cc(this,"_streamRemovedTimeout",void 0),cc(this,"_injectStreamingClient",void 0),cc(this,"_liveTranscodeStreamingClient",void 0),cc(this,"_liveRawStreamingClient",void 0),cc(this,"_channelMediaRelayClient",void 0),cc(this,"_networkQualitySensitivity","normal"),cc(this,"_p2pCh
1annel",void 0),cc(this,"_useLocalAccessPoint",!1),cc(this,"_setLocalAPVersion",void 0),cc(this,"_joinAndNotLeaveYet",!1),cc(this,"_numberOfJoinCount",0),cc(this,"_remoteDefaultVideoStreamType",void 0),cc(this,"_inspect",void 0),cc(this,"_license",void 0),cc(this,"_handleLocalTrackEnable",(e,t,i)=>{this.publish(e,!1).then(t).catch(i)}),cc(this,"_handleLocalTrackDisable",(e,t,i)=>{this.unpublish(e).then(t).catch(i)}),cc(this,"_handleUserOnline",e=>{if(dM.BLOCK_LOCAL_CLIENT&&dH(e.uid,this.channelName))return void dg.debug("[".concat(e.uid,"] will be ignored in local"));this.isStringUID&&"string"!=typeof e.uid&&dg.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;else{let t=new mI(e.uid,e.uint_id||e.uid);this._users.push(t),dg.debug("[".concat(this._clientId,"] user online"),e.uid),this.emit(v.USER_JOINED,t)}}),cc(this,"_handleUserOffline",e=>{if(dM.BLOCK_LOCAL_CLIENT&&dH(e.uid,this.channelName))return;let t=this._users.find(t=>t.uid===e.uid);t&&(this._handleRemoveStream(e),hq(this._users,t),this._remoteStreamTypeCacheMap.delete(t.uid),this._streamFallbackTypeCacheMap.delete(t.uid),dg.debug("[".concat(this._clientId,"] user offline"),e.uid,"reason:",e.reason),this.emit(v.USER_LEAVED,t,e.reason))}),cc(this,"_handleAddAudioOrVideoStream",(e,t,i,r,n,o,s)=>{if(dM.BLOCK_LOCAL_CLIENT&&dH(t,this.channelName))return;let a=this._users.find(e=>e.uid===t);if(!a)return void dg.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));dg.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(a.uid,e,void 0,void 0,void 0,Date.now());let c="audio"===e?a.hasAudio:a.hasVideo;a._uintid||(a._uintid=n||t),"audio"===e?a._trust_audio_stream_added_state_=!0:a._trust_video_stream_added_state_=!0,"audio"===e?(a._audio_added_=!0,void 0!==i&&(a._audioSSRC=i),void 0!==r&&(a._cname=r),o&&(a._audioOrtc=o)):(a._video_added_=!0,void 0!==i&&(a._videoSSRC=i),void 0!==r&&(a._cname=r),void 0!==s&&(a._rtxSsrcId=s),o&&(a._videoOrtc=o)),("audio"===e?a.hasAudio:a.hasVideo)&&!c&&(dg.info("[".concat(this._clientId,"] remote user ").concat(a.uid," published ").concat(e)),this.emit(v.USER_PUBLISHED,a,e)),"video"===e?uC.onGatewayStream(this._sessionId,d.ON_ADD_VIDEO_STREAM,l.ON_ADD_VIDEO_STREAM,{peer:n||t}):uC.onGatewayStream(this._sessionId,d.ON_ADD_AUDIO_STREAM,l.ON_ADD_AUDIO_STREAM,{peer:n||t}),this._p2pChannel.remoteMediaSsrcChanged(a,e,i).then(t=>{if(t)return dg.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(a.uid," after rejoin because SSRC id changed.")),this._p2pChannel.unsubscribe(a,e,!0).then(()=>this._subscribe(a,e,!0).catch(e=>{dg.error("[".concat(this._clientId,"] resubscribe error"),e.toString())}))}),this._p2pChannel.hasPendingRemoteMedia(a,e)&&(dg.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(a.uid," after reconnect.")),this._subscribe(a,e,!0).catch(e=>{dg.error("[".concat(this._clientId,"] resubscribe error"),e.toString())}))}),cc(this,"_handleRemoveStream",e=>{if(dM.BLOCK_LOCAL_CLIENT&&dH(e.uid,this.channelName))return;let t=this._users.find(t=>t.uid===e.uid);if(!t)return void dg.warning("[".concat(this._clientId,"] can not find target user!(on_remove_stream)"));dg.debug("[".concat(this._clientId,"] stream removed with uid ").concat(e.uid));let i=()=>{};t.hasAudio&&t.hasVideo?i=()=>{dg.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.emit(v.USER_UNPUBLISHED,t,"audio"),dg.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.emit(v.USER_UNPUBLISHED,t,"video")}:t.hasVideo?i=()=>{dg.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.emit(v.USER_UNPUBLISHED,t,"video")}:t.hasAudio&&(i=()=>{dg.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.emit(v.USER_UNPUBLISHED,t,"audio")}),t._trust_audio_stream_added_state_=!0,t._trust_video_stream_added_state_=!0,t._audio_added_=!1,t._video_added_=!1,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,uC.onGatewayStream(this._sessionId,d.ON_REMOVE_STREAM,l.ON_REMOVE_STREAM,{peer:e.uint_id||e.uid}),i()}),cc(this,"_handleSetStreamLocalEnable",(e,t,i)=>{if(dM.BLOCK_LOCAL_CLIENT&&dH(t,this.channelName))return;let r=this._users.find(e=>e.uid===t);if(!r)return void dg.error("[".concat(this._clientId,"] can not find target user!(disable_local)"));dg.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";dg.debug("[".concat(this._clientId,"] user-info-updated, uid: ").concat(t,", msg: ").concat(e)),this.emit
1(v.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";dg.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(t,", msg: ").concat(e)),this.emit(v.USER_INFO_UPDATED,t,e)}}let o="audio"===e?r.hasAudio:r.hasVideo;return n!==o?!n&&o?(dg.info("[".concat(this._clientId,"] remote user ").concat(t," published ").concat(e)),void this.emit(v.USER_PUBLISHED,r,e)):("video"===e&&r._videoTrack&&r._videoTrack._destroy(),"audio"===e&&r._audioTrack,this._p2pChannel.muteRemote(r,e),dg.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished ").concat(e)),void this.emit(v.USER_UNPUBLISHED,r,e)):void 0}),cc(this,"_handleMuteStream",(e,t,i)=>{if(dM.BLOCK_LOCAL_CLIENT&&dH(e,this.channelName))return;dg.debug("[".concat(this._clientId,"] receive mute message"),e,t,i);let r=this._users.find(t=>t.uid===e);if(!r)return void dg.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";dg.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.emit(v.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";dg.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.emit(v.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)?(dg.info("[".concat(this._clientId,"] remote user ").concat(e," published ").concat(t)),void this.emit(v.USER_PUBLISHED,r,t)):void dg.warning("[".concat(this._clientId,"] remote user ").concat(e," receive ").concat(t," unmute message  before add stream message, ").concat(t," SSRC doesn't exist yet."));"video"===t&&r._videoTrack&&r._videoTrack._destroy(),"audio"===t&&r._audioTrack,this._p2pChannel.muteRemote(r,t),dg.info("[".concat(this._clientId,"] remote user ").concat(e," unpublished ").concat(t)),this.emit(v.USER_UNPUBLISHED,r,t)}}),cc(this,"_handleP2PLost",async e=>{dg.debug("[".concat(this._clientId,"] receive p2p lost"),e),parseInt(e.p2pid,10)===this.store.p2pId?await this._p2pChannel.requestReconnect():dg.warning("P2PLost stream not found",e)}),cc(this,"_handleTokenWillExpire",()=>{dg.debug("[".concat(this._clientId,"] received message onTokenPrivilegeWillExpire")),this.emit(v.ON_TOKEN_PRIVILEGE_WILL_EXPIRE)}),cc(this,"_handleBeforeUnload",e=>{"beforeunload"===e.type&&void 0!==e.returnValue&&""!==e.returnValue||(this.leave(),dg.info("[".concat(this._clientId,"] auto leave onbeforeunload or pagehide")))}),cc(this,"_handleUpdateNetworkQuality",()=>{if("normal"===this._networkQualitySensitivity)return;if(navigator&&void 0!==navigator.onLine&&!navigator.onLine)return void this.emit(v.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6});let e={downlinkNetworkQuality:0,uplinkNetworkQuality:0};e.uplinkNetworkQuality=this._p2pChannel.getUplinkNetworkQuality(),e.downlinkNetworkQuality=this._p2pChannel.getDownlinkNetworkQuality(),this.emit(v.NETWORK_QUALITY,e)}),this._codec=e.codec,this._mode=e.mode,this._clientId=hV(5,"client-"),this.store=new ST(e.codec,e.audioCodec,e.mode,this._clientId),this.store.clientCreated(),e.proxyServer&&this.setProxyServer(e.proxyServer,!0),e.turnServer&&this.setTurnServer(e.turnServer,!0),dg.info("[".concat(this._clientId,"] Initializing AgoraRTC client v").concat(dI," build: ").concat(dR,", mode: ").concat(this._mode,", codec: ").concat(this._codec)),e.clientRoleOptions)try{lg(e.clientRoleOptions),t=Object.assign({},e.clientRoleOptions)}catch(e){dg.warning("[".concat(this._clientId,"] ").concat(e.toString()))}this._statsCollector=new hR(this.store),this._statsCollector.onStatsException=(e,t,i)=>{dg.debug("[".concat(this._clientId,"] receive exception msg, code: ").concat(e,", msg: ").concat(t,", uid: ").concat(i)),this.emit
1(v.EXCEPTION,{code:e,msg:t,uid:i})},this._statsCollector.onUploadPublishDuration=(e,t,i,r)=>{let n=this._users.find(t=>t.uid===e);n&&uC.peerPublishStatus(this._sessionId,{subscribeElapse:r,audioPublishDuration:t,videoPublishDuration:i,peer:n._uintid})},this.store.useDataChannel=lU.supportDataChannel&&dM.SIGNAL_CHANNEL,this._gateway=new pp(this.store,{clientId:this._clientId,mode:this._mode,codec:this._codec,websocketRetryConfig:e.websocketRetryConfig||dh,httpRetryConfig:e.httpRetryConfig||dh,forceWaitGatewayResponse:void 0===e.forceWaitGatewayResponse||e.forceWaitGatewayResponse,statsCollector:this._statsCollector,role:e.role,clientRoleOptions:t}),this._config=e,this._configDistribute=new pK,this._p2pChannel=new SE(this.store,this._statsCollector),this._handleP2PChannelEvents(),this._handleGatewayEvents(),this._handleGatewaySignalEvents()}async join(e,t,i,r,n){let s=++this._numberOfJoinCount;this.store.joinStart(),r&&(this.store.uid=r);let a=Sg(),c=SR()?window.isSecureContext:"Browser Not Support";(SR()||a)&&window.isSecureContext||dg.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");let d=hF();"DISCONNECTED"===this.connectionState&&(this.store.avoidJoinStart=Math.round(Date.now()),dg.debug("[".concat(this._clientId,"] set avoidJoinStart to ").concat(this.store.avoidJoinStart)));let l=uC.reportApiInvoke(d,{name:p.JOIN,options:[e,t,i,r],states:{isHttps:a,isSecureContext:c},tag:_.TRACER});uC.setAppId(e);try{if(!i&&null!==i)throw new du(o.INVALID_PARAMS,"Invalid token: ".concat(i,". If you don not use token, set it to null"));i&&lc(i,"token",1,2047),lc(e,"appid",1,2047),ll(t),r&&lu(r),n&&lc(n,"optionalInfo",1,2047)}catch(e){throw l.onError(e),e}if(dg.info("[".concat(this._clientId,"] start join channel ").concat(t,", join number: ").concat(s)),this._leaveMutex.isLocked&&(dg.debug("[".concat(this._clientId,"] join: waiting leave operation")),(await this._leaveMutex.lock())(),dg.debug("[".concat(this._clientId,"] join: continue"))),this._joinAndNotLeaveYet=!0,"DISCONNECTED"!==this.connectionState){let e=new du(o.INVALID_OPERATION,"[".concat(this._clientId,"] Client already in connecting/connected state"));throw l.onError(e),e}this._sessionId||(this._sessionId=d,this.store.sessionId=this._sessionId),this._gateway.state="CONNECTING";let u=SY({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:n,license:this._license,useLocalAccessPoint:this._useLocalAccessPoint},void 0!==this._remoteDefaultVideoStreamType&&{defaultVideoStream:this._remoteDefaultVideoStreamType});if(this._useLocalAccessPoint&&(u.setLocalAPVersion=this._setLocalAPVersion),"string"==typeof r&&(u.stringUid=r,this._uintUid?(u.uid=this._uintUid,this._uintUid=void 0):u.uid=0),"none"!==this._encryptionMode&&this._encryptionSecret){if(u.aesmode=this._encryptionMode,u.aespassword=await (async e=>{let t=h$("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCMnXAHkKIGAM+x4N22gCI+Wyu\nSTM9ztkT3uYslTT2PuKmZfPzhH6kVdO7PTjGCOZnAsyb3oTtWat0KcxQ4jxvqQV+\nHvYl3iI1Yd4vl2c3qRMJPLtRDfNxa2Mcxgq7e9aEUibzdd0st+OJAy3tOj/Y0aVy\nxQiYDz3vqa6bP29adwIDAQAB"),i=await window.crypto.subtle.importKey("spki",t,{name:"RSA-OAEP",hash:"SHA-256"},!0,["encrypt"]),r=uf(e);return h0(new Uint8Array(await window.crypto.subtle.encrypt({name:"RSA-OAEP"},i,r)))})(this._encryptionSecret),!this._joinAndNotLeaveYet)throw new du(o.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this._encryptionSalt&&(u.aessalt=this._encryptionSalt)}this._startSession(this._sessionId,{channel:t,appId:e});let h=this._sessionId;setTimeout(()=>{"CONNECTING"===this.connectionState&&h===this._sessionId&&uC.joinChannelTimeout(this._sessionId,5)},5e3);try{let r,n=u.cloudProxyServer;if(["proxy3","proxy4","proxy5"].includes(n)){let e=dM.PROXY_SERVER_TYPE3;Array.isArray(e)?u.proxyServer=e[0]:u.proxyServer=e}if(uC.setProxyServer(u.proxyServer),dg.setProxyServer(u.proxyServer),this.store.requestAPStart(),u.stringUid&&!u.uid){let e=await px(u.stringUid,u,this._axiosCancelSource.token,this._config.httpRetryConfig||dh,this.store);dg.debug("getUserAccount Success ".concat(u.stringUid," => ").concat(e)),u.uid=e,r=await pU(u,this._axiosCancelSource.token,this._config.httpRetryConfig||dh,!0,this.store)}else r=await pU(u,this._axiosCancelSource.token,this._config.httpRetryConfig||dh,!0,this.store);if(!this._joinAndNotLeaveYet)throw new du(o.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this.store.requestAPEnd(),setTimeout(()=>{this._configDistribute.startGetConfigDistribute(u,this._axiosCancelSource.token),this._configDistribute.on(ei.UPDATE_BITRATE_LIMIT,e=>{this._p2pChannel.updateBitrateLimit(e)})},0),this._key=i||e;let s=r.gatewayInfo;this._joinInfo=SY(SY({},u),{},{cid:s.cid,uid:u.uid?u.uid:s.uid,vid:s.vid,apResponse:s.res,uni_lbs_ip:s.uni_lbs_ip,gatewayAddrs:s.gatewayAddrs});let a=await this._joinGateway();if(!this._joinAndNotLeaveYet)throw new du(o.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));l.onSuccess(a),this._appId=e,this._channelName=u.cname,this._uid=a,this.store.uid=a,setTimeout(()=>{this._networkQualityInterval&&window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=window.setInterval(this._handleUpdateNetworkQuality,2e3),window.addEventListener(aX()?"beforeunload":"pagehide",this._handleBeforeUnload)},0);let c=u.stringUid?"string uid: ".concat(u.stringUid,",uid: ").concat(u.uid):"uid: ".concat(this._uid);
1return dg.info("[".concat(this._clientId,"] Joining channel success: channel: ").concat(t,",").concat(c)),setTimeout(()=>{dg.startUpload()},5e3),this.store.joinEnd(),dG.includes(this)||dG.push(this),a}catch(t){let e=Array.isArray(t)?t[0]:t;throw dg.error("[".concat(this._clientId,"] join number: ").concat(s,", Joining channel failed, rollback"),e),e.code!==o.OPERATION_ABORTED&&this._numberOfJoinCount===s&&(this._gateway.state="DISCONNECTED",this._reset()),l.onError(e),e}}_joinGateway(){if(!this._joinInfo||!this._key)throw new du(o.INVALID_OPERATION);return this._gateway.join(this._joinInfo,this._key,!("disabled"!==this._joinInfo.cloudProxyServer||this._joinInfo.proxyServer||!dM.JOIN_WITH_FALLBACK_SIGNAL_PROXY)).then(e=>e).catch(e=>{if(e.code===o.INIT_WEBSOCKET_TIMEOUT||e.code===o.INIT_DATACHANNEL_TIMEOUT)return this._gateway.leave(!0,C.FALLBACK),e;throw e}).then(e=>{if(e instanceof du){if(e.code===o.INIT_WEBSOCKET_TIMEOUT){if(dg.info("[".concat(this._clientId,"] join timeout, fallback to proxy")),!this._joinInfo||!this._key)throw new du(o.INVALID_OPERATION);this._joinInfo.cloudProxyServer="fallback",this._cloudProxyServerMode="fallback",this.store.cloudProxyServerMode="fallback";let e=dM.PROXY_SERVER_TYPE3;if(Array.isArray(e))if(this._joinInfo.apUrl){let t=/^https?:\/\/(.+?)(\/.*)?$/.exec(this._joinInfo.apUrl)[1].split("."),i=t.slice(t.length-2).join(".");e.forEach(e=>{this._joinInfo&&e.includes(i)&&(this._joinInfo.proxyServer=e)}),this._joinInfo.proxyServer||(this._joinInfo.proxyServer=e[0])}else this._joinInfo.proxyServer=e[0];else this._joinInfo.proxyServer=e;let t=dM.LOG_UPLOAD_SERVER.match(/.+:(\d{1,5})$/);return t&&t[1]&&"443"!==t[1]&&dg.setProxyServer(this._joinInfo.proxyServer),"443"!==dM.STATS_COLLECTOR_PORT.toString()&&uC.setProxyServer(this._joinInfo.proxyServer),uC.reportApiInvoke(this._sessionId,{name:p.JOIN_FALLBACK_TO_PROXY,options:[this._joinInfo.proxyServer],tag:_.TRACER}).onSuccess(),this.emit(v.JOIN_FALLBACK_TO_PROXY,this._joinInfo.proxyServer),dM.JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE&&this._joinInfo.turnServer.servers.forEach(e=>{"forceturn"in e&&(e.forceturn=!0)}),this._gateway.join(this._joinInfo,this._key)}if(dg.info("[".concat(this._clientId,"] join by datachannel timeout, fallback to websocket")),!this._joinInfo||!this._key)throw new du(o.INVALID_OPERATION);return uC.reportApiInvoke(this._sessionId,{name:p.DATACHANNEL_FAILBACK,options:[this.store.clientId],tag:_.TRACER}).onSuccess(),this._joinGateway()}return e}).then(e=>e)}async leave(){dg.info("[".concat(this._clientId,"] Leaving channel")),window.removeEventListener(aX()?"beforeunload":"pagehide",this._handleBeforeUnload),this._reset(),function(e){let t=dG.indexOf(e);-1!==t&&dG.splice(t,1)}(this);let e=await this._leaveMutex.lock();if("DISCONNECTED"===this.connectionState)return dg.info("[".concat(this._clientId,"] Leaving channel repeated, success")),void e();await this._gateway.leave("CONNECTED"!==this.connectionState),dg.info("[".concat(this._clientId,"] Leaving channel success")),this._joinAndNotLeaveYet=!1,this.store.resetJoinChannelServiceRecords(),e()}async publish(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(Array.isArray(e)||(e=[e]),0===e.length)throw new du(o.INVALID_PARAMS,"track list is empty");if("audience"===this._gateway.role)throw new du(o.INVALID_OPERATION,"audience can not publish stream");for(let i of e){if(!(i instanceof uN))throw new du(o.INVALID_PARAMS,"parameter is not local track");if(!i._enabled&&t)throw new du(o.TRACK_IS_DISABLED,"can not publish a disabled track: ".concat(i.getTrackId()))}dg.info("[".concat(this._clientId,"] Publishing tracks, id ").concat(e.map(e=>"".concat(e.getTrackId()," ")))),await this._configDistribute.awaitConfigDistributeComplete(),t&&e.forEach(e=>{let t=this._configDistribute.getBitrateLimit();e instanceof mg&&t&&e.setBitrateLimit(t.uplink)});let i=await this._publishMutex.lock();try{await this._publishHighStream(e),dg.info("[".concat(this._clientId,"] Publish success, id ").concat(e.map(e=>"".concat(e.getTrackId()," "))))}catch(e){throw dg.error("[".concat(this._clientId,"] publish error"),e.toString()),e}finally{i()}}async unpublish(e){if(!this._joinInfo||void 0===this._uid)throw new du(o.INVALID_OPERATION,"Can't unpublish stream, haven't joined yet!");e?Array.isArray(e)||(e=[e]):e=this._p2pChannel.getAllTracks(!0),dg.info("[".concat(this._clientId,"] Unpublish tracks, tracks ").concat(e.map(e=>"".concat(e.getTrackId()," "))," "));let t=await this._publishMutex.lock();try{let t=await this._p2pChannel.unpublish(e);t&&await this._gateway.unpublish(t,this._uid),dg.info("[".concat(this._clientId,"] Unpublish success,tracks ").concat(e.map(e=>"".concat(e.getTrackId()))))}catch(e){throw dg.error("[".concat(this._clientId,"] unpublish error"),e.toString()),e}finally{t&&t()}}async subscribe(e,t){return this._subscribe(e,t)}async _subscribe(e,t,i){if(lo(t,"mediaType",["audio","video"]),!this._joinInfo)throw new du(o.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new du(o.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));if(!this._users.find(t=>t===e)){let t=new du(o.INVALID_REMOTE_USER,"user is not in the channel");throw dg.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 du(o.INVALID_REMOTE_USER,"user is not published");throw dg.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 du(o.REMOTE_USER_IS_NOT_PUBLISHED);throw dg.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,s="video"===t?e._rtxSsrcId:void 0,a={stream_type:"audio"===t?en.AUDIO:en.VIDEO,ssrcId:r},c=await this._subscribeMutex.lock();dg.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{hS.markSubscribeStart(this.store.clientId,r),this.store.subscribe(e.uid,t,Date.now()),await this._p2pChannel.subscribe(e,t,r,s,n);try{await this._gateway.subscribe(e.uid,a,!0)}catch(i){if((null==i?void 0:i.code)!==o.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}dg.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch(e=>{dg.warning("[".concat(this._clientId,"] auto set fallback failed"),e)});let i="audio"===t?e._audioTrack:e._videoTrack;if(!i)throw new du(o.UNEXPECTED_ERROR,"can not find remote track in user object");return i}catch(t){throw dg.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{c()}}async massSubscribe(e){if(ld(e,"subscribeList"),!this._joinInfo)throw new du(o.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new du(o.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));let t=Date.now(),i=new Map,r=await this._subscribeMutex.lock();dg.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}}),s=await this._p2pChannel.globalLock();try{var a;for(let t=e.length-1;t>=0;t--){let{user:r,mediaType:s}=e[t];if(lo(s,"mediaType",["audio","video"]),!r){let e=new du(o.INVALID_PARAMS,"user property does not exist in subscribeList item");throw dg.error("[".concat(this._clientId,"] user property does not exist in subscribeList item")),e}if(!this._users.find(e=>e===r)){let i=new du(o.INVALID_REMOTE_USER,"user is not in the channel");dg.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"===s&&(!r.hasAudio||void 0===r._audioSSRC)||"video"===s&&(!r.hasVideo||void 0===r._videoSSRC)){let i=new du(o.REMOTE_USER_IS_NOT_PUBLISHED);dg.error("[".concat(this._clientId,"] can not subscribe ").concat(r.uid," with mediaType ").concat(s,", remote user is not published")),n[t].error=i,e.splice(t,1);continue}let a=Y.Video|Y.LwoVideo,c=i.get(r);if(c){if("video"===s?c&a:c&Y.Audio){e.splice(t,1),dg.warning("repeat massSubscribe user:".concat(r.uid,", mediaType:").concat(s," twice"));continue}i.set(r,c|("video"===s?a:Y.Audio))}else i.set(r,"video"===s?a:Y.Audio)}for(let t=e.length-1;t>=0;t--){let{user:r,mediaType:n}=e[t],o=Y.Video|Y.LwoVideo;if(this._p2pChannel.hasRemoteMedia(r,n)){await this._p2pChannel.unmuteRemoteNoLock(r,n);let s=i.get(r);i.set(r,"video"===n?s^o:s^Y.Audio),e.splice(t,1)}}this.store.massSubscribe(e.map(e=>({userId:e.user.uid,type:e.mediaType})),t);let r=rs(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&Y.Audio&&(n.audio_ssrc=i._audioSSRC),r&Y.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===en.VIDEO?t._videoSSRC:t._audioSSRC,rtxSsrcId:t._rtxSsrcId}}));let i=new Map;if(r.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()).map(e=>{let t,[i,r]=e;return r.error_code||r.video_error_code&&r.audio_error_code?t=void 0:r.video_error_code?t=en.VIDEO:r.audio_error_code&&(t=en.AUDIO),{user:this.remoteUsers.find(e=>e.uid===i),mediaType:t}});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=h7(i);dg.error("user:".concat(e.user.uid," mediaType:").concat(e.mediaType," has massSubscribe error ").concat(t.desc)),e.error=new du(o.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;uC.subscribe(this.store.sessionId,{succ:!!e.error,ec:(null==(i=e.error)?void 0:i.code)||null,video:e.mediaType===en.VIDEO,audio:e.mediaType===en.AUDIO,peerid:e.user.uid,subscribeRequestid:e.mediaType===en.VIDEO?e.user._videoSSRC:e.user._audioSSRC,p2pid:this.store.p2pId,eventElapse:Math.floor(performance.now()-t)},!0)}),dg.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{s(),r()}}async unsubscribe(e,t){if(t&&lo(t,"mediaType",["audio","video"]),!this._joinInfo)throw new du(o.INVALID_OPERATION,"Can't unsubscribe stream, haven't joined yet!");if(!this._users.find(t=>t===e)){let t=new du(o.INVALID_REMOTE_USER,"user is not in the channel");throw dg.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}dg.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: ").concat(t));try{let i=await this._p2pChannel.unsubscribe(e,t);i&&await this._gateway.unsubscribe(i,e.uid),dg.info("[".concat(this._clientId,"] unsubscribe success uid: ").concat(e.uid,", mediaType: ").concat(t))}catch(t){if(t.code===o.DISCONNECT_P2P)return void dg.warning("disconnecting p2p, abort unsubscribe request.");throw dg.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}}async massUnsubscribe(e){if(ld(e,"unsubscribeList"),!this._joinInfo)throw new du(o.INVALID_OPERATION,"Can't unsubscribeAll stream, haven't joined yet!");dg.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 du(o.INVALID_PARAMS,"user property does not exist in unsubscribeList item");throw dg.error("[".concat(this._clientId,"] user property does not exist in unsubscribeList item")),e}if(lo(n,"mediaType",["video","audio",void 0]),!this._users.find(e=>e===r)){dg.warning("[".concat(this._clientId,"] can not unsubscribe ").concat(r.uid,", user is not in the channel")),e.splice(i,1);continue}let s=Y.Video|Y.LwoVideo;if(t.has(r)){let o,a=t.get(r);switch(n){case"video":o=a&s;break;case"audio":o=a&Y.Audio;break;default:o=a&(Y.Audio|s)}if(o){dg.warning("repeat massUnsubscribe user:".concat(r.uid,",mediaType:").concat(n," twice.")),e.splice(i,1);continue}n?"audio"===n?t.set(r,a|Y.Audio):"video"===n&&t.set(r,a|s):t.set(r,a|Y.Audio|s)}else n?"audio"===n?t.set(r,Y.Audio):"video"===n&&t.set(r,s):t.set(r,Y.Audio|s)}try{let t=await this._p2pChannel.massUnsubscribe(e);t&&await this._gateway.massUnsubscribe(t),dg.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===o.DISCONNECT_P2P)return void dg.warning("disconnecting p2p, abort unsubscribe request.");throw dg.error("[".concat(this._clientId,"] massUnsubscribe error"),e.toString()),e}}setLowStreamParameter(e){!function(e){if(!e)throw new du(o.INVALID_PARAMS);lh(e.width)||la(e.width,"streamParameter.width"),lh(e.height)||la(e.height,"streamParameter.height"),lh(e.framerate)||la(e.framerate,"streamParameter.framerate"),lh(e.bitrate)||ls(e.bitrate,"streamParameter.bitrate")}(e),(!e.width&&e.height||e.width&&!e.height)&&dg.warning("[".concat(this._clientId,"] The width and height parameters take effect only when both are set")),dg.info("[".concat(this._clientId,"] set low stream parameter to"),JSON.stringify(e));let t=this._configDistribute.getLowStreamConfigDistribute();t&&t.bitrate&&e.bitrate&&t.bitrate<e.bitrate&&(e.bitrate=t.bitrate),this._lowStreamParameter=e}async enableDualStream(){if(!lU.supportDualStream)throw uC.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),new du(o.NOT_SUPPORTED,"Your browser is not support dual stream");if(this._isDualStreamEnabled)throw new du(o.INVALID_OPERATION,"Dual stream is already enabled");if(this._p2pChannel.canPublishLowStream())try{await this._publishLowStream()}catch(e){throw uC.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),e}this._isDualStreamEnabled=!0,uC.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!0}),dg.info("[".concat(this._clientId,"] enable dual stream"))}async disableDualStream(){if(this._isDualStreamEnabled){if(!this._joinInfo)throw new du(o.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if(this._p2pChannel.getLocalMedia(eo.LocalVideoLowTrack))try{let e=await this._p2pChannel.unpublishLowStream();e&&await this._gateway.unpublish(e,this._joinInfo.stringUid||this._joinInfo.uid)}catch(e){throw uC.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!1}),e}this._isDualStreamEnabled=!1,uC.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!0}),dg.info("[".concat(this._clientId,"] disable dual stream"))}}
1async setClientRole(e,t){if(lo(e,"role",["audience","host"]),t&&lg(t),"rtc"===this._mode)throw dg.warning("[".concat(this._clientId,"]rtc mode can not use setClientRole")),new du(o.INVALID_OPERATION,"rtc mode can not use setClientRole");if(t&&t.level&&"host"===e)throw new du(o.INVALID_OPERATION,"host mode can not set audience latency level");if("audience"===e&&this._p2pChannel.hasLocalMedia())throw new du(o.INVALID_OPERATION,"can not set client role to audience when publishing stream");await this._gateway.setClientRole(e,t),dg.info("[".concat(this._clientId,"] set client role to ").concat(e,", level: ").concat(t&&t.level))}setProxyServer(e,t){if(lc(e,"proxyServer"),!t){if("DISCONNECTED"!==this.connectionState)throw new du(o.INVALID_OPERATION,"Set proxy server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new du(o.INVALID_OPERATION,"You have already set the proxy")}this._proxyServer=e,uC.setProxyServer(this._proxyServer),dg.setProxyServer(this._proxyServer),dg.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 du(o.INVALID_OPERATION,"Set turn server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new du(o.INVALID_OPERATION,"You have already set the proxy")}if(lS(e))return this._turnServer={servers:e,mode:"original-manual"},void dg.info("[".concat(this._clientId,"] Set original turnserver ").concat(t?"by initialize call":""," success: ").concat(e.map(e=>e.urls).join(","),"."));e.forEach(e=>lT(e)),this._turnServer={servers:e,mode:"manual"},dg.info("[".concat(this._clientId,"] Set turnserver ").concat(t?"by initialize call":""," success."))}setLicense(e){if("DISCONNECTED"!==this.connectionState)throw new du(o.INVALID_OPERATION,"you should set license before join channel");if(lc(e,"license",32,32),!/^[A-Za-z\d]+$/.test(e))throw new du(o.INVALID_PARAMS,"license should only contains characters from A-Z a-z 0-9");this._license=e,dg.info("[".concat(this._clientId,"] set license success"),e)}startProxyServer(e){let t;if("DISCONNECTED"!==this.connectionState)throw new du(o.INVALID_OPERATION,"Start proxy server before join channel");if(this._proxyServer||"manual"===this._turnServer.mode||this._useLocalAccessPoint)throw new du(o.INVALID_OPERATION,"You have already set the proxy");switch(void 0===e&&(e=3),e){case 1:case 2:throw new du(o.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 du(o.INVALID_PARAMS,"proxy server mode must be ".concat("3|4|5"))}this._cloudProxyServerMode=t,this.store.cloudProxyServerMode=t,dg.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode)}stopProxyServer(){if("DISCONNECTED"!==this.connectionState)throw new du(o.INVALID_OPERATION,"Stop proxy server after leave channel");uC.setProxyServer(),dg.setProxyServer(),this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled",dg.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 du(o.INVALID_PARAMS,"accessPoints is required.");ld(e.accessPoints.serverList,"accessPoints.serverList"),lc(e.accessPoints.domain,"accessPoints.domain");let t=(e,t)=>{ls(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 du(o.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");dM.CLOSE_AFB_FOR_LOCAL_AP&&(dk("JOIN_WITH_FALLBACK_SIGNAL_PROXY",!1),dk("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,s=e.accessPoints.serverList.map(e=>r.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(n):e),a=s.map(e=>"".concat(e,":").concat(i));this._useLocalAccessPoint=!0,this._setLocalAPVersion=2,dk("WEBCS_DOMAIN",a),dk("WEBCS_DOMAIN_BACKUP_LIST",a),dk("GATEWAY_DOMAINS",[n]),e.report&&e.report.hostname&&Array.isArray(e.report.hostname)&&e.report.hostname.length?(ld(e.report.hostname,"report.hostname"),dk("EVENT_REPORT_DOMAIN",e.report.hostname[0]),dk("EVENT_REPORT_BACKUP_DOMAIN",e.report.hostname[1]||e.report.hostname[0])
1):(dk("EVENT_REPORT_DOMAIN",s[0]),dk("EVENT_REPORT_BACKUP_DOMAIN",s[1]||s[0]));let c=6443;e.report&&e.report.port&&(t(e.report.port,"report.port"),c=e.report.port),dk("STATS_COLLECTOR_PORT",c),e.report?dk("ENABLE_EVENT_REPORT",!0):dk("ENABLE_EVENT_REPORT",!1);let d="";e.log&&e.log.hostname&&Array.isArray(e.log.hostname)&&e.log.hostname.length?(ld(e.log.hostname,"log.hostname"),d=e.log.hostname[0]):d=s[0];let l=6444;e.log&&e.log.port&&(t(e.log.port,"log.port"),l=e.log.port),dk("LOG_UPLOAD_SERVER","".concat(d,":").concat(l));let u=[];e.cds&&e.cds.hostname&&Array.isArray(e.cds.hostname)&&e.cds.hostname.length?(ld(e.cds.hostname,"cds.hostname"),u=e.cds.hostname):u=s;let h=443;e.cds&&e.cds.port&&(t(e.cds.port,"cds.port"),h=e.cds.port),dk("CDS_AP",u.map(e=>"".concat(e,":").concat(h))),e.cds?dk("ENABLE_CONFIG_DISTRIBUTE",!0):dk("ENABLE_CONFIG_DISTRIBUTE",!1),dg.info("set local access point v2 success")}setLocalAccessPoints(e,t){if(ld(e,"serverList"),lc(t,"domain"),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new du(o.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,dk("WEBCS_DOMAIN",e),dk("WEBCS_DOMAIN_BACKUP_LIST",e),dk("GATEWAY_DOMAINS",[t]),dk("EVENT_REPORT_DOMAIN",e[0]),dk("EVENT_REPORT_BACKUP_DOMAIN",e[1]||e[0]),dk("LOG_UPLOAD_SERVER","".concat(e[0],":6444")),dg.info("set local access point success")}async setRemoteDefaultVideoStreamType(e){if(lo(e,"streamType",[0,1]),this._remoteDefaultVideoStreamType=e,this._joinInfo)try{await this._gateway.setDefaultRemoteVideoStreamType(e),this._joinInfo.defaultVideoStream=this._remoteDefaultVideoStreamType}catch(e){throw dg.error("[".concat(this._clientId,"] set default remote video stream type error"),e.toString()),e}else dg.debug("haven't joined yet, cache remoteDefaultVideoStreamType ".concat(e))}async setRemoteVideoStreamType(e,t){lo(t,"streamType",[0,1]);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 dg.error("[".concat(this._clientId,"] set remote video stream type error"),e.toString()),e}dg.info("[".concat(this._clientId,"] set remote ").concat(e," video stream type to ").concat(t)),this._remoteStreamTypeCacheMap.set(e,t)}async setStreamFallbackOption(e,t){lo(t,"fallbackType",[0,1,2]);try{await this._gateway.setStreamFallbackOption(e,t)}catch(e){throw dg.error("[".concat(this._clientId,"] set stream fallback option"),e.toString()),e}dg.info("[".concat(this._clientId,"] set remote ").concat(e," stream fallback type to ").concat(t)),this._streamFallbackTypeCacheMap.set(e,t)}setEncryptionConfig(e,t,i){if(lo(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"]),lc(t,"secret"),["aes-128-gcm2","aes-256-gcm2"].includes(e)){if(!i||!(i instanceof Uint8Array&&32===i.length))throw new du(o.INVALID_PARAMS,"salt must be an Uint8Array and exactly equal to 32 bytes")}else if(i)throw new du(o.INVALID_PARAMS,"current encrypt mode does not need salt");RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*,.<>?/:;'\"|{}\\[\\]])(?=.{8,})").test(t)||dg.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=h0(i))}async renewToken(e){if(lc(e,"token",1,2047),!this._key||!this._joinInfo)throw new du(o.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(dM.USE_NEW_TOKEN){dg.debug("start renew token with ticket from unilbs");let t=await pG(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||dh);dg.debug("[".concat(this._clientId,"] get ticket from unilbs success")),await this._gateway.renewToken({token:e,ticket:t})}else dg.debug("start renew token without ticket"),await this._gateway.renewToken({token:e});dg.debug("[".concat(this._clientId,"] renewToken success"))}catch(e){throw this._key=t,this._joinInfo.token=t,dg.error("[".concat(this._clientId,"] renewToken failed"),e.toString()),e}finally{i()}}enableAudioVolumeIndicator(){this._audioVolumeIndicationInterval?dg.warning("you have already enabled audio volume indicator!"):this._audioVolumeIndicationInterval=window.setInterval(()=>{let e=this._p2pChannel.getAudioLevels();
1this.emit(v.VOLUME_INDICATOR,e)},dM.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 du(o.LIVE_STREAMING_INVALID_RAW_STREAM,"raw streaming is only support h264");if(!this._p2pChannel.hasLocalMedia())throw new du(o.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 du(o.LIVE_STREAMING_TASK_CONFLICT);let i=t?k.TRANSCODE:k.RAW;return this._createLiveStreamingClient(i).startLiveStreamingTask(e,i)}setLiveTranscoding(e){return this._createLiveStreamingClient(k.TRANSCODE).setTranscodingConfig(e)}async stopLiveStreaming(e){let t=[this._liveRawStreamingClient,this._liveTranscodeStreamingClient].filter(t=>t&&t.hasUrl(e));if(!t.length)throw new du(o.INVALID_PARAMS,"can not find live streaming url to stop");await sG.all(t.map(t=>t&&t.stopLiveStreamingTask(e)))}async addInjectStreamUrl(e,t){if(!this._joinInfo)throw new du(o.INVALID_OPERATION,"can not addInjectStreamUrl, no joininfo");let i=this._createLiveStreamingClient(k.INJECT);i.setInjectStreamConfig(t,0),await i.startLiveStreamingTask(e,k.INJECT)}async removeInjectStreamUrl(){var e;let t=this._createLiveStreamingClient(k.INJECT),i=Array.from(u8(e=t.streamingTasks).call(e)).find(e=>e.mode===k.INJECT);if(!this._joinInfo||!i)throw new du(o.INVALID_OPERATION,"can remove addInjectStreamUrl, no joininfo or inject task");await t.stopLiveStreamingTask(i.url)}async startChannelMediaRelay(e){p$(e);let t=this._createChannelMediaRelayClient();await t.startChannelMediaRelay(e)}async updateChannelMediaRelay(e){p$(e);let t=this._createChannelMediaRelayClient();await t.updateChannelMediaRelay(e)}async stopChannelMediaRelay(){let e=this._createChannelMediaRelayClient();await e.stopChannelMediaRelay()}sendStreamMessage(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!this._joinInfo)throw new du(o.INVALID_OPERATION,"can not send data stream, not joined");if("string"==typeof e&&(e=(new TextEncoder).encode(e)),new Blob([e]).size>1024)throw new du(o.INVALID_PARAMS,"stream message out of range.");return this._gateway.signal.request(b.DATA_STREAM,{payload:h0(e)},!t)}sendMetadata(e){if(!this._joinInfo)throw new du(o.INVALID_OPERATION,"can not send metadata, not joined");if(new Blob([e]).size>1024)throw new du(o.METADATA_OUT_OF_RANGE);return this._gateway.signal.request(b.SEND_METADATA,{session_id:this._joinInfo.sid,metadata:h0(e)})}async sendCustomReportMessage(e){if(Array.isArray(e)||(e=[e]),e.forEach(lE),!this._joinInfo)throw new du(o.INVALID_OPERATION,"can not send custom report, not joined");await uC.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(){return this._statsCollector.getRemoteNetworkQualityStats()}async pickSVCLayer(e,t){lo(t.spatialLayer,"spatialLayer",[0,1,2,3]),lo(t.temporalLayer,"temporalLayer",[0,1,2,3]);try{await this._gateway.pickSVCLayer(e,t)}catch(e){throw dg.error("[".concat(this._clientId,"] pick SVC layer failed"),e.toString()),e}}_reset(){if(dg.debug("[".concat(this._clientId,"] reset client")),this._axiosCancelSource.cancel(),this._axiosCancelSource=da.CancelToken.source(),this._streamFallbackTypeCacheMap=new Map,this._remoteStreamTypeCacheMap=new Map,this._configDistribute.stopGetConfigDistribute(),this._joinInfo=void 0,this._proxyServer=void 0,this._defaultStreamFallbackType=void 0,this._sessionId=null,this.store.sessionId=null,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._users.forEac
1h(e=>{e._audioTrack&&e._audioTrack._destroy(),e._videoTrack&&e._videoTrack._destroy()}),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 uO("client-publish"),this._subscribeMutex=new uO("client-subscribe"),this._networkQualityInterval&&(window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=void 0),this._injectStreamingClient&&(this._injectStreamingClient.terminate(),this._injectStreamingClient.removeAllListeners(),this._injectStreamingClient=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){}}_startSession(e,t){let i=e||hF();e?dg.debug("[".concat(this._clientId,"] new Session ").concat(i)):dg.debug("[".concat(this._clientId,"] renewSession ").concat(this._sessionId," => ").concat(i)),this._sessionId=i,this.store.sessionId=i,t?uC.sessionInit(this._sessionId,{lts:(new Date).getTime(),cname:t.channel,appid:t.appId,mode:this._mode}):this._joinInfo?uC.sessionInit(this._sessionId,{lts:(new Date).getTime(),cname:this._joinInfo.cname,a
1ppid:this._joinInfo.appId,mode:this._mode}):this._gateway.joinInfo&&uC.sessionInit(this._sessionId,{lts:(new Date).getTime(),cname:this._gateway.joinInfo.cname,appid:this._gateway.joinInfo.appId,mode:this._mode}),this._joinInfo&&(this._joinInfo.sid=i),this._gateway.joinInfo&&(this._gateway.joinInfo.sid=i)}async _publishHighStream(e){if(!this._joinInfo||void 0===this._uid)throw new du(o.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new du(o.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&dM.FORCE_TURN&&!dM.TURN_ENABLE_TCP&&!dM.TURN_ENABLE_UDP)throw new du(o.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");dg.debug("[".concat(this._clientId,"] publish high stream"));try{let i=await this._p2pChannel.publish(e,this._isDualStreamEnabled,this._lowStreamParameter),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!==o.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 mg&&t._encoderConfig&&this._gateway.setVideoProfile(t._encoderConfig),!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)===o.WS_ABORT)return;throw t}}async _publishLowStream(){if(!this._joinInfo||void 0===this._uid)throw new du(o.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new du(o.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));dg.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!==o.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)===o.WS_ABORT)return;throw e}}_createLiveStreamingClient(e){if(!this._joinInfo||!this._appId)return new du(o.INVALID_OPERATION,"can not create live streaming client, please join channel first").throw();let t=()=>new pQ(this._joinInfo,this._config.websocketRetryConfig||dh,this._config.httpRetryConfig||dh),i=e=>{e.onLiveStreamError=(e,t)=>{uC.reportApiInvoke(this._sessionId,{name:p.ON_LIVE_STREAM_ERROR,options:[e,t],tag:_.TRACER}).onSuccess(),this.emit(v.LIVE_STREAMING_ERROR,e,t)},e.onLiveStreamWarning=(e,t)=>{uC.reportApiInvoke(this._sessionId,{name:p.ON_LIVE_STREAM_WARNING,options:[e,t],tag:_.TRACER}).onSuccess(),this.emit(v.LIVE_STREAMING_WARNING,e,t)},e.on(x.REQUEST_WORKER_MANAGER_LIST,(e,t,i)=>{if(!this._joinInfo)return i(new du(o.INVALID_OPERATION,"can not find join info to get worker manager"));pj(e,this._joinInfo,this._axiosCancelSource.token,dh).then(t).catch(i)})};switch(e){case k.RAW:return this._liveRawStreamingClient||(this._liveRawStreamingClient=t(),i(this._liveRawStreamingClient)),this._liveRawStreamingClient;case k.TRANSCODE:return this._liveTranscodeStreamingClient||(this._liveTranscodeStreamingClient=t(),i(this._liveTranscodeStreamingClient)),this._liveTranscodeStreamingClient;case k.INJECT:return this._injectStreamingClient||(this._injectStreamingClient=t(),this._injectStreamingClient.on(x.REQUEST_WORKER_MANAGER_LIST,(e,t,i)=>{if(!this._joinInfo)return i(new du(o.INVALID_OPERATION,"can not find join info to get worker manager"));pj(e,this._joinInfo,this._axiosCancelSource.token,dh).then(t).cat
1ch(i)}),this._injectStreamingClient.onInjectStatusChange=(e,t,i)=>{this.emit(v.INJECT_STREAM_STATUS,e,t,i)}),this._injectStreamingClient}}_createChannelMediaRelayClient(){return this._joinInfo?(this._channelMediaRelayClient||(this._channelMediaRelayClient=new p1(this._joinInfo,this._clientId,this._config.websocketRetryConfig||dh,this._config.httpRetryConfig||dh),this._channelMediaRelayClient.on("state",e=>{e===G.RELAY_STATE_FAILURE&&this._channelMediaRelayClient&&this._channelMediaRelayClient.dispose(),this.emit(v.CHANNEL_MEDIA_RELAY_STATE,e)}),this._channelMediaRelayClient.on("event",e=>{this.emit(v.CHANNEL_MEDIA_RELAY_EVENT,e)})),this._channelMediaRelayClient):new du(o.INVALID_OPERATION,"can not create channel media relay client, please join channel first").throw()}_handleGatewayEvents(){this._gateway.on(K.DISCONNECT_P2P,async()=>{await this._p2pChannel.disconnectForReconnect()}),this._gateway.on(K.CONNECTION_STATE_CHANGE,(e,t,i)=>{var r,n;if(i===C.FALLBACK)return;let o=()=>{this.emit(v.CONNECTION_STATE_CHANGE,e,t,i)};if(uC.reportApiInvoke(this._sessionId||(null==(r=this._gateway.joinInfo)?void 0:r.sid)||null,{name:p.CONNECTION_STATE_CHANGE,options:[e,t,i],tag:_.TRACER}).onSuccess(JSON.stringify({cur:e,prev:t,reason:i})),dg.info("[".concat(this._clientId,"] connection state change: ").concat(t," -> ").concat(e)),"DISCONNECTED"===e)return this._reset(),void o();"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._audioSSRC=void 0,e._videoSSRC=void 0,e._videoOrtc=void 0,e._audioOrtc=void 0,e._cname=void 0,e._rtxSsrcId=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.forEac
1h((e,t)=>{this._gateway.setStreamFallbackOption(t,e).catch(e=>{dg.warning("[".concat(this._clientId,"] auto set stream fallback option failed"),e)})}),this._remoteStreamTypeCacheMap.forEach((e,t)=>{this._gateway.setRemoteVideoStreamType(t,e).catch(e=>{dg.warning("[".concat(this._clientId,"] auto set remote stream type failed"),e)})}),void 0!==this._remoteDefaultVideoStreamType&&void 0===(null==(n=this._joinInfo)?void 0:n.defaultVideoStream)&&this.setRemoteDefaultVideoStreamType(this._remoteDefaultVideoStreamType).then(()=>{dg.debug("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway connected"))}).catch(e=>{dg.error("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway failed, ").concat(e))}),this._p2pChannel.republish(),this._userOfflineTimeout=window.setTimeout(()=>{"CONNECTED"===this.connectionState&&(this._userOfflineTimeout=void 0,this._users.filter(e=>!e._trust_in_room_).forEach(e=>{dg.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_||(dg.debug("[".concat(this._clientId,"] auto dispatch audio unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,"audio",!1)),e._trust_video_mute_state_||(dg.debug("[".concat(this._clientId,"] auto dispatch video unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,"video",!1)),e._trust_audio_enabled_state_||(dg.debug("[".concat(this._clientId,"] auto dispatch enable local audio ").concat(e.uid)),this._handleSetStreamLocalEnable("audio",e.uid,!0)),e._trust_video_enabled_state_||(dg.debug("[".concat(this._clientId,"] auto dispatch enable local video ").concat(e.uid)),this._handleSetStreamLocalEnable("video",e.uid,!0)),e._trust_video_stream_added_state_||(dg.debug("[".concat(this._clientId,"] auto dispatch reset video stream added ").concat(e.uid)),this._handleResetAddStream(e,"video")),e._trust_audio_stream_added_state_||(dg.debug("[".concat(this._clientId,"] auto dispatch reset audio stream added ").concat(e.uid)),this._handleResetAddStream(e,"audio")),e._video_added_||e._audio_added_||(dg.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(K.REQUEST_NEW_GATEWAY_LIST,(e,t)=>{if(!this._joinInfo)return t(new du(o.UNEXPECTED_ERROR,"can not recover, no join info"));pM(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||dh,this.store).then(t=>{this._joinInfo&&(this._joinInfo.apResponse=t.gatewayInfo.res,this._joinInfo.gatewayAddrs=t.gatewayInfo.gatewayAddrs,this._joinInfo.uni_lbs_ip=t.gatewayInfo.uni_lbs_ip),e(t.gatewayInfo.gatewayAddrs.map(e=>{if(this._joinInfo&&this._joinInfo.proxyServer){let t=e.address.split(":");return"wss://".concat(this._joinInfo.proxyServer,"/ws/?h=").concat(t[0],"&p=").concat(t[1])}return"wss://".concat(e.address)}))}).catch(t)}),this._gateway.on(K.NETWORK_QUALITY,e=>{"normal"===this._networkQualitySensitivity&&this.emit(v.NETWORK_QUALITY,e)}),this._gateway.on(K.STREAM_TYPE_CHANGE,(e,t)=>{this.emit(v.STREAM_TYPE_CHANGED,e,t),uC.reportApiInvoke(this._sessionId,{name:p.STREAM_TYPE_CHANGE,options:[e,t],tag:_.TRACER}).onSuccess(JSON.stringify({uid:e,streamType:t}))}),this._gateway.on(K.IS_P2P_DISCONNECTED,e=>{e(!!this._p2pChannel.isP2PDisconnected()||!(this._p2pChannel.hasLocalMedia()||this._p2pChannel.hasRemoteMedia()))}),this._gateway.on(K.NEED_RENEW_SESSION,()=>{this._startSession()}),this._gateway.on(K.REQUEST_P2P_CONNECTION_PARAMS,async(e,t,i)=>{try{t(await this._p2pChannel.startP2PConnection(e))}catch(e){i(e)}}),this._gateway.on(K.JOIN_RESPONSE,(e,t)=>{let{dtlsParameters:i,iceParameters:r,candidates:n,rtpCapabilities:o,setup:s,cname:a}=ff(e.ortc,t);this._p2pChannel.connect(r,i,n,o,s,a)}),this._gateway.on(K.REQUEST_DC_CONNECTION_PARAMS,e=>{e(this._p2pChannel.getEstablishParams())}),this._gateway.on(K.RESET_SIGNAL,e=>{this._p2pChannel.resetConnection(e),this._handleGatewaySignalEvents()}),this._gateway.on(K.DATACHANNEL_FAILBACK,()=>{this._joinGateway()}),this._gateway.on(K.DATACHANNEL_PRECONNECT,async(e,t,i,r)=>{var n,o,s,a,c,d;let l;await this._p2pChannel.startP2PConnection({turnServer:null==(n=this._joinInfo)?void 0:n.turnServer},!0);let u=(t&&t.ip&&"number"==typeof t.port?(l=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:t.ip,port:t.port.toString(),type:"host",extension:{}}],dg.debug("Using remote candidate from AP ".concat(t.ip,":").concat(t.port)),t.ip6&&(l.push({foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:t.ip6,port:t.port.toString(),type:"host",extension:{}}),dg.debug("Using IPV6 remote candidate from AP ".concat(t.ip6,":").concat(t.port)))):l=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:e.ip,port:e.port.toString(),type:"host",extension:{}}],l);return this._p2pChannel.preConnect({iceUfrag:"".concat(null==(o=this._joinInfo)?void 0:o.apResponse.cid,"_").concat(null==(s=this._joinInfo)?void 0:s.apResponse.cert),icePwd:"".concat(null==(a=this._joinInfo)?void 0:a.apResponse.cid,"_").concat(null==(c=this._joinInfo)?void 0:c.apResponse.cert)},{fingerprints:[{hashFunction:"sha-256",fingerprint:null!=(d=dM.FINGERPRINT)?d:e.fingerprint}]},u,{send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},"active","o/i14u9pJrxRKAsu").then(i).catch(r)})}_handleGatewaySignalEvents(){this._gateway.signal.on(w.ON_USER_ONLINE,this._handleUserOnline),this._gateway.signal.on(w.ON_USER_OFFLINE,this._handleUserOffline),this._gateway.signal.on(w.ON_ADD_AUDIO_STREAM,e=>this._handleAddAudioOrVideoStream("audio",e.uid,e.ssrcId,e.cname,e.uint_id,e.ortc)),this._gateway.signal.on(w.ON_ADD_VIDEO_STREAM,e=>this._handleAddAudioOrVideoStream("video",e.uid,e.ssrcId,e.cname,e.uint_id,e.ortc,e.rtxSsrcId)),this._gateway.signal.on(w.ON_REMOVE_STREAM,this._handleRemoveStream),this._gateway.signal.on(w.ON_P2P_LOST,this._handleP2PLost),this._gateway.signal.on(w.MUTE_AUDIO,e=>this._handleMuteStream(e.uid,"audio",!0)),this._gateway.signal.on(w.UNMUTE_AUDIO,e=>this._handleMuteStream(e.uid,"audio",!1)),this._gateway.signal.on(w.MUTE_VIDEO,e=>this._handleMuteStream(e.uid,"video",!0)),this._gateway.signal.on(w.UNMUTE_VIDEO,e=>this._handleMuteStream(e.uid,"video",!1)),this._gateway.signal.on(w.RECEIVE_METADATA,e=>{let t=h$(e.metadata);
1this.emit(v.RECEIVE_METADATA,e.uid,t)}),this._gateway.signal.on(w.ON_DATA_STREAM,e=>{e.seq&&delete e.seq,e.payload=h$(e.payload),this.emit(v.STREAM_MESSAGE,e.uid,e.payload),this.onStreamMessage&&this.onStreamMessage(e)}),this._gateway.signal.on(w.ON_CRYPT_ERROR,()=>{hZ(()=>{dg.warning("[".concat(this._clientId,"] on crypt error")),this.emit(v.CRYPT_ERROR)},this._sessionId)}),this._gateway.signal.on(w.ON_TOKEN_PRIVILEGE_WILL_EXPIRE,this._handleTokenWillExpire),this._gateway.signal.on(w.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{dg.warning("[".concat(this._clientId,"] received message onTokenPrivilegeDidExpire, please get new token and join again")),this._gateway.leave(!0),this.emit(v.ON_TOKEN_PRIVILEGE_DID_EXPIRE),this._reset()}),this._gateway.signal.on(w.ON_STREAM_FALLBACK_UPDATE,e=>{dg.debug("[".concat(this._clientId,"] stream fallback peerId: ").concat(e.stream_id,", attr: ").concat(e.stream_type)),this.emit(v.STREAM_FALLBACK,e.stream_id,1===e.stream_type?"fallback":"recover")}),this._gateway.signal.on(w.ON_PUBLISH_STREAM,e=>{this.uid===this._uid&&(this._p2pChannel.reportPublishEvent(!0,null,void 0,!1,JSON.stringify({proxy:e.proxy})),dg.info("[".concat(this._clientId,"] on publish stream, ").concat(JSON.stringify(e))))}),this._gateway.signal.on(w.ENABLE_LOCAL_VIDEO,e=>{this._handleSetStreamLocalEnable("video",e.uid,!0)}),this._gateway.signal.on(w.DISABLE_LOCAL_VIDEO,e=>{this._handleSetStreamLocalEnable("video",e.uid,!1)}),this._gateway.signal.on(O.REQUEST_TIMEOUT,(e,t)=>{if(this._joinInfo)switch(e){case b.PUBLISH:{if(!t)return;let e=t.ortc;if(e){var i,r,n,s;let a=e.some(e=>{let{stream_type:t}=e;return t===H.Audio}),c=e.some(e=>{let{stream_type:t}=e;return t!==H.Audio}),d=e.some(e=>{let{stream_type:t}=e;return t===H.Screen||t===H.ScreenLow});"offer"===t.state&&uC.publish(this._joinInfo.sid,{eventElapse:hS.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:!1,ec:o.TIMEOUT,audio:a,video:c,p2pid:t.p2p_id,publishRequestid:this.store.pubId,screenshare:d,audioName:a?null==(i=e.find(e=>{let{stream_type:t}=e;return t===H.Audio}))||null==(r=i.ssrcs[0])?void 0:r.ssrcId.toString():void 0,videoName:c?null==(n=e.find(e=>{let{stream_type:t}=e;return t!==H.Audio}))||null==(s=n.ssrcs[0])?void 0:s.ssrcId.toString():void 0})}break}case b.SUBSCRIBE:t&&uC.subscribe(this._joinInfo.sid,{succ:!1,ec:o.TIMEOUT,audio:t.stream_type===en.AUDIO,video:t.stream_type===en.VIDEO,peerid:t.stream_id,subscribeRequestid:t.ssrcId,p2pid:this.store.p2pId,eventElapse:hS.measureFromSubscribeStart(this.store.clientId,t.ssrcId)})}}),this._gateway.signal.on(w.ON_P2P_OK,e=>{this.uid,this._uid}),this._gateway.signal.on(w.ON_PUBLISHED_USER_LIST,e=>{if(null==e||!e.users)return;dM.BLOCK_LOCAL_CLIENT&&(e.users=e.users.filter(e=>!dH(e.audio_ssrc,this.channelName)));let t=[],i=[];for(let r of e.users){let e=this._users.find(e=>e.uid===r.stream_id);e?e._trust_in_room_=!0:(e=new mI(r.stream_id,r.stream_id),this._users.push(e),0===this.getListeners(v.PUBLISHED_USER_LIST).length&&(dg.debug("[".concat(this._clientId,"] user online"),r.stream_id),this.emit(v.USER_JOINED,e)));let n=Y.Audio&r.stream_type,o=(Y.Video|Y.LwoVideo)&r.stream_type,s=n&&e.hasAudio,a=o&&e.hasVideo;o&&(e._trust_video_stream_added_state_=!0,e._video_added_=!0,e._videoSSRC=r.video_ssrc),n&&(e._trust_audio_stream_added_state_=!0,e._audio_added_=!0,e._audioSSRC=r.audio_ssrc),n&&!s&&0===this.getListeners(v.PUBLISHED_USER_LIST).length&&(dg.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published audio")),this.emit(v.USER_PUBLISHED,e,"audio")),o&&!a&&0===this.getListeners(v.PUBLISHED_USER_LIST).length&&(dg.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published video")),this.emit(v.USER_PUBLISHED,e,"video")),(n&&!s||o&&!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&&(dg.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=>{dg.error("[".concat(this._clientId,"] mass resubscribe error"),e.toString())})),this.getListeners(v.PUBLISHED_USER_LIST).length>0?(dg.info("[".concat(this._clientId,"] client emit user-list event, users: ").concat(t.map(e=>
1e.uid).join(", "))),this.emit(v.PUBLISHED_USER_LIST,t)):dg.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(", ")))})}_handleP2PChannelEvents(){this._p2pChannel.on(ea.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===o.DISCONNECT_P2P?t():i(e)}else t()}),this._p2pChannel.on(ea.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===o.DISCONNECT_P2P?t():i(e)}else t()}),this._p2pChannel.on(ea.RequestRePublish,(e,t,i)=>{this.publish(e,!1).then(t).catch(i)}),this._p2pChannel.on(ea.RequestReSubscribe,async(e,t,i)=>{try{for(let{user:t,kind:i}of e)i===en.VIDEO?await this.subscribe(t,"video"):await this.subscribe(t,"audio");t()}catch(e){i(e)}}),this._p2pChannel.on(ea.RequestUploadStats,(e,t)=>{this._gateway.uploadStats(e,t)}),this._p2pChannel.on(ea.MediaReconnectStart,e=>{this.emit(v.MEDIA_RECONNECT_START,e)}),this._p2pChannel.on(ea.MediaReconnectEnd,e=>{this.emit(v.MEDIA_RECONNECT_END,e)}),this._p2pChannel.on(ea.NeedSignalRTT,e=>{e(this._gateway.getSignalRTT())}),this._p2pChannel.on(ea.RequestRestartICE,async()=>{let e,t=await this._p2pChannel.restartICE(),i=await t.next();if(i.done)return;let r=i.value;try{e=await this._gateway.restartICE({iceParameters:r})}catch(e){return void t.throw(e)}let{iceParameters:n}=function(e){let t=e.iceParameters;return{iceParameters:{iceUfrag:t.iceUfrag,icePwd:t.icePwd}}}(e);await t.next({remoteIceParameters:n})}),this._p2pChannel.on(ea.RequestReconnect,async()=>{this._gateway.reconnect()}),this._p2pChannel.on(ea.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}),{dtlsParameters:s,iceParameters:a,candidates:c,rtpCapabilities:d,setup:l,cname:u}=ff(n,o);await this._p2pChannel.connect(a,s,c,d,l,u),await this._p2pChannel.republish(),await this._p2pChannel.reSubscribe()}),this._p2pChannel.on(ea.RequestUnpublishForReconnectPC,async(e,t,i)=>{this._joinInfo&&void 0!==this._uid?(await this._gateway.unpublish(e,this._uid),t()):i()}),this._p2pChannel.on(ea.P2PLost,()=>{this.emit(v.P2P_LOST,this.store.uid)}),this._p2pChannel.on(ea.UpdateVideoEncoder,e=>{e._encoderConfig&&this._gateway.setVideoProfile(e._encoderConfig)}),this._p2pChannel.on(ea.ConnectionTypeChange,e=>{this.emit(v.IS_USING_CLOUD_PROXY,e)}),this._p2pChannel.on(ea.RequestLowStreamParameter,e=>{e(this._lowStreamParameter||{width:160,height:120,framerate:15,bitrate:50})}),this._p2pChannel.on(ea.QueryClientConnectionState,e=>{e(this.connectionState)})}getKeyMetrics(){return this.store.keyMetrics}async enableContentInspect(e){if("CONNECTED"!==this.connectionState||!this._joinInfo)throw new du(o.INVALID_OPERATION,"[".concat(this._clientId,"] Client did not join channel"));if(this._inspect)throw new du(o.INVALID_OPERATION,"[".concat(this._clientId,"] Inspect content service already in connecting/connected state"));if(!e)throw new du(o.INVALID_PARAMS,"[".concat(this._clientId,"] inspectConfig is necessary"));if(!e.inspectType||!Array.isArray(e.inspectType))throw new du(o.INVALID_PARAMS,"[".concat(this._clientId,"] inspectConfig.inspectType is necessary and is an instance of Array."));{let t=[...new Set(e.inspectType)];t.forEach(e=>{if(!["supervise","moderation"].includes(e))throw new du(o.INVALID_PARAMS,"[".concat(this._clientId,"] ").concat(e," is not a valid inspect type."))}),e.inspectType=t}if(e&&e.extraInfo&&e.extraInfo.length>1024)throw new du(o.INVALID_PARAMS,"[".concat(this._clientId,"] inspectConfig.extraInfo length cannot exceed 1024 bytes"));try{let t=new SH(e);this._inspect=t,this.handleVideoInspectEvents(this._inspect),await t.init({appId:this._joinInfo.appId,areaCode:"",cname:this._joinInfo.cname,sid:this._joinInfo.sid,token:this._joinInfo.token,uid:this._joinInfo.uid,cid:this._joinInfo.cid,vid:this._joinInfo.vid?Number(this._joinInfo.vid):0},dh)}catch(e){throw Array.isArray(e)?e[0]:e}}async disableContentInspect(){if(!this._inspect)throw new du(o.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}}handleVideoInspectEvents(e){e.on(e_.CONNECTION_STATE_CHANGE,(t,i)=>
1{if(this.emit(v.CONTENT_INSPECT_CONNECTION_STATE_CHANGE,t,i),i===eh.CONNECTED){if("CONNECTED"!==this.connectionState)return void this.emit(v.CONTENT_INSPECT_ERROR,new du(o.OPERATION_ABORTED,"Content inspect was cancelled because it left the channel"));e.inspectImage()}}),e.on(e_.INSPECT_RESULT,(e,t)=>{var i;if((null==t?void 0:t.code)===o.INVALID_OPERATION&&"DISCONNECTED"===this.connectionState)return dg.debug("Stop inspect content because that has left channel"),null==this||null==(i=this._inspect)||i.close(),void(this._inspect=void 0);this.emit(v.CONTENT_INSPECT_RESULT,e,t)}),e.on(e_.CLIENT_LOCAL_VIDEO_TRACK,e=>{e(this.localTracks.filter(e=>"video"===e.trackMediaType)[0])})}getJoinChannelServiceRecords(){return dg.debug("getJoinChannelServiceRecords"),this.store.joinChannelServiceRecords}async setPublishAudioFilterEnabled(e){ln(e,"enabled"),dk("ENABLE_PUBLISH_AUDIO_FILTER",e),this._joinInfo&&await this._gateway.setPublishAudioFilterEnabled(e)}_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}}}).prototype,"leave",[eF],Object.getOwnPropertyDescriptor(tp.prototype,"leave"),tp.prototype),ui(tp.prototype,"publish",[ej],Object.getOwnPropertyDescriptor(tp.prototype,"publish"),tp.prototype),ui(tp.prototype,"unpublish",[eB],Object.getOwnPropertyDescriptor(tp.prototype,"unpublish"),tp.prototype),ui(tp.prototype,"subscribe",[eG],Object.getOwnPropertyDescriptor(tp.prototype,"subscribe"),tp.prototype),ui(tp.prototype,"massSubscribe",[eW],Object.getOwnPropertyDescriptor(tp.prototype,"massSubscribe"),tp.prototype),ui(tp.prototype,"unsubscribe",[eH],Object.getOwnPropertyDescriptor(tp.prototype,"unsubscribe"),tp.prototype),ui(tp.prototype,"massUnsubscribe",[eK],Object.getOwnPropertyDescriptor(tp.prototype,"massUnsubscribe"),tp.prototype),ui(tp.prototype,"setLowStreamParameter",[eY],Object.getOwnPropertyDescriptor(tp.prototype,"setLowStreamParameter"),tp.prototype),ui(tp.prototype,"enableDualStream",[eq],Object.getOwnPropertyDescriptor(tp.prototype,"enableDualStream"),tp.prototype),ui(tp.prototype,"disableDualStream",[eJ],Object.getOwnPropertyDescriptor(tp.prototype,"disableDualStream"),tp.prototype),ui(tp.prototype,"setClientRole",[eX],Object.getOwnPropertyDescriptor(tp.prototype,"setClientRole"),tp.prototype),ui(tp.prototype,"setProxyServer",[ez],Object.getOwnPropertyDescriptor(tp.prototype,"setProxyServer"),tp.prototype),ui(tp.prototype,"setTurnServer",[eQ],Object.getOwnPropertyDescriptor(tp.prototype,"setTurnServer"),tp.prototype),ui(tp.prototype,"setLicense",[eZ],Object.getOwnPropertyDescriptor(tp.prototype,"setLicense"),tp.prototype),ui(tp.prototype,"startProxyServer",[e$],Object.getOwnPropertyDescriptor(tp.prototype,"startProxyServer"),tp.prototype),ui(tp.prototype,"stopProxyServer",[e0],Object.getOwnPropertyDescriptor(tp.prototype,"stopProxyServer"),tp.prototype),ui(tp.prototype,"setLocalAccessPointsV2",[e1],Object.getOwnPropertyDescriptor(tp.prototype,"setLocalAccessPointsV2"),tp.prototype),ui(tp.prototype,"setLocalAccessPoints",[e2],Object.getOwnPropertyDescriptor(tp.prototype,"setLocalAccessPoints"),tp.prototype),ui(tp.prototype,"setRemoteDefaultVideoStreamType",[e3],Object.getOwnPropertyDescriptor(tp.prototype,"setRemoteDefaultVideoStreamType"),tp.prototype),ui(tp.prototype,"setRemoteVideoStreamType",[e4],Object.getOwnPropertyDescriptor(tp.prototype,"setRemoteVideoStreamType"),tp.prototype),ui(tp.prototype,"setStreamFallbackOption",[e5],Object.getOwnPropertyDescriptor(tp.prototype,"setStreamFallbackOption"),tp.prototype),ui(tp.prototype,"setEncryptionConfig",[e6],Object.getOwnPropertyDescriptor(tp.prototype,"setEncryptionConfig"),tp.prototype),ui(tp.prototype,"renewToken",[e8],Object.getOwnPropertyDescriptor(tp.prototype,"renewToken"),tp.prototype),ui(tp.prototype,"enableAudioVolumeIndicator",[e7],Object.getOwnPropertyDescriptor(tp.prototype,"enableAudioVolumeIndicator"),tp.prototype),ui(tp.prototype,"startLiveStreaming",[e9],Object.getOwnPropertyDescriptor(tp.prototype,"startLiveStreaming"),tp.prototype),ui(tp.prototype,"setLiveTranscoding",[te],Object.getOwnPropertyDescriptor(tp.prototype,"setLiveTranscoding"),tp.prototype),ui(tp.prototype,"stopLiveStreaming",[tt],Object.getOwnPropertyDescriptor(tp.prototype,"stopLiveStreaming"),tp.prototype),ui(tp.prototype,"addInjectStreamUrl",[ti],Object.getOwnPropertyDescriptor(tp.prototype,"addInjectStreamUrl"),tp.prototype),ui(tp.prototype,"removeInjectStreamUrl",[tr],Object.getOwnPropertyDescriptor(tp.prototype,"removeInjectStreamUrl"),tp.prototype),ui(tp.prototype,"startChannelMediaRelay",[tn],Object.getOwnPropertyDescriptor(tp.prototype,"startChannelMediaRelay"),tp.prototype),ui(tp.prototype,"updateChannelMediaRelay",[to],Object.getOwnPropertyDescriptor(tp.prototype,"updateChannelMediaRelay"),tp.prototype),ui(tp.prototype,"stopChannelMediaRelay",[ts],Object.getOwnPropertyDescriptor(tp.prototype,"stopChannelMediaRelay"),tp.prototype),ui(tp.prototype,"sendCustomReportMessage",[ta],Object.getOwnPropertyDescriptor(tp.prototype,"sendCustomReportMessage"),tp.prototype),ui(tp.prototype,"pickSVCLayer",[tc],Object.getOwnPropertyDescriptor(tp.prototype,"pickSVCLayer"),tp.prototype),ui(tp.prototype,"enableContentInspect",[td],Object.getOwnPropertyDescriptor(tp.prototype,"enableContentInspect"),tp.prototype),ui(tp.prototype,"disableContentInspect",[tl],Object.getOwnPropertyDescriptor(tp.prototype,"disableContentInspect"),tp.prototype),ui(tp.prototype,"getJoinChannelServiceRecords",[tu],Object.getOwnPropertyDescriptor(tp.prototype,"getJoinChannelServiceRecords"),tp.prototype),ui(tp.prototype,"setPublishAudioFilterEnabled",[th],Object.getOwnPropertyDescriptor(tp.prototype,"setPublishAudioFilterEnabled"),tp.prototype),tp);class SJ extends uF{set currentState(e){e!==this._currentState&&(this._currentState=e,this.emit
1(P.AUDIO_SOURCE_STATE_CHANGE,this._currentState))}get currentState(){return this._currentState}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),cc(this,"audioBuffer",void 0),cc(this,"sourceNode",void 0),cc(this,"startPlayTime",0),cc(this,"startPlayOffset",0),cc(this,"pausePlayTime",0),cc(this,"options",void 0),cc(this,"currentLoopCount",0),cc(this,"_currentState","stopped"),this.audioBuffer=e,this.options=t,this.startPlayOffset=this.options.startPlayTime||0}createWebAudioDiagram(){return this.context.createGain()}get duration(){return this.audioBuffer.duration}get currentTime(){return"stopped"===this.currentState?0:"paused"===this.currentState?this.pausePlayTime:(this.context.currentTime-this.startPlayTime+this.startPlayOffset)%this.audioBuffer.duration}updateOptions(e){"stopped"===this.currentState?(this.options=e,this.startPlayOffset=this.options.startPlayTime||0):dg.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()}}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}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}}let SX=new Map;async function Sz(e,t){let i=null;if("string"==typeof e){let t=SX.get(e);if(t)return dg.debug("use cached audio resource: ",e),t;try{i=(await d_(()=>da.get(e,{responseType:"arraybuffer"}),void 0,void 0,{maxRetryCount:3})).data}catch(e){throw new du(o.FETCH_AUDIO_FILE_FAILED,e.toString())}}else{let t=new sG((t,i)=>{let r=new FileReader;r.onload=e=>{e.target?t(e.target.result):i(new du(o.READ_LOCAL_AUDIO_FILE_ERROR))},r.onerror=()=>{i(new du(o.READ_LOCAL_AUDIO_FILE_ERROR))},r.readAsArrayBuffer(e)});i=await t}let r=await function(e){let t=uk();return new sG((i,r)=>{t.decodeAudioData(e,e=>{i(e)},e=>{r(new du(o.DECODE_AUDIO_FILE_FAILED,e.toString()))})})}(i);return"string"==typeof e&&t&&SX.set(e,r),r}function SQ(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 SZ(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?SQ(Object(i),!0).forEach(function(t){cc(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):SQ(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}function S$(e,t,i,r){i.optimizationMode&&(r&&r.width&&r.height?(i.encoderConfig=SZ(SZ({},r),{},{bitrateMin:r.bitrateMin,bitrateMax:r.bitrateMax}),"motion"!==i.optimizationMode&&"detail"!==i.optimizationMode||(t.contentHint=i.optimizationMode,t.contentHint===i.optimizationMode?dg.debug("[".concat(e,"] set content hint to"),i.optimizationMode):dg.debug("[".concat(e,"] set content hint failed")))):dg.warning("[".concat(e,"] can not apply optimization mode bitrate config, no encoderConfig")))}let S0=aY().name;class S1{constructor(e,t){cc(this,"id",0),cc(this,"element",void 0),cc(this,"peerPair",void 0),cc(this,"context",void 0),cc(this,"audioPlayerElement",void 0),cc(this,"audioTrack",void 0),S1.count+=1,this.id=S1.count,this.element=e,this.context=t}initPeers(){this.peerPair=[new RTCPeerConnection,new RTCPeerConnection],this.peerPair[1].ontrack=e=>{let t=document.createElement("audio");
1t.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 sG(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 du(o.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 du(o.LOCAL_AEC_ERROR,e.toString()).print()}if(!t)throw new du(o.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(){dg.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}}cc(S1,"count",0);let S2=window.AudioContext||window.webkitAudioContext,S3=new(t_=uI({report:uC}),ui((tE=class{constructor(){cc(this,"units",[]),cc(this,"context",void 0)}processExternalMediaAEC(e){if(!this._doesEnvironmentNeedAEC())return dg.debug("the system does not need to process local aec"),-1;this.context||(this.context=new S2);let t=this.units.find(t=>t&&t.getElement()===e);return t||(t=new S1(e,this.context),this.units.push(t)),t.startEchoCancellation(),dg.debug("start processing local audio echo cancellation, id is",t.id),t.id}_doesEnvironmentNeedAEC(){return aY().name!==t.SAFARI}}).prototype,"processExternalMediaAEC",[t_],Object.getOwnPropertyDescriptor(tE.prototype,"processExternalMediaAEC"),tE.prototype),tE);dk("PROCESS_ID","process-".concat(hV(8,""),"-").concat(hV(4,""),"-").concat(hV(4,""),"-").concat(hV(4,""),"-").concat(hV(12,""))),function(){let i=aY();lU.getDisplayMedia=!!navigator.mediaDevices&&!!navigator.mediaDevices.getDisplayMedia,lU.getStreamFromExtension=i.name===t.CHROME&&Number(i.version)>34,lU.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}(),lU.supportMinBitrate=i.name===t.CHROME||i.name===t.EDGE,lU.supportSetRtpSenderParameters=function(){let e=aY();return!!window.RTCRtpSender&&!!window.RTCRtpSender.prototype.setParameters&&!!window.RTCRtpSender.prototype.getParameters&&(!!ce()||!(!aX()&&!aq())||e.name===t.FIREFOX&&Number(e.version)>=64)}(),i.name===t.SAFARI&&(Number(i.version)>=14?lU.supportDualStream=!0:lU.supportDualStream=!1),lU.webAudioMediaStreamDest=function(){let e=aY();return!(e.name===t.SAFARI&&12>Number(e.version))}(),lU.supportReplaceTrack=!!window.RTCRtpSender&&"function"==typeof RTCRtpSender.prototype.replaceTrack,lU.supportWebGL="undefined"!=typeof WebGLRenderingContext,lU.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,ce()||(lU.webAudioWithAEC=!0),lU.supportShareAudio=function(){let i=aY();return!!((i.os===e.WIN_10||i.os===e.WIN_81||i.os===e.WIN_7||i.os===e.LINUX||i.os===e.MAC_OS)&&i.name===t.CHROME&&Number(i.version)>=74)}(),lU.supportDualStreamEncoding=function(){let e=aY();return!!dM.DISABLE_WEBAUDIO||"Safari"===e.name&&Number(e.version)>=14||!!("Chrome"===e.name&&/Windows/i.test(e.os||"")&&Number(e.version)>=100&&dM.CHROME_DUAL_STREAM_USE_ENCODING)}(),lU.supportDataChannel=!!(aZ(76)||function(e){let i=aY();return!(i.name!==t.FIREFOX||!i.osVersion)&&Number(i.version)>=68}(0)||function(e){let i=aY();return!(i.name!==t.SAFARI||!i.osVersion)&&Number(i.version)>=14}(0)),lU.supportPCSetConfiguration=!az()&&!!RTCPeerConnection.prototype.setConfiguration,dg.info("browser compatibility",JSON.stringify(lU),JSON.stringify(i))}(),function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void dg.error("Error loading sdk config",e.message)}if(e)try{let t=JSON.parse(window.atob(e)),i=Date.now();dg.debug("Loading global parameters from cache",t),Object.keys(t).forEach(e
1=>{if(Object.prototype.hasOwnProperty.call(dM,e)){let{value:r,expires:n}=t[e];n&&n<=i||(dU[e]=r,dM[e]=r)}})}catch(t){dg.error("Error loading mutableParamsCache: ".concat(e),t.message)}}(),Array.isArray(dU.AREAS)&&dU.AREAS.length>0&&pI(dU.AREAS,!0);let S4={__CLIENT_LIST__:dG,__TRACK_LIST__:dW,VERSION:dI,BUILD:dR,setParameter:(e,t,i)=>{dg.debug("setParameter key:".concat(e,", value:").concat(JSON.stringify(t))),dk(e,t,i)},getParameter:function(e){return dM[e]},getSupportedCodec:async function(){let e={audio:[],video:[]};try{let t=new RTCPeerConnection;t.addTransceiver("video",{direction:"recvonly"}),t.addTransceiver("audio",{direction:"recvonly"});let i=(await t.createOffer()).sdp;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(/ 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 du(o.CREATE_OFFER_FAILED,e.toString&&e.toString()).print()}return e},checkSystemRequirements:function(){let i=uC.reportApiInvoke(null,{name:p.CHECK_SYSTEM_REQUIREMENTS,options:[],tag:_.TRACER}),r=!1;try{let e=window.RTCPeerConnection,t=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,i=window.WebSocket;r=!!(e&&t&&i)}catch(e){return dg.error("check system requirement failed: ",e),!1}let n=!1,o=aY();o.name===t.CHROME&&Number(o.version)>=58&&("WebKit"!==aK.engine.name||function(){let t=aY();if(aq()){if(t.os===e.MAC_OS)return!0;if(t.os===e.IOS){let e=aK.os.version&&aK.os.version.split(".");if(e&&14===Number(e[0])&&e[1]&&Number(e[1])>=3||e&&Number(e[0])>14)return!0}}return!1}())&&(n=!0),o.name===t.FIREFOX&&Number(o.version)>=56&&(n=!0),o.name===t.OPERA&&Number(o.version)>=45&&(n=!0),o.name===t.SAFARI&&Number(o.version)>=11&&(n=!0),(a7()||aY().name===t.QQ)&&(n=!0),dg.debug("checkSystemRequirements, api:",r,"browser",n);let s=r&&n;return i.onSuccess(s),s},getDevices:function(e){return u0.enumerateDevices(!0,!0,e)},getMicrophones:function(e){return u0.getRecordingDevices(e)},getCameras:function(e){return u0.getCamerasDevices(e)},getElectronScreenSources:uW,getPlaybackDevices:function(e){return u0.getSpeakers(e)},createClient:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{codec:"vp8",audioCodec:"opus",mode:"rtc"},t=uC.reportApiInvoke(null,{name:p.CREATE_CLIENT,options:[e],tag:_.TRACER});try{lo(e.codec,"config.codec",["vp8","vp9","av1","h264"]),lo(e.mode,"config.mode",["rtc","live"]),void 0!==e.audioCodec&&lo(e.audioCodec,"config.audioCodec",["opus","pcmu","pcma","g722"]),void 0!==e.proxyServer&&lc(e.proxyServer,"config.proxyServer",1,1e4),void 0!==e.turnServer&&lT(e.turnServer),void 0!==e.httpRetryConfig&&lf(e.httpRetryConfig),void 0!==e.websocketRetryConfig&&lf(e.websocketRetryConfig)}catch(e){throw t.onError(e),e}return void 0===e.audioCodec&&(e.audioCodec="opus"),t.onSuccess(),new Sq(SY(SY({forceWaitGatewayResponse:!0},e),{},{role:"rtc"===e.mode?"host":e.role}))},createCameraVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=uC.reportApiInvoke(null,{tag:_.TRACER,name:p.CREATE_CAM_VIDEO_TRACK,options:[SZ({},e)]}),i=p9(e),r=hV(8,"track-cam-"),n=null;dg.info("start create camera video track with config",JSON.stringify(e),"trackId",r);try{n=(await uz({video:i},r)).getVideoTracks()[0]||null}catch(e){throw t.onError(e),e}if(!n){let e=new du(o.UNEXPECTED_ERROR,"can not find track in media stream");return t.onError(e),e.throw()}e.optimizationMode&&S$(r,n,e,dN(e.encoderConfig));let s=new mR(n,e,i,e.scalabiltyMode?dD(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,r);return t.onSuccess(s.getTrackId()),dg.info("create camera video success, trackId:",r),s},createCustomVideoTrack:function(e){let t=uC.reportApiInvoke(null,{tag:_.TRACER,name:p.CREATE_CUSTOM_VIDEO_TRACK,options:[e]}),i=new mg(e.mediaStreamTrack,{width:e.width,height:e.height,frameRate:e.frameRate,bitrateMax:e.bitrateMax,bitrateMin:e.bitrateMin}
1,e.scalabiltyMode?dD(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,hV(8,"track-cus-"),[X.CUSTOM_TRACK]);return t.onSuccess(i.getTrackId()),dg.info("create custom video track success with config",e,"trackId",i.getTrackId()),i},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=uC.reportApiInvoke(null,{tag:_.TRACER,name:p.CREATE_SCREEN_VIDEO_TRACK,options:[SZ({},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 r=function(e){let t={};e.screenSourceType&&(t.mediaSource=e.screenSourceType),e.extensionId&&aJ()&&(t.extensionId=e.extensionId);let{displaySurface:i,selfBrowserSurface:r,surfaceSwitching:n,systemAudio:o}=e;(aZ(107)||a$(107)||a0(93))&&(i&&(lo(i,"displaySurface",["browser","window","monitor"]),t.displaySurface=i),r?(lo(r,"selfBrowserSurface",["exclude","include"]),t.selfBrowserSurface=r):t.selfBrowserSurface="include",n&&(lo(n,"surfaceSwitching",["exclude","include"]),t.surfaceSwitching=n)),(aZ(105)||a$(105)||a0(91))&&o&&(lo(o,"systemAudio",["exclude","include"]),t.systemAudio=o),e.electronScreenSourceId&&(t.sourceId=e.electronScreenSourceId);let s=e.encoderConfig?dw(e.encoderConfig):null;return t.mandatory={chromeMediaSource:"desktop",maxWidth:s?s.width:void 0,maxHeight:s?s.height:void 0},s&&(s.frameRate&&("number"==typeof s.frameRate?(t.mandatory.maxFrameRate=s.frameRate,t.mandatory.minFrameRate=s.frameRate):(t.mandatory.maxFrameRate=s.frameRate.max||s.frameRate.ideal||s.frameRate.exact||void 0,t.mandatory.minFrameRate=s.frameRate.min||s.frameRate.ideal||s.frameRate.exact||void 0),t.frameRate=s.frameRate),s.width&&(t.width=s.width),s.height&&(t.height=s.height)),t}(e),n=hV(8,"track-scr-v-"),s=null,a=null;if(!lU.supportShareAudio&&"enable"===t){let e=new du(o.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return i.onError(e),e.throw()}dg.info("start create screen video track with config",e,"withAudio",t,"trackId",n);try{let e=await uz({screen:r,screenAudio:"auto"===t?lU.supportShareAudio:"enable"===t},n);s=e.getVideoTracks()[0]||null,a=e.getAudioTracks()[0]||null}catch(e){throw i.onError(e),e}if(!s){let e=new du(o.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(e),e.throw()}if(!a&&"enable"===t){s&&s.stop();let e=new du(o.SHARE_AUDIO_NOT_ALLOWED);return i.onError(e),e.throw()}e.optimizationMode||(e.optimizationMode="detail"),e.optimizationMode&&(S$(n,s,e,e.encoderConfig&&dw(e.encoderConfig)),e.encoderConfig&&"string"!=typeof e.encoderConfig&&(e.encoderConfig.bitrateMin=e.encoderConfig.bitrateMax));let c=new mg(s,e.encoderConfig?dw(e.encoderConfig):{},e.scalabiltyMode?dD(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,n,[X.SCREEN_TRACK]);if(!a)return i.onSuccess(c.getTrackId()),dg.info("create screen video track success","video:",c.getTrackId()),c;let d=new hh(a,void 0,hV(8,"track-scr-a-"),!1,!0);return i.onSuccess([c.getTrackId(),d.getTrackId()]),dg.info("create screen video track success","video:",c.getTrackId(),"audio:",d.getTrackId()),[c,d]},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=uC.reportApiInvoke(null,{tag:_.TRACER,name:p.CREATE_MIC_AND_CAM_TRACKS,options:[e,t]}),r=p9(t),n=_e(e),s=hV(8,"track-mic-"),a=hV(8,"track-cam-"),c=null,d=null;dg.info("start create camera video track(".concat(a,") and microphone audio track(").concat(s,") with config, audio: ").concat(JSON.stringify(e),", video: ").concat(JSON.stringify(t)));try{let e=await uz({audio:n,video:r},"".concat(s,"-").concat(a));c=e.getAudioTracks()[0],d=e.getVideoTracks()[0]}catch(e){throw i.onError(e),e}if(!c||!d){let e=new du(o.UNEXPECTED_ERROR,"can not find tracks in media stream");return i.onError(e),e.throw()}t.optimizationMode&&S$(a,d,t,dN(t.encoderConfig));let l=new hp(c,e,n,s),u=new mR(d,t,r,t.scalabiltyMode?dD(t.scalabiltyMode):{numSpatialL
1ayers:1,numTemporalLayers:1},t.optimizationMode,a);return i.onSuccess([l.getTrackId(),u.getTrackId()]),dg.info("create camera video track(".concat(a,") and microphone audio track(").concat(s,") success")),[l,u]},createMicrophoneAudioTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=uC.reportApiInvoke(null,{tag:_.TRACER,name:p.CREATE_MIC_AUDIO_TRACK,options:[e]}),i=_e(e),r=hV(8,"track-mic-"),n=null;dg.info("start create microphone audio track with config",JSON.stringify(e),"trackId",r);try{n=(await uz({audio:i},r)).getAudioTracks()[0]||null}catch(e){throw t.onError(e),e}if(!n){let e=new du(o.UNEXPECTED_ERROR,"can not find track in media stream");return t.onError(e),e.throw()}let s=new hp(n,e,i,r);return t.onSuccess(s.getTrackId()),dg.info("create microphone audio track success, trackId:",r),s},createCustomAudioTrack:function(e){let t=uC.reportApiInvoke(null,{tag:_.TRACER,name:p.CREATE_CUSTOM_AUDIO_TRACK,options:[e]}),i=new hh(e.mediaStreamTrack,e.encoderConfig?dL(e.encoderConfig):{},hV(8,"track-cus-"),!1,!0);return dg.info("create custom audio track success with config",e,"trackId",i.getTrackId()),t.onSuccess(i.getTrackId()),i},createBufferSourceAudioTrack:async function(e){let t=uC.reportApiInvoke(null,{tag:_.TRACER,name:p.CREATE_BUFFER_AUDIO_TRACK,options:[e]});if(dM.DISABLE_WEBAUDIO)throw new du(o.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");let i=hV(8,"track-buf-");dg.info("start create buffer source audio track with config",JSON.stringify(e),"trackId",i);let r=e.source;if(!(e.source instanceof AudioBuffer))try{e.source=await Sz(e.source,e.cacheOnlineFile)}catch(e){return t.onError(e),e.throw()}let n=new h_(r,new SJ(e.source),e.encoderConfig?dL(e.encoderConfig):{},i);return dg.info("create buffer source audio track success, trackId:",i),t.onSuccess(n.getTrackId()),n},setAppType:function(e){if(dg.debug("setAppType: ".concat(e)),!(Number.isInteger(e)&&e>=0))throw dg.debug("Invalid appType"),new du(o.INVALID_PARAMS,"invalid app type",e);dk("APP_TYPE",Math.floor(e))},setLogLevel:function(e){dg.setLogLevel(e)},enableLogUpload:function(){dM.USE_NEW_LOG?dk("UPLOAD_LOG",!0):dg.enableLogUpload()},disableLogUpload:function(){dM.USE_NEW_LOG?dk("UPLOAD_LOG",!1):dg.disableLogUpload()},createChannelMediaRelayConfiguration:function(){return new pZ},checkAudioTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3,i=uC.reportApiInvoke(null,{tag:_.TRACER,name:p.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof hh||e instanceof f8)){let e=new du(o.INVALID_TRACK,"the parameter is not a audio track");return i.onError(e),e.throw()}t&&t<1e3&&(t=1e3);
1let r=e instanceof hh?e.getTrackLabel():"remote_track",n=e.getVolumeLevel(),s=n,a=n,c=Date.now();return new sG(n=>{let o=setInterval(()=>{let d=e.getVolumeLevel(),l=(s=d>s?d:s)-(a=d<a?d:a)>1e-4,u=Date.now()-c;if(l||u>t){clearInterval(o);let t={duration:u,deviceLabel:r,maxVolumeLevel:s,result:l};dg.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 i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3,r=uC.reportApiInvoke(null,{tag:_.TRACER,name:p.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[i]});if(!(e instanceof mg||e instanceof f6)){let e=new du(o.INVALID_TRACK,"the parameter is not a video track");return r.onError(e),e.throw()}i&&i<1e3&&(i=1e3);let n=e instanceof mg?e.getTrackLabel():"remote_track",s=e.getMediaStreamTrack(!0),a=document.createElement("video");a.style.width="1px",a.style.height="1px",a.setAttribute("muted",""),a.muted=!0,a.setAttribute("playsinline",""),a.controls=!1,(aX()||aq())&&(a.style.opacity="0.01",a.style.position="fixed",a.style.left="0",a.style.top="0",document.body.appendChild(a)),a.srcObject=new MediaStream([s]),a.play();let c=document.createElement("canvas");c.width=160,c.height=120;let d=0,l=0;try{var u;let e,t,r,n=Date.now();d=await (u=i,t=0,r=null,new sG((i,n)=>{setTimeout(()=>{e&&(e(),i(t))},u),e=ux(()=>{!function(){t>4&&e&&(e(),i(t));let s=c.getContext("2d");if(!s){let e=new du(o.UNEXPECTED_ERROR,"can not get canvas 2d context.");return dg.error(e.toString()),n(e)}s.drawImage(a,0,0,160,120);let d=s.getImageData(0,0,c.width,c.height),l=Math.floor(d.data.length/3);if(r){for(let e=0;e<l;e+=3)if(d.data[e]!==r[e])return t+=1,void(r=d.data);r=d.data}else r=d.data}()},30)})),l=Date.now()-n}catch(e){throw r.onError(e),e}S0===t.SAFARI&&(a.pause(),a.remove()),a.srcObject=null;let h=d>4,E={duration:l,changedPicNum:d,deviceLabel:n,result:h};return dg.info("[track-".concat(e.getTrackId(),"] check video track active completed. ").concat(JSON.stringify(E))),r.onSuccess(E),h},setArea:pI,audioElementPlayCenter:u2,processExternalMediaAEC:function(e){S3.processExternalMediaAEC(e)},registerExtensions:function(e){e.forEach(e=>{e.__registered__=!0,e.logger.hookLog=dg.extLog,e.reporter.hookApiInvoke=uC.extApiInvoke,e.parameters&&Object.keys(e.parameters).forEach(t=>{e.parameters[t]=dM[t]})})},ChannelMediaRelayError:W,ChannelMediaRelayEvent:B,ChannelMediaRelayState:G,RemoteStreamFallbackType:Q,RemoteStreamType:z,ConnectionDisconnectedReason:C,AudienceLatencyLevelType:I,AREAS:ee},S5=window||document;return Object.defineProperties(S4,{onAudioAutoplayFailed:{get:()=>uE.onAudioAutoplayFailed,set:e=>{uE.onAudioAutoplayFailed=e}},onAutoplayFailed:{get:()=>uE.onAutoplayFailed,set:e=>{uE.onAutoplayFailed=e}},_onSecurityPolicyViolation:{value:void 0,writable:!0},_cspEventHandlerPointer:{value:void 0,writable:!0},onSecurityPolicyViolation:{get:()=>S4._onSecurityPolicyViolation,set(e){if(S4._onSecurityPolicyViolation=e,!S5)return;let t=e=>{if(!(e&&e.blockedURI&&S4.onSecurityPolicyViolation))return;let t=e.blockedURI;dM.CSP_DETECTED_HOSTNAME_LIST.some(e=>t.includes(e))&&S4.onSecurityPolicyViolation&&"function"==typeof S4.onSecurityPolicyViolation&&S4.onSecurityPolicyViolation(e)},i=S4._cspEventHandlerPointer;i&&S5.removeEventListener("securitypolicyviolation",i),e&&"function"==typeof e&&S5.addEventListener("securitypolicyviolation",t),S4._cspEventHandlerPointer=t}}}),u0.on(m.CAMERA_DEVICE_CHANGED,e=>{dg.info("camera device changed",JSON.stringify(e)),S4.onCameraChanged&&S4.onCameraChanged(e)}),u0.on(m.RECORDING_DEVICE_CHANGED,e=>{dg.info("microphone device changed",JSON.stringify(e)),S4.onMicrophoneChanged&&S4.onMicrophoneChanged(e)}),u0.on(m.PLAYOUT_DEVICE_CHANGED,e=>{dg.debug("playout device changed",JSON.stringify(e)),S4.onPlaybackDeviceChanged&&S4.onPlaybackDeviceChanged(e)}),u2.onAutoplayFailed=()=>{dg.info("detect audio element autoplay failed"),uE.onAudioAutoplayFailed&&uE.onAudioAutoplayFailed()},uL.on("autoplay-failed",()=>{dg.info("detect webaudio autoplay failed"),uE.onAudioAutoplayFailed&&uE.onAudioAutoplayFailed()}),window&&(window.__ARTC__=S4),S4}()}}]);

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.