mirror of
https://github.com/kuaifan/dootask.git
synced 2026-01-26 04:18:29 +00:00
7 lines
858 KiB
JavaScript
Vendored
7 lines
858 KiB
JavaScript
Vendored
/**
|
||
* AgoraWebSDK_N-v4.17.0-0-gf6ae6c87-dirty Copyright AgoraInc.
|
||
*/
|
||
|
||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).AgoraRTC=t()}(this,(function(){"use strict";function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}))})),Object.freeze(e)}var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},i=function(e){try{return!!e()}catch(e){return!0}},n=!i((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),r=n,o=Function.prototype,s=o.bind,a=o.call,c=r&&s.bind(a,a),d=r?function(e){return e&&c(e)}:function(e){return e&&function(){return a.apply(e,arguments)}},u=d({}.isPrototypeOf),l=function(e){return e&&e.Math==Math&&e},h=l("object"==typeof globalThis&&globalThis)||l("object"==typeof window&&window)||l("object"==typeof self&&self)||l("object"==typeof t&&t)||function(){return this}()||Function("return this")(),p=n,_=Function.prototype,E=_.apply,m=_.call,f="object"==typeof Reflect&&Reflect.apply||(p?m.bind(E):function(){return m.apply(E,arguments)}),S=function(e){return"function"==typeof e},T={},g=!i((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),R=n,I=Function.prototype.call,v=R?I.bind(I):function(){return I.apply(I,arguments)},C={},y={}.propertyIsEnumerable,A=Object.getOwnPropertyDescriptor,O=A&&!y.call({1:2},1);C.f=O?function(e){var t=A(this,e);return!!t&&t.enumerable}:y;var b,w,N=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},D=d,P=D({}.toString),L=D("".slice),k=function(e){return L(P(e),8,-1)},M=d,U=i,x=k,V=h.Object,F=M("".split),j=U((function(){return!V("z").propertyIsEnumerable(0)}))?function(e){return"String"==x(e)?F(e,""):V(e)}:V,B=h.TypeError,G=function(e){if(null==e)throw B("Can't call method on "+e);return e},W=j,H=G,K=function(e){return W(H(e))},Y=S,q=function(e){return"object"==typeof e?null!==e:Y(e)},J={},X=J,z=h,Q=S,Z=function(e){return Q(e)?e:void 0},$=function(e,t){return arguments.length<2?Z(X[e])||Z(z[e]):X[e]&&X[e][t]||z[e]&&z[e][t]},ee=$("navigator","userAgent")||"",te=h,ie=ee,ne=te.process,re=te.Deno,oe=ne&&ne.versions||re&&re.version,se=oe&&oe.v8;se&&(w=(b=se.split("."))[0]>0&&b[0]<4?1:+(b[0]+b[1])),!w&&ie&&(!(b=ie.match(/Edge\/(\d+)/))||b[1]>=74)&&(b=ie.match(/Chrome\/(\d+)/))&&(w=+b[1]);var ae=w,ce=ae,de=i,ue=!!Object.getOwnPropertySymbols&&!de((function(){var e=Symbol();return!String(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&ce&&ce<41})),le=ue&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,he=$,pe=S,_e=u,Ee=le,me=h.Object,fe=Ee?function(e){return"symbol"==typeof e}:function(e){var t=he("Symbol");return pe(t)&&_e(t.prototype,me(e))},Se=h.String,Te=function(e){try{return Se(e)}catch(e){return"Object"}},ge=S,Re=Te,Ie=h.TypeError,ve=function(e){if(ge(e))return e;throw Ie(Re(e)+" is not a function")},Ce=ve,ye=function(e,t){var i=e[t];return null==i?void 0:Ce(i)},Ae=v,Oe=S,be=q,we=h.TypeError,Ne={exports:{}},De=h,Pe=Object.defineProperty,Le=function(e,t){try{Pe(De,e,{value:t,configurable:!0,writable:!0})}catch(i){De[e]=t}return t},ke="__core-js_shared__",Me=h[ke]||Le(ke,{}),Ue=Me;(Ne.exports=function(e,t){return Ue[e]||(Ue[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.20.3",mode:"pure",copyright:"© 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 xe=G,Ve=h.Object,Fe=function(e){return Ve(xe(e))},je=Fe,Be=d({}.hasOwnProperty),Ge=Object.hasOwn||function(e,t){return Be(je(e),t)},We=d,He=0,Ke=Math.random(),Ye=We(1..toString),qe=function(e){return"Symbol("+(void 0===e?"":e)+")_"+Ye(++He+Ke,36)},Je=h,Xe=Ne.exports,ze=Ge,Qe=qe,Ze=ue,$e=le,et=Xe("wks"),tt=Je.Symbol,it=tt&&tt.for,nt=$e?tt:tt&&tt.withoutSetter||Qe,rt=function(e){if(!ze(et,e)||!Ze&&"string"!=typeof et[e]){var t="Symbol."+e;Ze&&ze(tt,e)?et[e]=tt[e]:et[e]=$e&&it?it(t):nt(t)}return et[e]},ot=v,st=q,at=fe,ct=ye,dt=function(e,t){var i,n;if("string"===t&&Oe(i=e.toString)&&!be(n=Ae(i,e)))return n;if(Oe(i=e.valueOf)&&!be(n=Ae(i,e)))return n;if("string"!==t&&Oe(i=e.toString)&&!be(n=Ae(i,e)))return n;throw we("Can't convert object to primitive value")},ut=rt,lt=h.TypeError,ht=ut("toPrimitive"),pt=function(e,t){if(!st(e)||at(e))return e;var i,n=ct(e,ht);if(n){if(void 0===t&&(t="default"),i=ot(n,e,t),!st(i)||at(i))return i;throw lt("Can't convert object to primitive value")}return void 0===t&&(t="number"),dt(e,t)},_t=fe,Et=function(e){var t=pt(e,"string");return _t(t)?t:t+""},mt=q,ft=h.document,St=mt(ft)&&mt(ft.createElement),Tt=function(e){return St?ft.createElement(e):{}},gt=Tt,Rt=!g&&!i((function(){return 7!=Object.defineProperty(gt("div"),"a",{get:function(){return 7}}).a})),It=g,vt=v,Ct=C,yt=N,At=K,Ot=Et,bt=Ge,wt=Rt,Nt=Object.getOwnPropertyDescriptor;T.f=It?Nt:function(e,t){if(e=At(e),t=Ot(t),wt)try{return Nt(e,t)}catch(e){}if(bt(e,t))return yt(!vt(Ct.f,e,t),e[t])};var Dt=i,Pt=S,Lt=/#|\.prototype\./,kt=function(e,t){var i=Ut[Mt(e)];return i==Vt||i!=xt&&(Pt(t)?Dt(t):!!t)},Mt=kt.normalize=function(e){return String(e).replace(Lt,".").toLowerCase()},Ut=kt.data={},xt=kt.NATIVE="N",Vt=kt.POLYFILL="P",Ft=kt,jt=ve,Bt=n,Gt=d(d.bind),Wt=function(e,t){return jt(e),void 0===t?e:Bt?Gt(e,t):function(){return e.apply(t,arguments)}},Ht={},Kt=g&&i((function(){return 42!=Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),Yt=h,qt=q,Jt=Yt.String,Xt=Yt.TypeError,zt=function(e){if(qt(e))return e;throw Xt(Jt(e)+" is not an object")},Qt=g,Zt=Rt,$t=Kt,ei=zt,ti=Et,ii=h.TypeError,ni=Object.defineProperty,ri=Object.getOwnPropertyDescriptor,oi="enumerable",si="configurable",ai="writable";Ht.f=Qt?$t?function(e,t,i){if(ei(e),t=ti(t),ei(i),"function"==typeof e&&"prototype"===t&&"value"in i&&ai in i&&!i.writable){var n=ri(e,t);n&&n.writable&&(e[t]=i.value,i={configurable:si in i?i.configurable:n.configurable,enumerable:oi in i?i.enumerable:n.enumerable,writable:!1})}return ni(e,t,i)}:ni:function(e,t,i){if(ei(e),t=ti(t),ei(i),Zt)try{return ni(e,t,i)}catch(e){}if("get"in i||"set"in i)throw ii("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var ci=Ht,di=N,ui=g?function(e,t,i){return ci.f(e,t,di(1,i))}:function(e,t,i){return e[t]=i,e},li=h,hi=f,pi=d,_i=S,Ei=T.f,mi=Ft,fi=J,Si=Wt,Ti=ui,gi=Ge,Ri=function(e){var t=function(i,n,r){if(this instanceof t){switch(arguments.length){case 0:return new e;case 1:return new e(i);case 2:return new e(i,n)}return new e(i,n,r)}return hi(e,this,arguments)};return t.prototype=e.prototype,t},Ii=function(e,t){var i,n,r,o,s,a,c,d,u=e.target,l=e.global,h=e.stat,p=e.proto,_=l?li:h?li[u]:(li[u]||{}).prototype,E=l?fi:fi[u]||Ti(fi,u,{})[u],m=E.prototype;for(r in t)i=!mi(l?r:u+(h?".":"#")+r,e.forced)&&_&&gi(_,r),s=E[r],i&&(a=e.noTargetGet?(d=Ei(_,r))&&d.value:_[r]),o=i&&a?a:t[r],i&&typeof s==typeof o||(c=e.bind&&i?Si(o,li):e.wrap&&i?Ri(o):p&&_i(o)?pi(o):o,(e.sham||o&&o.sham||s&&s.sham)&&Ti(c,"sham",!0),Ti(E,r,c),p&&(gi(fi,n=u+"Prototype")||Ti(fi,n,{}),Ti(fi[n],r,o),e.real&&m&&!m[r]&&Ti(m,r,o)))},vi=Math.ceil,Ci=Math.floor,yi=function(e){var t=+e;return t!=t||0===t?0:(t>0?Ci:vi)(t)},Ai=yi,Oi=Math.min,bi=function(e){return e>0?Oi(Ai(e),9007199254740991):0},wi=function(e){return bi(e.length)},Ni=ve,Di=Fe,Pi=j,Li=wi,ki=h.TypeError,Mi=function(e){return function(t,i,n,r){Ni(i);var o=Di(t),s=Pi(o),a=Li(o),c=e?a-1:0,d=e?-1:1;if(n<2)for(;;){if(c in s){r=s[c],c+=d;break}if(c+=d,e?c<0:a<=c)throw ki("Reduce of empty array with no initial value")}for(;e?c>=0:a>c;c+=d)c in s&&(r=i(r,s[c],c,o));return r}},Ui={left:Mi(!1),right:Mi(!0)},xi=i,Vi=function(e,t){var i=[][e];return!!i&&xi((function(){i.call(null,t||function(){throw 1},1)}))},Fi="process"==k(h.process),ji=Ui.left,Bi=ae,Gi=Fi;Ii({target:"Array",proto:!0,forced:!Vi("reduce")||!Gi&&Bi>79&&Bi<83},{reduce:function(e){var t=arguments.length;return ji(this,e,t,t>1?arguments[1]:void 0)}});var Wi=J,Hi=function(e){return Wi[e+"Prototype"]},Ki=Hi("Array").reduce,Yi=u,qi=Ki,Ji=Array.prototype,Xi=function(e){var t=e.reduce;return e===Ji||Yi(Ji,e)&&t===Ji.reduce?qi:t},zi=Xi;let Qi=!0,Zi=!0;function $i(e,t,i){const n=e.match(t);return n&&n.length>=i&&parseInt(n[i],10)}function en(e,t,i){if(!e.RTCPeerConnection)return;const n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);const o=e=>{const t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,o),r.apply(this,[e,o])};const o=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(i))return o.apply(this,arguments);const n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function tn(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Qi=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function nn(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Zi=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function rn(){if("object"==typeof window){if(Qi)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function on(e,t){Zi&&console.warn(e+" is deprecated, please use "+t+" instead.")}function sn(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:i}=e;if(i.mozGetUserMedia)t.browser="firefox",t.version=$i(i.userAgent,/Firefox\/(\d+)\./,1);else if(i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=$i(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=$i(i.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}function an(e){return"[object Object]"===Object.prototype.toString.call(e)}function cn(e){var t;return an(e)?zi(t=Object.keys(e)).call(t,(function(t,i){const n=an(e[i]),r=n?cn(e[i]):e[i],o=n&&!Object.keys(r).length;return void 0===r||o?t:Object.assign(t,{[i]:r})}),{}):e}function dn(e,t,i){const n=i?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;const o=[];return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)}),o.forEach(t=>{e.forEach(i=>{i.type===n&&i.trackId===t.id&&function e(t,i,n){i&&!n.has(i.id)&&(n.set(i.id,i),Object.keys(i).forEach(r=>{r.endsWith("Id")?e(t,t.get(i[r]),n):r.endsWith("Ids")&&i[r].forEach(i=>{e(t,t.get(i),n)})}))}(e,i,r)})}),r}var un=Ne.exports,ln=qe,hn=un("keys"),pn=function(e){return hn[e]||(hn[e]=ln(e))},_n=!i((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),En=h,mn=Ge,fn=S,Sn=Fe,Tn=_n,gn=pn("IE_PROTO"),Rn=En.Object,In=Rn.prototype,vn=Tn?Rn.getPrototypeOf:function(e){var t=Sn(e);if(mn(t,gn))return t[gn];var i=t.constructor;return fn(i)&&t instanceof i?i.prototype:t instanceof Rn?In:null},Cn=h,yn=S,An=Cn.String,On=Cn.TypeError,bn=d,wn=zt,Nn=function(e){if("object"==typeof e||yn(e))return e;throw On("Can't set "+An(e)+" as a prototype")},Dn=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=bn(Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set))(i,[]),t=i instanceof Array}catch(e){}return function(i,n){return wn(i),Nn(n),t?e(i,n):i.__proto__=n,i}}():void 0),Pn={},Ln=yi,kn=Math.max,Mn=Math.min,Un=function(e,t){var i=Ln(e);return i<0?kn(i+t,0):Mn(i,t)},xn=K,Vn=Un,Fn=wi,jn=function(e){return function(t,i,n){var r,o=xn(t),s=Fn(o),a=Vn(n,s);if(e&&i!=i){for(;s>a;)if((r=o[a++])!=r)return!0}else for(;s>a;a++)if((e||a in o)&&o[a]===i)return e||a||0;return!e&&-1}},Bn={includes:jn(!0),indexOf:jn(!1)},Gn={},Wn=Ge,Hn=K,Kn=Bn.indexOf,Yn=Gn,qn=d([].push),Jn=function(e,t){var i,n=Hn(e),r=0,o=[];for(i in n)!Wn(Yn,i)&&Wn(n,i)&&qn(o,i);for(;t.length>r;)Wn(n,i=t[r++])&&(~Kn(o,i)||qn(o,i));return o},Xn=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],zn=Jn,Qn=Xn.concat("length","prototype");Pn.f=Object.getOwnPropertyNames||function(e){return zn(e,Qn)};var Zn={};Zn.f=Object.getOwnPropertySymbols;var $n=$,er=Pn,tr=Zn,ir=zt,nr=d([].concat),rr=$n("Reflect","ownKeys")||function(e){var t=er.f(ir(e)),i=tr.f;return i?nr(t,i(e)):t},or=Ge,sr=rr,ar=T,cr=Ht,dr={},ur=Jn,lr=Xn,hr=Object.keys||function(e){return ur(e,lr)},pr=g,_r=Kt,Er=Ht,mr=zt,fr=K,Sr=hr;dr.f=pr&&!_r?Object.defineProperties:function(e,t){mr(e);for(var i,n=fr(t),r=Sr(t),o=r.length,s=0;o>s;)Er.f(e,i=r[s++],n[i]);return e};var Tr,gr=$("document","documentElement"),Rr=zt,Ir=dr,vr=Xn,Cr=Gn,yr=gr,Ar=Tt,Or=pn("IE_PROTO"),br=function(){},wr=function(e){return"<script>"+e+"</"+"script>"},Nr=function(e){e.write(wr("")),e.close();var t=e.parentWindow.Object;return e=null,t},Dr=function(){try{Tr=new ActiveXObject("htmlfile")}catch(e){}var e,t;Dr="undefined"!=typeof document?document.domain&&Tr?Nr(Tr):((t=Ar("iframe")).style.display="none",yr.appendChild(t),t.src=String("javascript:"),(e=t.contentWindow.document).open(),e.write(wr("document.F=Object")),e.close(),e.F):Nr(Tr);for(var i=vr.length;i--;)delete Dr.prototype[vr[i]];return Dr()};Cr[Or]=!0;var Pr=Object.create||function(e,t){var i;return null!==e?(br.prototype=Rr(e),i=new br,br.prototype=null,i[Or]=e):i=Dr(),void 0===t?i:Ir.f(i,t)},Lr=d("".replace),kr=String(Error("zxcasd").stack),Mr=/\n\s*at [^:]*:[^\n]*/,Ur=Mr.test(kr),xr=q,Vr=ui,Fr={},jr=Fr,Br=rt("iterator"),Gr=Array.prototype,Wr={};Wr[rt("toStringTag")]="z";var Hr="[object z]"===String(Wr),Kr=h,Yr=Hr,qr=S,Jr=k,Xr=rt("toStringTag"),zr=Kr.Object,Qr="Arguments"==Jr(function(){return arguments}()),Zr=Yr?Jr:function(e){var t,i,n;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,t){try{return e[t]}catch(e){}}(t=zr(e),Xr))?i:Qr?Jr(t):"Object"==(n=Jr(t))&&qr(t.callee)?"Arguments":n},$r=Zr,eo=ye,to=Fr,io=rt("iterator"),no=function(e){if(null!=e)return eo(e,io)||eo(e,"@@iterator")||to[$r(e)]},ro=v,oo=ve,so=zt,ao=Te,co=no,uo=h.TypeError,lo=v,ho=zt,po=ye,_o=Wt,Eo=v,mo=zt,fo=Te,So=function(e){return void 0!==e&&(jr.Array===e||Gr[Br]===e)},To=wi,go=u,Ro=function(e,t){var i=arguments.length<2?co(e):t;if(oo(i))return so(ro(i,e));throw uo(ao(e)+" is not iterable")},Io=no,vo=function(e,t,i){var n,r;ho(e);try{if(!(n=po(e,"return"))){if("throw"===t)throw i;return i}n=lo(n,e)}catch(e){r=!0,n=e}if("throw"===t)throw i;if(r)throw n;return ho(n),i},Co=h.TypeError,yo=function(e,t){this.stopped=e,this.result=t},Ao=yo.prototype,Oo=function(e,t,i){var n,r,o,s,a,c,d,u=i&&i.that,l=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_ITERATOR),p=!(!i||!i.INTERRUPTED),_=_o(t,u),E=function(e){return n&&vo(n,"normal",e),new yo(!0,e)},m=function(e){return l?(mo(e),p?_(e[0],e[1],E):_(e[0],e[1])):p?_(e,E):_(e)};if(h)n=e;else{if(!(r=Io(e)))throw Co(fo(e)+" is not iterable");if(So(r)){for(o=0,s=To(e);s>o;o++)if((a=m(e[o]))&&go(Ao,a))return a;return new yo(!1)}n=Ro(e,r)}for(c=n.next;!(d=Eo(c,n)).done;){try{a=m(d.value)}catch(e){vo(n,"throw",e)}if("object"==typeof a&&a&&go(Ao,a))return a}return new yo(!1)},bo=Zr,wo=h.String,No=function(e){if("Symbol"===bo(e))throw TypeError("Cannot convert a Symbol value to a string");return wo(e)},Do=No,Po=N,Lo=!i((function(){var e=Error("a");return!("stack"in e)||(Object.defineProperty(e,"stack",Po(1,7)),7!==e.stack)})),ko=Ii,Mo=h,Uo=u,xo=vn,Vo=Dn,Fo=function(e,t,i){for(var n=sr(t),r=cr.f,o=ar.f,s=0;s<n.length;s++){var a=n[s];or(e,a)||i&&or(i,a)||r(e,a,o(t,a))}},jo=Pr,Bo=ui,Go=N,Wo=function(e,t){if(Ur&&"string"==typeof e)for(;t--;)e=Lr(e,Mr,"");return e},Ho=function(e,t){xr(t)&&"cause"in t&&Vr(e,"cause",t.cause)},Ko=Oo,Yo=function(e,t){return void 0===e?arguments.length<2?"":t:Do(e)},qo=Lo,Jo=rt("toStringTag"),Xo=Mo.Error,zo=[].push,Qo=function(e,t){var i,n=arguments.length>2?arguments[2]:void 0,r=Uo(Zo,this);Vo?i=Vo(new Xo,r?xo(this):Zo):(i=r?this:jo(Zo),Bo(i,Jo,"Error")),void 0!==t&&Bo(i,"message",Yo(t)),qo&&Bo(i,"stack",Wo(i.stack,1)),Ho(i,n);var o=[];return Ko(e,zo,{that:o}),Bo(i,"errors",o),i};Vo?Vo(Qo,Xo):Fo(Qo,Xo,{name:!0});var Zo=Qo.prototype=jo(Xo.prototype,{constructor:Go(1,Qo),message:Go(1,""),name:Go(1,"AggregateError")});ko({global:!0},{AggregateError:Qo});var $o=S,es=Me,ts=d(Function.toString);$o(es.inspectSource)||(es.inspectSource=function(e){return ts(e)});var is,ns,rs,os=es.inspectSource,ss=S,as=os,cs=h.WeakMap,ds=ss(cs)&&/native code/.test(as(cs)),us=h,ls=d,hs=q,ps=ui,_s=Ge,Es=Me,ms=pn,fs=Gn,Ss="Object already initialized",Ts=us.TypeError,gs=us.WeakMap;if(ds||Es.state){var Rs=Es.state||(Es.state=new gs),Is=ls(Rs.get),vs=ls(Rs.has),Cs=ls(Rs.set);is=function(e,t){if(vs(Rs,e))throw new Ts(Ss);return t.facade=e,Cs(Rs,e,t),t},ns=function(e){return Is(Rs,e)||{}},rs=function(e){return vs(Rs,e)}}else{var ys=ms("state");fs[ys]=!0,is=function(e,t){if(_s(e,ys))throw new Ts(Ss);return t.facade=e,ps(e,ys,t),t},ns=function(e){return _s(e,ys)?e[ys]:{}},rs=function(e){return _s(e,ys)}}var As,Os,bs,ws={set:is,get:ns,has:rs,enforce:function(e){return rs(e)?ns(e):is(e,{})},getterFor:function(e){return function(t){var i;if(!hs(t)||(i=ns(t)).type!==e)throw Ts("Incompatible receiver, "+e+" required");return i}}},Ns=g,Ds=Ge,Ps=Function.prototype,Ls=Ns&&Object.getOwnPropertyDescriptor,ks=Ds(Ps,"name"),Ms={EXISTS:ks,PROPER:ks&&"something"===function(){}.name,CONFIGURABLE:ks&&(!Ns||Ns&&Ls(Ps,"name").configurable)},Us=ui,xs=function(e,t,i,n){n&&n.enumerable?e[t]=i:Us(e,t,i)},Vs=i,Fs=S,js=Pr,Bs=vn,Gs=xs,Ws=rt("iterator"),Hs=!1;[].keys&&("next"in(bs=[].keys())?(Os=Bs(Bs(bs)))!==Object.prototype&&(As=Os):Hs=!0);var Ks=null==As||Vs((function(){var e={};return As[Ws].call(e)!==e}));Fs((As=Ks?{}:js(As))[Ws])||Gs(As,Ws,(function(){return this}));var Ys={IteratorPrototype:As,BUGGY_SAFARI_ITERATORS:Hs},qs=Zr,Js=Hr?{}.toString:function(){return"[object "+qs(this)+"]"},Xs=Hr,zs=Ht.f,Qs=ui,Zs=Ge,$s=Js,ea=rt("toStringTag"),ta=function(e,t,i,n){if(e){var r=i?e:e.prototype;Zs(r,ea)||zs(r,ea,{configurable:!0,value:t}),n&&!Xs&&Qs(r,"toString",$s)}},ia=Ys.IteratorPrototype,na=Pr,ra=N,oa=ta,sa=Fr,aa=function(){return this},ca=Ii,da=v,ua=function(e,t,i,n){var r=t+" Iterator";return e.prototype=na(ia,{next:ra(+!n,i)}),oa(e,r,!1,!0),sa[r]=aa,e},la=vn,ha=ta,pa=xs,_a=Fr,Ea=Ms.PROPER,ma=Ys.BUGGY_SAFARI_ITERATORS,fa=rt("iterator"),Sa="keys",Ta="values",ga="entries",Ra=function(){return this},Ia=function(e,t,i,n,r,o,s){ua(i,t,n);var a,c,d,u=function(e){if(e===r&&E)return E;if(!ma&&e in p)return p[e];switch(e){case Sa:case Ta:case ga:return function(){return new i(this,e)}}return function(){return new i(this)}},l=t+" Iterator",h=!1,p=e.prototype,_=p[fa]||p["@@iterator"]||r&&p[r],E=!ma&&_||u(r),m="Array"==t&&p.entries||_;if(m&&(a=la(m.call(new e)))!==Object.prototype&&a.next&&(ha(a,l,!0,!0),_a[l]=Ra),Ea&&r==Ta&&_&&_.name!==Ta&&(h=!0,E=function(){return da(_,this)}),r)if(c={values:u(Ta),keys:o?E:u(Sa),entries:u(ga)},s)for(d in c)(ma||h||!(d in p))&&pa(p,d,c[d]);else ca({target:t,proto:!0,forced:ma||h},c);return s&&p[fa]!==E&&pa(p,fa,E,{name:r}),_a[t]=E,c},va=K,Ca=Fr,ya=ws;Ht.f;var Aa=Ia,Oa="Array Iterator",ba=ya.set,wa=ya.getterFor(Oa);Aa(Array,"Array",(function(e,t){ba(this,{type:Oa,target:va(e),index:0,kind:t})}),(function(){var e=wa(this),t=e.target,i=e.kind,n=e.index++;return!t||n>=t.length?(e.target=void 0,{value:void 0,done:!0}):"keys"==i?{value:n,done:!1}:"values"==i?{value:t[n],done:!1}:{value:[n,t[n]],done:!1}}),"values"),Ca.Arguments=Ca.Array;var Na=h.Promise,Da=xs,Pa=$,La=Ht,ka=g,Ma=rt("species"),Ua=u,xa=h.TypeError,Va=rt("iterator"),Fa=!1;try{var ja=0,Ba={next:function(){return{done:!!ja++}},return:function(){Fa=!0}};Ba[Va]=function(){return this},Array.from(Ba,(function(){throw 2}))}catch(e){}var Ga=d,Wa=i,Ha=S,Ka=Zr,Ya=os,qa=function(){},Ja=[],Xa=$("Reflect","construct"),za=/^\s*(?:class|function)\b/,Qa=Ga(za.exec),Za=!za.exec(qa),$a=function(e){if(!Ha(e))return!1;try{return Xa(qa,Ja,e),!0}catch(e){return!1}},ec=function(e){if(!Ha(e))return!1;switch(Ka(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Za||!!Qa(za,Ya(e))}catch(e){return!0}};ec.sham=!0;var tc,ic,nc,rc,oc=!Xa||Wa((function(){var e;return $a($a.call)||!$a(Object)||!$a((function(){e=!0}))||e}))?ec:$a,sc=oc,ac=Te,cc=h.TypeError,dc=zt,uc=function(e){if(sc(e))return e;throw cc(ac(e)+" is not a constructor")},lc=rt("species"),hc=function(e,t){var i,n=dc(e).constructor;return void 0===n||null==(i=dc(n)[lc])?t:uc(i)},pc=d([].slice),_c=/(?:ipad|iphone|ipod).*applewebkit/i.test(ee),Ec=h,mc=f,fc=Wt,Sc=S,Tc=Ge,gc=i,Rc=gr,Ic=pc,vc=Tt,Cc=_c,yc=Fi,Ac=Ec.setImmediate,Oc=Ec.clearImmediate,bc=Ec.process,wc=Ec.Dispatch,Nc=Ec.Function,Dc=Ec.MessageChannel,Pc=Ec.String,Lc=0,kc={},Mc="onreadystatechange";try{tc=Ec.location}catch(e){}var Uc=function(e){if(Tc(kc,e)){var t=kc[e];delete kc[e],t()}},xc=function(e){return function(){Uc(e)}},Vc=function(e){Uc(e.data)},Fc=function(e){Ec.postMessage(Pc(e),tc.protocol+"//"+tc.host)};Ac&&Oc||(Ac=function(e){var t=Ic(arguments,1);return kc[++Lc]=function(){mc(Sc(e)?e:Nc(e),void 0,t)},ic(Lc),Lc},Oc=function(e){delete kc[e]},yc?ic=function(e){bc.nextTick(xc(e))}:wc&&wc.now?ic=function(e){wc.now(xc(e))}:Dc&&!Cc?(rc=(nc=new Dc).port2,nc.port1.onmessage=Vc,ic=fc(rc.postMessage,rc)):Ec.addEventListener&&Sc(Ec.postMessage)&&!Ec.importScripts&&tc&&"file:"!==tc.protocol&&!gc(Fc)?(ic=Fc,Ec.addEventListener("message",Vc,!1)):ic=Mc in vc("script")?function(e){Rc.appendChild(vc("script")).onreadystatechange=function(){Rc.removeChild(this),Uc(e)}}:function(e){setTimeout(xc(e),0)});var jc,Bc,Gc,Wc,Hc,Kc,Yc,qc,Jc={set:Ac,clear:Oc},Xc=h,zc=/ipad|iphone|ipod/i.test(ee)&&void 0!==Xc.Pebble,Qc=/web0s(?!.*chrome)/i.test(ee),Zc=h,$c=Wt,ed=T.f,td=Jc.set,id=_c,nd=zc,rd=Qc,od=Fi,sd=Zc.MutationObserver||Zc.WebKitMutationObserver,ad=Zc.document,cd=Zc.process,dd=Zc.Promise,ud=ed(Zc,"queueMicrotask"),ld=ud&&ud.value;ld||(jc=function(){var e,t;for(od&&(e=cd.domain)&&e.exit();Bc;){t=Bc.fn,Bc=Bc.next;try{t()}catch(e){throw Bc?Wc():Gc=void 0,e}}Gc=void 0,e&&e.enter()},id||od||rd||!sd||!ad?!nd&&dd&&dd.resolve?((Yc=dd.resolve(void 0)).constructor=dd,qc=$c(Yc.then,Yc),Wc=function(){qc(jc)}):od?Wc=function(){cd.nextTick(jc)}:(td=$c(td,Zc),Wc=function(){td(jc)}):(Hc=!0,Kc=ad.createTextNode(""),new sd(jc).observe(Kc,{characterData:!0}),Wc=function(){Kc.data=Hc=!Hc}));var hd=ld||function(e){var t={fn:e,next:void 0};Gc&&(Gc.next=t),Bc||(Bc=t,Wc()),Gc=t},pd={},_d=ve,Ed=function(e){var t,i;this.promise=new e((function(e,n){if(void 0!==t||void 0!==i)throw TypeError("Bad Promise constructor");t=e,i=n})),this.resolve=_d(t),this.reject=_d(i)};pd.f=function(e){return new Ed(e)};var md=zt,fd=q,Sd=pd,Td=function(e,t){if(md(e),fd(t)&&t.constructor===e)return t;var i=Sd.f(e);return(0,i.resolve)(t),i.promise},gd=h,Rd=function(e){try{return{error:!1,value:e()}}catch(e){return{error:!0,value:e}}},Id=function(){this.head=null,this.tail=null};Id.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 vd,Cd,yd,Ad="object"==typeof window,Od=Ii,bd=h,wd=$,Nd=v,Dd=Na,Pd=function(e,t,i){for(var n in t)i&&i.unsafe&&e[n]?e[n]=t[n]:Da(e,n,t[n],i);return e},Ld=ta,kd=function(e){var t=Pa(e),i=La.f;ka&&t&&!t[Ma]&&i(t,Ma,{configurable:!0,get:function(){return this}})},Md=ve,Ud=S,xd=q,Vd=function(e,t){if(Ua(t,e))return e;throw xa("Incorrect invocation")},Fd=os,jd=Oo,Bd=function(e,t){if(!t&&!Fa)return!1;var i=!1;try{var n={};n[Va]=function(){return{next:function(){return{done:i=!0}}}},e(n)}catch(e){}return i},Gd=hc,Wd=Jc.set,Hd=hd,Kd=Td,Yd=function(e,t){var i=gd.console;i&&i.error&&(1==arguments.length?i.error(e):i.error(e,t))},qd=pd,Jd=Rd,Xd=Id,zd=ws,Qd=Ft,Zd=Ad,$d=Fi,eu=ae,tu=rt("species"),iu="Promise",nu=zd.getterFor(iu),ru=zd.set,ou=zd.getterFor(iu),su=Dd&&Dd.prototype,au=Dd,cu=su,du=bd.TypeError,uu=bd.document,lu=bd.process,hu=qd.f,pu=hu,_u=!!(uu&&uu.createEvent&&bd.dispatchEvent),Eu=Ud(bd.PromiseRejectionEvent),mu="unhandledrejection",fu=Qd(iu,(function(){var e=Fd(au),t=e!==String(au);if(!t&&66===eu)return!0;if(!cu.finally)return!0;if(eu>=51&&/native code/.test(e))return!1;var i=new au((function(e){e(1)})),n=function(e){e((function(){}),(function(){}))};return(i.constructor={})[tu]=n,!(i.then((function(){}))instanceof n)||!t&&Zd&&!Eu})),Su=fu||!Bd((function(e){au.all(e).catch((function(){}))})),Tu=function(e){var t;return!(!xd(e)||!Ud(t=e.then))&&t},gu=function(e,t){var i,n,r,o=t.value,s=1==t.state,a=s?e.ok:e.fail,c=e.resolve,d=e.reject,u=e.domain;try{a?(s||(2===t.rejection&&yu(t),t.rejection=1),!0===a?i=o:(u&&u.enter(),i=a(o),u&&(u.exit(),r=!0)),i===e.promise?d(du("Promise-chain cycle")):(n=Tu(i))?Nd(n,i,c,d):c(i)):d(o)}catch(e){u&&!r&&u.exit(),d(e)}},Ru=function(e,t){e.notified||(e.notified=!0,Hd((function(){for(var i,n=e.reactions;i=n.get();)gu(i,e);e.notified=!1,t&&!e.rejection&&vu(e)})))},Iu=function(e,t,i){var n,r;_u?((n=uu.createEvent("Event")).promise=t,n.reason=i,n.initEvent(e,!1,!0),bd.dispatchEvent(n)):n={promise:t,reason:i},!Eu&&(r=bd["on"+e])?r(n):e===mu&&Yd("Unhandled promise rejection",i)},vu=function(e){Nd(Wd,bd,(function(){var t,i=e.facade,n=e.value;if(Cu(e)&&(t=Jd((function(){$d?lu.emit("unhandledRejection",n,i):Iu(mu,i,n)})),e.rejection=$d||Cu(e)?2:1,t.error))throw t.value}))},Cu=function(e){return 1!==e.rejection&&!e.parent},yu=function(e){Nd(Wd,bd,(function(){var t=e.facade;$d?lu.emit("rejectionHandled",t):Iu("rejectionhandled",t,e.value)}))},Au=function(e,t,i){return function(n){e(t,n,i)}},Ou=function(e,t,i){e.done||(e.done=!0,i&&(e=i),e.value=t,e.state=2,Ru(e,!0))},bu=function(e,t,i){if(!e.done){e.done=!0,i&&(e=i);try{if(e.facade===t)throw du("Promise can't be resolved itself");var n=Tu(t);n?Hd((function(){var i={done:!1};try{Nd(n,t,Au(bu,i,e),Au(Ou,i,e))}catch(t){Ou(i,t,e)}})):(e.value=t,e.state=1,Ru(e,!1))}catch(t){Ou({done:!1},t,e)}}};fu&&(cu=(au=function(e){Vd(this,cu),Md(e),Nd(vd,this);var t=nu(this);try{e(Au(bu,t),Au(Ou,t))}catch(e){Ou(t,e)}}).prototype,(vd=function(e){ru(this,{type:iu,done:!1,notified:!1,parent:!1,reactions:new Xd,rejection:!1,state:0,value:void 0})}).prototype=Pd(cu,{then:function(e,t){var i=ou(this),n=hu(Gd(this,au));return i.parent=!0,n.ok=!Ud(e)||e,n.fail=Ud(t)&&t,n.domain=$d?lu.domain:void 0,0==i.state?i.reactions.add(n):Hd((function(){gu(n,i)})),n.promise},catch:function(e){return this.then(void 0,e)}}),Cd=function(){var e=new vd,t=nu(e);this.promise=e,this.resolve=Au(bu,t),this.reject=Au(Ou,t)},qd.f=hu=function(e){return e===au||e===yd?new Cd(e):pu(e)}),Od({global:!0,wrap:!0,forced:fu},{Promise:au}),Ld(au,iu,!1,!0),kd(iu),yd=wd(iu),Od({target:iu,stat:!0,forced:fu},{reject:function(e){var t=hu(this);return Nd(t.reject,void 0,e),t.promise}}),Od({target:iu,stat:!0,forced:true},{resolve:function(e){return Kd(this===yd?au:this,e)}}),Od({target:iu,stat:!0,forced:Su},{all:function(e){var t=this,i=hu(t),n=i.resolve,r=i.reject,o=Jd((function(){var i=Md(t.resolve),o=[],s=0,a=1;jd(e,(function(e){var c=s++,d=!1;a++,Nd(i,t,e).then((function(e){d||(d=!0,o[c]=e,--a||n(o))}),r)})),--a||n(o)}));return o.error&&r(o.value),i.promise},race:function(e){var t=this,i=hu(t),n=i.reject,r=Jd((function(){var r=Md(t.resolve);jd(e,(function(e){Nd(r,t,e).then(i.resolve,n)}))}));return r.error&&n(r.value),i.promise}});var wu=v,Nu=ve,Du=pd,Pu=Rd,Lu=Oo;Ii({target:"Promise",stat:!0},{allSettled:function(e){var t=this,i=Du.f(t),n=i.resolve,r=i.reject,o=Pu((function(){var i=Nu(t.resolve),r=[],o=0,s=1;Lu(e,(function(e){var a=o++,c=!1;s++,wu(i,t,e).then((function(e){c||(c=!0,r[a]={status:"fulfilled",value:e},--s||n(r))}),(function(e){c||(c=!0,r[a]={status:"rejected",reason:e},--s||n(r))}))})),--s||n(r)}));return o.error&&r(o.value),i.promise}});var ku=ve,Mu=$,Uu=v,xu=pd,Vu=Rd,Fu=Oo,ju="No one promise resolved";Ii({target:"Promise",stat:!0},{any:function(e){var t=this,i=Mu("AggregateError"),n=xu.f(t),r=n.resolve,o=n.reject,s=Vu((function(){var n=ku(t.resolve),s=[],a=0,c=1,d=!1;Fu(e,(function(e){var u=a++,l=!1;c++,Uu(n,t,e).then((function(e){l||d||(d=!0,r(e))}),(function(e){l||d||(l=!0,s[u]=e,--c||o(new i(s,ju)))}))})),--c||o(new i(s,ju))}));return s.error&&o(s.value),n.promise}});var Bu=Na,Gu=$,Wu=S,Hu=hc,Ku=Td;Ii({target:"Promise",proto:!0,real:!0,forced:!!Bu&&i((function(){Bu.prototype.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=Hu(this,Gu("Promise")),i=Wu(e);return this.then(i?function(i){return Ku(t,e()).then((function(){return i}))}:e,i?function(i){return Ku(t,e()).then((function(){throw i}))}:e)}});var Yu=d,qu=yi,Ju=No,Xu=G,zu=Yu("".charAt),Qu=Yu("".charCodeAt),Zu=Yu("".slice),$u=function(e){return function(t,i){var n,r,o=Ju(Xu(t)),s=qu(i),a=o.length;return s<0||s>=a?e?"":void 0:(n=Qu(o,s))<55296||n>56319||s+1===a||(r=Qu(o,s+1))<56320||r>57343?e?zu(o,s):n:e?Zu(o,s,s+2):r-56320+(n-55296<<10)+65536}},el={codeAt:$u(!1),charAt:$u(!0)}.charAt,tl=No,il=ws,nl=Ia,rl="String Iterator",ol=il.set,sl=il.getterFor(rl);nl(String,"String",(function(e){ol(this,{type:rl,string:tl(e),index:0})}),(function(){var e,t=sl(this),i=t.string,n=t.index;return n>=i.length?{value:void 0,done:!0}:(e=el(i,n),t.index+=e.length,{value:e,done:!1})}));var al=J.Promise,cl={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},dl=h,ul=Zr,ll=ui,hl=Fr,pl=rt("toStringTag");for(var _l in cl){var El=dl[_l],ml=El&&El.prototype;ml&&ul(ml)!==pl&&ll(ml,pl,_l),hl[_l]=hl.Array}var fl=al,Sl=fl;const Tl=rn;function gl(e,t){const i=e&&e.navigator;if(!i.mediaDevices)return;const n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach(i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;const n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[r("min",i)]=n.ideal,t.optional.push(e),e={},e[r("max",i)]=n.ideal,t.optional.push(e)):(e[r("",i)]=n.ideal,t.optional.push(e))}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach(e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return i.mediaDevices.enumerateDevices().then(i=>{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=n(e.video),Tl("chrome: "+JSON.stringify(e)),r(e)})}e.video=n(e.video)}return Tl("chrome: "+JSON.stringify(e)),r(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(e,t,n){r(e,e=>{i.webkitGetUserMedia(e,t,e=>{n&&n(o(e))})})}.bind(i),i.mediaDevices.getUserMedia){const e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException("","NotFoundError");return e},e=>Sl.reject(o(e))))}}}function Rl(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function Il(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.track.id):{track:i.track};const r=new Event("track");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)}),t.stream.getTracks().forEach(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.id):{track:i};const r=new Event("track");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else en(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function vl(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{const t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Cl(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,i,n]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const r=function(e){const t={};return e.result().forEach(e=>{const i={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach(t=>{i[t]=e.stat(t)}),t[i.id]=i}),t},o=function(e){return new Map(Object.keys(e).map(t=>[t,e[t]]))};if(arguments.length>=2){const n=function(e){i(o(r(e)))};return t.apply(this,[n,e])}return new Sl((e,i)=>{t.apply(this,[function(t){e(o(r(t)))},i])}).then(i,n)}}function yl(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>dn(t,e.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),en(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then(t=>dn(t,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,i,n;return this.getSenders().forEach(i=>{i.track===e&&(t?n=!0:t=i)}),this.getReceivers().forEach(t=>(t.track===e&&(i?n=!0:i=t),t.track===e)),n||t&&i?Sl.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():i?i.getStats():Sl.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function Al(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")});const t=this.getSenders();i.apply(this,arguments);const n=this.getSenders().filter(e=>-1===t.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(n)};const n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{const i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]}),r.apply(this,arguments)}}function Ol(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Al(e);const i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[t.id]){const i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};const r=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(r.id,"g"),n.id)}),new RTCSessionDescription({type:t.type,sdp:i})}function s(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{const n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(new RegExp(n.id,"g"),r.id)}),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find(e=>e===t))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");const r=this.getSenders().find(e=>e.track===t);if(r)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const o=this._streams[i.id];if(o)o.addTrack(t),Sl.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find(e=>e.track===t)},["createOffer","createAnswer"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?i.apply(this,[t=>{const i=o(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then(e=>o(this,e))}};e.RTCPeerConnection.prototype[t]=n[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=s(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=c.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach(i=>{this._streams[i].getTracks().find(t=>e.track===t)&&(t=this._streams[i])}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function bl(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}))}function wl(e,t){en(e,"negotiationneeded",e=>{const i=e.target;if(!(t.version<72||i.getConfiguration&&"plan-b"===i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e})}var Nl=Object.freeze({__proto__:null,shimMediaStream:Rl,shimOnTrack:Il,shimGetSendersWithDtmf:vl,shimGetStats:Cl,shimSenderReceiverGetStats:yl,shimAddTrackRemoveTrackWithNative:Al,shimAddTrackRemoveTrack:Ol,shimPeerConnection:bl,fixNegotiationNeeded:wl,shimGetUserMedia:gl,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(i){return t(i).then(t=>{const n=i.video&&i.video.width,r=i.video&&i.video.height,o=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},n&&(i.video.mandatory.maxWidth=n),r&&(i.video.mandatory.maxHeight=r),e.navigator.mediaDevices.getUserMedia(i)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function Dl(e,t){const i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){on("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(i=JSON.parse(JSON.stringify(i)),e(i.audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){const t=n.prototype.getSettings;n.prototype.getSettings=function(){const i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){const t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(i=JSON.parse(JSON.stringify(i)),e(i,"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function Pl(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ll(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const i=e.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=n[t]}));const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,o]=arguments;return n.apply(this,[e||null]).then(e=>{if(t.version<53&&!r)try{e.forEach(e=>{e.type=i[e.type]||e.type})}catch(t){if("TypeError"!==t.name)throw t;e.forEach((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))})}return e}).then(r,o)}}function kl(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Sl.resolve(new Map)}}function Ml(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),en(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Ul(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){on("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function xl(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Vl(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const i=e.length>0;i&&e.forEach(e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const n=t.apply(this,arguments);if(i){const{sender:t}=n,i=t.getParameters();(!("encodings"in i)||1===i.encodings.length&&0===Object.keys(i.encodings[0]).length)&&(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return n})}function Fl(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function jl(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Sl.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function Bl(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Sl.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var Gl=Object.freeze({__proto__:null,shimOnTrack:Pl,shimPeerConnection:Ll,shimSenderGetStats:kl,shimReceiverGetStats:Ml,shimRemoveStream:Ul,shimRTCDataChannel:xl,shimAddTransceiver:Vl,shimGetParameters:Fl,shimCreateOffer:jl,shimCreateAnswer:Bl,shimGetUserMedia:Dl,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Sl.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})}});function Wl(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(i=>t.call(this,i,e)),e.getVideoTracks().forEach(i=>t.call(this,i,e))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return n&&n.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const i=e.getTracks();this.getSenders().forEach(e=>{i.includes(e.track)&&this.removeTrack(e)})})}}function Hl(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)})})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const i=new Event("addstream");i.stream=t,e.dispatchEvent(i)})}),t.apply(e,arguments)}}}function Kl(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Sl.resolve()):r},t.createAnswer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Sl.resolve()):r};let a=function(e,t,i){const n=r.apply(this,[e]);return i?(n.then(t,i),Sl.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){const n=o.apply(this,[e]);return i?(n.then(t,i),Sl.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){const n=s.apply(this,[e]);return i?(n.then(t,i),Sl.resolve()):n},t.addIceCandidate=a}function Yl(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(ql(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}.bind(t))}function ql(e){return e&&void 0!==e.video?Object.assign({},e,{video:cn(e.video)}):e}function Jl(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){const t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];!n.hasOwnProperty("urls")&&n.hasOwnProperty("url")?(on("RTCIceServer.url","RTCIceServer.urls"),n=JSON.parse(JSON.stringify(n)),n.urls=n.url,delete n.url,t.push(n)):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 Xl(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 zl(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find(e=>"audio"===e.receiver.track.kind);!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const i=this.getTransceivers().find(e=>"video"===e.receiver.track.kind);!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Ql(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Zl=Object.freeze({__proto__:null,shimLocalStreamsAPI:Wl,shimRemoteStreamsAPI:Hl,shimCallbacksAPI:Kl,shimGetUserMedia:Yl,shimConstraints:ql,shimRTCIceServerUrls:Jl,shimTrackEventTransceiver:Xl,shimCreateOfferLegacy:zl,shimAudioContext:Ql}),$l="\t\n\v\f\r \u2028\u2029\ufeff",eh=G,th=No,ih=d("".replace),nh="[\t\n\v\f\r \u2028\u2029\ufeff]",rh=RegExp("^"+nh+nh+"*"),oh=RegExp(nh+nh+"*$"),sh=function(e){return function(t){var i=th(eh(t));return 1&e&&(i=ih(i,rh,"")),2&e&&(i=ih(i,oh,"")),i}},ah={start:sh(1),end:sh(2),trim:sh(3)},ch=Ms.PROPER,dh=i,uh=$l,lh=ah.trim;Ii({target:"String",proto:!0,forced:function(e){return dh((function(){return!!uh[e]()||"
"!=="
"[e]()||ch&&uh[e].name!==e}))}("trim")},{trim:function(){return lh(this)}});var hh=Hi("String").trim,ph=u,_h=hh,Eh=String.prototype,mh=function(e){var t=e.trim;return"string"==typeof e||e===Eh||ph(Eh,e)&&t===Eh.trim?_h:t},fh={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return mh(e).call(e).split("\n").map(e=>mh(e).call(e))},t.splitSections=function(e){return e.split("\nm=").map((e,t)=>{var i;return mh(i=t>0?"m="+e:e).call(i)+"\r\n"})},t.getDescription=function(e){const i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){const i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter(e=>0===e.indexOf(i))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let 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},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const 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);const n=e.type;return t.push("typ"),t.push(n),"host"!==n&&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.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substr(14).split(" ")},t.parseRtpMap=function(e){let t=e.substr(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substr(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1]}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+"\r\n"},t.parseFmtp=function(e){const t={};let i;const n=e.substr(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++){var r,o;i=mh(r=n[e]).call(r).split("="),t[mh(o=i[0]).call(o)]=i[1]}return t},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const n=[];Object.keys(e.parameters).forEach(t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)}),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substr(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),i={ssrc:parseInt(e.substr(7,t-7),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substr(t+1,n-t-1),i.value=e.substr(n+1)):i.attribute=e.substr(t+1),i},t.parseSsrcGroup=function(e){const t=e.substr(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},t.getMid=function(e){const i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substr(6)},t.parseFingerprint=function(e){const t=e.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach(e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),i},t.parseCryptoLine=function(e){const t=e.substr(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.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}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){const n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],r=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substr(12),password:r.substr(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");for(let r=3;r<n.length;r++){const o=n[r],s=t.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(s){const n=t.parseRtpMap(s),r=t.matchPrefix(e,"a=fmtp:"+o+" ");switch(n.parameters=r.length?t.parseFmtp(r[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+o+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}return t.matchPrefix(e,"a=extmap:").forEach(e=>{i.headerExtensions.push(t.parseExtmap(e))}),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" ",n+=i.codecs.length>0?"9":"0",n+=" UDP/TLS/RTP/SAVPF ",n+=i.codecs.map(e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach(e=>{n+=t.writeRtpMap(e),n+=t.writeFmtp(e),n+=t.writeRtcpFb(e)});let r=0;return i.codecs.forEach(e=>{e.maxptime>r&&(r=e.maxptime)}),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach(e=>{n+=t.writeExtmap(e)}),n},t.parseRtpEncodingParameters=function(e){const i=[],n=t.parseRtpParameters(e),r=-1!==n.fecMechanisms.indexOf("RED"),o=-1!==n.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute),a=s.length>0&&s[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map(e=>e.substr(17).split(" ").map(e=>parseInt(e,10)));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),n.codecs.forEach(e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),i.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},i.push(t))}}),0===i.length&&a&&i.push({ssrc:a});let u=t.matchPrefix(e,"b=");return u.length&&(u=0===u[0].indexOf("b=TIAS:")?parseInt(u[0].substr(7),10):0===u[0].indexOf("b=AS:")?1e3*parseInt(u[0].substr(5),10)*.95-16e3:void 0,i.forEach(e=>{e.maxBitrate=u})),i},t.parseRtcpParameters=function(e){const i={},n=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute)[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const r=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=0===r.length;const o=t.matchPrefix(e,"a=rtcp-mux");return i.mux=o.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;const n=t.matchPrefix(e,"a=msid:");if(1===n.length)return i=n[0].substr(7).split(" "),{stream:i[0],track:i[1]};const r=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"msid"===e.attribute);return r.length>0?(i=r[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(e){const i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");let r;n.length>0&&(r=parseInt(n[0].substr(19),10)),isNaN(r)&&(r=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substr(12),10),protocol:i.fmt,maxMessageSize:r};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substr(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,21)},t.writeSessionBoilerplate=function(e,i,n){let r;const o=void 0!==i?i:2;r=e||t.generateSessionId();return"v=0\r\no="+(n||"thisisadapterortc")+" "+r+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){const n=t.splitLines(e);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substr(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substr(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const i=t.splitLines(e)[0].substr(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){const i=t.matchPrefix(e,"o=")[0].substr(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}(fh);var Sh=fh.exports,Th=Object.freeze(e({__proto__:null,default:Sh},[fh.exports]));function gh(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const 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){const i=new t(e),n=Sh.parseCandidate(e.candidate),r=Object.assign(i,n);return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,en(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Rh(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||en(e,"icecandidate",e=>{if(e.candidate){const t=Sh.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Ih(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const i=function(e){if(!e||!e.sdp)return!1;const t=Sh.splitSections(e.sdp);return t.shift(),t.some(e=>{const t=Sh.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")})},n=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const i=parseInt(t[1],10);return i!=i?-1:i},r=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i},o=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);const r=Sh.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substr(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n},s=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(i(arguments[0])){const e=n(arguments[0]),t=r(e),i=o(arguments[0],e);let s;s=0===t&&0===i?Number.POSITIVE_INFINITY:0===t||0===i?Math.max(t,i):Math.min(t,i);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>s}),this._sctp=a}return s.apply(this,arguments)}}function vh(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const i=e.send;e.send=function(){const n=arguments[0],r=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}const i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=i.apply(this,arguments);return t(e,this),e},en(e,"datachannel",e=>(t(e.channel,e.target),e))}function Ch(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(e=>{const i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function yh(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const i=t.sdp.split("\n").filter(e=>"a=extmap-allow-mixed"!==mh(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 Ah(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Sl.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Sl.resolve())})}function Oh(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return i.apply(this,[e]);const t="offer"===e.type?this.createOffer:this.createAnswer;return t.apply(this).then(e=>i.apply(this,[e]))})}var bh=Object.freeze({__proto__:null,shimRTCIceCandidate:gh,shimRTCIceCandidateRelayProtocol:Rh,shimMaxMessageSize:Ih,shimSendThrowTypeError:vh,shimConnectionState:Ch,removeExtmapAllowMixed:yh,shimAddIceCandidateNullOrEmpty:Ah,shimParameterlessSetLocalDescription:Oh});let wh,Nh;!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};const i=rn,n=sn(e),r={browserDetails:n,commonShim:bh,extractVersion:$i,disableLog:tn,disableWarnings:nn,sdp:Th};switch(n.browser){case"chrome":if(!Nl||!bl||!t.shimChrome)return i("Chrome shim is not included in this adapter release."),r;if(null===n.version)return i("Chrome shim can not determine version, not shimming."),r;i("adapter.js shimming chrome."),r.browserShim=Nl,Ah(e,n),Oh(e),gl(e,n),Rl(e),bl(e,n),Il(e),Ol(e,n),vl(e),Cl(e),yl(e),wl(e,n),gh(e),Rh(e),Ch(e),Ih(e,n),vh(e),yh(e,n);break;case"firefox":if(!Gl||!Ll||!t.shimFirefox)return i("Firefox shim is not included in this adapter release."),r;i("adapter.js shimming firefox."),r.browserShim=Gl,Ah(e,n),Oh(e),Dl(e,n),Ll(e,n),Pl(e),Ul(e),kl(e),Ml(e),xl(e),Vl(e),Fl(e),jl(e),Bl(e),gh(e),Ch(e),Ih(e,n),vh(e);break;case"safari":if(!Zl||!t.shimSafari)return i("Safari shim is not included in this adapter release."),r;i("adapter.js shimming safari."),r.browserShim=Zl,Ah(e,n),Oh(e),Jl(e),zl(e),Kl(e),Wl(e),Hl(e),Xl(e),Yl(e),Ql(e),gh(e),Rh(e),Ih(e,n),vh(e),yh(e,n);break;default:i("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window}),function(e){e.WIN_10="Windows 10",e.WIN_81="Windows 8.1",e.WIN_8="Windows 8",e.WIN_7="Windows 7",e.WIN_VISTA="Windows Vista",e.WIN_SERVER_2003="Windows Server 2003",e.WIN_XP="Windows XP",e.WIN_2000="Windows 2000",e.ANDROID="Android",e.OPEN_BSD="Open BSD",e.SUN_OS="Sun OS",e.LINUX="Linux",e.IOS="iOS",e.MAC_OS="Mac OS",e.QNX="QNX",e.UNIX="UNIX",e.BEOS="BeOS",e.OS_2="OS/2",e.SEARCH_BOT="Search Bot"}(wh||(wh={})),function(e){e.CHROME="Chrome",e.SAFARI="Safari",e.EDGE="Edge",e.FIREFOX="Firefox",e.OPERA="OPR",e.QQ="QQBrowser",e.WECHAT="MicroMessenger"}(Nh||(Nh={}));var Dh={exports:{}};!function(e,i){!function(t,n){var r="function",o="undefined",s="object",a="string",c="major",d="model",u="name",l="type",h="vendor",p="version",_="architecture",E="console",m="mobile",f="tablet",S="smarttv",T="wearable",g="embedded",R="Amazon",I="Apple",v="ASUS",C="BlackBerry",y="Firefox",A="Google",O="Huawei",b="LG",w="Microsoft",N="Motorola",D="Opera",P="Samsung",L="Sharp",k="Sony",M="Xiaomi",U="Zebra",x="Facebook",V="Chromium OS",F="Mac OS",j=function(e){for(var t={},i=0;i<e.length;i++)t[e[i].toUpperCase()]=e[i];return t},B=function(e,t){return typeof e===a&&-1!==G(t).indexOf(G(e))},G=function(e){return e.toLowerCase()},W=function(e,t){if(typeof e===a)return e=e.replace(/^\s\s*/,""),typeof t===o?e:e.substring(0,350)},H=function(e,t){for(var i,o,a,c,d,u,l=0;l<t.length&&!d;){var h=t[l],p=t[l+1];for(i=o=0;i<h.length&&!d&&h[i];)if(d=h[i++].exec(e))for(a=0;a<p.length;a++)u=d[++o],typeof(c=p[a])===s&&c.length>0?2===c.length?typeof c[1]==r?this[c[0]]=c[1].call(this,u):this[c[0]]=c[1]:3===c.length?typeof c[1]!==r||c[1].exec&&c[1].test?this[c[0]]=u?u.replace(c[1],c[2]):n:this[c[0]]=u?c[1].call(this,u,c[2]):n:4===c.length&&(this[c[0]]=u?c[3].call(this,u.replace(c[1],c[2])):n):this[c]=u||n;l+=2}},K=function(e,t){for(var i in t)if(typeof t[i]===s&&t[i].length>0){for(var r=0;r<t[i].length;r++)if(B(t[i][r],e))return"?"===i?n:i}else if(B(t[i],e))return"?"===i?n:i;return e},Y={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"},q={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[p,[u,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[p,[u,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[u,p],[/opios[\/ ]+([\w\.]+)/i],[p,[u,"Opera Mini"]],[/\bopr\/([\w\.]+)/i],[p,[u,D]],[/(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],[u,p],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[p,[u,"UCBrowser"]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[p,[u,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[p,[u,"WeChat"]],[/konqueror\/([\w\.]+)/i],[p,[u,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[p,[u,"IE"]],[/yabrowser\/([\w\.]+)/i],[p,[u,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[u,/(.+)/,"$1 Secure Browser"],p],[/\bfocus\/([\w\.]+)/i],[p,[u,"Firefox Focus"]],[/\bopt\/([\w\.]+)/i],[p,[u,"Opera Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[p,[u,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[p,[u,"Dolphin"]],[/coast\/([\w\.]+)/i],[p,[u,"Opera Coast"]],[/miuibrowser\/([\w\.]+)/i],[p,[u,"MIUI Browser"]],[/fxios\/([-\w\.]+)/i],[p,[u,y]],[/\bqihu|(qi?ho?o?|360)browser/i],[[u,"360 Browser"]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[u,/(.+)/,"$1 Browser"],p],[/(comodo_dragon)\/([\w\.]+)/i],[[u,/_/g," "],p],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[u,p],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[u],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[u,x],p],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/ ]([-\w\.]+)/i],[u,p],[/\bgsa\/([\w\.]+) .*safari\//i],[p,[u,"GSA"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[p,[u,"Chrome Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[u,"Chrome WebView"],p],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[p,[u,"Android Browser"]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[u,p],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[p,[u,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[p,u],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[u,[p,K,{"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],[u,p],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[u,"Netscape"],p],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[p,[u,"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],[u,p],[/(cobalt)\/([\w\.]+)/i],[u,[p,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[_,"amd64"]],[/(ia32(?=;))/i],[[_,G]],[/((?:i[346]|x)86)[;\)]/i],[[_,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[_,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[_,"armhf"]],[/windows (ce|mobile); ppc;/i],[[_,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[_,/ower/,"",G]],[/(sun4\w)[;\)]/i],[[_,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[_,G]]],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],[d,[h,P],[l,f]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[d,[h,P],[l,m]],[/\((ip(?:hone|od)[\w ]*);/i],[d,[h,I],[l,m]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[d,[h,I],[l,f]],[/(macintosh);/i],[d,[h,I]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[d,[h,L],[l,m]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[d,[h,O],[l,f]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[d,[h,O],[l,m]],[/\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],[[d,/_/g," "],[h,M],[l,m]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[d,/_/g," "],[h,M],[l,f]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[d,[h,"OPPO"],[l,m]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[d,[h,"Vivo"],[l,m]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[d,[h,"Realme"],[l,m]],[/\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],[d,[h,N],[l,m]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[d,[h,N],[l,f]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[d,[h,b],[l,f]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[d,[h,b],[l,m]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[d,[h,"Lenovo"],[l,f]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[d,/_/g," "],[h,"Nokia"],[l,m]],[/(pixel c)\b/i],[d,[h,A],[l,f]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[d,[h,A],[l,m]],[/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],[d,[h,k],[l,m]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[d,"Xperia Tablet"],[h,k],[l,f]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[d,[h,"OnePlus"],[l,m]],[/(alexa)webm/i,/(kf[a-z]{2}wi)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[d,[h,R],[l,f]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[d,/(.+)/g,"Fire Phone $1"],[h,R],[l,m]],[/(playbook);[-\w\),; ]+(rim)/i],[d,h,[l,f]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[d,[h,C],[l,m]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[d,[h,v],[l,f]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[d,[h,v],[l,m]],[/(nexus 9)/i],[d,[h,"HTC"],[l,f]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[h,[d,/_/g," "],[l,m]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[d,[h,"Acer"],[l,f]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[d,[h,"Meizu"],[l,m]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[h,d,[l,m]],[/(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],[h,d,[l,f]],[/(surface duo)/i],[d,[h,w],[l,f]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[d,[h,"Fairphone"],[l,m]],[/(u304aa)/i],[d,[h,"AT&T"],[l,m]],[/\bsie-(\w*)/i],[d,[h,"Siemens"],[l,m]],[/\b(rct\w+) b/i],[d,[h,"RCA"],[l,f]],[/\b(venue[\d ]{2,7}) b/i],[d,[h,"Dell"],[l,f]],[/\b(q(?:mv|ta)\w+) b/i],[d,[h,"Verizon"],[l,f]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[d,[h,"Barnes & Noble"],[l,f]],[/\b(tm\d{3}\w+) b/i],[d,[h,"NuVision"],[l,f]],[/\b(k88) b/i],[d,[h,"ZTE"],[l,f]],[/\b(nx\d{3}j) b/i],[d,[h,"ZTE"],[l,m]],[/\b(gen\d{3}) b.+49h/i],[d,[h,"Swiss"],[l,m]],[/\b(zur\d{3}) b/i],[d,[h,"Swiss"],[l,f]],[/\b((zeki)?tb.*\b) b/i],[d,[h,"Zeki"],[l,f]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[h,"Dragon Touch"],d,[l,f]],[/\b(ns-?\w{0,9}) b/i],[d,[h,"Insignia"],[l,f]],[/\b((nxa|next)-?\w{0,9}) b/i],[d,[h,"NextBook"],[l,f]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[h,"Voice"],d,[l,m]],[/\b(lvtel\-)?(v1[12]) b/i],[[h,"LvTel"],d,[l,m]],[/\b(ph-1) /i],[d,[h,"Essential"],[l,m]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[d,[h,"Envizen"],[l,f]],[/\b(trio[-\w\. ]+) b/i],[d,[h,"MachSpeed"],[l,f]],[/\btu_(1491) b/i],[d,[h,"Rotor"],[l,f]],[/(shield[\w ]+) b/i],[d,[h,"Nvidia"],[l,f]],[/(sprint) (\w+)/i],[h,d,[l,m]],[/(kin\.[onetw]{3})/i],[[d,/\./g," "],[h,w],[l,m]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[d,[h,U],[l,f]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[d,[h,U],[l,m]],[/smart-tv.+(samsung)/i],[h,[l,S]],[/hbbtv.+maple;(\d+)/i],[[d,/^/,"SmartTV"],[h,P],[l,S]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[h,b],[l,S]],[/(apple) ?tv/i],[h,[d,"Apple TV"],[l,S]],[/crkey/i],[[d,"Chromecast"],[h,A],[l,S]],[/droid.+aft(\w)( bui|\))/i],[d,[h,R],[l,S]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[d,[h,L],[l,S]],[/(bravia[\w ]+)( bui|\))/i],[d,[h,k],[l,S]],[/(mitv-\w{5}) bui/i],[d,[h,M],[l,S]],[/Hbbtv.*(technisat) (.*);/i],[h,d,[l,S]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[h,W],[d,W],[l,S]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[l,S]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[h,d,[l,E]],[/droid.+; (shield) bui/i],[d,[h,"Nvidia"],[l,E]],[/(playstation [345portablevi]+)/i],[d,[h,k],[l,E]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[d,[h,w],[l,E]],[/((pebble))app/i],[h,d,[l,T]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[d,[h,I],[l,T]],[/droid.+; (glass) \d/i],[d,[h,A],[l,T]],[/droid.+; (wt63?0{2,3})\)/i],[d,[h,U],[l,T]],[/(quest( 2| pro)?)/i],[d,[h,x],[l,T]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[h,[l,g]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[d,[l,m]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[d,[l,f]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[l,f]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[l,m]],[/(android[-\w\. ]{0,9});.+buil/i],[d,[h,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[p,[u,"EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[p,[u,"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],[u,p],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[p,u]],os:[[/microsoft (windows) (vista|xp)/i],[u,p],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[u,[p,K,Y]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[u,"Windows"],[p,K,Y]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/cfnetwork\/.+darwin/i],[[p,/_/g,"."],[u,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[u,F],[p,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[p,u],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[u,p],[/\(bb(10);/i],[p,[u,C]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[p,[u,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[p,[u,"Firefox OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[p,[u,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[p,[u,"watchOS"]],[/crkey\/([\d\.]+)/i],[p,[u,"Chromecast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[u,V],p],[/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],[u,p],[/(sunos) ?([\w\.\d]*)/i],[[u,"Solaris"],p],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux)/i,/(unix) ?([\w\.]*)/i],[u,p]]},J=function(e,i){if(typeof e===s&&(i=e,e=n),!(this instanceof J))return new J(e,i).getResult();var c=typeof t!==o&&t.navigator?t.navigator:n,d=e||(c&&c.userAgent?c.userAgent:""),u=c&&c.userAgentData?c.userAgentData:n,l=i?function(e,t){var i={};for(var n in e)t[n]&&t[n].length%2==0?i[n]=t[n].concat(e[n]):i[n]=e[n];return i}(q,i):q;return this.getBrowser=function(){var e={};return e.name=n,e.version=n,H.call(e,d,l.browser),e.major=function(e){return typeof e===a?e.replace(/[^\d\.]/g,"").split(".")[0]:n}(e.version),c&&c.brave&&typeof c.brave.isBrave==r&&(e.name="Brave"),e},this.getCPU=function(){var e={};return e.architecture=n,H.call(e,d,l.cpu),e},this.getDevice=function(){var e={};return e.vendor=n,e.model=n,e.type=n,H.call(e,d,l.device),!e.type&&u&&u.mobile&&(e.type=m),"Macintosh"==e.model&&c&&typeof c.standalone!==o&&c.maxTouchPoints&&c.maxTouchPoints>2&&(e.model="iPad",e.type=f),e},this.getEngine=function(){var e={};return e.name=n,e.version=n,H.call(e,d,l.engine),e},this.getOS=function(){var e={};return e.name=n,e.version=n,H.call(e,d,l.os),!e.name&&u&&"Unknown"!=u.platform&&(e.name=u.platform.replace(/chrome os/i,V).replace(/macos/i,F)),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===a&&e.length>350?W(e,350):e,this},this.setUA(d),this};J.VERSION="0.7.34",J.BROWSER=j([u,p,c]),J.CPU=j([_]),J.DEVICE=j([d,h,l,E,m,S,f,T,g]),J.ENGINE=J.OS=j([u,p]),e.exports&&(i=e.exports=J),i.UAParser=J;var X=typeof t!==o&&(t.jQuery||t.Zepto);if(X&&!X.ua){var z=new J;X.ua=z.getResult(),X.ua.get=function(){return z.getUA()},X.ua.set=function(e){z.setUA(e);var t=z.getResult();for(var i in t)X.ua[i]=t[i]}}}("object"==typeof window?window:t)}(Dh,Dh.exports);const Ph=new(0,Dh.exports);let Lh,kh=Ph.getResult();function Mh(e){return e&&Ph.setUA(e),kh=Ph.getResult(),{name:Uh(kh),version:xh(kh),os:Vh(kh),osVersion:kh.os.version}}function Uh(e){if("Blink"===e.engine.name&&"WeChat"!==e.browser.name)return Nh.CHROME;switch(e.browser.name){case"Chrome Headless":case"Chrome":case"Chromium":return Nh.CHROME;case"Safari":case"Mobile Safari":return Nh.SAFARI;case"Edge":return Nh.EDGE;case"Firefox":return Nh.FIREFOX;case"QQBrowser":return Nh.QQ;case"Opera":return Nh.OPERA;case"WeChat":return Nh.WECHAT;default:return e.browser.name||""}}function xh(e){let t;return t="Blink"===e.engine.name?e.engine.version||"":e.browser.version||"",t.split(".")[0]}function Vh(e){switch(e.os.name){case"Windows":return e.os.version?e.os.name+" "+e.os.version:e.os.name;default:return e.os.name||""}}function Fh(){const e=Mh();return!!("WebKit"===kh.engine.name&&e.os===wh.MAC_OS&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0&&e.name!==Nh.SAFARI||Kh()&&e.name!==Nh.SAFARI)}function jh(){const e=Mh();if(Fh()){if(e.os===wh.MAC_OS)return!0;if(e.os===wh.IOS){const e=kh.os.version&&kh.os.version.split(".");if(e&&14===Number(e[0])&&e[1]&&Number(e[1])>=3)return!0;if(e&&Number(e[0])>14)return!0}}return!1}function Bh(){return"WebKit"===kh.engine.name}function Gh(){return Mh().name===Nh.CHROME}function Wh(){return Mh().name===Nh.SAFARI}function Hh(){return Mh().name===Nh.FIREFOX}function Kh(){return Mh().os===wh.IOS}function Yh(){const e=Mh();return!(e.name!==Nh.CHROME||!e.osVersion)&&Number(e.version)<=90}function qh(){const e=Mh();if(e.os!==wh.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return Number(t[0])<14||14===Number(t[0])&&Number(t[1])<=6}function Jh(){const e=Mh();if(e.os!==wh.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])}function Xh(){const e=Mh();if(e.os!==wh.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])&&0===Number(t[1])}function zh(){const e=Mh();if(e.os!==wh.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=1}function Qh(){const e=Mh();if(e.os!==wh.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=2}function Zh(){return Wh()&&navigator.maxTouchPoints>0}function $h(){return Mh().name===Nh.WECHAT}function ep(){return window.navigator.appVersion&&null!==window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)&&window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)[1]<=35}function tp(){const e=Mh();if(e.name===Nh.EDGE||e.name===Nh.SAFARI)return!1;return!!navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]./i)}function ip(){return Mh().os===wh.ANDROID}function np(){const e=Mh();return"Android"===e.os&&("Chrome"===e.name||e.name===Nh.WECHAT||/chrome|chromium/i.test(navigator.userAgent))}!function(e){e.CERTIFICATE="certificate",e.CODEC="codec",e.CANDIDATE_PAIR="candidate-pair",e.LOCAL_CANDIDATE="local-candidate",e.REMOTE_CANDIDATE="remote-candidate",e.INBOUND="inbound-rtp",e.TRACK="track",e.OUTBOUND="outbound-rtp",e.PC="peer-connection",e.REMOTE_INBOUND="remote-inbound-rtp",e.REMOTE_OUTBOUND="remote-outbound-rtp",e.TRANSPORT="transport",e.CSRC="csrc",e.DATA_CHANNEL="data-channel",e.STREAM="stream",e.SENDER="sender",e.RECEIVER="receiver"}(Lh||(Lh={}));var rp={exports:{}},op=Ii,sp=g,ap=Ht.f;op({target:"Object",stat:!0,forced:Object.defineProperty!==ap,sham:!sp},{defineProperty:ap});var cp=J.Object,dp=rp.exports=function(e,t,i){return cp.defineProperty(e,t,i)};cp.defineProperty.sham&&(dp.sham=!0);var up=rp.exports;function lp(e,t,i){return t in e?up(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}var hp,pp={exports:{}},_p=function(e,t){return function(){for(var i=new Array(arguments.length),n=0;n<i.length;n++)i[n]=arguments[n];return e.apply(t,i)}},Ep=_p,mp=Object.prototype.toString,fp=(hp=Object.create(null),function(e){var t=mp.call(e);return hp[t]||(hp[t]=t.slice(8,-1).toLowerCase())});function Sp(e){return e=e.toLowerCase(),function(t){return fp(t)===e}}function Tp(e){return Array.isArray(e)}function gp(e){return void 0===e}var Rp=Sp("ArrayBuffer");function Ip(e){return null!==e&&"object"==typeof e}function vp(e){if("object"!==fp(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}var Cp=Sp("Date"),yp=Sp("File"),Ap=Sp("Blob"),Op=Sp("FileList");function bp(e){return"[object Function]"===mp.call(e)}var wp=Sp("URLSearchParams");function Np(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),Tp(e))for(var i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.call(null,e[r],r,e)}var Dp,Pp=(Dp="undefined"!=typeof Uint8Array&&Object.getPrototypeOf(Uint8Array),function(e){return Dp&&e instanceof Dp}),Lp={isArray:Tp,isArrayBuffer:Rp,isBuffer:function(e){return null!==e&&!gp(e)&&null!==e.constructor&&!gp(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||mp.call(e)===t||bp(e.toString)&&e.toString()===t)},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Rp(e.buffer)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:Ip,isPlainObject:vp,isUndefined:gp,isDate:Cp,isFile:yp,isBlob:Ap,isFunction:bp,isStream:function(e){return Ip(e)&&bp(e.pipe)},isURLSearchParams:wp,isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)},forEach:Np,merge:function e(){var t={};function i(i,n){vp(t[n])&&vp(i)?t[n]=e(t[n],i):vp(i)?t[n]=e({},i):Tp(i)?t[n]=i.slice():t[n]=i}for(var n=0,r=arguments.length;n<r;n++)Np(arguments[n],i);return t},extend:function(e,t,i){return Np(t,(function(t,n){e[n]=i&&"function"==typeof t?Ep(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,n){e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,i&&Object.assign(e.prototype,i)},toFlatObject:function(e,t,i){var n,r,o,s={};t=t||{};do{for(r=(n=Object.getOwnPropertyNames(e)).length;r-- >0;)s[o=n[r]]||(t[o]=e[o],s[o]=!0);e=Object.getPrototypeOf(e)}while(e&&(!i||i(e,t))&&e!==Object.prototype);return t},kindOf:fp,kindOfTest:Sp,endsWith:function(e,t,i){e=String(e),(void 0===i||i>e.length)&&(i=e.length),i-=t.length;var n=e.indexOf(t,i);return-1!==n&&n===i},toArray:function(e){if(!e)return null;var t=e.length;if(gp(t))return null;for(var i=new Array(t);t-- >0;)i[t]=e[t];return i},isTypedArray:Pp,isFileList:Op},kp=Lp;function Mp(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var Up=function(e,t,i){if(!t)return e;var n;if(i)n=i(t);else if(kp.isURLSearchParams(t))n=t.toString();else{var r=[];kp.forEach(t,(function(e,t){null!=e&&(kp.isArray(e)?t+="[]":e=[e],kp.forEach(e,(function(e){kp.isDate(e)?e=e.toISOString():kp.isObject(e)&&(e=JSON.stringify(e)),r.push(Mp(t)+"="+Mp(e))})))})),n=r.join("&")}if(n){var o=e.indexOf("#");-1!==o&&(e=e.slice(0,o)),e+=(-1===e.indexOf("?")?"?":"&")+n}return e},xp=Lp;function Vp(){this.handlers=[]}Vp.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},Vp.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},Vp.prototype.forEach=function(e){xp.forEach(this.handlers,(function(t){null!==t&&e(t)}))};var Fp=Vp,jp=Lp,Bp=Lp;function Gp(e,t,i,n,r){Error.call(this),this.message=e,this.name="AxiosError",t&&(this.code=t),i&&(this.config=i),n&&(this.request=n),r&&(this.response=r)}Bp.inherits(Gp,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 Wp=Gp.prototype,Hp={};["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){Hp[e]={value:e}})),Object.defineProperties(Gp,Hp),Object.defineProperty(Wp,"isAxiosError",{value:!0}),Gp.from=function(e,t,i,n,r,o){var s=Object.create(Wp);return Bp.toFlatObject(e,s,(function(e){return e!==Error.prototype})),Gp.call(s,e.message,t,i,n,r),s.name=e.name,o&&Object.assign(s,o),s};var Kp=Gp,Yp={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},qp=Lp;var Jp=function(e,t){t=t||new FormData;var i=[];function n(e){return null===e?"":qp.isDate(e)?e.toISOString():qp.isArrayBuffer(e)||qp.isTypedArray(e)?"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}return function e(r,o){if(qp.isPlainObject(r)||qp.isArray(r)){if(-1!==i.indexOf(r))throw Error("Circular reference detected in "+o);i.push(r),qp.forEach(r,(function(i,r){if(!qp.isUndefined(i)){var s,a=o?o+"."+r:r;if(i&&!o&&"object"==typeof i)if(qp.endsWith(r,"{}"))i=JSON.stringify(i);else if(qp.endsWith(r,"[]")&&(s=qp.toArray(i)))return void s.forEach((function(e){!qp.isUndefined(e)&&t.append(a,n(e))}));e(i,a)}})),i.pop()}else t.append(o,n(r))}(e),t},Xp=Kp,zp=Lp,Qp=zp.isStandardBrowserEnv()?{write:function(e,t,i,n,r,o){var s=[];s.push(e+"="+encodeURIComponent(t)),zp.isNumber(i)&&s.push("expires="+new Date(i).toGMTString()),zp.isString(n)&&s.push("path="+n),zp.isString(r)&&s.push("domain="+r),!0===o&&s.push("secure"),document.cookie=s.join("; ")},read:function(e){var t=document.cookie.match(new 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(){}},Zp=function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)},$p=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e},e_=function(e,t){return e&&!Zp(t)?$p(e,t):t},t_=Lp,i_=["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"],n_=Lp,r_=n_.isStandardBrowserEnv()?function(){var e,t=/(msie|trident)/i.test(navigator.userAgent),i=document.createElement("a");function n(e){var n=e;return t&&(i.setAttribute("href",n),n=i.href),i.setAttribute("href",n),{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=n(window.location.href),function(t){var i=n_.isString(t)?n(t):t;return i.protocol===e.protocol&&i.host===e.host}}():function(){return!0},o_=Kp;function s_(e){o_.call(this,null==e?"canceled":e,o_.ERR_CANCELED),this.name="CanceledError"}Lp.inherits(s_,o_,{__CANCEL__:!0});var a_=s_,c_=Lp,d_=function(e,t,i){var n=i.config.validateStatus;i.status&&n&&!n(i.status)?t(new Xp("Request failed with status code "+i.status,[Xp.ERR_BAD_REQUEST,Xp.ERR_BAD_RESPONSE][Math.floor(i.status/100)-4],i.config,i.request,i)):e(i)},u_=Qp,l_=Up,h_=e_,p_=function(e){var t,i,n,r={};return e?(t_.forEach(e.split("\n"),(function(e){if(n=e.indexOf(":"),t=t_.trim(e.substr(0,n)).toLowerCase(),i=t_.trim(e.substr(n+1)),t){if(r[t]&&i_.indexOf(t)>=0)return;r[t]="set-cookie"===t?(r[t]?r[t]:[]).concat([i]):r[t]?r[t]+", "+i:i}})),r):r},__=r_,E_=Yp,m_=Kp,f_=a_,S_=function(e){var t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""},T_=function(e){return new Promise((function(t,i){var n,r=e.data,o=e.headers,s=e.responseType;function a(){e.cancelToken&&e.cancelToken.unsubscribe(n),e.signal&&e.signal.removeEventListener("abort",n)}c_.isFormData(r)&&c_.isStandardBrowserEnv()&&delete o["Content-Type"];var c=new XMLHttpRequest;if(e.auth){var d=e.auth.username||"",u=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";o.Authorization="Basic "+btoa(d+":"+u)}var l=h_(e.baseURL,e.url);function h(){if(c){var n="getAllResponseHeaders"in c?p_(c.getAllResponseHeaders()):null,r={data:s&&"text"!==s&&"json"!==s?c.response:c.responseText,status:c.status,statusText:c.statusText,headers:n,config:e,request:c};d_((function(e){t(e),a()}),(function(e){i(e),a()}),r),c=null}}if(c.open(e.method.toUpperCase(),l_(l,e.params,e.paramsSerializer),!0),c.timeout=e.timeout,"onloadend"in c?c.onloadend=h:c.onreadystatechange=function(){c&&4===c.readyState&&(0!==c.status||c.responseURL&&0===c.responseURL.indexOf("file:"))&&setTimeout(h)},c.onabort=function(){c&&(i(new m_("Request aborted",m_.ECONNABORTED,e,c)),c=null)},c.onerror=function(){i(new m_("Network Error",m_.ERR_NETWORK,e,c,c)),c=null},c.ontimeout=function(){var t=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded",n=e.transitional||E_;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),i(new m_(t,n.clarifyTimeoutError?m_.ETIMEDOUT:m_.ECONNABORTED,e,c)),c=null},c_.isStandardBrowserEnv()){var p=(e.withCredentials||__(l))&&e.xsrfCookieName?u_.read(e.xsrfCookieName):void 0;p&&(o[e.xsrfHeaderName]=p)}"setRequestHeader"in c&&c_.forEach(o,(function(e,t){void 0===r&&"content-type"===t.toLowerCase()?delete o[t]:c.setRequestHeader(t,e)})),c_.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)&&(n=function(e){c&&(i(!e||e&&e.type?new f_:e),c.abort(),c=null)},e.cancelToken&&e.cancelToken.subscribe(n),e.signal&&(e.signal.aborted?n():e.signal.addEventListener("abort",n))),r||(r=null);var _=S_(l);_&&-1===["http","https","file"].indexOf(_)?i(new m_("Unsupported protocol "+_+":",m_.ERR_BAD_REQUEST,e)):c.send(r)}))},g_=Lp,R_=function(e,t){jp.forEach(e,(function(i,n){n!==t&&n.toUpperCase()===t.toUpperCase()&&(e[t]=i,delete e[n])}))},I_=Kp,v_=Jp,C_={"Content-Type":"application/x-www-form-urlencoded"};function y_(e,t){!g_.isUndefined(e)&&g_.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var A_,O_={transitional:Yp,adapter:(("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(A_=T_),A_),transformRequest:[function(e,t){if(R_(t,"Accept"),R_(t,"Content-Type"),g_.isFormData(e)||g_.isArrayBuffer(e)||g_.isBuffer(e)||g_.isStream(e)||g_.isFile(e)||g_.isBlob(e))return e;if(g_.isArrayBufferView(e))return e.buffer;if(g_.isURLSearchParams(e))return y_(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString();var i,n=g_.isObject(e),r=t&&t["Content-Type"];if((i=g_.isFileList(e))||n&&"multipart/form-data"===r){var o=this.env&&this.env.FormData;return v_(i?{"files[]":e}:e,o&&new o)}return n||"application/json"===r?(y_(t,"application/json"),function(e,t,i){if(g_.isString(e))try{return(t||JSON.parse)(e),g_.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(i||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){var t=this.transitional||O_.transitional,i=t&&t.silentJSONParsing,n=t&&t.forcedJSONParsing,r=!i&&"json"===this.responseType;if(r||n&&g_.isString(e)&&e.length)try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw I_.from(e,I_.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, */*"}}};g_.forEach(["delete","get","head"],(function(e){O_.headers[e]={}})),g_.forEach(["post","put","patch"],(function(e){O_.headers[e]=g_.merge(C_)}));var b_=O_,w_=Lp,N_=b_,D_=function(e){return!(!e||!e.__CANCEL__)},P_=Lp,L_=function(e,t,i){var n=this||N_;return w_.forEach(i,(function(i){e=i.call(n,e,t)})),e},k_=D_,M_=b_,U_=a_;function x_(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new U_}var V_=Lp,F_=function(e,t){t=t||{};var i={};function n(e,t){return V_.isPlainObject(e)&&V_.isPlainObject(t)?V_.merge(e,t):V_.isPlainObject(t)?V_.merge({},t):V_.isArray(t)?t.slice():t}function r(i){return V_.isUndefined(t[i])?V_.isUndefined(e[i])?void 0:n(void 0,e[i]):n(e[i],t[i])}function o(e){if(!V_.isUndefined(t[e]))return n(void 0,t[e])}function s(i){return V_.isUndefined(t[i])?V_.isUndefined(e[i])?void 0:n(void 0,e[i]):n(void 0,t[i])}function a(i){return i in t?n(e[i],t[i]):i in e?n(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 V_.forEach(Object.keys(e).concat(Object.keys(t)),(function(e){var t=c[e]||r,n=t(e);V_.isUndefined(n)&&t!==a||(i[e]=n)})),i},j_="0.27.2",B_=j_,G_=Kp,W_={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){W_[e]=function(i){return typeof i===e||"a"+(t<1?"n ":" ")+e}}));var H_={};W_.transitional=function(e,t,i){function n(e,t){return"[Axios v"+B_+"] Transitional option '"+e+"'"+t+(i?". "+i:"")}return function(i,r,o){if(!1===e)throw new G_(n(r," has been removed"+(t?" in "+t:"")),G_.ERR_DEPRECATED);return t&&!H_[r]&&(H_[r]=!0,console.warn(n(r," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(i,r,o)}};var K_=Lp,Y_=Up,q_=Fp,J_=function(e){return x_(e),e.headers=e.headers||{},e.data=L_.call(e,e.data,e.headers,e.transformRequest),e.headers=P_.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),P_.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||M_.adapter)(e).then((function(t){return x_(e),t.data=L_.call(e,t.data,t.headers,e.transformResponse),t}),(function(t){return k_(t)||(x_(e),t&&t.response&&(t.response.data=L_.call(e,t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))},X_=F_,z_=e_,Q_={assertOptions:function(e,t,i){if("object"!=typeof e)throw new G_("options must be an object",G_.ERR_BAD_OPTION_VALUE);for(var n=Object.keys(e),r=n.length;r-- >0;){var o=n[r],s=t[o];if(s){var a=e[o],c=void 0===a||s(a,o,e);if(!0!==c)throw new G_("option "+o+" must be "+c,G_.ERR_BAD_OPTION_VALUE)}else if(!0!==i)throw new G_("Unknown option "+o,G_.ERR_BAD_OPTION)}},validators:W_},Z_=Q_.validators;function $_(e){this.defaults=e,this.interceptors={request:new q_,response:new q_}}$_.prototype.request=function(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},(t=X_(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&&Q_.assertOptions(i,{silentJSONParsing:Z_.transitional(Z_.boolean),forcedJSONParsing:Z_.transitional(Z_.boolean),clarifyTimeoutError:Z_.transitional(Z_.boolean)},!1);var n=[],r=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(r=r&&e.synchronous,n.unshift(e.fulfilled,e.rejected))}));var o,s=[];if(this.interceptors.response.forEach((function(e){s.push(e.fulfilled,e.rejected)})),!r){var a=[J_,void 0];for(Array.prototype.unshift.apply(a,n),a=a.concat(s),o=Promise.resolve(t);a.length;)o=o.then(a.shift(),a.shift());return o}for(var c=t;n.length;){var d=n.shift(),u=n.shift();try{c=d(c)}catch(e){u(e);break}}try{o=J_(c)}catch(e){return Promise.reject(e)}for(;s.length;)o=o.then(s.shift(),s.shift());return o},$_.prototype.getUri=function(e){e=X_(this.defaults,e);var t=z_(e.baseURL,e.url);return Y_(t,e.params,e.paramsSerializer)},K_.forEach(["delete","get","head","options"],(function(e){$_.prototype[e]=function(t,i){return this.request(X_(i||{},{method:e,url:t,data:(i||{}).data}))}})),K_.forEach(["post","put","patch"],(function(e){function t(t){return function(i,n,r){return this.request(X_(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:i,data:n}))}}$_.prototype[e]=t(),$_.prototype[e+"Form"]=t(!0)}));var eE=$_,tE=a_;function iE(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise((function(e){t=e}));var i=this;this.promise.then((function(e){if(i._listeners){var t,n=i._listeners.length;for(t=0;t<n;t++)i._listeners[t](e);i._listeners=null}})),this.promise.then=function(e){var t,n=new Promise((function(e){i.subscribe(e),t=e})).then(e);return n.cancel=function(){i.unsubscribe(t)},n},e((function(e){i.reason||(i.reason=new tE(e),t(i.reason))}))}iE.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},iE.prototype.subscribe=function(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]},iE.prototype.unsubscribe=function(e){if(this._listeners){var t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}},iE.source=function(){var e;return{token:new iE((function(t){e=t})),cancel:e}};var nE=iE,rE=Lp,oE=Lp,sE=_p,aE=eE,cE=F_;var dE=function e(t){var i=new aE(t),n=sE(aE.prototype.request,i);return oE.extend(n,aE.prototype,i),oE.extend(n,i),n.create=function(i){return e(cE(t,i))},n}(b_);dE.Axios=aE,dE.CanceledError=a_,dE.CancelToken=nE,dE.isCancel=D_,dE.VERSION=j_,dE.toFormData=Jp,dE.AxiosError=Kp,dE.Cancel=dE.CanceledError,dE.all=function(e){return Promise.all(e)},dE.spread=function(e){return function(t){return e.apply(null,t)}},dE.isAxiosError=function(e){return rE.isObject(e)&&!0===e.isAxiosError},pp.exports=dE,pp.exports.default=dE;var uE=pp.exports;class lE{constructor(e){lp(this,"logger",void 0),lp(this,"prefixLists",[]),this.logger=e}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.debug(...this.prefixLists,...t)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.info(...this.prefixLists,...t)}warning(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];this.logger.warning(...this.prefixLists,...t)}error(){for(var e=arguments.length,t=new 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 hE{constructor(){lp(this,"_events",{}),lp(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]=[]);const i=this._events[e];-1===this._indexOfListener(i,t)&&i.push({listener:t,once:!1})}once(e,t){this._events[e]||(this._events[e]=[]);const i=this._events[e];-1===this._indexOfListener(i,t)&&i.push({listener:t,once:!0})}off(e,t){if(!this._events[e])return;const i=this._events[e],n=this._indexOfListener(i,t);-1!==n&&i.splice(n,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]=[]);const t=this._events[e].map(e=>e);for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];for(let i=0;i<t.length;i+=1){const r=t[i];r.once&&this.off(e,r.listener),r.listener.apply(this,n||[])}}_indexOfListener(e,t){let i=e.length;for(;i--;)if(e[i].listener===t)return i;return-1}}const pE=new class extends hE{reportLogUploadError(e){this.emit("REPORT_LOG_UPLOAD",e)}};let _E;!function(e){e.UNEXPECTED_ERROR="UNEXPECTED_ERROR",e.UNEXPECTED_RESPONSE="UNEXPECTED_RESPONSE",e.TIMEOUT="TIMEOUT",e.INVALID_PARAMS="INVALID_PARAMS",e.NOT_READABLE="NOT_READABLE",e.NOT_SUPPORTED="NOT_SUPPORTED",e.INVALID_OPERATION="INVALID_OPERATION",e.OPERATION_ABORTED="OPERATION_ABORTED",e.WEB_SECURITY_RESTRICT="WEB_SECURITY_RESTRICT",e.EXCHANGE_SDP_FAILED="EXCHANGE_SDP_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.NETWORK_TIMEOUT="NETWORK_TIMEOUT",e.NETWORK_RESPONSE_ERROR="NETWORK_RESPONSE_ERROR",e.API_INVOKE_TIMEOUT="API_INVOKE_TIMEOUT",e.ENUMERATE_DEVICES_FAILED="ENUMERATE_DEVICES_FAILED",e.DEVICE_NOT_FOUND="DEVICE_NOT_FOUND",e.ELECTRON_IS_NULL="ELECTRON_IS_NULL",e.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR="ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR",e.CHROME_PLUGIN_NO_RESPONSE="CHROME_PLUGIN_NO_RESPONSE",e.CHROME_PLUGIN_NOT_INSTALL="CHROME_PLUGIN_NOT_INSTALL",e.MEDIA_OPTION_INVALID="MEDIA_OPTION_INVALID",e.PERMISSION_DENIED="PERMISSION_DENIED",e.CONSTRAINT_NOT_SATISFIED="CONSTRAINT_NOT_SATISFIED",e.TRACK_IS_DISABLED="TRACK_IS_DISABLED",e.GET_VIDEO_ELEMENT_VISIBLE_ERROR="GET_VIDEO_ELEMENT_VISIBLE_ERROR",e.SHARE_AUDIO_NOT_ALLOWED="SHARE_AUDIO_NOT_ALLOWED",e.LOW_STREAM_ENCODING_ERROR="LOW_STREAM_ENCODING_ERROR",e.SET_ENCODING_PARAMETER_ERROR="SET_ENCODING_PARAMETER_ERROR",e.TRACK_STATE_UNREACHABLE="TRACK_STATE_UNREACHABLE",e.INVALID_UINT_UID_FROM_STRING_UID="INVALID_UINT_UID_FROM_STRING_UID",e.CAN_NOT_GET_PROXY_SERVER="CAN_NOT_GET_PROXY_SERVER",e.CAN_NOT_GET_GATEWAY_SERVER="CAN_NOT_GET_GATEWAY_SERVER",e.VOID_GATEWAY_ADDRESS="VOID_GATEWAY_ADDRESS",e.UID_CONFLICT="UID_CONFLICT",e.MULTI_UNILBS_RESPONSE_ERROR="MULTI_UNILBS_RESPONSE_ERROR",e.UPDATE_TICKET_FAILED="UPDATE_TICKET_FAILED",e.INVALID_LOCAL_TRACK="INVALID_LOCAL_TRACK",e.INVALID_TRACK="INVALID_TRACK",e.SENDER_NOT_FOUND="SENDER_NOT_FOUND",e.CREATE_OFFER_FAILED="CREATE_OFFER_FAILED",e.SET_ANSWER_FAILED="SET_ANSWER_FAILED",e.ICE_FAILED="ICE_FAILED",e.PC_CLOSED="PC_CLOSED",e.SENDER_REPLACE_FAILED="SENDER_REPLACE_FAILED",e.GET_LOCAL_CAPABILITIES_FAILED="GET_LOCAL_CAPABILITIES_FAILED",e.GET_LOCAL_CONNECTION_PARAMS_FAILED="GET_LOCAL_CONNECTION_PARAMS_FAILED",e.SUBSCRIBE_FAILED="SUBSCRIBE_FAILED",e.UNSUBSCRIBE_FAILED="UNSUBSCRIBE_FAILED",e.GATEWAY_P2P_LOST="GATEWAY_P2P_LOST",e.NO_ICE_CANDIDATE="NO_ICE_CANDIDATE",e.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS="CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS",e.EXIST_DISABLED_VIDEO_TRACK="EXIST_DISABLED_VIDEO_TRACK",e.INVALID_REMOTE_USER="INVALID_REMOTE_USER",e.REMOTE_USER_IS_NOT_PUBLISHED="REMOTE_USER_IS_NOT_PUBLISHED",e.CUSTOM_REPORT_SEND_FAILED="CUSTOM_REPORT_SEND_FAILED",e.CUSTOM_REPORT_FREQUENCY_TOO_HIGH="CUSTOM_REPORT_FREQUENCY_TOO_HIGH",e.FETCH_AUDIO_FILE_FAILED="FETCH_AUDIO_FILE_FAILED",e.READ_LOCAL_AUDIO_FILE_ERROR="READ_LOCAL_AUDIO_FILE_ERROR",e.DECODE_AUDIO_FILE_FAILED="DECODE_AUDIO_FILE_FAILED",e.WS_ABORT="WS_ABORT",e.WS_DISCONNECT="WS_DISCONNECT",e.WS_ERR="WS_ERR",e.LIVE_STREAMING_TASK_CONFLICT="LIVE_STREAMING_TASK_CONFLICT",e.LIVE_STREAMING_INVALID_ARGUMENT="LIVE_STREAMING_INVALID_ARGUMENT",e.LIVE_STREAMING_INTERNAL_SERVER_ERROR="LIVE_STREAMING_INTERNAL_SERVER_ERROR",e.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED="LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED",e.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED="LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED",e.LIVE_STREAMING_CDN_ERROR="LIVE_STREAMING_CDN_ERROR",e.LIVE_STREAMING_INVALID_RAW_STREAM="LIVE_STREAMING_INVALID_RAW_STREAM",e.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT="LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT",e.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE="LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE",e.LIVE_STREAMING_WARN_FREQUENT_REQUEST="LIVE_STREAMING_WARN_FREQUENT_REQUEST",e.WEBGL_INTERNAL_ERROR="WEBGL_INTERNAL_ERROR",e.BEAUTY_PROCESSOR_INTERNAL_ERROR="BEAUTY_PROCESSOR_INTERNAL_ERROR",e.CROSS_CHANNEL_WAIT_STATUS_ERROR="CROSS_CHANNEL_WAIT_STATUS_ERROR",e.CROSS_CHANNEL_FAILED_JOIN_SRC="CROSS_CHANNEL_FAILED_JOIN_SEC",e.CROSS_CHANNEL_FAILED_JOIN_DEST="CROSS_CHANNEL_FAILED_JOIN_DEST",e.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST="CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST",e.CROSS_CHANNEL_SERVER_ERROR_RESPONSE="CROSS_CHANNEL_SERVER_ERROR_RESPONSE",e.METADATA_OUT_OF_RANGE="METADATA_OUT_OF_RANGE",e.LOCAL_AEC_ERROR="LOCAL_AEC_ERROR",e.INVALID_PLUGIN="INVALID_PLUGIN",e.DISCONNECT_P2P="DISCONNECT_P2P",e.INIT_WEBSOCKET_TIMEOUT="INIT_WEBSOCKET_TIMEOUT",e.CONVERTING_IMAGEDATA_TO_BLOB_FAILED="CONVERTING_IMAGEDATA_TO_BLOB_FAILED",e.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED="CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED",e.INIT_DATACHANNEL_TIMEOUT="INIT_DATACHANNEL_TIMEOUT",e.DATACHANNEL_CONNECTION_TIMEOUT="DATACHANNEL_CONNECTION_TIMEOUT",e.PROHIBITED_OPERATION="PROHIBITED_OPERATION"}(_E||(_E={}));class EE 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),lp(this,"code",void 0),lp(this,"message",void 0),lp(this,"data",void 0),lp(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&&CE.error(this.toString()),"warning"===e&&CE.warning(this.toString()),this}throw(){throw this.print(),this}}const mE={timeout:500,timeoutFactor:1.5,maxRetryCount:1/0,maxRetryTimeout:1e4};function fE(e,t){const i=Math.floor(t.timeout*Math.pow(t.timeoutFactor,e));return Math.min(t.maxRetryTimeout,i)}function SE(e,t,i,n){const r=Object.assign({},mE,n);let o=r.timeout;const s=async()=>{await function(e){return new Sl(t=>{window.setTimeout(t,e)})}(o),o*=r.timeoutFactor,o=Math.min(r.maxRetryTimeout,o)};let a=!1;const c=new Sl(async(n,o)=>{t=t||(()=>!1),i=i||(()=>!0);for(let c=0;c<r.maxRetryCount;c+=1){if(a)return o(new EE(_E.OPERATION_ABORTED));try{const i=await e();if(!t(i,c))return n(i);if(c+1===r.maxRetryCount)return n(i);await s()}catch(e){if(!i(e,c))return o(e);if(c+1===r.maxRetryCount)return o(e);await s()}}});return c.cancel=()=>a=!0,c}function TE(){const e=new Date;return e.toTimeString().split(" ")[0]+":"+e.getMilliseconds()}function gE(){const 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()}const RE={DEBUG:0,INFO:1,WARNING:2,ERROR:3,NONE:4},IE=Date.now(),vE=e=>{for(const t in RE)if(Object.prototype.hasOwnProperty.call(RE,t)&&RE[t]===e)return t;return"DEFAULT"};const CE=new class{constructor(){lp(this,"proxyServerURL",void 0),lp(this,"logLevel",RE.DEBUG),lp(this,"uploadState","collecting"),lp(this,"uploadLogWaitingList",[]),lp(this,"uploadLogUploadingList",[]),lp(this,"uploadErrorCount",0),lp(this,"currentLogID",0),lp(this,"url",void 0),lp(this,"extLog",(e,t)=>{this.appendLogToWaitingList(e,...t)})}debug(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[RE.DEBUG].concat(t);this.log.apply(this,n)}info(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[RE.INFO].concat(t);this.log.apply(this,n)}warning(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[RE.WARNING].concat(t);this.log.apply(this,n)}error(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[RE.ERROR].concat(t);this.log.apply(this,n)}upload(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const n=[RE.DEBUG].concat(t);this.uploadLog.apply(this,n)}setLogLevel(e){e=Math.min(Math.max(0,e),4),this.logLevel=e}enableLogUpload(){VE("UPLOAD_LOG",!0)}disableLogUpload(){VE("UPLOAD_LOG",!1),this.uploadLogUploadingList=[],this.uploadLogWaitingList=[]}setProxyServer(e){this.proxyServerURL=e}prefix(e){return new lE(this).prefix(e)}log(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];if(Date.now()-IE<100)return void setTimeout(()=>{this.log(...t)},Date.now()-IE);const n=Math.max(0,Math.min(4,t[0]));if(t[0]=TE()+" Agora-SDK [".concat(vE(n),"]:"),this.appendLogToWaitingList(n,...t),n<this.logLevel)return;const r=TE()+" %cAgora-SDK [".concat(vE(n),"]:");let o=[];if(!FE("USE_NEW_LOG"))switch(n){case RE.DEBUG:o=[r,"color: #64B5F6;"].concat(t.slice(1)),console.log.apply(console,o);break;case RE.INFO:o=[r,"color: #1E88E5; font-weight: bold;"].concat(t.slice(1)),console.log.apply(console,o);break;case RE.WARNING:o=[r,"color: #FB8C00; font-weight: bold;"].concat(t.slice(1)),console.warn.apply(console,o);break;case RE.ERROR:o=[r,"color: #B00020; font-weight: bold;"].concat(t.slice(1)),console.error.apply(console,o)}}uploadLog(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];if(Date.now()-IE<100)return void setTimeout(()=>{this.uploadLog(...t)},Date.now()-IE);const n=Math.max(0,Math.min(4,t[0]));t[0]=TE()+" Agora-SDK [".concat(vE(n),"]:"),this.appendLogToWaitingList(n,...t)}appendLogToWaitingList(e){if(!FE("UPLOAD_LOG"))return;for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];Array.isArray(i[0])?i[0][0]=gE()+" Agora-SDK [".concat(vE(e),"]:"):i[0]=gE()+" Agora-SDK [".concat(vE(e),"]:");let r="";i.forEach(e=>{"object"==typeof e&&(e=JSON.stringify(e)),r+="".concat(e," ")}),this.uploadLogWaitingList.push({payload_str:r,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(){const e=this.uploadLogUploadingList,t={sdk_version:AE,process_id:FE("PROCESS_ID"),payload:JSON.stringify(e)};return SE(async()=>{const e=await uE.post(this.url||(this.proxyServerURL?"https://".concat(this.proxyServerURL,"/ls/?h=").concat(FE("LOG_UPLOAD_SERVER"),"&p=443&d=upload/v1"):"https://".concat(FE("LOG_UPLOAD_SERVER"),"/upload/v1")),t,{responseType:"text"});if("OK"!==e.data){const t=new Error("unexpected upload log response");throw t.response=e,t}},()=>(this.uploadLogUploadingList=[],!1),e=>(e.response?pE.reportLogUploadError({status:e.response.status,data:e.response.data,headers:e.response.headers,message:e.message}):e.request?pE.reportLogUploadError({status:e.request.status,message:e.message}):pE.reportLogUploadError({status:-1,message:e.message}),!0),{timeout:FE("UPLOAD_LOG_REQUEST_RETRY_INTERVAL"),maxRetryTimeout:FE("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,FE("UPLOAD_LOG_LENGTH_EACH_TIME"))),this.uploadLogs().then(()=>{this.uploadErrorCount=0,this.uploadLogWaitingList.length>0&&window.setTimeout(()=>this.uploadLogInterval(),FE("UPLOAD_LOG_INTERVAL"))}).catch(e=>{this.uploadErrorCount+=1,this.uploadErrorCount<2?window.setTimeout(()=>this.uploadLogInterval(),FE("UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1")):window.setTimeout(()=>this.uploadLogInterval(),FE("UPLOAD_LOG_RETRY_INTERVAL_V1"))}))}},yE="v4.17.0-0-gf6ae6c87-dirty(3/22/2023, 2:41:22 PM)",AE=function(e){if(e.match(/[0-9]+\.[0-9]+\.[0-9]+$/))return e;const t=e.match(/([0-9]+\.[0-9]+\.[0-9]+)\-alpha\.([0-9]+)/);if(t&&t[1]&&t[2]){const e=t[1],i=t[2];return"".concat(e,".").concat(i)}const i=e.match(/([0-9]+\.[0-9]+\.[0-9]+)\-special\.([0-9]+)/);if(i&&i[1]&&i[2]){const e=i[1],t=i[2];return"".concat(e,".").concat(100*(Number(t)+1))}return"4.0.0.999"}("4.17.0"),OE=function(){try{return!0===JSON.parse("true")}catch(e){return!0}}(),bE=["CHINA","GLOBAL"],wE=function(){const e="us".concat("erna","me"),t="pa".concat("sswo","rd"),i=["t","s","t"];i.splice(1,0,"e");const n=i.join(""),r=[];for(let e=0;e<6;e++)r.push("1");const o=r.join(""),s={};return s[e]=n,s[t]=o,Object.assign(s,{turnServerURL:"",tcpport:3433,udpport:3478,forceturn:!1})}();window.DEFAULT_TURN_CONFIG=wE;const NE={"90p":WE(160,90),"90p_1":WE(160,90),"120p":WE(160,120,15,30,65),"120p_1":WE(160,120,15,30,65),"120p_3":WE(120,120,15,30,50),"120p_4":WE(212,120),"180p":WE(320,180,15,30,140),"180p_1":WE(320,180,15,30,140),"180p_3":WE(180,180,15,30,100),"180p_4":WE(240,180,15,30,120),"240p":WE(320,240,15,40,200),"240p_1":WE(320,240,15,40,200),"240p_3":WE(240,240,15,40,140),"240p_4":WE(424,240,15,40,220),"360p":WE(640,360,15,80,400),"360p_1":WE(640,360,15,80,400),"360p_3":WE(360,360,15,80,260),"360p_4":WE(640,360,30,80,600),"360p_6":WE(360,360,30,80,400),"360p_7":WE(480,360,15,80,320),"360p_8":WE(480,360,30,80,490),"360p_9":WE(640,360,15,80,800),"360p_10":WE(640,360,24,80,800),"360p_11":WE(640,360,24,80,1e3),"480p":WE(640,480,15,100,500),"480p_1":WE(640,480,15,100,500),"480p_2":WE(640,480,30,100,1e3),"480p_3":WE(480,480,15,100,400),"480p_4":WE(640,480,30,100,750),"480p_6":WE(480,480,30,100,600),"480p_8":WE(848,480,15,100,610),"480p_9":WE(848,480,30,100,930),"480p_10":WE(640,480,10,100,400),"720p":WE(1280,720,15,120,1130),"720p_1":WE(1280,720,15,120,1130),"720p_2":WE(1280,720,30,120,2e3),"720p_3":WE(1280,720,30,120,1710),"720p_5":WE(960,720,15,120,910),"720p_6":WE(960,720,30,120,1380),"1080p":WE(1920,1080,15,120,2080),"1080p_1":WE(1920,1080,15,120,2080),"1080p_2":WE(1920,1080,30,120,3e3),"1080p_3":WE(1920,1080,30,120,3150),"1080p_5":WE(1920,1080,60,120,4780),"1440p":WE(2560,1440,30,120,4850),"1440p_1":WE(2560,1440,30,120,4850),"1440p_2":WE(2560,1440,60,120,7350),"4k":WE(3840,2160,30,120,8910),"4k_1":WE(3840,2160,30,120,8910),"4k_3":WE(3840,2160,60,120,13500)},DE={"480p":HE(640,480,5),"480p_1":HE(640,480,5),"480p_2":HE(640,480,30),"480p_3":HE(640,480,15),"720p":HE(1280,720,5),"720p_1":HE(1280,720,5),"720p_2":HE(1280,720,30),"720p_3":HE(1280,720,15),"1080p":HE(1920,1080,5),"1080p_1":HE(1920,1080,5),"1080p_2":HE(1920,1080,30),"1080p_3":HE(1920,1080,15)},PE={"1SL1TL":KE(1,1),"3SL3TL":KE(3,3),"2SL3TL":KE(2,3)};function LE(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},NE[e]):e}function kE(e){return"string"==typeof e?Object.assign({},DE[e]):e}function ME(e){return"string"==typeof e?Object.assign({},PE[e]):e}const UE={speech_low_quality:GE(16e3,!1),speech_standard:GE(32e3,!1,18),music_standard:GE(48e3,!1),standard_stereo:GE(48e3,!0,56),high_quality:GE(48e3,!1,128),high_quality_stereo:GE(48e3,!0,192)};function xE(e){return"string"==typeof e?Object.assign({},UE[e]):e}function VE(e,t,i){Object.keys(jE).includes(e)&&(!i&&Object.keys(BE).includes(e)||(jE[e]=t))}function FE(e){return jE[e]}const jE={PROCESS_ID:"",ENCRYPT_AES:!0,AREAS:bE,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,AUDIO_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_SUBSCRIPTION: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,AV_SYNC:!0,ACCOUNT_REGISTER_RETRY_TIMEOUT:1,ACCOUNT_REGISTER_RETRY_RATIO:2,ACCOUNT_REGISTER_RETRY_TIMEOUT_MAX:6e4,ACCOUNT_REGISTER_RETRY_COUNT_MAX:1e5,AUDIO_CONTEXT:null,WEBCS_BACKUP_CONNECT_TIMEOUT:6e3,PLAYER_STATE_DEFER:2e3,SIGNAL_REQUEST_WATCH_INTERVAL:1e3,FILEPATH_LENMAX:255,DUALSTREAM_OPERATION_CHECK:!0,MEDIA_ELEMENT_EXISTS_DEPTH:3,SHIM_CANDIDATE:!1,LEAVE_MSG_TIMEOUT:2e3,STATS_FILTER:{transportId:!0,googTrackId:!0}},BE={};function GE(e,t,i){return{sampleRate:e,stereo:t,bitrate:i}}function WE(e,t,i,n,r){return{width:e,height:t,frameRate:i,bitrateMin:n,bitrateMax:r}}function HE(e,t,i,n,r){return{width:{max:e},height:{max:t},frameRate:i,bitrateMin:n,bitrateMax:r}}function KE(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}OE||(jE.WEBCS_DOMAIN=["ap-web-1-oversea.agora.io","ap-web-1-north-america.agora.io"],jE.WEBCS_DOMAIN_BACKUP_LIST=["ap-web-2-oversea.agora.io","ap-web-2-north-america.agora.io"],jE.PROXY_CS=["proxy-ap-web-oversea.agora.io","proxy-ap-web-america.agora.io"],jE.CDS_AP=["cds-ap-web-oversea.agora.io","cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],jE.ACCOUNT_REGISTER=["sua-ap-web-oversea.agora.io","sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],jE.UAP_AP=["uap-ap-web-oversea.agora.io","uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],jE.LOG_UPLOAD_SERVER="logservice-oversea.agora.io",jE.EVENT_REPORT_DOMAIN="statscollector-1-oversea.agora.io",jE.EVENT_REPORT_BACKUP_DOMAIN="statscollector-2-oversea.agora.io",jE.PROXY_SERVER_TYPE3="webrtc-cloud-proxy.agora.io",jE.AREAS=["NORTH_AMERICA","OVERSEA"]);const YE=[[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]],qE=[],JE=[];var XE=Et,zE=Ht,QE=N,ZE=function(e,t,i){var n=XE(t);n in e?zE.f(e,n,QE(0,i)):e[n]=i},$E=Un,em=wi,tm=ZE,im=h.Array,nm=Math.max,rm=function(e,t,i){for(var n=em(e),r=$E(t,n),o=$E(void 0===i?n:i,n),s=im(nm(o-r,0)),a=0;r<o;r++,a++)tm(s,a,e[r]);return s.length=a,s},om=rm,sm=Math.floor,am=function(e,t){var i=e.length,n=sm(i/2);return i<8?cm(e,t):dm(e,am(om(e,0,n),t),am(om(e,n),t),t)},cm=function(e,t){for(var i,n,r=e.length,o=1;o<r;){for(n=o,i=e[o];n&&t(e[n-1],i)>0;)e[n]=e[--n];n!==o++&&(e[n]=i)}return e},dm=function(e,t,i,n){for(var r=t.length,o=i.length,s=0,a=0;s<r||a<o;)e[s+a]=s<r&&a<o?n(t[s],i[a])<=0?t[s++]:i[a++]:s<r?t[s++]:i[a++];return e},um=am,lm=ee.match(/firefox\/(\d+)/i),hm=!!lm&&+lm[1],pm=/MSIE|Trident/.test(ee),_m=ee.match(/AppleWebKit\/(\d+)\./),Em=!!_m&&+_m[1],mm=Ii,fm=d,Sm=ve,Tm=Fe,gm=wi,Rm=No,Im=i,vm=um,Cm=Vi,ym=hm,Am=pm,Om=ae,bm=Em,wm=[],Nm=fm(wm.sort),Dm=fm(wm.push),Pm=Im((function(){wm.sort(void 0)})),Lm=Im((function(){wm.sort(null)})),km=Cm("sort"),Mm=!Im((function(){if(Om)return Om<70;if(!(ym&&ym>3)){if(Am)return!0;if(bm)return bm<603;var e,t,i,n,r="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:i=3;break;case 68:case 71:i=4;break;default:i=2}for(n=0;n<47;n++)wm.push({k:t+n,v:i})}for(wm.sort((function(e,t){return t.v-e.v})),n=0;n<wm.length;n++)t=wm[n].k.charAt(0),r.charAt(r.length-1)!==t&&(r+=t);return"DGBEFHACIJK"!==r}}));mm({target:"Array",proto:!0,forced:Pm||!Lm||!km||!Mm},{sort:function(e){void 0!==e&&Sm(e);var t=Tm(this);if(Mm)return void 0===e?Nm(t):Nm(t,e);var i,n,r=[],o=gm(t);for(n=0;n<o;n++)n in t&&Dm(r,t[n]);for(vm(r,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:Rm(t)>Rm(i)?1:-1}}(e)),i=r.length,n=0;n<i;)t[n]=r[n++];for(;n<o;)delete t[n++];return t}});var Um=Hi("Array").sort,xm=u,Vm=Um,Fm=Array.prototype,jm=function(e){var t=e.sort;return e===Fm||xm(Fm,e)&&t===Fm.sort?Vm:t};function Bm(e,t){if("boolean"!=typeof e)throw new EE(_E.INVALID_PARAMS,"Invalid ".concat(t,": The value is of the boolean type."))}function Gm(e,t,i){if(i.includes(e))return;throw new EE(_E.INVALID_PARAMS,"".concat(t," can only be set as ").concat(JSON.stringify(i)))}function Wm(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e4,r=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];if(e<i||e>n||r&&!Qm(e)){throw new EE(_E.INVALID_PARAMS,"invalid ".concat(t,": the value range is [").concat(i,", ").concat(n,"]. integer only"))}}function Hm(e,t){if("number"!=typeof e){if(!(e.min||e.max||e.ideal||e.exact)){throw new EE(_E.INVALID_PARAMS,"".concat(t," is not a valid ConstrainLong"))}void 0!==e.min&&Wm(e.min,"".concat(t,".min"),0,1/0),void 0!==e.max&&Wm(e.max,"".concat(t,".max"),1,1/0),void 0!==e.exact&&Wm(e.exact,"".concat(t,".exact"),1,1/0),void 0!==e.ideal&&Wm(e.ideal,"".concat(t,".ideal"),1,1/0)}else Wm(e,t,1,1/0)}function Km(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:255,r=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];if(null==e)throw new EE(_E.INVALID_PARAMS,"".concat(t||"param"," cannot be empty"));if(!zm(e,i,n,r))throw new EE(_E.INVALID_PARAMS,"Invalid ".concat(t||"string param",": Length of the string: [").concat(i,",").concat(n,"].").concat(r?" ASCII characters only.":""))}function Ym(e,t){if(!Array.isArray(e))throw new EE(_E.INVALID_PARAMS,"".concat(t," should be an array"))}function qm(e){if("string"!=typeof e||!/^[a-zA-Z0-9 \!\#\$\%\&\(\)\+\-\:\;\<\=\.\>\?\@\[\]\^\_\{\}\|\~\,]{1,64}$/.test(e))throw CE.error("Invalid Channel Name ".concat(e)),new EE(_E.INVALID_PARAMS,"The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _, {, }, |, ~, ,")}function Jm(e){if(!(t=e,"number"==typeof t&&Math.floor(t)===t&&0<=t&&t<=4294967295||zm(e,1,255)))throw CE.error("Invalid UID ".concat(e," ").concat(typeof e)),new EE(_E.INVALID_PARAMS,"[String uid] Length of the string: [1,255]. ASCII characters only. [Number uid] The value range is [0,10000]");var t;"string"==typeof e&&CE.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 Xm(e){return null==e}function zm(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:255,n=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return"string"==typeof e&&e.length<=i&&e.length>=t&&(!n||Zm(e))}function Qm(e){return"number"==typeof e&&e%1==0}function Zm(e){if("string"!=typeof e)return!1;for(let t=0;t<e.length;t+=1){const i=e.charCodeAt(t);if(i<0||i>255)return!1}return!0}let $m,ef,tf;!function(e){e.FREE="free",e.UPLOADING="uploading"}($m||($m={})),function(e){e[e.MISC=0]="MISC",e[e.INTERNAL_EVENT=1]="INTERNAL_EVENT",e[e.PUBLIC_EVENT=2]="PUBLIC_EVENT",e[e.WEB_EVENT=3]="WEB_EVENT",e[e.INTERNAL_API=4]="INTERNAL_API",e[e.WEB_API=5]="WEB_API",e[e.PUBLIC_API=6]="PUBLIC_API"}(ef||(ef={})),function(e){e.NONE="none",e.INIT="init",e.CANPLAY="canplay",e.PLAYING="playing",e.PAUSED="paused",e.SUSPEND="suspend",e.STALLED="stalled",e.WAITING="waiting",e.ERROR="error",e.DESTROYED="destroyed",e.ABORT="abort",e.ENDED="ended",e.EMPTIED="emptied",e.LOADEDDATA="loadeddata"}(tf||(tf={}));const nf={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 rf(e){return Km(e.reportId,"params.reportId",0,100,!1),Km(e.category,"params.category",0,100,!1),Km(e.event,"params.event",0,100,!1),Km(e.label,"params.label",0,100,!1),Wm(e.value,"params.value",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,!1),!0}const of={sid:"",lts:0,success:null,cname:null,uid:null,peer:null,cid:null,elapse:null,extend:null,vid:0};let sf,af,cf,df,uf,lf,hf,pf,_f,Ef,mf,ff,Sf,Tf,gf,Rf,If,vf,Cf,yf,Af,Of,bf,wf;function Nf(e){return Wm(e.timeout,"config.timeout",0,1e5),Wm(e.timeoutFactor,"config.timeoutFactor",0,100,!1),Wm(e.maxRetryCount,"config.maxRetryConfig",0,1/0),Wm(e.maxRetryTimeout,"config.maxRetryTimeout",0,1/0),!0}function Df(e){return Gm(e.codec,"config.codec",["vp8","vp9","av1","h264"]),Gm(e.mode,"config.mode",["rtc","live"]),void 0!==e.audioCodec&&Gm(e.audioCodec,"config.audioCodec",["opus","pcmu","pcma","g722"]),void 0!==e.proxyServer&&Km(e.proxyServer,"config.proxyServer",1,1e4),void 0!==e.turnServer&&Lf(e.turnServer),void 0!==e.httpRetryConfig&&Nf(e.httpRetryConfig),void 0!==e.websocketRetryConfig&&Nf(e.websocketRetryConfig),!0}function Pf(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 Lf(e){return Km(e.turnServerURL,"turnServerURL"),Km(e.username,"username"),Km(e.password,"password"),e.udpport&&Wm(e.udpport,"udpport",1,99999,!0),e.forceturn&&Bm(e.forceturn,"forceturn"),e.security&&Bm(e.security,"security"),e.tcpport&&Wm(e.tcpport,"tcpport",1,99999,!0),!0}function kf(e){return void 0!==e.level&&Gm(e.level,"level",[1,2,3]),!0}!function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe",e.WS_COMPRESSOR_INIT="ws_compressor_init",e.SESSION_INIT="session_init",e.JOIN_CHOOSE_SERVER="join_choose_server",e.REQ_USER_ACCOUNT="req_user_account",e.JOIN_GATEWAY="join_gateway",e.REJOIN_GATEWAY="rejoin_gateway",e.STREAM_SWITCH="stream_switch",e.REQUEST_PROXY_WORKER_MANAGER="request_proxy_worker_manager",e.REQUEST_PROXY_APPCENTER="request_proxy_appcenter",e.FIRST_VIDEO_RECEIVED="first_video_received",e.FIRST_AUDIO_RECEIVED="first_audio_received",e.FIRST_VIDEO_DECODE="first_video_decode",e.FIRST_AUDIO_DECODE="first_audio_decode",e.ON_ADD_AUDIO_STREAM="on_add_audio_stream",e.ON_ADD_VIDEO_STREAM="on_add_video_stream",e.ON_UPDATE_STREAM="on_update_stream",e.ON_REMOVE_STREAM="on_remove_stream",e.USER_ANALYTICS="req_user_analytics"}(sf||(sf={})),function(e){e.SESSION="io.agora.pb.Wrtc.Session",e.JOIN_CHOOSE_SERVER="io.agora.pb.Wrtc.JoinChooseServer",e.REQ_USER_ACCOUNT="io.agora.pb.Wrtc.ReqUserAccount",e.JOIN_GATEWAY="io.agora.pb.Wrtc.JoinGateway",e.RE_JOIN_GATEWAY="io.agora.pb.Wrtc.ReJoinGateway",e.PUBLISH="io.agora.pb.Wrtc.Publish",e.SUBSCRIBE="io.agora.pb.Wrtc.Subscribe",e.WS_COMPRESSOR_INIT="io.agora.pb.Wrtc.WsCompressorInit",e.STREAM_SWITCH="io.agora.pb.Wrtc.StreamSwitch",e.AUDIO_SENDING_STOPPED="io.agora.pb.Wrtc.AudioSendingStopped",e.VIDEO_SENDING_STOPPED="io.agora.pb.Wrtc.VideoSendingStopped",e.REQUEST_PROXY_APPCENTER="io.agora.pb.Wrtc.RequestProxyAppCenter",e.REQUEST_PROXY_WORKER_MANAGER="io.agora.pb.Wrtc.RequestProxyWorkerManager",e.API_INVOKE="io.agora.pb.Wrtc.ApiInvoke",e.FIRST_VIDEO_RECEIVED="io.agora.pb.Wrtc.FirstVideoReceived",e.FIRST_AUDIO_RECEIVED="io.agora.pb.Wrtc.FirstAudioReceived",e.FIRST_VIDEO_DECODE="io.agora.pb.Wrtc.FirstVideoDecode",e.FIRST_AUDIO_DECODE="io.agora.pb.Wrtc.FirstAudioDecode",e.ON_ADD_AUDIO_STREAM="io.agora.pb.Wrtc.OnAddAudioStream",e.ON_ADD_VIDEO_STREAM="io.agora.pb.Wrtc.OnAddVideoStream",e.ON_UPDATE_STREAM="io.agora.pb.Wrtc.OnUpdateStream",e.ON_REMOVE_STREAM="io.agora.pb.Wrtc.OnRemoveStream",e.JOIN_CHANNEL_TIMEOUT="io.agora.pb.Wrtc.JoinChannelTimeout",e.PEER_PUBLISH_STATUS="io.agora.pb.Wrtc.PeerPublishStatus",e.WORKER_EVENT="io.agora.pb.Wrtc.WorkerEvent",e.AP_WORKER_EVENT="io.agora.pb.Wrtc.APWorkerEvent",e.JOIN_WEB_PROXY_AP="io.agora.pb.Wrtc.JoinWebProxyAP",e.WEBSOCKET_QUIT="io.agora.pb.Wrtc.WebSocketQuit",e.USER_ANALYTICS="io.agora.pb.Wrtc.UserAnalytics",e.AUTOPLAY_FAILED="io.agora.pb.Wrtc.AutoplayFailed"}(af||(af={})),function(e){e[e.WORKER_EVENT=156]="WORKER_EVENT",e[e.AP_WORKER_EVENT=160]="AP_WORKER_EVENT"}(cf||(cf={})),function(e){e[e.SESSION=26]="SESSION",e[e.JOIN_CHOOSE_SERVER=27]="JOIN_CHOOSE_SERVER",e[e.REQ_USER_ACCOUNT=196]="REQ_USER_ACCOUNT",e[e.JOIN_GATEWAY=28]="JOIN_GATEWAY",e[e.PUBLISH=30]="PUBLISH",e[e.SUBSCRIBE=29]="SUBSCRIBE",e[e.WS_COMPRESSOR_INIT=9430]="WS_COMPRESSOR_INIT",e[e.STREAM_SWITCH=32]="STREAM_SWITCH",e[e.AUDIO_SENDING_STOPPED=33]="AUDIO_SENDING_STOPPED",e[e.VIDEO_SENDING_STOPPED=34]="VIDEO_SENDING_STOPPED",e[e.REQUEST_PROXY_APPCENTER=35]="REQUEST_PROXY_APPCENTER",e[e.REQUEST_PROXY_WORKER_MANAGER=36]="REQUEST_PROXY_WORKER_MANAGER",e[e.API_INVOKE=41]="API_INVOKE",e[e.FIRST_VIDEO_RECEIVED=348]="FIRST_VIDEO_RECEIVED",e[e.FIRST_AUDIO_RECEIVED=349]="FIRST_AUDIO_RECEIVED",e[e.FIRST_VIDEO_DECODE=350]="FIRST_VIDEO_DECODE",e[e.FIRST_AUDIO_DECODE=351]="FIRST_AUDIO_DECODE",e[e.ON_ADD_AUDIO_STREAM=352]="ON_ADD_AUDIO_STREAM",e[e.ON_ADD_VIDEO_STREAM=353]="ON_ADD_VIDEO_STREAM",e[e.ON_UPDATE_STREAM=356]="ON_UPDATE_STREAM",e[e.ON_REMOVE_STREAM=355]="ON_REMOVE_STREAM",e[e.JOIN_CHANNEL_TIMEOUT=407]="JOIN_CHANNEL_TIMEOUT",e[e.PEER_PUBLISH_STATUS=408]="PEER_PUBLISH_STATUS",e[e.WORKER_EVENT=156]="WORKER_EVENT",e[e.AP_WORKER_EVENT=160]="AP_WORKER_EVENT",e[e.JOIN_WEB_PROXY_AP=700]="JOIN_WEB_PROXY_AP",e[e.WEBSOCKET_QUIT=671]="WEBSOCKET_QUIT",e[e.USER_ANALYTICS=1e4]="USER_ANALYTICS",e[e.AUTOPLAY_FAILED=9178]="AUTOPLAY_FAILED"}(df||(df={})),function(e){e.CREATE_CLIENT="createClient",e.CHECK_SYSTEM_REQUIREMENTS="checkSystemRequirements",e.SET_AREA="setArea",e.CHECK_VIDEO_TRACK_IS_ACTIVE="checkVideoTrackIsActive",e.CHECK_AUDIO_TRACK_IS_ACTIVE="checkAudioTrackIsActive",e.CREATE_MIC_AUDIO_TRACK="createMicrophoneAudioTrack",e.CREATE_CUSTOM_AUDIO_TRACK="createCustomAudioTrack",e.CREATE_BUFFER_AUDIO_TRACK="createBufferSourceAudioTrack",e.CREATE_CAM_VIDEO_TRACK="createCameraVideoTrack",e.CREATE_CUSTOM_VIDEO_TRACK="createCustomVideoTrack",e.CREATE_MIC_AND_CAM_TRACKS="createMicrophoneAndCameraTracks",e.CREATE_SCREEN_VIDEO_TRACK="createScreenVideoTrack",e.SET_ENCRYPTION_CONFIG="Client.setEncryptionConfig",e.START_PROXY_SERVER="Client.startProxyServer",e.STOP_PROXY_SERVER="Client.stopProxyServer",e.SET_PROXY_SERVER="Client.setProxyServer",e.SET_TURN_SERVER="Client.setTurnServer",e.SET_CLIENT_ROLE="Client.setClientRole",e.SET_LOW_STREAM_PARAMETER="Client.setLowStreamParameter",e.ENABLE_DUAL_STREAM="Client.enableDualStream",e.DISABLE_DUAL_STREAM="Client.disableDualStream",e.JOIN="Client.join",e.LEAVE="Client.leave",e.PUBLISH="Client.publish",e.UNPUBLISH="Client.unpublish",e.SUBSCRIBE="Client.subscribe",e.MASS_SUBSCRIBE="Client.massSubscribe",e.MASS_UNSUBSCRIBE="Client.massUnsubscribe",e.UNSUBSCRIBE="Client.unsubscribe",e.RENEW_TOKEN="Client.renewToken",e.SET_REMOTE_VIDEO_STREAM_TYPE="Client.setRemoteVideoStreamType",e.SET_STREAM_FALLBACK_OPTION="Client.setStreamFallbackOption",e.ENABLE_AUDIO_VOLUME_INDICATOR="Client.enableAudioVolumeIndicator",e.SEND_CUSTOM_REPORT_MESSAGE="Client.sendCustomReportMessage",e.INSPECT_VIDEO_CONTENT="Client.inspectVideoContent",e.STOP_INSPECT_VIDEO_CONTENT="Client.stopInspectVideoContent",e.JOIN_FALLBACK_TO_PROXY="Client._joinFallbackToProxy",e.DATACHANNEL_FAILBACK="Client._datachannelFailback",e.ON_LIVE_STREAM_WARNING="Client.onLiveStreamWarning",e.ON_LIVE_STREAM_ERROR="Client.onLiveStreamingError",e.START_LIVE_STREAMING="Client.startLiveStreaming",e.SET_LIVE_TRANSCODING="Client.setLiveTranscoding",e.STOP_LIVE_STREAMING="Client.stopLiveStreaming",e.ADD_INJECT_STREAM_URL="Client.addInjectStreamUrl",e.REMOVE_INJECT_STREAM_URL="Client.removeInjectStreamUrl",e.START_CHANNEL_MEDIA_RELAY="Client.startChannelMediaRelay",e.UPDATE_CHANNEL_MEDIA_RELAY="Client.updateChannelMediaRelay",e.STOP_CHANNEL_MEDIA_RELAY="Client.stopChannelMediaRelay",e.REQUEST_CONFIG_DISTRIBUTE="_config-distribute-request",e.SET_CONFIG_DISTRIBUTE="_configDistribute",e.LOCAL_TRACK_SET_MUTED="LocalTrack.setMute",e.LOCAL_AUDIO_TRACK_PLAY="LocalAudioTrack.play",e.LOCAL_AUDIO_TRACK_PLAY_IN_ELEMENT="LocalAudioTrack.playInElement",e.LOCAL_AUDIO_TRACK_STOP="LocalAudioTrack.stop",e.LOCAL_AUDIO_TRACK_SET_VOLUME="LocalAudioTrack.setVolume",e.MIC_AUDIO_TRACK_SET_DEVICE="MicrophoneAudioTrack.setDevice",e.BUFFER_AUDIO_TRACK_START="BufferSourceAudioTrack.startProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_STOP="BufferSourceAudioTrack.stopProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_PAUSE="BufferSourceAudioTrack.pauseProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_RESUME="BufferSourceAudioTrack.resumeProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_SEEK="BufferSourceAudioTrack.seekAudioBuffer",e.LOCAL_VIDEO_TRACK_PLAY="LocalVideoTrack.play",e.LOCAL_VIDEO_TRACK_STOP="LocalVideoTrack.stop",e.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE="LocalVideoTrack.getVideoElementVisibleStatus",e.LOCAL_VIDEO_TRACK_BEAUTY="LocalVideoTrack.setBeautyEffect",e.CAM_VIDEO_TRACK_SET_DEVICE="CameraVideoTrack.setDevice",e.CAM_VIDEO_TRACK_SET_ENCODER_CONFIG="CameraVideoTrack.setEncoderConfiguration",e.REMOTE_VIDEO_TRACK_PLAY="RemoteVideoTrack.play",e.REMOTE_VIDEO_TRACK_STOP="RemoteVideoTrack.stop",e.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE="RemoteVideoTrack.getVideoElementVisibleStatus",e.REMOTE_AUDIO_TRACK_PLAY="RemoteAudioTrack.play",e.REMOTE_AUDIO_TRACK_STOP="RemoteAudioTrack.stop",e.REMOTE_AUDIO_SET_VOLUME="RemoteAudioTrack.setVolume",e.REMOTE_AUDIO_SET_OUTPUT_DEVICE="RemoteAudioTrack.setOutputDevice",e.GET_MEDIA_STREAM_TRACK="Track.getMediaStreamTrack",e.STREAM_TYPE_CHANGE="streamTypeChange",e.CONNECTION_STATE_CHANGE="connectionStateChange",e.LOAD_CONFIG_FROM_LOCALSTORAGE="loadConfigFromLocalStorage"}(uf||(uf={})),function(e){e.TRACER="tracer"}(lf||(lf={})),function(e){e.IDLE="IDLE",e.INITING="INITING",e.INITEND="INITEND"}(hf||(hf={})),function(e){e.STATE_CHANGE="state_change",e.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",e.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",e.CAMERA_DEVICE_CHANGED="cameraDeviceChanged"}(pf||(pf={})),function(e){e[e.ACCESS_POINT=101]="ACCESS_POINT",e[e.UNILBS=201]="UNILBS",e[e.STRING_UID_ALLOCATOR=901]="STRING_UID_ALLOCATOR"}(_f||(_f={})),function(e){e[e.IIIEGAL_APPID=1]="IIIEGAL_APPID",e[e.IIIEGAL_UID=2]="IIIEGAL_UID",e[e.INTERNAL_ERROR=3]="INTERNAL_ERROR"}(Ef||(Ef={})),function(e){e[e.INVALID_VENDOR_KEY=5]="INVALID_VENDOR_KEY",e[e.INVALID_CHANNEL_NAME=7]="INVALID_CHANNEL_NAME",e[e.INTERNAL_ERROR=8]="INTERNAL_ERROR",e[e.NO_AUTHORIZED=9]="NO_AUTHORIZED",e[e.DYNAMIC_KEY_TIMEOUT=10]="DYNAMIC_KEY_TIMEOUT",e[e.NO_ACTIVE_STATUS=11]="NO_ACTIVE_STATUS",e[e.DYNAMIC_KEY_EXPIRED=13]="DYNAMIC_KEY_EXPIRED",e[e.STATIC_USE_DYNAMIC_KEY=14]="STATIC_USE_DYNAMIC_KEY",e[e.DYNAMIC_USE_STATIC_KEY=15]="DYNAMIC_USE_STATIC_KEY",e[e.USER_OVERLOAD=16]="USER_OVERLOAD",e[e.FORBIDDEN_REGION=18]="FORBIDDEN_REGION",e[e.CANNOT_MEET_AREA_DEMAND=19]="CANNOT_MEET_AREA_DEMAND"}(mf||(mf={})),function(e){e[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"}(ff||(ff={})),function(e){e[e.K_TIMESTAMP_EXPIRED=2]="K_TIMESTAMP_EXPIRED",e[e.K_CHANNEL_PERMISSION_INVALID=3]="K_CHANNEL_PERMISSION_INVALID",e[e.K_CERTIFICATE_INVALID=4]="K_CERTIFICATE_INVALID",e[e.K_CHANNEL_NAME_EMPTY=5]="K_CHANNEL_NAME_EMPTY",e[e.K_CHANNEL_NOT_FOUND=6]="K_CHANNEL_NOT_FOUND",e[e.K_TICKET_INVALID=7]="K_TICKET_INVALID",e[e.K_CHANNEL_CONFLICTED=8]="K_CHANNEL_CONFLICTED",e[e.K_SERVICE_NOT_READY=9]="K_SERVICE_NOT_READY",e[e.K_SERVICE_TOO_HEAVY=10]="K_SERVICE_TOO_HEAVY",e[e.K_UID_BANNED=14]="K_UID_BANNED",e[e.K_IP_BANNED=15]="K_IP_BANNED",e[e.K_CHANNEL_BANNED=16]="K_CHANNEL_BANNED",e[e.WARN_NO_AVAILABLE_CHANNEL=103]="WARN_NO_AVAILABLE_CHANNEL",e[e.WARN_LOOKUP_CHANNEL_TIMEOUT=104]="WARN_LOOKUP_CHANNEL_TIMEOUT",e[e.WARN_LOOKUP_CHANNEL_REJECTED=105]="WARN_LOOKUP_CHANNEL_REJECTED",e[e.WARN_OPEN_CHANNEL_TIMEOUT=106]="WARN_OPEN_CHANNEL_TIMEOUT",e[e.WARN_OPEN_CHANNEL_REJECTED=107]="WARN_OPEN_CHANNEL_REJECTED",e[e.WARN_REQUEST_DEFERRED=108]="WARN_REQUEST_DEFERRED",e[e.ERR_DYNAMIC_KEY_TIMEOUT=109]="ERR_DYNAMIC_KEY_TIMEOUT",e[e.ERR_NO_AUTHORIZED=110]="ERR_NO_AUTHORIZED",e[e.ERR_VOM_SERVICE_UNAVAILABLE=111]="ERR_VOM_SERVICE_UNAVAILABLE",e[e.ERR_NO_CHANNEL_AVAILABLE_CODE=112]="ERR_NO_CHANNEL_AVAILABLE_CODE",e[e.ERR_MASTER_VOCS_UNAVAILABLE=114]="ERR_MASTER_VOCS_UNAVAILABLE",e[e.ERR_INTERNAL_ERROR=115]="ERR_INTERNAL_ERROR",e[e.ERR_NO_ACTIVE_STATUS=116]="ERR_NO_ACTIVE_STATUS",e[e.ERR_INVALID_UID=117]="ERR_INVALID_UID",e[e.ERR_DYNAMIC_KEY_EXPIRED=118]="ERR_DYNAMIC_KEY_EXPIRED",e[e.ERR_STATIC_USE_DYANMIC_KE=119]="ERR_STATIC_USE_DYANMIC_KE",e[e.ERR_DYNAMIC_USE_STATIC_KE=120]="ERR_DYNAMIC_USE_STATIC_KE",e[e.ERR_NO_VOCS_AVAILABLE=2e3]="ERR_NO_VOCS_AVAILABLE",e[e.ERR_NO_VOS_AVAILABLE=2001]="ERR_NO_VOS_AVAILABLE",e[e.ERR_JOIN_CHANNEL_TIMEOUT=2002]="ERR_JOIN_CHANNEL_TIMEOUT",e[e.ERR_REPEAT_JOIN_CHANNEL=2003]="ERR_REPEAT_JOIN_CHANNEL",e[e.ERR_JOIN_BY_MULTI_IP=2004]="ERR_JOIN_BY_MULTI_IP",e[e.ERR_NOT_JOINED=2011]="ERR_NOT_JOINED",e[e.ERR_REPEAT_JOIN_REQUEST=2012]="ERR_REPEAT_JOIN_REQUEST",e[e.ERR_INVALID_VENDOR_KEY=2013]="ERR_INVALID_VENDOR_KEY",e[e.ERR_INVALID_CHANNEL_NAME=2014]="ERR_INVALID_CHANNEL_NAME",e[e.ERR_INVALID_STRINGUID=2015]="ERR_INVALID_STRINGUID",e[e.ERR_TOO_MANY_USERS=2016]="ERR_TOO_MANY_USERS",e[e.ERR_SET_CLIENT_ROLE_TIMEOUT=2017]="ERR_SET_CLIENT_ROLE_TIMEOUT",e[e.ERR_SET_CLIENT_ROLE_NO_PERMISSION=2018]="ERR_SET_CLIENT_ROLE_NO_PERMISSION",e[e.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE=2019]="ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",e[e.ERR_PUBLISH_REQUEST_INVALID=2020]="ERR_PUBLISH_REQUEST_INVALID",e[e.ERR_SUBSCRIBE_REQUEST_INVALID=2021]="ERR_SUBSCRIBE_REQUEST_INVALID",e[e.ERR_NOT_SUPPORTED_MESSAGE=2022]="ERR_NOT_SUPPORTED_MESSAGE",e[e.ERR_ILLEAGAL_PLUGIN=2023]="ERR_ILLEAGAL_PLUGIN",e[e.ERR_REJOIN_TOKEN_INVALID=2024]="ERR_REJOIN_TOKEN_INVALID",e[e.ERR_REJOIN_USER_NOT_JOINED=2025]="ERR_REJOIN_USER_NOT_JOINED",e[e.ERR_INVALID_OPTIONAL_INFO=2027]="ERR_INVALID_OPTIONAL_INFO",e[e.ILLEGAL_AES_PASSWORD=2028]="ILLEGAL_AES_PASSWORD",e[e.ILLEGAL_CLIENT_ROLE_LEVEL=2029]="ILLEGAL_CLIENT_ROLE_LEVEL",e[e.ERR_TOO_MANY_BROADCASTERS=2031]="ERR_TOO_MANY_BROADCASTERS",e[e.ERR_TOO_MANY_SUBSCRIBERS=2032]="ERR_TOO_MANY_SUBSCRIBERS",e[e.ERR_LICENSE_MISSING=32769]="ERR_LICENSE_MISSING",e[e.ERR_LICENSE_EXPIRED=32771]="ERR_LICENSE_EXPIRED",e[e.ERR_LICENSE_MINUTES_EXCEEDED=32773]="ERR_LICENSE_MINUTES_EXCEEDED",e[e.ERR_LICENSE_PERIOD_INVALID=32774]="ERR_LICENSE_PERIOD_INVALID",e[e.ERR_LICENSE_MULTIPLE_SDK_SERVICE=32778]="ERR_LICENSE_MULTIPLE_SDK_SERVICE",e[e.ERR_LICENSE_ILLEGAL=32783]="ERR_LICENSE_ILLEGAL",e[e.ERR_TEST_RECOVER=9e3]="ERR_TEST_RECOVER",e[e.ERR_TEST_TRYNEXT=9001]="ERR_TEST_TRYNEXT",e[e.ERR_TEST_RETRY=9002]="ERR_TEST_RETRY"}(Sf||(Sf={})),function(e){e[e.AUDIENCE_LEVEL_LOW_LATENCY=1]="AUDIENCE_LEVEL_LOW_LATENCY",e[e.AUDIENCE_LEVEL_ULTRA_LOW_LATENCY=2]="AUDIENCE_LEVEL_ULTRA_LOW_LATENCY",e[e.AUDIENCE_LEVEL_SYNC_LATENCY=3]="AUDIENCE_LEVEL_SYNC_LATENCY"}(Tf||(Tf={})),function(e){e.LEAVE="LEAVE",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.UID_BANNED="UID_BANNED",e.IP_BANNED="IP_BANNED",e.CHANNEL_BANNED="CHANNEL_BANNED",e.FALLBACK="FALLBACK",e.LICENSE_MISSING="LICENSE_MISSING",e.LICENSE_EXPIRED="LICENSE_EXPIRED",e.LICENSE_MINUTES_EXCEEDED="LICENSE_MINUTES_EXCEEDED",e.LICENSE_PERIOD_INVALID="LICENSE_PERIOD_INVALID",e.LICENSE_MULTIPLE_SDK_SERVICE="LICENSE_MULTIPLE_SDK_SERVICE",e.LICENSE_ILLEGAL="LICENSE_ILLEGAL"}(gf||(gf={})),function(e){e.CONNECTION_STATE_CHANGE="connection-state-change",e.MEDIA_RECONNECT_START="media-reconnect-start",e.MEDIA_RECONNECT_END="media-reconnect-end",e.IS_USING_CLOUD_PROXY="is-using-cloud-proxy",e.USER_JOINED="user-joined",e.USER_LEAVED="user-left",e.USER_PUBLISHED="user-published",e.USER_UNPUBLISHED="user-unpublished",e.USER_INFO_UPDATED="user-info-updated",e.CLIENT_BANNED="client-banned",e.CHANNEL_MEDIA_RELAY_STATE="channel-media-relay-state",e.CHANNEL_MEDIA_RELAY_EVENT="channel-media-relay-event",e.VOLUME_INDICATOR="volume-indicator",e.CRYPT_ERROR="crypt-error",e.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="token-privilege-will-expire",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="token-privilege-did-expire",e.NETWORK_QUALITY="network-quality",e.STREAM_TYPE_CHANGED="stream-type-changed",e.STREAM_FALLBACK="stream-fallback",e.RECEIVE_METADATA="receive-metadata",e.STREAM_MESSAGE="stream-message",e.LIVE_STREAMING_ERROR="live-streaming-error",e.LIVE_STREAMING_WARNING="live-streaming-warning",e.INJECT_STREAM_STATUS="stream-inject-status",e.EXCEPTION="exception",e.ERROR="error",e.P2P_LOST="p2p_lost",e.JOIN_FALLBACK_TO_PROXY="join-fallback-to-proxy",e.CHANNEL_FALLBACK_TO_WEBSOCKET="channel-fallback-to-websocket",e.MEDIA_CONNECTION_TYPE_CHANGE="media-connection-type-change",e.PUBLISHED_USER_LIST="published-user-list",e.CONTENT_INSPECT_CONNECTION_STATE_CHANGE="content-inspect-connection-state-change",e.CONTENT_INSPECT_ERROR="content-inspect-error",e.CONTENT_INSPECT_RESULT="content-inspect-result"}(Rf||(Rf={})),function(e){e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.MULTI_IP="MULTI_IP",e.TIMEOUT="TIMEOUT",e.OFFLINE="OFFLINE",e.LEAVE="LEAVE",e.P2P_FAILED="P2P_FAILED",e.FALLBACK="FALLBACK"}(If||(If={})),function(e){e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.CLOSED="closed"}(vf||(vf={})),function(e){e.WS_CONNECTED="ws_connected",e.WS_RECONNECTING="ws_reconnecting",e.WS_CLOSED="ws_closed",e.WS_RECONNECT_WAITTING_FINISH="ws_reconnect_waitting_finish",e.WS_RECONNECT_CREATE_CONNECTION="ws_reconnect_create_connection",e.ON_BINARY_DATA="on_binary_data",e.REQUEST_RECOVER="request_recover",e.REQUEST_JOIN_INFO="request_join_info",e.REQUEST_REJOIN_INFO="req_rejoin_info",e.IS_P2P_DISCONNECTED="is_p2p_dis",e.DISCONNECT_P2P="dis_p2p",e.ABORT_P2P_EXECUTION="abort_p2p_execution",e.NEED_RENEW_SESSION="need-sid",e.REPORT_JOIN_GATEWAY="report_join_gateway",e.REQUEST_TIMEOUT="request_timeout",e.REQUEST_SUCCESS="request_success",e.JOIN_RESPONSE="join_response",e.DATACHANNEL_PRECONNECT="datachannel_preconnect",e.DATACHANNEL_CONNECTING="datachannel_connecting",e.DATACHANNEL_FAILBACK="datachannel_failback"}(Cf||(Cf={})),function(e){e.PING="ping",e.PING_BACK="ping_back",e.JOIN="join_v3",e.REJOIN="rejoin_v3",e.LEAVE="leave",e.SET_CLIENT_ROLE="set_client_role",e.PUBLISH="publish",e.UNPUBLISH="unpublish",e.SUBSCRIBE="subscribe",e.SUBSCRIBE_STREAMS="subscribe_streams",e.UNSUBSCRIBE="unsubscribe",e.UNSUBSCRIBE_STREAMS="unsubscribe_streams",e.SUBSCRIBE_CHANGE="subscribe_change",e.TRAFFIC_STATS="traffic_stats",e.RENEW_TOKEN="renew_token",e.SWITCH_VIDEO_STREAM="switch_video_stream",e.DEFAULT_VIDEO_STREAM="default_video_stream",e.SET_FALLBACK_OPTION="set_fallback_option",e.GATEWAY_INFO="gateway_info",e.CONTROL="control",e.SEND_METADATA="send_metadata",e.DATA_STREAM="data_stream",e.PICK_SVC_LAYER="pick_svc_layer",e.RESTART_ICE="restart_ice",e.CONNECT_PC="connect_pc",e.SET_VIDEO_PROFILE="set_video_profile",e.SET_PARAMETER="set_parameter"}(yf||(yf={})),function(e){e.PUBLISH_STATS="publish_stats",e.PUBLISH_RELATED_STATS="publish_related_stats",e.SUBSCRIBE_STATS="subscribe_stats",e.SUBSCRIBE_RELATED_STATS="subscribe_related_stats",e.WS_INFLATE_DATA_LENGTH="ws_inflate_data_length",e.DENOISER_STATS="denoiser_stats",e.TRANSPORT_STATS="transport_stats",e.EXTENSION_USAGE_STATS="extension_usage_stats"}(Af||(Af={})),function(e){e.ON_USER_ONLINE="on_user_online",e.ON_USER_OFFLINE="on_user_offline",e.ON_STREAM_FALLBACK_UPDATE="on_stream_fallback_update",e.ON_PUBLISH_STREAM="on_publish_stream",e.ON_UPLINK_STATS="on_uplink_stats",e.ON_P2P_LOST="on_p2p_lost",e.ON_REMOVE_STREAM="on_remove_stream",e.ON_ADD_AUDIO_STREAM="on_add_audio_stream",e.ON_ADD_VIDEO_STREAM="on_add_video_stream",e.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="on_token_privilege_will_expire",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="on_token_privilege_did_expire",e.ON_USER_BANNED="on_user_banned",e.ON_USER_LICENSE_BANNED="on_user_license_banned",e.ON_NOTIFICATION="on_notification",e.ON_CRYPT_ERROR="on_crypt_error",e.MUTE_AUDIO="mute_audio",e.MUTE_VIDEO="mute_video",e.UNMUTE_AUDIO="unmute_audio",e.UNMUTE_VIDEO="unmute_video",e.ON_P2P_OK="on_p2p_ok",e.RECEIVE_METADATA="receive_metadata",e.ON_DATA_STREAM="on_data_stream",e.ENABLE_LOCAL_VIDEO="enable_local_video",e.DISABLE_LOCAL_VIDEO="disable_local_video",e.ENABLE_LOCAL_AUDIO="enable_local_audio",e.DISABLE_LOCAL_AUDIO="disable_local_audio",e.ON_PUBLISHED_USER_LIST="on_published_user_list"}(Of||(Of={})),function(e){e.CONNECTION_STATE_CHANGE="CONNECTION_STATE_CHANGE",e.NEED_ANSWER="NEED_ANSWER",e.NEED_RENEGOTIATE="NEED_RENEGOTIATE",e.P2P_LOST="P2P_LOST",e.GATEWAY_P2P_LOST="GATEWAY_P2P_LOST",e.NEED_UNPUB="NEED_UNPUB",e.NEED_UNSUB="NEED_UNSUB",e.NEED_UPLOAD="NEED_UPLOAD",e.NEED_CONTROL="NEED_CONTROL",e.START_RECONNECT="START_RECONNECT",e.END_RECONNECT="END_RECONNECT",e.NEED_SIGNAL_RTT="NEED_SIGNAL_RTT"}(bf||(bf={})),function(e){e.AUDIO_SOURCE_STATE_CHANGE="audio_source_state_change",e.RECEIVE_TRACK_BUFFER="receive_track_buffer",e.ON_AUDIO_BUFFER="on_audio_buffer",e.UPDATE_SOURCE="update_source"}(wf||(wf={}));const Mf={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,currentPacketLossRate:0},Uf={sendBytes:0,sendBitrate:0,sendPackets:0,sendPacketsLost:0,sendResolutionHeight:0,sendResolutionWidth:0,captureResolutionHeight:0,captureResolutionWidth:0,targetSendBitrate:0,totalDuration:0,totalFreezeTime:0,currentPacketLossRate:0},xf={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},Vf={uplinkNetworkQuality:0,downlinkNetworkQuality:0},Ff={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};let jf,Bf,Gf;!function(e){e.CONNECTED="websocket:connected",e.RECONNECTING="websocket:reconnecting",e.WILL_RECONNECT="websocket:will_reconnect",e.CLOSED="websocket:closed",e.FAILED="websocket:failed",e.ON_MESSAGE="websocket:on_message",e.REQUEST_NEW_URLS="websocket:request_new_urls",e.RECONNECT_WAITTING_FINISH="websocket:reconnect_waitting_finish",e.RECONNECT_CREATE_CONNECTION="websocket:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire"}(jf||(jf={})),function(e){e.TRANSCODE="mix_streaming",e.RAW="raw_streaming",e.INJECT="inject_streaming"}(Bf||(Bf={})),function(e){e[e.INJECT_STREAM_STATUS_START_SUCCESS=0]="INJECT_STREAM_STATUS_START_SUCCESS",e[e.INJECT_STREAM_STATUS_START_ALREADY_EXISTS=1]="INJECT_STREAM_STATUS_START_ALREADY_EXISTS",e[e.INJECT_STREAM_STATUS_START_UNAUTHORIZED=2]="INJECT_STREAM_STATUS_START_UNAUTHORIZED",e[e.INJECT_STREAM_STATUS_START_TIMEOUT=3]="INJECT_STREAM_STATUS_START_TIMEOUT",e[e.INJECT_STREAM_STATUS_START_FAILED=4]="INJECT_STREAM_STATUS_START_FAILED",e[e.INJECT_STREAM_STATUS_STOP_SUCCESS=5]="INJECT_STREAM_STATUS_STOP_SUCCESS",e[e.INJECT_STREAM_STATUS_STOP_NOT_FOUND=6]="INJECT_STREAM_STATUS_STOP_NOT_FOUND",e[e.INJECT_STREAM_STATUS_STOP_UNAUTHORIZED=7]="INJECT_STREAM_STATUS_STOP_UNAUTHORIZED",e[e.INJECT_STREAM_STATUS_STOP_TIMEOUT=8]="INJECT_STREAM_STATUS_STOP_TIMEOUT",e[e.INJECT_STREAM_STATUS_STOP_FAILED=9]="INJECT_STREAM_STATUS_STOP_FAILED",e[e.INJECT_STREAM_STATUS_BROKEN=10]="INJECT_STREAM_STATUS_BROKEN"}(Gf||(Gf={}));const Wf={alpha:1,height:640,width:360,x:0,y:0,zOrder:0,audioChannel:0},Hf={x:0,y:0,width:160,height:160,zOrder:255,alpha:1};function Kf(e,t){Km(e.url,"".concat(t,".url"),1,1e3,!1),Xm(e.x)||Wm(e.x,"".concat(t,".x"),0,1e4),Xm(e.y)||Wm(e.y,"".concat(t,".y"),0,1e4),Xm(e.width)||Wm(e.width,"".concat(t,".width"),0,1e4),Xm(e.height)||Wm(e.height,"".concat(t,".height"),0,1e4),Xm(e.zOrder)||Wm(e.zOrder,"".concat(t,".zOrder"),0,255),Xm(e.alpha)||Wm(e.alpha,"".concat(t,".alpha"),0,1,!1)}const Yf={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:""},qf={audioBitrate:48,audioChannels:2,audioVolume:100,audioSampleRate:48e3,height:0,width:0,videoBitrate:400,videoFramerate:15,videoGop:30};let Jf,Xf,zf,Qf,Zf,$f,eS,tS,iS,nS,rS,oS,sS,aS,cS,dS,uS,lS,hS;function pS(e){if(!e.channelName)throw new EE(_E.INVALID_PARAMS,"invalid channelName in info");if("number"!=typeof e.uid)throw new EE(_E.INVALID_PARAMS,"invalid uid in info, uid must be a number");return e.token&&Km(e.token,"info.token",1,2047),Jm(e.uid),qm(e.channelName),!0}function _S(e){return Gm(e,"mediaSource",["screen","window","application"]),!0}!function(e){e.WARNING="@live_uap-warning",e.ERROR="@line_uap-error",e.PUBLISH_STREAM_STATUS="@live_uap-publish-status",e.INJECT_STREAM_STATUS="@live_uap-inject-status",e.WORKER_STATUS="@live_uap-worker-status",e.REQUEST_NEW_ADDRESS="@live_uap-request-address"}(Jf||(Jf={})),function(e){e.REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager"}(Xf||(Xf={})),function(e){e[e.LIVE_STREAM_RESPONSE_SUCCEED=200]="LIVE_STREAM_RESPONSE_SUCCEED",e[e.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM=454]="LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM",e[e.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR=450]="LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_BAD_STREAM=451]="LIVE_STREAM_RESPONSE_BAD_STREAM",e[e.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR=400]="LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST=404]="LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST",e[e.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED=456]="LIVE_STREAM_RESPONSE_NOT_AUTHORIZED",e[e.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE=457]="LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE",e[e.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN=429]="LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN",e[e.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH=452]="LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH",e[e.LIVE_STREAM_RESPONSE_NOT_SUPPORTED=453]="LIVE_STREAM_RESPONSE_NOT_SUPPORTED",e[e.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM=455]="LIVE_STREAM_RESPONSE_MAX_STREAM_NUM",e[e.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR=500]="LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR",e[e.LIVE_STREAM_RESPONSE_WORKER_LOST=501]="LIVE_STREAM_RESPONSE_WORKER_LOST",e[e.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT=502]="LIVE_STREAM_RESPONSE_RESOURCE_LIMIT",e[e.LIVE_STREAM_RESPONSE_WORKER_QUIT=503]="LIVE_STREAM_RESPONSE_WORKER_QUIT",e[e.ERROR_FAIL_SEND_MESSAGE=504]="ERROR_FAIL_SEND_MESSAGE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE=30]="PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT=31]="PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH=32]="PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH",e[e.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN=33]="PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN"}(zf||(zf={})),function(e){e.CONNECT_FAILED="connect failed",e.CONNECT_TIMEOUT="connect timeout",e.WS_DISCONNECTED="websocket disconnected",e.REQUEST_TIMEOUT="request timeout",e.REQUEST_FAILED="request failed",e.WAIT_STATUS_TIMEOUT="wait status timeout",e.WAIT_STATUS_ERROR="wait status error",e.BAD_STATE="bad state",e.WS_ABORT="ws abort",e.AP_REQUEST_TIMEOUT="AP request timeout",e.AP_JSON_PARSE_ERROR="AP json parse error",e.AP_REQUEST_ERROR="AP request error",e.AP_REQUEST_ABORT="AP request abort"}(Qf||(Qf={})),function(e){e[e.SetSdkProfile=0]="SetSdkProfile",e[e.SetSourceChannel=1]="SetSourceChannel",e[e.SetSourceUserId=2]="SetSourceUserId",e[e.SetDestChannel=3]="SetDestChannel",e[e.StartPacketTransfer=4]="StartPacketTransfer",e[e.StopPacketTransfer=5]="StopPacketTransfer",e[e.UpdateDestChannel=6]="UpdateDestChannel",e[e.Reconnect=7]="Reconnect",e[e.SetVideoProfile=8]="SetVideoProfile"}(Zf||(Zf={})),function(e){e.NETWORK_DISCONNECTED="NETWORK_DISCONNECTED",e.NETWORK_CONNECTED="NETWORK_CONNECTED",e.PACKET_JOINED_SRC_CHANNEL="PACKET_JOINED_SRC_CHANNEL",e.PACKET_JOINED_DEST_CHANNEL="PACKET_JOINED_DEST_CHANNEL",e.PACKET_SENT_TO_DEST_CHANNEL="PACKET_SENT_TO_DEST_CHANNEL",e.PACKET_RECEIVED_VIDEO_FROM_SRC="PACKET_RECEIVED_VIDEO_FROM_SRC",e.PACKET_RECEIVED_AUDIO_FROM_SRC="PACKET_RECEIVED_AUDIO_FROM_SRC",e.PACKET_UPDATE_DEST_CHANNEL="PACKET_UPDATE_DEST_CHANNEL",e.PACKET_UPDATE_DEST_CHANNEL_REFUSED="PACKET_UPDATE_DEST_CHANNEL_REFUSED",e.PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE="PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE"}($f||($f={})),function(e){e.RELAY_STATE_IDLE="RELAY_STATE_IDLE",e.RELAY_STATE_CONNECTING="RELAY_STATE_CONNECTING",e.RELAY_STATE_RUNNING="RELAY_STATE_RUNNING",e.RELAY_STATE_FAILURE="RELAY_STATE_FAILURE"}(eS||(eS={})),function(e){e.RELAY_OK="RELAY_OK",e.SERVER_CONNECTION_LOST="SERVER_CONNECTION_LOST",e.SRC_TOKEN_EXPIRED="SRC_TOKEN_EXPIRED",e.DEST_TOKEN_EXPIRED="DEST_TOKEN_EXPIRED"}(tS||(tS={})),function(e){e.High="high",e.Low="low",e.Audio="audio",e.Screen="screen",e.ScreenLow="screen_low"}(iS||(iS={})),function(e){e.DISCONNECT="disconnect",e.CONNECTION_STATE_CHANGE="connection-state-change",e.NETWORK_QUALITY="network-quality",e.STREAM_TYPE_CHANGE="stream-type-change",e.IS_P2P_DISCONNECTED="is-p2p-dis",e.DISCONNECT_P2P="dis-p2p",e.REQUEST_NEW_GATEWAY_LIST="req-gate-url",e.NEED_RENEW_SESSION="need-sid",e.REQUEST_P2P_CONNECTION_PARAMS="request-p2p-connection-params",e.JOIN_RESPONSE="join-response",e.REQUEST_DC_CONNECTION_PARAMS="request-dc-connection-params",e.RESET_CONNECTION_EVENTS="reset-connection-events",e.DATACHANNEL_PRECONNECT="datachannel_preconnect",e.DATACHANNEL_FAILBACK="datachannel_failback",e.RESET_SIGNAL="reset-signal"}(nS||(nS={})),function(e){e[e.Nothing=0]="Nothing",e[e.Audio=1]="Audio",e[e.LwoVideo=2]="LwoVideo",e[e.Video=4]="Video",e[e.Data=8]="Data"}(rS||(rS={})),function(e){e[e.websocket=0]="websocket",e[e.datachannel=1]="datachannel"}(oS||(oS={})),function(e){e.NEED_RENEGOTIATE="@need_renegotiate",e.NEED_REPLACE_TRACK="@need_replace_track",e.NEED_CLOSE="@need_close",e.NEED_ENABLE_TRACK="@need_enable_track",e.NEED_DISABLE_TRACK="@need_disable_track",e.NEED_SESSION_ID="@need_sid",e.SET_OPTIMIZATION_MODE="@set_optimization_mode",e.GET_STATS="@get_stats",e.GET_LOW_VIDEO_TRACK="@get_low_video_track",e.NEED_RESET_REMOTE_SDP="@need_reset_remote_sdp",e.NEED_UPDATE_VIDEO_ENCODER="@need_update_video_encoder",e.NEED_MUTE_TRACK="@need_mute_track",e.NEED_UNMUTE_TRACK="@need_unmute_track"}(sS||(sS={})),function(e){e.SCREEN_TRACK="screen_track",e.LOW_STREAM="low_stream"}(aS||(aS={})),function(e){e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM"}(cS||(cS={})),function(e){e[e.DISABLE=0]="DISABLE",e[e.LOW_STREAM=1]="LOW_STREAM",e[e.AUDIO_ONLY=2]="AUDIO_ONLY"}(dS||(dS={})),function(e){e.SOURCE_STATE_CHANGE="source-state-change",e.TRACK_ENDED="track-ended",e.BEAUTY_EFFECT_OVERLOAD="beauty-effect-overload",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.CLOSED="closed"}(uS||(uS={})),function(e){e.FIRST_FRAME_DECODED="first-frame-decoded",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status"}(lS||(lS={})),function(e){e.CHINA="CHINA",e.ASIA="ASIA",e.NORTH_AMERICA="NORTH_AMERICA",e.EUROPE="EUROPE",e.JAPAN="JAPAN",e.INDIA="INDIA",e.KOREA="KOREA",e.HKMC="HKMC",e.US="US",e.OCEANIA="OCEANIA",e.SOUTH_AMERICA="SOUTH_AMERICA",e.AFRICA="AFRICA",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="EXTENSIONS"}(hS||(hS={}));const ES=[hS.AFRICA,hS.ASIA,hS.CHINA,hS.EUROPE,hS.GLOBAL,hS.INDIA,hS.JAPAN,hS.NORTH_AMERICA,hS.OCEANIA,hS.OVERSEA,hS.SOUTH_AMERICA];let mS;!function(e){e.CHINA="CN",e.ASIA="AS",e.NORTH_AMERICA="NA",e.EUROPE="EU",e.JAPAN="JP",e.INDIA="IN",e.KOREA="KR",e.HKMC="HK",e.US="US",e.OCEANIA="OC",e.SOUTH_AMERICA="SA",e.AFRICA="AF",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="GLOBAL"}(mS||(mS={}));const fS={CHINA:{},ASIA:{CODE:mS.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:mS.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:mS.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:mS.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","\tuap-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:mS.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:mS.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:mS.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:mS.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:mS.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:mS.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:mS.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:mS.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:mS.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:{}};let SS,TS,gS,RS,IS,vS,CS,yS,AS,OS,bS,wS,NS,DS,PS;OE&&(fS.CHINA={CODE:mS.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"]}),function(e){e.UPDATE_BITRATE_LIMIT="update_bitrate_limit"}(SS||(SS={}));class LS extends hE{constructor(e,t){super(),lp(this,"onICEConnectionStateChange",void 0),lp(this,"onConnectionStateChange",void 0),lp(this,"onDTLSTransportStateChange",void 0),lp(this,"onDTLSTransportError",void 0),lp(this,"onICETransportStateChange",void 0),lp(this,"onFirstAudioReceived",void 0),lp(this,"onFirstVideoReceived",void 0),lp(this,"onFirstAudioDecoded",void 0),lp(this,"onFirstVideoDecoded",void 0),lp(this,"onFirstVideoDecodedTimeout",void 0),lp(this,"onSelectedLocalCandidateChanged",void 0),lp(this,"onSelectedRemoteCandidateChanged",void 0),lp(this,"establishPromise",void 0)}}!function(e){e.SEND="sendonly",e.RECV="recvonly",e.SENDRECV="sendrecv",e.INACTIVE="inactive"}(TS||(TS={})),function(e){e.VIDEO="video",e.AUDIO="audio"}(gS||(gS={})),function(e){e.LocalVideoTrack="videoTrack",e.LocalAudioTrack="audioTrack",e.LocalVideoLowTrack="videoLowTrack"}(RS||(RS={})),function(e){e.New="new",e.Connected="connected",e.Reconnecting="reconnecting",e.Disconnected="disconnected"}(IS||(IS={})),function(e){e.StateChange="stateChange",e.IceConnectionStateChange="iceConnectionStateChange",e.RequestMuteLocal="requestMuteLocal",e.RequestUnmuteLocal="requestUnmuteLocal",e.RequestRePublish="requestRePublish",e.RequestReSubscribe="requestReSubscribe",e.RequestUploadStats="requestUploadStats",e.MediaReconnectStart="MediaReconnectStart",e.MediaReconnectEnd="MediaReconnectEnd",e.NeedSignalRTT="NeedSignalRTT",e.RequestRestartICE="RequestRestartIce",e.PeerConnectionStateChange="PeerConnectionStateChange",e.RequestReconnect="RequestReconnect",e.RequestReconnectPC="RequestReconnectPC",e.RequestUnpublishForReconnectPC="RequestUnpublishForReconnectPC",e.P2PLost="P2PLost",e.UpdateVideoEncoder="UpdateVideoEncoder",e.ConnectionTypeChange="ConnectionTypeChange",e.RequestLowStreamParameter="RequestLowStreamParameter",e.QueryClientConnectionState="QueryClientConnectionState"}(vS||(vS={})),function(e){e.ONLINE="ONLINE",e.OFFLINE="OFFLINE"}(CS||(CS={})),function(e){e.NETWORK_STATE_CHANGE="NETWORK_STATE_CHANGE",e.ONLINE="ONLINE",e.OFFLINE="OFFLINE"}(yS||(yS={})),function(e){e.ON_TRACK="on_track",e.ON_NODE="on_node"}(AS||(AS={})),function(e){e.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",e.REQUEST_CONSTRAINTS="request_constraints"}(OS||(OS={})),function(e){e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED"}(bS||(bS={})),function(e){e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED"}(wS||(wS={})),function(e){e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url"}(NS||(NS={})),function(e){e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.MULTI_IP="MULTI_IP",e.TIMEOUT="TIMEOUT",e.OFFLINE="OFFLINE",e.LEAVE="LEAVE",e.P2P_FAILED="P2P_FAILED",e.FALLBACK="FALLBACK"}(DS||(DS={})),function(e){e.CONNECTED="transmitter:connected",e.RECONNECTING="transmitter:reconnecting",e.WILL_RECONNECT="transmitter:will_reconnect",e.CLOSED="transmitter:closed",e.FAILED="transmitter:failed",e.ON_MESSAGE="transmitter:on_message",e.REQUEST_NEW_URLS="transmitter:request_new_urls",e.RECONNECT_WAITTING_FINISH="transmitter:reconnect_waitting_finish",e.RECONNECT_CREATE_CONNECTION="transmitter:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="transmitter:on_token_privilege_did_expire",e.TO_CONNECT_DATACHANNEL="transmitter:to_connect_datachannel",e.FAILBACK="transmitter:failback"}(PS||(PS={}));const kS={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};function MS(){return kS}let US;!function(e){e[e.CHOOSE_SERVER=11]="CHOOSE_SERVER",e[e.CLOUD_PROXY=18]="CLOUD_PROXY",e[e.CLOUD_PROXY_5=20]="CLOUD_PROXY_5",e[e.CLOUD_PROXY_FALLBACK=26]="CLOUD_PROXY_FALLBACK"}(US||(US={}));var xS=k,VS=Array.isArray||function(e){return"Array"==xS(e)},FS=h,jS=VS,BS=oc,GS=q,WS=rt("species"),HS=FS.Array,KS=function(e){var t;return jS(e)&&(t=e.constructor,(BS(t)&&(t===HS||jS(t.prototype))||GS(t)&&null===(t=t[WS]))&&(t=void 0)),void 0===t?HS:t},YS=function(e,t){return new(KS(e))(0===t?0:t)},qS=Wt,JS=j,XS=Fe,zS=wi,QS=YS,ZS=d([].push),$S=function(e){var t=1==e,i=2==e,n=3==e,r=4==e,o=6==e,s=7==e,a=5==e||o;return function(c,d,u,l){for(var h,p,_=XS(c),E=JS(_),m=qS(d,u),f=zS(E),S=0,T=l||QS,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:ZS(g,h)}else switch(e){case 4:return!1;case 7:ZS(g,h)}return o?-1:n||r?r:g}},eT={forEach:$S(0),map:$S(1),filter:$S(2),some:$S(3),every:$S(4),find:$S(5),findIndex:$S(6),filterReject:$S(7)},tT=eT.forEach,iT=Vi("forEach")?[].forEach:function(e){return tT(this,e,arguments.length>1?arguments[1]:void 0)};Ii({target:"Array",proto:!0,forced:[].forEach!=iT},{forEach:iT});var nT=Hi("Array").forEach,rT=Zr,oT=Ge,sT=u,aT=nT,cT=Array.prototype,dT={DOMTokenList:!0,NodeList:!0},uT=function(e){var t=e.forEach;return e===cT||sT(cT,e)&&t===cT.forEach||oT(dT,rT(e))?aT:t},lT=Fe,hT=hr;Ii({target:"Object",stat:!0,forced:i((function(){hT(1)}))},{keys:function(e){return hT(lT(e))}});var pT=J.Object.keys,_T=Xi,ET=Ii,mT=VS,fT=d([].reverse),ST=[1,2];ET({target:"Array",proto:!0,forced:String(ST)===String(ST.reverse())},{reverse:function(){return mT(this)&&(this.length=this.length),fT(this)}});var TT=Hi("Array").reverse,gT=u,RT=TT,IT=Array.prototype,vT=function(e){var t=e.reverse;return e===IT||gT(IT,e)&&t===IT.reverse?RT:t},CT=i,yT=ae,AT=rt("species"),OT=function(e){return yT>=51||!CT((function(){var t=[];return(t.constructor={})[AT]=function(){return{foo:1}},1!==t[e](Boolean).foo}))},bT=Ii,wT=h,NT=VS,DT=oc,PT=q,LT=Un,kT=wi,MT=K,UT=ZE,xT=rt,VT=pc,FT=OT("slice"),jT=xT("species"),BT=wT.Array,GT=Math.max;bT({target:"Array",proto:!0,forced:!FT},{slice:function(e,t){var i,n,r,o=MT(this),s=kT(o),a=LT(e,s),c=LT(void 0===t?s:t,s);if(NT(o)&&(i=o.constructor,(DT(i)&&(i===BT||NT(i.prototype))||PT(i)&&null===(i=i[jT]))&&(i=void 0),i===BT||void 0===i))return VT(o,a,c);for(n=new(void 0===i?BT:i)(GT(c-a,0)),r=0;a<c;a++,r++)a in o&&UT(n,r,o[a]);return n.length=r,n}});var WT=Hi("Array").slice,HT=u,KT=WT,YT=Array.prototype,qT=function(e){var t=e.slice;return e===YT||HT(YT,e)&&t===YT.slice?KT:t};function JT(e,t,i,n,r){var o,s,a,c={};return uT(o=pT(n)).call(o,(function(e){c[e]=n[e]})),c.enumerable=!!c.enumerable,c.configurable=!!c.configurable,("value"in c||c.initializer)&&(c.writable=!0),c=_T(s=vT(a=qT(i).call(i)).call(a)).call(s,(function(i,n){return n(e,t,i)||i}),c),r&&void 0!==c.initializer&&(c.value=c.initializer?c.initializer.call(r):void 0,c.initializer=void 0),void 0===c.initializer&&(up(e,t,c),c=null),c}var XT=Hi("Array").keys,zT=Zr,QT=Ge,ZT=u,$T=XT,eg=Array.prototype,tg={DOMTokenList:!0,NodeList:!0},ig=function(e){var t=e.keys;return e===eg||ZT(eg,e)&&t===eg.keys||QT(tg,zT(e))?$T:t};function ng(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function rg(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?ng(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):ng(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let og=0,sg=0;function ag(e,t,i,n){return new Sl((r,o)=>{t.timeout=t.timeout||FE("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),og+=AI(t.data)):i&&(t.data.size?og+=t.data.size:t.data instanceof FormData?og+=function(e){let t=0;/DingTalk/i.test(navigator.userAgent)&&e.realFormData&&(e=e.realFormData);return e.forEach(e=>{t+="string"==typeof e?AI(e):e.size}),t+138}(t.data):og+=AI(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,uE.request(t).then(e=>{"string"==typeof e.data?sg+=AI(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?sg+=e.data.byteLength:sg+=AI(JSON.stringify(e.data)),n&&r({data:e.data,headers:e.headers}),r(e.data)}).catch(e=>{uE.isCancel(e)?o(new EE(_E.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?o(new EE(_E.NETWORK_TIMEOUT,e.message)):e.response?o(new EE(_E.NETWORK_RESPONSE_ERROR,e.response.status)):o(new EE(_E.NETWORK_ERROR,e.message))})})}async function cg(e,t){const i=new Blob([t.data],{type:"buffer"});return await ag(e,rg(rg({},t),{},{data:i,headers:{"Content-Type":"application/octet-stream"}}),!0)}const dg=new class extends hE{set networkState(e){CE.info("[".concat(this._moduleName,"]")+"network state changed, "+this._networkState+" -> "+e),this.emit(yS.NETWORK_STATE_CHANGE,e,this._networkState),e===CS.ONLINE?this.emit(yS.ONLINE):e===CS.OFFLINE&&(this.onlineWaiter=new Sl(e=>{this.once(yS.ONLINE,()=>{this.onlineWaiter=void 0,e(CS.ONLINE)})}),this.emit(yS.OFFLINE)),this._networkState=e}get networkState(){return this._networkState}constructor(){super(),lp(this,"_moduleName","network-indicator"),lp(this,"_networkState",CS.ONLINE),lp(this,"onlineWaiter",void 0),window.addEventListener("online",()=>{this.networkState=CS.ONLINE}),window.addEventListener("offline",()=>{this.networkState=CS.OFFLINE})}};let ug=!1;const lg=new class extends hE{constructor(){super(...arguments),lp(this,"onAutoplayFailed",void 0),lp(this,"onAudioAutoplayFailed",void 0)}};function hg(){if(Mh(),!ug){const e=t=>{t.preventDefault(),ug=!1,np()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};ug=!0,np()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),CE.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),lg.onAutoplayFailed?lg.onAutoplayFailed():lg.onAudioAutoplayFailed?CE.warning("AgoraRTC.onAudioAutoplayFailed has been deprecated in favor of AgoraRTC.onAutoplayFailed.\n\n Please refer to the Agora document to migrate the newer API, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."):CE.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 ."),lg.emit("autoplay-failed")}}function pg(e){return(new TextEncoder).encode(e)}const _g=function(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(new Uint8Array(e),0),i.set(new Uint8Array(t),e.byteLength),i};const Eg=async e=>function(e,t){let i="";return new Uint8Array(e).forEach(e=>{i+=e.toString(t).padStart(2,"0")}),i}(await crypto.subtle.digest("SHA-256",pg(e)),16);function mg(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function fg(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?mg(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):mg(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function Sg(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(t,i,n){const r=n.value;if("function"==typeof r){const o=e.className||t.__className__||("AgoraRTCClient"===t.constructor.name?"Client":t.constructor.name);n.value=function(){for(var t=arguments.length,n=new Array(t),s=0;s<t;s++)n[s]=arguments[s];let a=n;if(e.argsMap)try{a=e.argsMap(this,...n)}catch(e){CE.warning(e),a=[]}try{JSON.stringify(a)}catch(e){CE.warning("arguments for method ".concat(o,".").concat(i," not serializable for apiInvoke.")),a=[]}const c=(e.report||Tg).reportApiInvoke(this._sessionId||null,{name:"".concat(o,".").concat(i),options:a,tag:lf.TRACER,reportResult:e.reportResult},e.throttleTime);try{const t=r.apply(this,n);return t instanceof Sl?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 n}}const Tg=new class{constructor(){lp(this,"baseInfoMap",new Map),lp(this,"proxyServer",void 0),lp(this,"clientList",qE),lp(this,"eventUploadTimer",void 0),lp(this,"setSessionIdTimer",void 0),lp(this,"url",void 0),lp(this,"backupUrl",void 0),lp(this,"_appId",void 0),lp(this,"keyEventUploadPendingItems",[]),lp(this,"normalEventUploadPendingItems",[]),lp(this,"apiInvokeUploadPendingItems",[]),lp(this,"apiInvokeCount",0),lp(this,"ltsList",[]),lp(this,"lastSendNormalEventTime",Date.now()),lp(this,"customReportCounterTimer",void 0),lp(this,"customReportCount",0),lp(this,"extApiInvoke",async e=>{for(const t of e){const e=fg(fg({},t),{},{sid:null,invokeId:++this.apiInvokeCount,tag:lf.TRACER});this.sendApiInvoke(e)}}),this.eventUploadTimer=window.setInterval(this.doSend.bind(this),FE("EVENT_REPORT_SEND_INTERVAL")),this.setSessionIdTimer=window.setInterval(this.appendSessionId.bind(this),FE("EVENT_REPORT_SEND_INTERVAL"))}adjustSessionStartTime(e){if(!this.baseInfoMap.has(e)&&!this.baseInfoMap.get(e))return void CE.error("adjust session ".concat(e," start time, sid is not exist or info is undefined"));const t=this.baseInfoMap.get(e),i=Date.now(),n=t.startTime;t.startTime=i,CE.debug("rewrite session ".concat(e," startTime: ").concat(i," , ").concat(i-n,"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;const n=Date.now();this.apiInvokeCount+=1;const r=this.apiInvokeCount,o=()=>({tag:t.tag,invokeId:r,sid:e,name:t.name,apiInvokeTime:n,options:t.options,states:t.states||null}),s=!!FE("SHOW_REPORT_INVOKER_LOG");s&&CE.info("".concat(t.name," start"),t.options);let a=!1;OI(t.timeout).then(()=>{a||(this.sendApiInvoke(fg(fg({},o()),{},{error:_E.API_INVOKE_TIMEOUT,success:!1})),CE.debug("".concat(t.name," timeout")))});const c=new EE(_E.UNEXPECTED_ERROR,"".concat(t.name,": this api invoke is end"));return{onSuccess:e=>{const n=()=>{if(a)throw c;return a=!0,this.sendApiInvoke(fg(fg({},o()),{},{success:!0},t.reportResult&&{result:e})),s&&CE.info("".concat(t.name," onSuccess")),e};return i?qI(n,t.name+"Success",i,()=>a=!0):n()},onError:e=>{const n=()=>{if(a)throw e;a=!0,this.sendApiInvoke(fg(fg({},o()),{},{success:!1,error:e})),s&&CE.info("".concat(t.name," onFailure"),e.toString())};return i?qI(n,t.name+"Error",i,()=>a=!0):n()}}}sessionInit(e,t){if(this.baseInfoMap.has(e))return;const i=Date.now(),n=this.createBaseInfo(e,i);n.cname=t.cname;const r=Object.assign({},{willUploadConsoleLog:FE("UPLOAD_LOG"),maxTouchPoints:navigator.maxTouchPoints,areaVersion:OE?"global":"oversea",areas:FE("AREAS")&&FE("AREAS").join(",")},t.extend),o=Date.now(),s=fg(fg({},n),{},{eventType:sf.SESSION_INIT,appid:t.appid,browser:navigator.userAgent,build:yE,lts:o,elapse:o-i,extend:JSON.stringify(r),mode:t.mode,process:FE("PROCESS_ID"),appType:FE("APP_TYPE"),success:!0,version:AE});this.send({type:af.SESSION,data:s},!0)}joinChooseServer(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=fg(fg({},n),{},{eventType:sf.JOIN_CHOOSE_SERVER,lts:r,eventElapse:r-t.lts,chooseServerAddr:t.csAddr,errorCode:t.ec,elapse:r-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:af.JOIN_CHOOSE_SERVER,data:o},!0)}reqUserAccount(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=fg(fg({},n),{},{eventType:sf.REQ_USER_ACCOUNT,lts:r,success:t.success,serverAddress:t.serverAddr,stringUid:t.stringUid,uid:t.uid,errorCode:t.errorCode,elapse:r-i.startTime,eventElapse:r-t.lts,extend:JSON.stringify(t.extend)});this.send({type:af.REQ_USER_ACCOUNT,data:o},!0)}joinGateway(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info;t.vid&&(n.vid=t.vid),n.uid=t.uid,n.cid=t.cid;const r=Date.now(),{firstSuccess:o,avoidJoinStartTime:s,isProxy:a,addr:c}=t,d=r-(o&&s?s:i.startTime),u=fg(fg({},n),{},{eventType:sf.JOIN_GATEWAY,lts:r,gatewayAddr:t.addr,success:t.succ,errorCode:t.ec,elapse:d,eventElapse:r-t.lts,firstSuccess:o,signalChannel:t.signalChannel}),l=u.success?1:0;if(t.succ&&(i.lastJoinSuccessTime=r),o)this.send({type:af.JOIN_GATEWAY,data:u},!0);else{let e;if(c)if(a){const t=c.match(/h=(\d{1,3}-){3}\d{1,3}/g),i=c.match(/p=[0-9]{1,6}/g);e={isSuccess:l,gatewayIp:t&&t.length?t[0].split("=")[1].replace(/-/g,"."):"",port:i&&i.length?i[0].split("=")[1]:"",isProxy:a?1:0}}else{const t=c.match(/wss:\/\/(\d{1,3}-){3}\d{1,3}/g),i=c.match(/:[0-9]{1,6}/g);e={isSuccess:l,gatewayIp:t&&t.length?t[0].split("//")[1].replace(/-/g,"."):"",port:i&&i.length?i[0].split(":")[1]:"",isProxy:a?1:0}}else e={isSuccess:l,gatewayIp:"",port:"",isProxy:a?1:0};delete u.success,delete u.eventType,delete u.firstSuccess,u.vid=Number(u.vid);const t=Object.assign({},u,e,{eventType:sf.REJOIN_GATEWAY});this.send({type:af.RE_JOIN_GATEWAY,data:t},!0)}}joinChannelTimeout(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=Date.now(),r=fg(fg({},i.info),{},{lts:n,timeout:t,elapse:n-i.startTime});this.send({type:af.JOIN_CHANNEL_TIMEOUT,data:r},!0)}publish(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=fg(fg({},n),{},{eventType:sf.PUBLISH,lts:r,eventElapse:t.eventElapse,elapse:r-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:af.PUBLISH,data:o},!0)}subscribe(e,t,i){const n=this.baseInfoMap.get(e);if(!n)return;const r=n.info,o=Date.now(),s=fg(fg({},r),{},{eventType:sf.SUBSCRIBE,lts:o,eventElapse:t.eventElapse,elapse:o-n.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:af.SUBSCRIBE,data:s},!0)}wsCompressorInit(e){var t;const i=[...ig(t=this.baseInfoMap).call(t)],n=i.length?i[0]:"UnableToGetSid",r=this.baseInfoMap.get(n);if(!r)return;const o=r.info,s=Date.now(),a=fg(fg({},o),{},{eventType:sf.WS_COMPRESSOR_INIT,lts:s,eventElapse:e.eventElapse,elapse:s-r.startTime,status:e.status?1:2});this.send({type:af.WS_COMPRESSOR_INIT,data:a},!0)}firstRemoteVideoDecode(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=fg(fg(fg({},o),n),{},{elapse:s-r.startTime,eventType:t,lts:s,firstDecodeFrame:Math.max(s-r.startTime,0),apEnd:Math.max(n.apEnd-r.startTime,0),apStart:Math.max(n.apStart-r.startTime,0),joinGwEnd:Math.max(n.joinGwEnd-r.startTime,0),joinGwStart:Math.max(n.joinGwStart-r.startTime,0),pcEnd:Math.max(n.pcEnd-r.startTime,0),pcStart:Math.max(n.pcStart-r.startTime,0),subscriberEnd:Math.max(n.subscriberEnd-r.startTime,0),subscriberStart:Math.max(n.subscriberStart-r.startTime,0),videoAddNotify:Math.max(n.videoAddNotify-r.startTime,0)});this.send({type:i,data:a},!0)}firstRemoteFrame(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=fg(fg(fg({},o),n),{},{elapse:s-r.startTime,eventType:t,lts:s});this.send({type:i,data:a},!0)}onGatewayStream(e,t,i,n){const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=fg(fg(fg({},o),n),{},{eventType:t,lts:s});this.send({type:i,data:a},!0)}streamSwitch(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=fg(fg({},n),{},{eventType:sf.STREAM_SWITCH,lts:r,isDual:t.isdual,elapse:r-i.startTime,success:t.succ});this.send({type:af.STREAM_SWITCH,data:o},!0)}requestProxyAppCenter(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=fg(fg({},n),{},{eventType:sf.REQUEST_PROXY_APPCENTER,lts:r,eventElapse:r-t.lts,elapse:r-i.startTime,APAddr:t.APAddr,workerManagerList:t.workerManagerList,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:af.REQUEST_PROXY_APPCENTER,data:o},!0)}requestProxyWorkerManager(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=fg(fg({},n),{},{eventType:sf.REQUEST_PROXY_WORKER_MANAGER,lts:r,eventElapse:r-t.lts,elapse:r-i.startTime,workerManagerAddr:t.workerManagerAddr,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:af.REQUEST_PROXY_WORKER_MANAGER,data:o},!0)}setProxyServer(e){this.proxyServer=e,e?CE.debug("reportProxyServerurl: ".concat(e)):CE.debug("disable reportProxyServerurl: ".concat(e))}peerPublishStatus(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=fg(fg({},n),{},{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:r,elapse:r-i.startTime,joinChannelSuccessElapse:r-(i.lastJoinSuccessTime||r),peerPublishDurationVideo:t.videoPublishDuration,peerPublishDurationAudio:t.audioPublishDuration});this.send({type:af.PEER_PUBLISH_STATUS,data:o},!0)}workerEvent(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now();(function(e,t,i){const n=e[t];if(!n||"string"!=typeof n)return[e];e[t]="";const r=AI(JSON.stringify(e));let o=0;const s=[];let a=0;for(let c=0;c<n.length;c++)a+=n.charCodeAt(c)<=127?1:3,a<=i-r||(s[s.length]=yI(yI({},e),{},{[t]:n.substring(o,c)}),o=c,a=n.charCodeAt(c)<=127?1:3);o!==n.length-1&&(s[s.length]=yI(yI({},e),{},{[t]:n.substring(o)}));return s})(fg(fg(fg({},n),t),{},{elapse:r-i.startTime,lts:r,productType:"WebRTC"}),"payload",1300).forEach(e=>this.send({type:af.WORKER_EVENT,data:e},!0))}apworkerEvent(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=fg(fg(fg({},n),t),{},{elapse:r-i.startTime,lts:r});this.send({type:af.AP_WORKER_EVENT,data:o},!0)}joinWebProxyAP(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=fg(fg(fg({},n),t),{},{elapse:r-i.startTime,lts:r,extend:t.extend||void 0});this.send({type:af.JOIN_WEB_PROXY_AP,data:o},!0)}WebSocketQuit(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=fg(fg(fg({},n),t),{},{elapse:r-i.startTime,lts:r});this.send({type:af.WEBSOCKET_QUIT,data:o},!0)}async sendCustomReportMessage(e,t){if(this.customReportCount+=t.length,this.customReportCount>FE("CUSTOM_REPORT_LIMIT"))throw new EE(_E.CUSTOM_REPORT_FREQUENCY_TOO_HIGH);this.customReportCounterTimer||(this.customReportCounterTimer=window.setInterval(()=>{this.customReportCount=0},5e3));const i=Date.now(),n=t.map(t=>({type:af.USER_ANALYTICS,data:fg(fg({sid:e},t),{},{lts:i})}));try{FE("NEW_REPORT_SERVER")?await this.postDataToStatsCollector2(n):await this.postDataToStatsCollector(n)}catch(e){throw CE.error("send custom report message failed",e.toString()),new EE(_E.CUSTOM_REPORT_SEND_FAILED,e.message)}}autoplayFailed(e,t,i,n){if(!e)return;const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=fg(fg({},o),{},{vid:void 0===o.vid?0:Number(o.vid),lts:s,elapse:s-r.startTime,cbRegistered:lg.onAutoplayFailed||lg.onAudioAutoplayFailed?1:-1,errorMsg:i,mediaType:t,trackId:n,extend:void 0});this.send({type:af.AUTOPLAY_FAILED,data:a},!0)}sendApiInvoke(e){const t=FE("NOT_REPORT_EVENT");if(e.tag&&t.includes&&t.includes(e.tag))return!1;if(null===e.sid)return this.apiInvokeUploadPendingItems.push(e),!1;const i=this.baseInfoMap.get(e.sid);if(!i)return this.apiInvokeUploadPendingItems.push(e),!1;const{cname:n,uid:r,cid:o}=i.info;e.lts=e.lts||Date.now();let s=void 0;if(e.error)if(e.error instanceof EE){const{code:t,message:i}=e.error;s=t||(i||e.error.toString())}else s=e.error.toString();const a={invokeId:e.invokeId,sid:e.sid,cname:n,cid:o,uid:r,lts:e.lts,success:e.success,elapse:e.lts-i.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?s:void 0,errorMsg:e.error?JSON.stringify(e.error):void 0};return this.send({type:af.API_INVOKE,data:a},!1),!0}appendSessionId(){this.clientList.forEach(e=>{if(e._sessionId){const t=this.apiInvokeUploadPendingItems.length;for(let i=0;i<t;i++){const 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>FE("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){const i=[],n=[];for(;e.length;){const t=e.shift();i.length<20?i.push(t):n.push(t)}e.push(...n);for(const e of[...i]){var r;if(-1!==this.ltsList.indexOf(e.data.lts))e.data.lts=this.ltsList[this.ltsList.length-1]+1,this.ltsList.push(e.data.lts);else this.ltsList.push(e.data.lts),jm(r=this.ltsList).call(r,(e,t)=>e-t)}t||(this.lastSendNormalEventTime=Date.now());return FE("ENABLE_EVENT_REPORT")?(i.length&&(FE("NEW_REPORT_SERVER")?this.postDataToStatsCollector2(i):this.postDataToStatsCollector(i)).catch((e=>i=>{FE("EVENT_REPORT_RETRY")&&(t?this.keyEventUploadPendingItems=this.keyEventUploadPendingItems.concat(e):(this.normalEventUploadPendingItems=this.normalEventUploadPendingItems.concat(e),this.normalEventUploadPendingItems.length>FE("NORMAL_EVENT_QUEUE_CAPACITY")&&(this.normalEventUploadPendingItems.splice(0,this.normalEventUploadPendingItems.length-FE("NORMAL_EVENT_QUEUE_CAPACITY")),CE.warning("report: drop normal events"))))})(i)),e):e}async postDataToStatsCollector2(e){dg.networkState===CS.OFFLINE&&await Sl.race([dg.onlineWaiter,OI(2*mE.maxRetryTimeout)]);const t=e=>{let t=new Uint8Array;return e.forEach(e=>{const i=pg(JSON.stringify(e.data)),n=new ArrayBuffer(5),r=(e=>{let t=0;return Object.entries(af).forEach(i=>{let[n,r]=i;r===e.type&&(t=df[n])}),t})(e),o=new DataView(n);o.setUint16(0,i.byteLength,!0),o.setUint8(2,255&r),o.setUint8(3,r>>>8&255),o.setUint8(4,r>>>16&255),t=_g(t,new Uint8Array(n)),t=_g(t,i)}),t},i="event";let n=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(FE("NEW_REPORT_SERVER_DOMAINS")[0],"&p=443&d=").concat(i):"https://".concat(FE("NEW_REPORT_SERVER_DOMAINS")[0],"/").concat(i);for(let r=0;r<2;r+=1){1===r&&(n=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(FE("NEW_REPORT_SERVER_DOMAINS")[1],"&p=443&d=").concat(i):"https://".concat(FE("NEW_REPORT_SERVER_DOMAINS")[1],"/").concat(i));try{await ag(n,{timeout:1e4,data:t(e),headers:fg(fg({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===r)throw e;continue}return}}async postDataToStatsCollector(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i={msgType:"EventMessages",sentTs:Math.round(Date.now()/1e3),payloads:e.map(e=>JSON.stringify(e)),vid:(e=>{const t=e&&e.data.sid&&this.baseInfoMap.get(e.data.sid);return t&&t.info.vid&&+t.info.vid||0})(e[0])};dg.networkState===CS.OFFLINE&&await Sl.race([dg.onlineWaiter,OI(2*mE.maxRetryTimeout)]);const n=t?"/events/proto-raws":"/events/messages";let r=this.url||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(FE("EVENT_REPORT_DOMAIN"),"&p=").concat(FE("STATS_COLLECTOR_PORT"),"&d=").concat(n):"https://".concat(FE("EVENT_REPORT_DOMAIN"),":").concat(FE("STATS_COLLECTOR_PORT")).concat(n));for(let e=0;e<2;e+=1){1===e&&(r=this.backupUrl||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(FE("EVENT_REPORT_BACKUP_DOMAIN"),"&p=").concat(FE("STATS_COLLECTOR_PORT"),"&d=").concat(n):"https://".concat(FE("EVENT_REPORT_BACKUP_DOMAIN"),":").concat(FE("STATS_COLLECTOR_PORT")).concat(n)));try{t?await cg(r,{timeout:1e4,data:i}):await ag(r,{timeout:1e4,data:i})}catch(t){if(1===e)throw t;continue}return}}createBaseInfo(e,t){const i=Object.assign({},of);return i.sid=e,this.baseInfoMap.set(e,{info:i,startTime:t}),i}reportResourceTiming(e,t){const i=performance.getEntriesByName(e),n=i[i.length-1];n&&this.reportApiInvoke(t,{name:"Client.resourceTiming",options:n,tag:lf.TRACER}).onSuccess()}};pE.on("REPORT_LOG_UPLOAD",e=>{e.networkState=dg.networkState,Tg.reportApiInvoke(null,{name:"logUploadError",options:e,tag:lf.TRACER})});class gg extends hE{constructor(e,t){super(),lp(this,"trackMediaType",void 0),lp(this,"_ID",void 0),lp(this,"_hints",[]),lp(this,"_isClosed",!1),lp(this,"_originMediaStreamTrack",void 0),lp(this,"_mediaStreamTrack",void 0),lp(this,"_external",{}),this._ID=t||wI(8,"track-"),this._originMediaStreamTrack=e,this._mediaStreamTrack=e,function(e){JE.includes(e)||JE.push(e)}(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){if(!e){const e=Tg.reportApiInvoke(null,{name:uf.GET_MEDIA_STREAM_TRACK,options:[],tag:lf.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){const t=JE.indexOf(e);-1!==t&&JE.splice(t,1)}(this),this.emit(uS.CLOSED)}}let Rg,Ig=1;class vg{constructor(e){lp(this,"lockingPromise",Sl.resolve()),lp(this,"locks",0),lp(this,"name",""),lp(this,"lockId",void 0),this.lockId=Ig++,e&&(this.name=e),CE.debug("[lock-".concat(this.name,"-").concat(this.lockId,"] is created."))}get isLocked(){return this.locks>0}lock(e){let t;this.locks+=1,CE.debug("[lock-".concat(this.name,"-").concat(this.lockId,"] is locked, current queue ").concat(this.locks,". ").concat("string"==typeof e?e:""));const i=new Sl(i=>{t=()=>{this.locks-=1,CE.debug("[lock-".concat(this.name,"-").concat(this.lockId,"] is not locked, current queue ").concat(this.locks,". ").concat("string"==typeof e?e:"")),i()}}),n=this.lockingPromise.then(()=>t);return this.lockingPromise=this.lockingPromise.then(()=>i),n}}function Cg(e,t){return function(i,n,r){const o=r.value;if("function"!=typeof o)throw new Error("Cannot use mutex on object property.");return r.value=async function(){const i=this[t];if(!i)throw new Error("mutex property key ".concat(t," doesn't exist on ").concat(e));const r=await i.lock("From ".concat(e,".").concat(n));try{for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];return await o.apply(this,a)}finally{r()}},r}}class yg extends gg{get isExternalTrack(){return this._isExternalTrack}get muted(){return this._muted}get enabled(){return this._enabled}constructor(e,t){super(e,t),lp(this,"_enabled",!0),lp(this,"_muted",!1),lp(this,"_isExternalTrack",!1),lp(this,"_isClosed",!1),lp(this,"_enabledMutex",void 0),lp(this,"processor",void 0),lp(this,"processorContext",void 0),lp(this,"_handleTrackEnded",()=>{this.onTrackEnded()}),this._enabledMutex=new vg("".concat(t)),e.addEventListener("ended",this._handleTrackEnded)}getTrackLabel(){var e,t;return null!==(e=null===(t=this._originMediaStreamTrack)||void 0===t?void 0:t.label)&&void 0!==e?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,CE.debug("[".concat(this.getTrackId(),"] close")),this.emit(sS.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 MI(this,sS.NEED_REPLACE_TRACK,this),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){CE.debug("[".concat(this.getTrackId(),"] track ended")),this.emit(uS.TRACK_ENDED)}stateCheck(e,t){if(CE.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(t,"]")),Bm(t,e),this._enabled&&this._muted&&"enabled"===e&&!1===t)throw new EE(_E.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print();if(!this._enabled&&!this._muted&&"muted"===e&&!0===t)throw new EE(_E.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}function Ag(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}!function(e){e.IOS_15_INTERRUPTION_START="ios15-interruption-start",e.IOS_15_INTERRUPTION_END="ios15-interruption-end",e.IOS_INTERRUPTION_START="ios-interruption-start",e.IOS_INTERRUPTION_END="ios-interruption-end",e.STATE_CHANGE="state-change"}(Rg||(Rg={}));const Og=window.AudioContext||window.webkitAudioContext;let bg=null;const wg=new class extends hE{constructor(){super(...arguments),lp(this,"prevState",void 0),lp(this,"curState",void 0),lp(this,"currentTime",void 0),lp(this,"currentTimeStuckAt",void 0),lp(this,"interruptDetectorTrack",void 0),lp(this,"onLocalAudioTrackMute",()=>{CE.info("ios15-interruption-start"),this.emit(Rg.IOS_15_INTERRUPTION_START)}),lp(this,"onLocalAudioTrackUnmute",async()=>{CE.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?CE.info("ios15-interruption-end-canceled"):(bg&&await bg.suspend(),this.emit(Rg.IOS_15_INTERRUPTION_END))})}get duringInterruption(){return"running"===this.prevState&&"interrupted"===this.curState}bindInterruptDetectorTrack(e){CE.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){CE.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 Ng(){if(!Og)return void CE.error("your browser is not support web audio");CE.info("create audio context");const e=function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Ag(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Ag(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({},FE("WEBAUDIO_INIT_OPTIONS"));CE.debug("audio context init option:",JSON.stringify(e)),bg=new Og(e),wg.curState=bg.state,bg.onstatechange=()=>{wg.prevState=wg.curState,wg.curState=bg?bg.state:void 0,(Kh()||Zh())&&"running"===wg.prevState&&"interrupted"===wg.curState&&(CE.info("ios-interruption-start"),wg.emit(Rg.IOS_INTERRUPTION_START)),(Kh()||Zh())&&"interrupted"===wg.prevState&&"running"===wg.curState&&(CE.info("ios-interruption-end"),wg.emit(Rg.IOS_INTERRUPTION_END)),wg.prevState!==wg.curState&&(CE.debug("AudioContext State Change","".concat(wg.prevState,"=>").concat(wg.curState)),wg.emit(Rg.STATE_CHANGE))},setInterval(()=>{var e;const t=null===(e=bg)||void 0===e?void 0:e.currentTime;if(wg.currentTime!==t)wg.currentTimeStuckAt&&(CE.debug("AudioContext current time resume at ".concat(t)),wg.currentTimeStuckAt=void 0),wg.currentTime=t;else{if(t!==wg.currentTimeStuckAt){Tg.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:t},tag:lf.TRACER}).onSuccess(),CE.warning("AudioContext current time stuck at ".concat(t))}wg.currentTimeStuckAt=t}},5e3),async function(e){const t=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","touchend","keydown","keyup"];let i,n=!1,r=!1,o=!1;function s(t){"running"===e.state?a(!1):Kh()||Zh()?"suspended"===e.state&&(a(!0),t&&e.resume().then(d,d)):"closed"!==e.state&&(a(!0),t&&e.resume().then(d,d))}function a(e){if(n!==e){n=e;for(let i=0,n=t;i<n.length;i+=1){const t=n[i];e?window.addEventListener(t,u,{capture:!0,passive:!0}):window.removeEventListener(t,u,{capture:!0,passive:!0})}}}function c(){s(!0)}function d(){s(!1)}function u(){s(!0)}function l(e){if(!o)if(i.paused)if(e){h(!1),o=!0;let e=void 0;try{e=i.play(),e?e.then(p,p):(i.addEventListener("playing",p),i.addEventListener("abort",p),i.addEventListener("error",p))}catch(e){p()}}else h(!0);else h(!1)}function h(e){if(r!==e){r=e;for(let i=0,n=t;i<n.length;i++){const t=n[i];e?window.addEventListener(t,_,{capture:!0,passive:!0}):window.removeEventListener(t,_,{capture:!0,passive:!0})}}}function p(){i.removeEventListener("playing",p),i.removeEventListener("abort",p),i.removeEventListener("error",p),o=!1,l(!1)}function _(){l(!0)}if(Kh()){const t=e.createMediaStreamDestination(),n=document.createElement("div");n.innerHTML="<audio x-webkit-airplay='deny'></audio>",i=n.children.item(0),i.controls=!1,i.disableRemotePlayback=!0,i.preload="auto",i.srcObject=t.stream,l(!0)}wg.on(Rg.STATE_CHANGE,c),s(!1)}(bg)}function Dg(){if(!bg){if(Ng(),!bg)throw new EE(_E.NOT_SUPPORTED,"can not create audio context");return bg}return bg}function Pg(e){if(function(){if(null!==Lg)return Lg;const e=Dg(),t=e.createBufferSource(),i=e.createGain(),n=e.createGain();t.connect(i),t.connect(n),t.disconnect(i);let r=!1;try{t.disconnect(i)}catch(e){r=!0}return t.disconnect(),Lg=r,r}())return;const t=e.connect,i=e.disconnect;e.connect=(i,n,r)=>(e._inputNodes||(e._inputNodes=[]),e._inputNodes.includes(i)||(i instanceof AudioNode?(e._inputNodes.push(i),t.call(e,i,n,r)):t.call(e,i,n)),e),e.disconnect=(n,r,o)=>{i.call(e),n?VI(e._inputNodes,n):e._inputNodes=[];for(const i of e._inputNodes)t.call(e,i)}}let Lg=null;function kg(e,t){let i=!1;const n=1/t;if(FE("DISABLE_WEBAUDIO")){const t=window.setInterval(()=>{i?window.clearInterval(t):e(performance.now()/1e3)},1e3*n)}else{const t=Dg();let r=t.createGain();r.gain.value=0,r.connect(t.destination);const o=()=>{if(i)return void(r=null);const s=t.createOscillator();s.onended=o,s.connect(r),s.start(0),s.stop(t.currentTime+n),e(t.currentTime)};o()}return()=>{i=!0}}class Mg{constructor(){lp(this,"context",void 0),lp(this,"analyserNode",void 0),lp(this,"sourceNode",void 0),this.context=Dg(),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)return 0;if(!this.context||Kh()||Zh()||"running"!==this.context.state&&this.context.resume(),!this.analyserNode)return 0;const e=new Float32Array(this.analyserNode.fftSize);if(this.analyserNode.getFloatTimeDomainData)this.analyserNode.getFloatTimeDomainData(e);else{const t=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(t);for(let i=0;i<e.length;++i)e[i]=t[i]/128-1}const t=zi(e).call(e,(e,t)=>e+t*t,0)/e.length;return Math.max(10*Math.log10(t)+100,0)/100}getAnalyserNode(){return this.analyserNode}rebuildAnalyser(){try{var e,t;null===(e=this.sourceNode)||void 0===e||e.disconnect(this.analyserNode),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4,null===(t=this.sourceNode)||void 0===t||t.connect(this.analyserNode)}catch(e){CE.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}}class Ug extends hE{get processSourceNode(){return this.sourceNode}set processedNode(e){var t;if(!this.isDestroyed&&this._processedNode!==e){try{var i;null===(i=this.sourceNode)||void 0===i||i.disconnect(this.outputNode)}catch(e){}null===(t=this._processedNode)||void 0===t||t.disconnect(),this._processedNode=e,this.connect()}}get processedNode(){return this._processedNode}constructor(){super(),lp(this,"outputNode",void 0),lp(this,"outputTrack",void 0),lp(this,"isPlayed",!1),lp(this,"sourceNode",void 0),lp(this,"context",void 0),lp(this,"audioBufferNode",void 0),lp(this,"destNode",void 0),lp(this,"audioOutputLevel",0),lp(this,"volumeLevelAnalyser",void 0),lp(this,"_processedNode",void 0),lp(this,"playNode",void 0),lp(this,"isDestroyed",!1),lp(this,"onNoAudioInput",void 0),lp(this,"isNoAudioInput",!1),lp(this,"_noAudioInputCount",0),this.context=Dg(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),Pg(this.outputNode),this.volumeLevelAnalyser=new Mg}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(wf.ON_AUDIO_BUFFER,function(e){for(let t=0;t<e.outputBuffer.numberOfChannels;t+=1){const 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(!MS().webAudioMediaStreamDest)throw new EE(_E.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&&jI(()=>{wg.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=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if(e>5)return this.isNoAudioInput=!0,this.onNoAudioInput&&this.onNoAudioInput(),!1;Kh()||Zh()?"suspended"===this.context.state&&this.context.resume():"running"!==this.context.state&&this.context.resume();const t=this.volumeLevelAnalyser.getAnalyserNode();let i;t.getFloatTimeDomainData?(i=new Float32Array(t.fftSize),t.getFloatTimeDomainData(i)):(i=new Uint8Array(t.fftSize),t.getByteTimeDomainData(i));let n=!1;for(let e=0;e<i.length;e++)0!==i[e]&&(n=!0);return n?(this.isNoAudioInput=!1,!0):(await OI(200),await this.checkHasAudioInput(e?e+1:1)&&n)}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)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.outputNode&&this.outputNode.disconnect()}connect(){var e;this.processedNode?null===(e=this.processedNode)||void 0===e||e.connect(this.outputNode):this.sourceNode&&this.sourceNode.connect(this.outputNode);this.volumeLevelAnalyser.updateSource(this.outputNode)}}class xg extends Ug{get isFreeze(){return!1}constructor(e,t,i){var n;if(super(),lp(this,"sourceNode",void 0),lp(this,"track",void 0),lp(this,"clonedTrack",void 0),lp(this,"audioElement",void 0),lp(this,"isCurrentTrackCloned",!1),lp(this,"isRemoteTrack",!1),lp(this,"originVolumeLevelAnalyser",void 0),lp(this,"rebuildWebAudio",async()=>{if(CE.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 CE.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then(()=>CE.info("resume success")),CE.debug("rebuild web audio because of ios 12 bugs"),this.disconnect();const e=this.track;this.track=this.track.clone(),this.isCurrentTrackCloned?e.stop():this.isCurrentTrackCloned=!0;const t=new MediaStream([this.track]);this.sourceNode=this.context.createMediaStreamSource(t),Pg(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const i=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(i,this.context.currentTime),Pg(this.outputNode),this.emit(wf.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()}),"audio"!==e.kind)throw new EE(_E.UNEXPECTED_ERROR);this.track=e;const r=new MediaStream([this.track]);if(this.isRemoteTrack=!!t,this.sourceNode=this.context.createMediaStreamSource(r),Pg(this.sourceNode),i){const e=i.clone();e.enabled=!0,this.clonedTrack=e,CE.debug("create an unmuted track ".concat(e.id," from the original track ").concat(i.id," to get the volume"));const t=this.context.createMediaStreamSource(new MediaStream([e]));Pg(t),this.originVolumeLevelAnalyser=new Mg,this.originVolumeLevelAnalyser.updateSource(t)}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=r;const o=Mh();t&&o.os===wh.IOS&&Number(null===(n=o.osVersion)||void 0===n?void 0:n.split(".")[0])<15&&(wg.on(Rg.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;const t=new MediaStream([e]);this.sourceNode=this.context.createMediaStreamSource(t),Pg(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(wf.UPDATE_SOURCE),this.audioElement.srcObject=t}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),wg.off("state-change",this.rebuildWebAudio),null===(e=this.originVolumeLevelAnalyser)||void 0===e||e.destroy(),this.clonedTrack=void 0,super.destroy()}createMediaStreamSourceNode(e){return this.context.createMediaStreamSource(new MediaStream([e]))}updateOriginTrack(e){const t=e.clone();t.enabled=!0,this.clonedTrack&&(this.clonedTrack.stop(),this.clonedTrack=t),CE.debug("create an unmuted track ".concat(t.id," from the original track ").concat(e.id," to get the volume"));const i=this.context.createMediaStreamSource(new MediaStream([t]));Pg(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}}async function Vg(e,t){const i=(e,t)=>e?"number"!=typeof e?e.max||e.exact||e.ideal||e.min||t:e:t,n={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?(n.video.mandatory.maxFrameRate=t.frameRate.max,n.video.mandatory.minFrameRate=t.frameRate.min):"number"==typeof t.frameRate&&(n.video.mandatory.maxFrameRate=t.frameRate),await navigator.mediaDevices.getUserMedia(n)}async function Fg(e){const t=await jg(e.mediaSource),i=await function(e){return new Sl((t,i)=>{const n=document.createElement("div");n.innerText="share screen",n.setAttribute("style","text-align: center; height: 25px; line-height: 25px; border-radius: 4px 4px 0 0; background: #D4D2D4; border-bottom: solid 1px #B9B8B9;");const r=document.createElement("div");r.setAttribute("style","width: 100%; height: 500px; padding: 15px 25px ; box-sizing: border-box;");const 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%;");const 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; overflow-y: scroll; padding: 0 15px; box-sizing: border-box;");const a=document.createElement("div");a.setAttribute("style","text-align: right; padding: 16px 0;");const c=document.createElement("button");c.innerHTML="cancel",c.setAttribute("style","width: 85px;"),c.onclick=()=>{document.body.removeChild(d);const e=new Error("NotAllowedError");e.name="NotAllowedError",i(e)},a.appendChild(c),r.appendChild(o),r.appendChild(s),r.appendChild(a);const 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(n),d.appendChild(r),document.body.appendChild(d),e.map(e=>{if(e.id){const i=document.createElement("div");i.setAttribute("style","width: 30%; height: 160px; padding: 20px 0; text-align: center;box-sizing: content-box;");let n=e.thumbnail;const{width:r}=n.getSize();r>1920&&(n=n.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='+n.toDataURL()+' /></div><span style="\theight: 40px; line-height: 40px; display: inline-block; width: 70%; word-break: keep-all; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">'+(e.name.replace(/[\u00A0-\u9999<>\&]/g,(function(e){return"&#"+e.charCodeAt(0)+";"}))+"</span>"),i.onclick=()=>{document.body.removeChild(d),t(e.id)},s.appendChild(i)}})})}(t);return await Vg(i,e)}async function jg(e){let t=["window","screen"];"application"!==e&&"window"!==e||(t=["window"]),"screen"===e&&(t=["screen"]);const i=Gg();if(!i)throw new EE(_E.ELECTRON_IS_NULL);let n=null;try{var r;n=(null===(r=i.desktopCapturer)||void 0===r?void 0:r.getSources({types:t}))||i.ipcRenderer.invoke("DESKTOP_CAPTURER_GET_SOURCES",{types:t})}catch(e){n=null}n&&n.then||(n=new Sl((e,n)=>{i.desktopCapturer.getSources({types:t},(t,i)=>{t?n(t):e(i)})}));try{return await n}catch(e){throw new EE(_E.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}let Bg=null;function Gg(){if(Bg)return Bg;try{return Bg=window.require("electron"),Bg}catch(e){return null}}const Wg=new vg("safari");let Hg=!1,Kg=!1;async function Yg(e,t){let i=0,n=null;for(;i<2;)try{n=await qg(e,t,i>0);break}catch(e){if(e instanceof EE)throw CE.error("[".concat(t,"] ").concat(e.toString())),e;const n=Jg(e.name||e.code||e,e.message);if(n.code===_E.MEDIA_OPTION_INVALID){CE.debug("[".concat(t,"] detect media option invalid, retry")),i+=1,await OI(500);continue}throw CE.error("[".concat(t,"] ").concat(n.toString())),n}if(!n)throw new EE(_E.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return n}async function qg(e,t,i){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new EE(_E.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));const n=MS(),r=new MediaStream;if(e.audioSource&&r.addTrack(e.audioSource),e.videoSource&&r.addTrack(e.videoSource),!e.audio&&!e.video&&!e.screen)return CE.debug("Using Video Source/ Audio Source"),r;if(e.screen)if(Gg())if(e.screen.sourceId){Xg(r,await Vg(e.screen.sourceId,e.screen))}else{Xg(r,await Fg(e.screen))}else if(Gh()&&e.screen.extensionId&&e.screen.mandatory){if(!n.getStreamFromExtension)throw new EE(_E.NOT_SUPPORTED,"This browser does not support screen sharing");CE.debug("[".concat(t,'] Screen access on chrome stable, looking for extension"'));const i=await(o=e.screen.extensionId,s=t,new Sl((e,t)=>{try{chrome.runtime.sendMessage(o,{getStream:!0},i=>{if(!i||!i.streamId)return CE.error("[".concat(s,"] No response from Chrome Plugin. Plugin not installed properly"),i),void t(new EE(_E.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));e(i.streamId)})}catch(e){CE.error("[".concat(s,"] AgoraRTC screensharing plugin is not accessible(").concat(o,")"),e.toString()),t(new EE(_E.CHROME_PLUGIN_NOT_INSTALL))}}));e.screen.mandatory.chromeMediaSourceId=i;Xg(r,await navigator.mediaDevices.getUserMedia({video:{mandatory:e.screen.mandatory}}))}else if(n.getDisplayMedia){e.screen.mediaSource&&_S(e.screen.mediaSource);const i={width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate,displaySurface:"screen"===e.screen.mediaSource?"monitor":e.screen.mediaSource};CE.debug("[".concat(t,"] getDisplayMedia:"),JSON.stringify({video:i,audio:!!e.screenAudio}));Xg(r,await navigator.mediaDevices.getDisplayMedia({video:i,audio:!!e.screenAudio}))}else{if(!Hh())throw CE.error("[".concat(t,"] This browser does not support screenSharing")),new EE(_E.NOT_SUPPORTED,"This browser does not support screen sharing");{e.screen.mediaSource&&_S(e.screen.mediaSource);const i={video:{mediaSource:e.screen.mediaSource,width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate}};CE.debug("[".concat(t,"] getUserMedia: ").concat(JSON.stringify(i)));Xg(r,await navigator.mediaDevices.getUserMedia(i))}}var o,s;if(!e.video&&!e.audio)return r;let a={video:e.video,audio:e.audio},c=FE("MEDIA_DEVICE_CONSTRAINTS");if(c)try{"string"==typeof c&&(c=JSON.parse(c)),a=function e(t,i){if(!XI(t)||!XI(i))return i;if(Array.isArray(t)&&!Array.isArray(i)||!Array.isArray(t)&&Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t)){const n=[...t];for(let r=0;r<i.length;r++)n[r]=e(t[r],i[r]);return n}{const n=yI({},t);for(const r in i)Object.prototype.hasOwnProperty.call(i,r)&&(Object.prototype.hasOwnProperty.call(t,r)?n[r]=e(t[r],i[r]):n[r]=i[r]);return n}}(a,c)}catch(e){}CE.debug("[".concat(t,"] GetUserMedia"),JSON.stringify(a)),Mh();let d,u=null;(Wh()||Kh()||Fh())&&(u=await Wg.lock());try{d=await navigator.mediaDevices.getUserMedia(a)}catch(e){throw u&&u(),e}return a.audio&&(Hg=!0),a.video&&(Kg=!0),Xg(r,d),u&&u(),r}function Jg(e,t){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new EE(_E.MEDIA_OPTION_INVALID,"".concat(e,": ").concat(t));case"NotFoundError":case"DevicesNotFoundError":return new EE(_E.DEVICE_NOT_FOUND,"".concat(e,": ").concat(t));case"NotSupportedError":return new EE(_E.NOT_SUPPORTED,"".concat(e,": ").concat(t));case"NotReadableError":return new EE(_E.NOT_READABLE,"".concat(e,": ").concat(t));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new EE(_E.PERMISSION_DENIED,"".concat(e,": ").concat(t));case"ConstraintNotSatisfiedError":return new EE(_E.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(t));default:return CE.error("getUserMedia unexpected error",e),new EE(_E.UNEXPECTED_ERROR,"".concat(e,": ").concat(t))}}function Xg(e,t){const i=e.getVideoTracks()[0],n=e.getAudioTracks()[0],r=t.getVideoTracks()[0],o=t.getAudioTracks()[0];o&&(n&&e.removeTrack(n),e.addTrack(o)),r&&(i&&e.removeTrack(i),e.addTrack(r))}const zg=new class extends hE{get state(){return this._state}set state(e){e!==this._state&&(this.emit(pf.STATE_CHANGE,e),this._state=e)}constructor(){super(),lp(this,"_state",hf.IDLE),lp(this,"isAccessMicrophonePermission",!1),lp(this,"isAccessCameraPermission",!1),lp(this,"lastAccessMicrophonePermission",!1),lp(this,"lastAccessCameraPermission",!1),lp(this,"checkdeviceMatched",!1),lp(this,"deviceInfoMap",new Map),this.init().then(()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval(()=>{(FE("ENUMERATE_DEVICES_INTERVAL")||ip()&&tp())&&this.updateDevicesInfo()},FE("ENUMERATE_DEVICES_INTERVAL_TIME"))}).catch(e=>CE.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 EE(_E.NOT_SUPPORTED,"enumerateDevices() not supported.").throw()}const n=await navigator.mediaDevices.enumerateDevices(),r=this.checkMediaDeviceInfoIsOk(n);let o=!this.isAccessMicrophonePermission&&e,s=!this.isAccessCameraPermission&&t;r.audio&&(o=!1),r.video&&(s=!1);let a=null,c=null,d=null;if(!i&&(o||s)){if(Wg.isLocked){CE.debug("[device manager] wait GUM lock");(await Wg.lock())(),CE.debug("[device manager] GUM unlock")}if(Hg&&(o=!1,this.isAccessMicrophonePermission=!0),Kg&&(s=!1,this.isAccessCameraPermission=!0),CE.debug("[device manager] check media device permissions",e,t,o,s),o&&s){try{d=await navigator.mediaDevices.getUserMedia({audio:!0,video:!0})}catch(e){const t=Jg(e.name||e.code||e,e.message);if(t.code===_E.PERMISSION_DENIED)throw t;CE.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0,this.isAccessMicrophonePermission=!0}else if(o){try{a=await navigator.mediaDevices.getUserMedia({audio:e})}catch(e){const t=Jg(e.name||e.code||e,e.message);if(t.code===_E.PERMISSION_DENIED)throw t;CE.warning("getUserMedia failed in getDevices",t)}this.isAccessMicrophonePermission=!0}else if(s){try{c=await navigator.mediaDevices.getUserMedia({video:t})}catch(e){const t=Jg(e.name||e.code||e,e.message);if(t.code===_E.PERMISSION_DENIED)throw t;CE.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0}CE.debug("[device manager] mic permission",e,"cam permission",t)}try{const e=await navigator.mediaDevices.enumerateDevices();return a&&a.getTracks().forEach(e=>e.stop()),c&&c.getTracks().forEach(e=>e.stop()),d&&d.getTracks().forEach(e=>e.stop()),a=null,c=null,d=null,e}catch(e){a&&a.getTracks().forEach(e=>e.stop()),c&&c.getTracks().forEach(e=>e.stop()),d&&d.getTracks().forEach(e=>e.stop()),a=null,c=null,d=null;return new EE(_E.ENUMERATE_DEVICES_FAILED,e.toString()).throw()}}async getRecordingDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter(e=>"audioinput"===e.kind)}async getCamerasDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!1,!0,e)).filter(e=>"videoinput"===e.kind)}async getSpeakers(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter(e=>"audiooutput"===e.kind)}searchDeviceIdByName(e){let t=null;return this.deviceInfoMap.forEach(i=>{i.device.label===e&&(t=i.device.deviceId)}),t}async getDeviceById(e){const t=(await this.enumerateDevices(!0,!0,!0)).find(t=>t.deviceId===e);if(!t)throw new EE(_E.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return t}async init(){this.state=hf.INITING;try{await this.updateDevicesInfo(),this.state=hf.INITEND}catch(e){if(CE.warning("Device Detection functionality cannot start properly.",e.toString()),this.state=hf.IDLE,!function(){if("boolean"==typeof isSecureContext)return isSecureContext;return"https:"===location.protocol||"file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname||"::1"===location.hostname}()){new EE(_E.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.").throw()}throw e}}async updateDevicesInfo(){const e=await this.enumerateDevices(!0,!0,!0),t=Date.now(),i=[];if(e[0]&&e[0].label&&!1===this.checkdeviceMatched){this.checkdeviceMatched=!0;const 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?CE.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is the same group")):CE.warning("[device-check] default input ".concat(t.label," and output ").concat(i.label," is not the same group")):CE.debug("[device-check] default input or output not found")}const n=this.checkMediaDeviceInfoIsOk(e);if(e.forEach(e=>{if(!e.deviceId)return;const n=this.deviceInfoMap.get("".concat(e.kind,"_").concat(e.deviceId));if("ACTIVE"!==(n?n.state:"INACTIVE")){const n={initAt:t,updateAt:t,device:e,state:"ACTIVE"};this.deviceInfoMap.set("".concat(e.kind,"_").concat(e.deviceId),n),i.push(n)}n&&(n.updateAt=t)}),this.deviceInfoMap.forEach((e,n)=>{"ACTIVE"===e.state&&e.updateAt!==t&&(e.state="INACTIVE",i.push(e))}),this.state!==hf.INITEND)return n.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),void(n.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0));i.forEach(e=>{switch(e.device.kind){case"audioinput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(pf.RECORDING_DEVICE_CHANGED,e);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(pf.CAMERA_DEVICE_CHANGED,e);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(pf.PLAYOUT_DEVICE_CHANGED,e)}}),n.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),n.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0)}checkMediaDeviceInfoIsOk(e){const t=e.filter(e=>"audioinput"===e.kind),i=e.filter(e=>"videoinput"===e.kind),n={audio:!1,video:!1};for(const e of t)if(e.label&&e.deviceId){n.audio=!0;break}for(const e of i)if(e.label&&e.deviceId){n.video=!0;break}return n}};const Qg=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],Zg=new class{constructor(){lp(this,"onAutoplayFailed",void 0),lp(this,"elementMap",new Map),lp(this,"elementStateMap",new Map),lp(this,"elementsNeedToResume",[]),lp(this,"sinkIdMap",new Map),lp(this,"autoResumeAfterInterruption",()=>{Array.from(this.elementMap.entries()).forEach(e=>{let[t,i]=e;const n=this.elementStateMap.get(t),r=i.srcObject.getAudioTracks()[0];Jh()?r&&"live"===r.readyState&&"running"===wg.curState&&(CE.debug("auto resume after interruption for iOS 15"),i.pause(),i.play()):n&&"paused"===n&&r&&"live"===r.readyState&&"running"===wg.curState&&(CE.debug("auto resume after interruption for iOS"),i.play())})}),lp(this,"autoResumeAfterInterruptionOnIOS15",()=>{Array.from(this.elementMap.entries()).forEach(e=>{let[t,i]=e;const n=i.srcObject.getAudioTracks()[0];n&&"live"===n.readyState&&(CE.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),i.pause(),i.play())})}),this.autoResumeAudioElement(),wg.on(Rg.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),wg.on(Rg.IOS_15_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15),wg.on(Rg.STATE_CHANGE,()=>{Kh()&&"suspended"===wg.prevState&&"running"===wg.curState&&this.autoResumeAfterInterruption()})}async setSinkID(e,t){const i=this.elementMap.get(e);if(this.sinkIdMap.set(e,t),i)try{await i.setSinkId(t)}catch(e){throw new EE(_E.PERMISSION_DENIED,"can not set sink id: "+e.toString())}}play(e,t,i,n){if(this.elementMap.has(t))return;const r=document.createElement("audio");r.autoplay=!0,r.srcObject=new MediaStream([e]),this.bindAudioElementEvents(t,r),this.elementMap.set(t,r),this.elementStateMap.set(t,tf.INIT),this.setVolume(t,i);const o=this.sinkIdMap.get(t);if(o)try{r.setSinkId(o).catch(e=>{CE.warning("[".concat(t,"] set sink id failed"),e.toString())})}catch(e){CE.warning("[".concat(t,"] set sink id failed"),e.toString())}const s=r.play();s&&s.then&&s.catch(e=>{n&&Tg.autoplayFailed(n,"audio",e.message,t),CE.warning("audio element play warning",e.toString()),this.elementMap.has(t)&&"NotAllowedError"===e.name&&(CE.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(r),jI(()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),hg()}))})}updateTrack(e,t){const i=this.elementMap.get(e);i&&(i.srcObject=new MediaStream([t]))}isPlaying(e){return this.elementMap.has(e)}setVolume(e,t){const i=this.elementMap.get(e);i&&(t=Math.max(0,Math.min(100,t)),i.volume=t/100)}stop(e){const t=this.elementMap.get(e);if(this.sinkIdMap.delete(e),!t)return;const 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){Qg.forEach(i=>{t.addEventListener(i,i=>{const n=this.elementStateMap.get(e),r="pause"===i.type?"paused":i.type;if(CE.debug("[".concat(e,"] audio-element-status change ").concat(n," => ").concat(r)),"error"===i.type){const i=null==t?void 0:t.error;i&&CE.error("[".concat(e,"] media error, code: ").concat(i.code,", message: ").concat(i.message))}this.elementStateMap.set(e,r)})})}getPlayerState(e){return this.elementStateMap.get(e)||"uninit"}autoResumeAudioElement(){const e=()=>{this.elementsNeedToResume.forEach(e=>{e.play().then(e=>{CE.debug("Auto resume audio element success")}).catch(e=>{CE.warning("Auto resume audio element failed!",e)})}),this.elementsNeedToResume=[]};new Sl(e=>{document.body?e():window.addEventListener("load",()=>e())}).then(()=>{np()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0))})}};function $g(){return function(e,t,i){const n=i.value;return"function"==typeof n&&(i.value=function(){this._isClosed&&new EE(_E.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning");for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const r=n.apply(this,t);return r instanceof Sl?new Sl((e,t)=>{r.then(e).catch(t)}):r}),i}}var eR,tR,iR,nR,rR,oR,sR,aR,cR,dR,uR,lR,hR,pR,_R,ER,mR,fR,SR,TR,gR,RR,IR,vR,CR,yR,AR,OR,bR,wR,NR,DR,PR,LR,kR,MR,UR,xR=Hi("Array").values,VR=Zr,FR=Ge,jR=u,BR=xR,GR=Array.prototype,WR={DOMTokenList:!0,NodeList:!0},HR=function(e){var t=e.values;return e===GR||jR(GR,e)&&t===GR.values||FR(WR,VR(e))?BR:t};function KR(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function YR(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?KR(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):KR(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class qR extends hE{constructor(e){super(),lp(this,"name","VideoProcessorDestination"),lp(this,"ID","0"),lp(this,"_source",void 0),lp(this,"videoContext",void 0),lp(this,"inputTrack",void 0),this.videoContext=e}get kind(){return"video"}get enabled(){return!0}pipe(){throw new EE(_E.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor")}unpipe(){throw new EE(_E.NOT_SUPPORTED,"VideoProcessor cannot unpipe to any other Processor")}enable(){}disable(){}updateInput(e){if(e.context!==this.videoContext)throw new 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(AS.ON_TRACK,e.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(AS.ON_TRACK,void 0)}}class JR extends hE{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t){super(),lp(this,"constraintsMap",new Map),lp(this,"statsRegistry",[]),lp(this,"usageRegistry",[]),lp(this,"trackId",void 0),lp(this,"direction",void 0),lp(this,"_chained",!1),this.trackId=e,this.direction=t}async getConstraints(){return await kI(this,OS.REQUEST_CONSTRAINTS)}async requestApplyConstraints(e,t){var i;return CE.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),MI(this,OS.REQUEST_UPDATE_CONSTRAINTS,Array.from(HR(i=this.constraintsMap).call(i)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return CE.info("processor ".concat(e.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(e),MI(this,OS.REQUEST_UPDATE_CONSTRAINTS,Array.from(HR(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){const i=this.statsRegistry.findIndex(i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t);-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:n,cb:r}of this.statsRegistry)try{const o=r();e.push({processorID:t,processorName:i,type:n,stats:o})}catch(e){CE.error(new EE(_E.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){const t=this.usageRegistry.findIndex(t=>t.processorID===e.ID&&t.processorName===e.name);-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof Sl&&(i=await i),e.push(YR(YR({},i),{},{direction:this.direction}))}catch(e){CE.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class XR extends hE{constructor(e){super(),lp(this,"name","AudioProcessorDestination"),lp(this,"ID","0"),lp(this,"inputTrack",void 0),lp(this,"inputNode",void 0),lp(this,"audioProcessorContext",void 0),lp(this,"_source",void 0),this.audioProcessorContext=e}get kind(){return"audio"}get enabled(){return!0}pipe(){throw new EE(_E.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new EE(_E.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(AS.ON_TRACK,void 0),this.emit(AS.ON_NODE,void 0)}updateInput(e){if(e.context!==this.audioProcessorContext)throw new 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(AS.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(AS.ON_NODE,this.inputNode))}}class zR extends hE{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t,i){super(),lp(this,"constraintsMap",new Map),lp(this,"statsRegistry",[]),lp(this,"audioContext",void 0),lp(this,"trackId",void 0),lp(this,"direction",void 0),lp(this,"usageRegistry",[]),lp(this,"_chained",!1),this.audioContext=e,this.trackId=t,this.direction=i}async getConstraints(){return kI(this,OS.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(e,t){var i;return CE.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),MI(this,OS.REQUEST_UPDATE_CONSTRAINTS,Array.from(HR(i=this.constraintsMap).call(i)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),MI(this,OS.REQUEST_UPDATE_CONSTRAINTS,Array.from(HR(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){const i=this.statsRegistry.findIndex(i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t);-1!==i&&this.statsRegistry.splice(i,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:i,type:n,cb:r}of this.statsRegistry)try{const o=r();e.push({processorID:t,processorName:i,type:n,stats:o})}catch(e){CE.error(new EE(_E.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){const t=this.usageRegistry.findIndex(t=>t.processorID===e.ID&&t.processorName===e.name);-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let i=t();i instanceof Sl&&(i=await i),e.push(YR(YR({},i),{},{direction:this.direction}))}catch(e){CE.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class QR extends hE{get isPlayed(){return!0}get isFreeze(){return!1}constructor(){super(),lp(this,"context",void 0),lp(this,"processSourceNode",void 0),lp(this,"outputTrack",void 0),lp(this,"processedNode",void 0),lp(this,"clonedTrack",void 0),lp(this,"outputNode",void 0),this.outputNode=new ZR}setVolume(){}createOutputTrack(){throw new EE(_E.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 ZR{disconnect(){}connect(){}}function $R(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function eI(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?$R(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):$R(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let tI=(eR=Sg({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),tR=Sg({argsMap:(e,t)=>[e.getTrackId(),t]}),iR=$g(),nR=Cg("LocalAudioTrack","_enabledMutex"),rR=Sg({argsMap:(e,t)=>[e.getTrackId(),t]}),oR=$g(),sR=Cg("LocalAudioTrack","_enabledMutex"),aR=Sg({argsMap:(e,t)=>[e.getTrackId(),t]}),cR=$g(),dR=$g(),uR=$g(),lR=Sg({argsMap:e=>[e.getTrackId()]}),hR=$g(),pR=Sg({argsMap:e=>[e.getTrackId()]}),_R=$g(),ER=Sg({argsMap:e=>[e.getTrackId()]}),mR=Sg({argsMap:(e,t)=>[e.getTrackId(),t.name]}),fR=Sg({argsMap:e=>[e.getTrackId()]}),JT((SR=class extends yg{get isPlaying(){return this._useAudioElement?Zg.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"LocalAudioTrack"}constructor(e,t,i,n){super(e,i),lp(this,"trackMediaType","audio"),lp(this,"_encoderConfig",void 0),lp(this,"_source",void 0),lp(this,"_enabled",!0),lp(this,"_volume",100),lp(this,"_useAudioElement",!1),lp(this,"_bypassWebAudio",!1),lp(this,"processor",void 0),lp(this,"processorContext",void 0),lp(this,"processorDestination",void 0),lp(this,"_getOriginVolumeLevel",void 0),this._encoderConfig=t,this._getOriginVolumeLevel=!!n,FE("DISABLE_WEBAUDIO")?(this._source=new QR,this._useAudioElement=!0,this._bypassWebAudio=!0):(this._source=new xg(e,!1,this._getOriginVolumeLevel?e:void 0),FE("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")||(this._useAudioElement=!0)),this.processorContext=new zR(this._source.context,this.getTrackId(),"local"),this.processorDestination=new XR(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(wf.UPDATE_SOURCE,()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})})}setVolume(e){Wm(e,"volume",0,1e3),this._volume=e,this._source.setVolume(e/100),this._useAudioElement&&Zg.setVolume(this.getTrackId(),e);try{if(this._bypassWebAudio)return void CE.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));const e=this._source.createOutputTrack();this._mediaStreamTrack!==e&&(this._mediaStreamTrack=e,MI(this,sS.NEED_REPLACE_TRACK,this).then(()=>{CE.debug("[".concat(this.getTrackId(),"] replace web audio track success"))}).catch(e=>{CE.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 EE(_E.NOT_SUPPORTED,"your browser does not support setting the audio output device");await Zg.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(CE.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){this._originMediaStreamTrack.enabled=!0;try{i||(this._enabled=!0),await MI(this,sS.NEED_ENABLE_TRACK,this),CE.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(e," success"))}catch(e){throw i||(this._enabled=!1),CE.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}}else{this._originMediaStreamTrack.enabled=!1,i||(this._enabled=!1);try{await MI(this,sS.NEED_DISABLE_TRACK,this)}catch(e){throw i||(this._enabled=!0),CE.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,CE.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await MI(this,sS.NEED_MUTE_TRACK,this):await MI(this,sS.NEED_UNMUTE_TRACK,this))}getStats(){WI(()=>{CE.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")},"localAudioTrackGetStatsWarning");const e=UI(this,sS.GET_STATS);return e||eI({},Mf)}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(wf.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(wf.ON_AUDIO_BUFFER),this._source.on(wf.ON_AUDIO_BUFFER,t=>e(t))}play(){CE.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(CE.debug("[".concat(this.getTrackId(),"] start audio playback in element")),Zg.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){CE.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?Zg.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];CE.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&Zg.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 MI(this,sS.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(e))}renewMediaStreamTrack(e){return Sl.resolve(void 0)}pipe(e){if(this._bypassWebAudio)throw new EE(_E.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===e)return e;if(e._source)throw new EE(_E.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;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(AS.ON_TRACK,async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e),await MI(this,sS.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await MI(this,sS.NEED_REPLACE_TRACK,this))}),this.processorDestination.on(AS.ON_NODE,e=>{this._source.processedNode=e})}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(AS.ON_TRACK),this.processorDestination.removeAllListeners(AS.ON_NODE)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(OS.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(OS.REQUEST_CONSTRAINTS)}}).prototype,"setVolume",[eR],Object.getOwnPropertyDescriptor(SR.prototype,"setVolume"),SR.prototype),JT(SR.prototype,"setPlaybackDevice",[tR,iR],Object.getOwnPropertyDescriptor(SR.prototype,"setPlaybackDevice"),SR.prototype),JT(SR.prototype,"setEnabled",[nR,rR,oR],Object.getOwnPropertyDescriptor(SR.prototype,"setEnabled"),SR.prototype),JT(SR.prototype,"setMuted",[sR,aR,cR],Object.getOwnPropertyDescriptor(SR.prototype,"setMuted"),SR.prototype),JT(SR.prototype,"getStats",[dR],Object.getOwnPropertyDescriptor(SR.prototype,"getStats"),SR.prototype),JT(SR.prototype,"setAudioFrameCallback",[uR],Object.getOwnPropertyDescriptor(SR.prototype,"setAudioFrameCallback"),SR.prototype),JT(SR.prototype,"play",[lR,hR],Object.getOwnPropertyDescriptor(SR.prototype,"play"),SR.prototype),JT(SR.prototype,"stop",[pR,_R],Object.getOwnPropertyDescriptor(SR.prototype,"stop"),SR.prototype),JT(SR.prototype,"close",[ER],Object.getOwnPropertyDescriptor(SR.prototype,"close"),SR.prototype),JT(SR.prototype,"pipe",[mR],Object.getOwnPropertyDescriptor(SR.prototype,"pipe"),SR.prototype),JT(SR.prototype,"unpipe",[fR],Object.getOwnPropertyDescriptor(SR.prototype,"unpipe"),SR.prototype),SR),iI=(TR=Sg({argsMap:(e,t)=>[e.getTrackId(),t]}),gR=$g(),RR=Cg("MicrophoneAudioTrack","_enabledMutex"),IR=Sg({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),vR=$g(),CR=Sg({argsMap:e=>[e.getTrackId()]}),JT((yR=class extends tI{get __className__(){return"MicrophoneAudioTrack"}constructor(e,t,i,n){super(e,t.encoderConfig?xE(t.encoderConfig):{},n,FE("GET_VOLUME_OF_MUTED_AUDIO_TRACK")),lp(this,"_config",void 0),lp(this,"_deviceName","default"),lp(this,"_constraints",void 0),lp(this,"_originalConstraints",void 0),lp(this,"_enabled",!0),this._config=t,this._constraints=i,this._originalConstraints=i,this._deviceName=e.label,"boolean"==typeof t.bypassWebAudio&&(this._bypassWebAudio=t.bypassWebAudio),Jh()&&wg.bindInterruptDetectorTrack(this),this.bindProcessorContextEvents()}async setDevice(e){if(CE.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{const t=await zg.getDeviceById(e),i={};i.audio=eI({},this._constraints),i.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let n=null;try{n=await Yg(i,this.getTrackId())}catch(e){throw CE.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),n=await Yg({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(n.getAudioTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(n.getAudioTracks()[0],!1),this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw CE.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await zg.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw CE.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}CE.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"))}async setEnabled(e,t,i){if(t)return CE.debug("[".concat(this.getTrackId(),"] setEnabled false (do not close microphone)")),await super._setEnabled(e);if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(CE.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){var n;this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop(),null===(n=this._source.clonedTrack)||void 0===n||n.stop(),i||(this._enabled=!1);try{await MI(this,sS.NEED_DISABLE_TRACK,this)}catch(e){throw CE.error("[".concat(this.getTrackId(),"] setEnabled false failed"),e.toString()),e}return}const r=eI({},this._constraints),o=zg.searchDeviceIdByName(this._deviceName);o&&!r.deviceId&&(r.deviceId=o);try{i||(this._enabled=!0);const e=await Yg({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1),await MI(this,sS.NEED_ENABLE_TRACK,this)}catch(e){throw i||(this._enabled=!1),CE.error("[".concat(this.getTrackId(),"] setEnabled true failed"),e.toString()),e}CE.info("[".concat(this.getTrackId(),"] setEnabled success"))}close(){super.close(),Jh()&&wg.unbindInterruptDetectorTrack(this)}onTrackEnded(){if((Kh()||Zh())&&this._enabled&&!this._isClosed&&wg.duringInterruption){const e=async()=>{wg.off(Rg.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(CE.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};wg.on(Rg.IOS_INTERRUPTION_END,e)}else CE.debug("[".concat(this.getTrackId(),"] track ended")),this.emit(uS.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=zg.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId=i),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();const e=await Yg({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0)}}bindProcessorContextEvents(){this.processorContext.on(OS.REQUEST_UPDATE_CONSTRAINTS,async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t()}catch(e){i(e)}}),this.processorContext.on(OS.REQUEST_CONSTRAINTS,async e=>{e(this._originMediaStreamTrack.getSettings())})}}).prototype,"setDevice",[TR,gR],Object.getOwnPropertyDescriptor(yR.prototype,"setDevice"),yR.prototype),JT(yR.prototype,"setEnabled",[RR,IR,vR],Object.getOwnPropertyDescriptor(yR.prototype,"setEnabled"),yR.prototype),JT(yR.prototype,"close",[CR],Object.getOwnPropertyDescriptor(yR.prototype,"close"),yR.prototype),yR),nI=(AR=Sg({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),OR=$g(),bR=Sg({argsMap:e=>[e.getTrackId()]}),wR=$g(),NR=Sg({argsMap:e=>[e.getTrackId()]}),DR=$g(),PR=Sg({argsMap:e=>[e.getTrackId()]}),LR=$g(),kR=Sg({argsMap:e=>[e.getTrackId()]}),MR=$g(),JT((UR=class extends tI{get __className__(){return"BufferSourceAudioTrack"}constructor(e,t,i,n){super(t.createOutputTrack(),i,n),lp(this,"source",void 0),lp(this,"_bufferSource",void 0),this.source=e,this._bufferSource=t,this._bufferSource.on(wf.AUDIO_SOURCE_STATE_CHANGE,e=>{this.emit(uS.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",[AR,OR],Object.getOwnPropertyDescriptor(UR.prototype,"startProcessAudioBuffer"),UR.prototype),JT(UR.prototype,"pauseProcessAudioBuffer",[bR,wR],Object.getOwnPropertyDescriptor(UR.prototype,"pauseProcessAudioBuffer"),UR.prototype),JT(UR.prototype,"seekAudioBuffer",[NR,DR],Object.getOwnPropertyDescriptor(UR.prototype,"seekAudioBuffer"),UR.prototype),JT(UR.prototype,"resumeProcessAudioBuffer",[PR,LR],Object.getOwnPropertyDescriptor(UR.prototype,"resumeProcessAudioBuffer"),UR.prototype),JT(UR.prototype,"stopProcessAudioBuffer",[kR,MR],Object.getOwnPropertyDescriptor(UR.prototype,"stopProcessAudioBuffer"),UR.prototype),UR);class rI extends tI{get __className__(){return"MixingAudioTrack"}get isActive(){for(const e of this.trackList)if(e._enabled&&!e._isClosed&&!e.muted)return!0;return!1}constructor(){const e=Dg().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,wI(8,"track-mix-")),lp(this,"trackList",void 0),lp(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)?(CE.debug("add ".concat(e.getTrackId()," to mixing track")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):CE.debug("track ".concat(e.getTrackId()," is already added"))}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){CE.debug("remove ".concat(e.getTrackId()," from mixing track"));try{e._source.outputNode.disconnect(this.destNode)}catch(e){}VI(this.trackList,e),this.updateEncoderConfig()}}updateEncoderConfig(){const 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 oI extends hE{constructor(){super(...arguments),lp(this,"resultStorage",new Map)}setLocalAudioStats(e,t,i){this.record("AUDIO_INPUT_LEVEL_TOO_LOW",e,this.checkAudioInputLevel(i,t)),this.record("SEND_AUDIO_BITRATE_TOO_LOW",e,this.checkSendAudioBitrate(i,t))}setLocalVideoStats(e,t,i){this.record("SEND_VIDEO_BITRATE_TOO_LOW",e,this.checkSendVideoBitrate(i,t)),this.record("FRAMERATE_INPUT_TOO_LOW",e,this.checkFramerateInput(i,t)),this.record("FRAMERATE_SENT_TOO_LOW",e,this.checkFramerateSent(i))}setRemoteAudioStats(e,t){const i=e.getUserId();this.record("AUDIO_OUTPUT_LEVEL_TOO_LOW",i,this.checkAudioOutputLevel(t))}setRemoteVideoStats(e,t){const 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});const n=this.resultStorage.get(e);if(n&&(n.result.push(i),n.result.length>=5)){const i=n.result.includes(!0);n.isPrevNormal&&!i&&this.emit("exception",sI[e],e,t),!n.isPrevNormal&&i&&this.emit("exception",sI[e]+2e3,e+"_RECOVER",t),n.isPrevNormal=i,n.result=[]}}checkAudioOutputLevel(e){return!(e.receiveBitrate>0&&0===e.receiveLevel)}checkAudioInputLevel(e,t){return t instanceof rI&&!t.isActive||(!!t.muted||0!==e.sendVolumeLevel)}checkFramerateInput(e,t){let i=null;t._encoderConfig&&t._encoderConfig.frameRate&&(i=mI(t._encoderConfig.frameRate));const n=e.captureFrameRate;return!i||!n||!(i>10&&n<5||i<10&&i>=5&&n<=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 rI&&!t.isActive||(!!t.muted||0!==e.sendBitrate)}checkVideoDecode(e){return 0===e.receiveBitrate||0!==e.decodeFrameRate}}const sI={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};const aI=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){const i=performance.getEntriesByName("agora-web-sdk/".concat(e,"/subscribe-").concat(t));if(i.length>0){const e=i[i.length-1];return Math.round(performance.now()-e.startTime)}return 0}measureFromPublishStart(e,t){const i=performance.getEntriesByName("agora-web-sdk/".concat(e,"/publish-").concat(t));if(i.length>0){const e=i[i.length-1];return Math.round(performance.now()-e.startTime)}return 0}};function cI(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function dI(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?cI(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):cI(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class uI{constructor(e){lp(this,"store",void 0),lp(this,"onStatsException",void 0),lp(this,"onUploadPublishDuration",void 0),lp(this,"localStats",new Map),lp(this,"remoteStats",new Map),lp(this,"updateStatsInterval",void 0),lp(this,"trafficStats",void 0),lp(this,"trafficStatsPeerList",[]),lp(this,"uplinkStats",void 0),lp(this,"exceptionMonitor",void 0),lp(this,"p2pChannel",void 0),lp(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 oI,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(RS.LocalAudioTrack)||dI({},Mf)}getLocalVideoTrackStats(){return this.localStats.get(RS.LocalVideoTrack)||dI({},Uf)}getRemoteAudioTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const 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 n;const r=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.audioStats;r&&(i[e]=t(e,r))}else Array.from(this.remoteStats.entries()).forEach(e=>{let[n,{audioStats:r}]=e;r&&(i[n]=t(n,r))});return i}getRemoteNetworkQualityStats(e){const t={};if(e){var i;const n=null===(i=this.remoteStats.get(e))||void 0===i?void 0:i.networkStats;n&&(t[e]=n)}else Array.from(this.remoteStats.entries()).forEach(e=>{let[i,{networkStats:n}]=e;n&&(t[i]=n)});return t}getRemoteVideoTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const 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 n;const r=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.videoStats;r&&(i[e]=t(e,r))}else Array.from(this.remoteStats.entries()).forEach(e=>{let[n,{videoStats:r}]=e;r&&(i[n]=t(n,r))});return i}getRTCStats(){let e=0,t=0,i=0,n=0;const r=this.localStats.get(RS.LocalAudioTrack);r&&(e+=r.sendBytes,t+=r.sendBitrate);const o=this.localStats.get(RS.LocalVideoTrack);o&&(e+=o.sendBytes,t+=o.sendBitrate);const s=this.localStats.get(RS.LocalVideoLowTrack);s&&(e+=s.sendBytes,t+=s.sendBitrate),this.remoteStats.forEach(e=>{let{audioStats:t,videoStats:r}=e;t&&(i+=t.receiveBytes,n+=t.receiveBitrate),r&&(i+=r.receiveBytes,n+=r.receiveBitrate)});let a=1;return this.trafficStats&&(a+=this.trafficStats.peer_delay.length),{Duration:0,UserCount:a,SendBitrate:t,SendBytes:e,RecvBytes:i,RecvBitrate:n,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;const i=null===(t=this.p2pChannel)||void 0===t?void 0:t.getRemoteMedia(e.peer_uid),n=null!=i&&i.videoSSRC?aI.measureFromSubscribeStart(this.store.clientId,i.videoSSRC):0,r=null!=i&&i.audioSSRC?aI.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,n>r?n:r),this.trafficStatsPeerList.push(e.peer_uid))}),this.trafficStats=e}updateUplinkStats(e){this.uplinkStats&&this.uplinkStats.B_fir!==e.B_fir&&CE.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;const n=!!i&&t.framesDecodeFreezeTime>i.framesDecodeFreezeTime,r=!i||t.framesDecodeCount>i.framesDecodeCount;return n||!r}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,n]=t;switch(i){case RS.LocalVideoTrack:case RS.LocalVideoLowTrack:{const t=n,r=dI({},Uf),o=e.getStats(),s=e.getLocalMedia(i);if(o){const i=o.videoSend.find(e=>e.ssrc===(null==s?void 0:s.ssrcs[0].ssrcId));if(i){const n=e.getLocalVideoSize(),o=e.getEncoderConfig(RS.LocalVideoTrack);"H264"!==i.codec&&"VP8"!==i.codec&&"VP9"!==i.codec&&"AV1X"!==i.codec&&"AV1"!==i.codec||(r.codecType=i.codec),r.sendBytes=i.bytes,r.sendBitrate=t?8*Math.max(0,r.sendBytes-t.sendBytes):0,i.inputFrame?(r.captureFrameRate=i.inputFrame.frameRate,r.captureResolutionHeight=i.inputFrame.height,r.captureResolutionWidth=i.inputFrame.width):n&&(r.captureResolutionWidth=n.width,r.captureResolutionHeight=n.height),i.sentFrame?(r.sendFrameRate=i.sentFrame.frameRate,r.sendResolutionHeight=i.sentFrame.height,r.sendResolutionWidth=i.sentFrame.width):n&&(r.sendResolutionWidth=n.width,r.sendResolutionHeight=n.height),i.avgEncodeMs&&(r.encodeDelay=i.avgEncodeMs),o&&o.bitrateMax&&(r.targetSendBitrate=1e3*o.bitrateMax),r.sendPackets=i.packets,r.sendPacketsLost=i.packetsLost,r.totalDuration=t?t.totalDuration+1:1,r.totalFreezeTime=t?t.totalFreezeTime:0,this.isLocalVideoFreeze(i)&&(r.totalFreezeTime+=1)}this.trafficStats&&(r.sendPacketsLost=this.trafficStats.B_pvlr4/100)}this.localStats.set(i,r),r&&s&&this.exceptionMonitor.setLocalVideoStats(this.store.uid,s.track,r);break}case RS.LocalAudioTrack:{const t=n,r=dI({},Mf),o=e.getStats(),s=e.getLocalMedia(i);if(o){const i=o.audioSend.find(e=>e.ssrc===(null==s?void 0:s.ssrcs[0].ssrcId));if(i){if("opus"!==i.codec&&"aac"!==i.codec&&"PCMU"!==i.codec&&"PCMA"!==i.codec&&"G722"!==i.codec||(r.codecType=i.codec),i.inputLevel)r.sendVolumeLevel=Math.round(32767*i.inputLevel);else{const t=e.getLocalAudioVolume();t&&(r.sendVolumeLevel=Math.round(32767*t))}r.sendBytes=i.bytes,r.sendPackets=i.packets,r.sendPacketsLost=i.packetsLost,r.sendBitrate=t?8*Math.max(0,r.sendBytes-t.sendBytes):0}}this.trafficStats&&(r.sendPacketsLost=this.trafficStats.B_pvlr4/100),this.localStats.set(RS.LocalAudioTrack,r),r&&s&&this.exceptionMonitor.setLocalAudioStats(this.store.uid,s.track,r);break}}})}updateRemoteStats(e){Array.from(this.remoteStats.entries()).forEach(t=>{let[i,{videoStats:n,audioStats:r,videoPcStats:o}]=t;const s=r,a=n,c=o,d=dI({},xf),u=dI({},Ff),l=dI({},Vf),{audioTrack:h,videoTrack:p,audioSSRC:_,videoSSRC:E}=e.getRemoteMedia(i),m=e.getStats(),f=null==m?void 0:m.audioRecv.find(e=>e.ssrc===_),S=null==m?void 0:m.videoRecv.find(e=>e.ssrc===E),T=this.trafficStats&&this.trafficStats.peer_delay.find(e=>e.peer_uid===i);if(f&&("opus"!==f.codec&&"aac"!==f.codec&&"PCMU"!==f.codec&&"PCMA"!==f.codec&&"G722"!==f.codec||(d.codecType=f.codec),f.outputLevel?d.receiveLevel=Math.round(32767*f.outputLevel):h&&(d.receiveLevel=Math.round(32767*h.getVolumeLevel())),d.receiveBytes=f.bytes,d.receivePackets=f.packets,d.receivePacketsLost=f.packetsLost,d.packetLossRate=d.receivePacketsLost/(d.receivePackets+d.receivePacketsLost),d.receiveBitrate=s?8*Math.max(0,d.receiveBytes-s.receiveBytes):0,d.totalDuration=s?s.totalDuration+1:1,d.totalFreezeTime=s?s.totalFreezeTime:0,d.freezeRate=d.totalFreezeTime/d.totalDuration,d.receiveDelay=f.jitterBufferMs,d.totalDuration>10&&uI.isRemoteAudioFreeze(h)&&(d.totalFreezeTime+=1)),S){"H264"!==S.codec&&"VP8"!==S.codec&&"VP9"!==S.codec&&"AV1X"!==S.codec&&"AV1"!==S.codec||(u.codecType=S.codec),u.receiveBytes=S.bytes,u.receiveBitrate=a?8*Math.max(0,u.receiveBytes-a.receiveBytes):0,u.decodeFrameRate=S.decodeFrameRate<0?0:S.decodeFrameRate,u.renderFrameRate=S.decodeFrameRate<0?0:S.decodeFrameRate,S.outputFrame&&(u.renderFrameRate=S.outputFrame.frameRate),S.receivedFrame?(u.receiveFrameRate=S.receivedFrame.frameRate,u.receiveResolutionHeight=S.receivedFrame.height,u.receiveResolutionWidth=S.receivedFrame.width):p&&(u.receiveResolutionHeight=p._videoHeight||0,u.receiveResolutionWidth=p._videoWidth||0),void 0!==S.framesRateFirefox&&(u.receiveFrameRate=Math.round(S.framesRateFirefox)),u.receivePackets=S.packets,u.receivePacketsLost=S.packetsLost,u.packetLossRate=u.receivePacketsLost/(u.receivePackets+u.receivePacketsLost),u.totalDuration=a?a.totalDuration+1:1,u.totalFreezeTime=a?a.totalFreezeTime:0,u.receiveDelay=S.jitterBufferMs||0;const t=!!E&&e.getRemoteVideoIsReady(E);p&&t&&uI.isRemoteVideoFreeze(p,S,c)&&(u.totalFreezeTime+=1),u.freezeRate=u.totalFreezeTime/u.totalDuration}T&&(d.end2EndDelay=T.B_ad,u.end2EndDelay=T.B_vd,d.transportDelay=T.B_ed,u.transportDelay=T.B_ed,d.currentPacketLossRate=T.B_ealr4/100,u.currentPacketLossRate=T.B_evlr4/100,l.uplinkNetworkQuality=T.B_punq?T.B_punq:0,l.downlinkNetworkQuality=T.B_pdnq?T.B_pdnq:0),this.remoteStats.set(i,{audioStats:d,videoStats:u,videoPcStats:S,networkStats:l}),h&&this.exceptionMonitor.setRemoteAudioStats(h,d),p&&this.exceptionMonitor.setRemoteVideoStats(p,u)})}}const lI=new class extends hE{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}constructor(){super(),lp(this,"_lastHiddenTime",0),lp(this,"_lastVisibleTime",0),document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),CE.debug("document visibility went ".concat(document.visibilityState)),this.emit("VISIBILITY_CHANGE",document.visibilityState)})}};function hI(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function pI(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?hI(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):hI(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function _I(e){return e.match(/^[\.\:\d]+$/)?"".concat(e.replace(/[^\d]/g,"-"),".").concat(FE("TURN_DOMAIN")):(CE.info("Cannot recognized as IP address ".concat(e,". Used As Host instead")),e)}function EI(e,t){var i,n;const r=FE("GATEWAY_DOMAINS");let o=r[1]&&-1!==t.indexOf(r[1])?1:0;e.addresses=e.addresses||[];const s=e.addresses.map(e=>e.domain_prefix?{address:"".concat(e.domain_prefix,".").concat(r[o++%r.length],":").concat(e.port)}:e.ip.match(/^[\.\:\d]+$/)?{ip:e.ip,port:e.port,address:"".concat(e.ip.replace(/[^\d]/g,"-"),".").concat(r[o++%r.length],":").concat(e.port)}:(CE.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)&&void 0!==i&&i[18]&&"string"==typeof(null===(n=e.detail)||void 0===n?void 0:n[18])){const t=e.detail[18],i=null==t?void 0:t.split(";");for(let e=0;e<i.length;e++){var a;const t=mh(a=i[e]).call(a);s[e]&&t&&(s[e].ip6=t)}}return{gatewayAddrs:s,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 mI(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function fI(e){const t=e._encoderConfig;if(!t)return{};const i={resolution:t.width&&t.height?"".concat(mI(t.width),"x").concat(mI(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 SI(e,t,i){var n,r,o,s,a,c,d,u;const l=t.videoSend.find(t=>t.ssrc===e);if(!l)return null;const h={id:wI(10,""),timestamp:new Date(t.timestamp).toISOString(),mediaType:"video",type:"ssrc",ssrc:l.ssrc.toString()},p=null!==(n=null!==(r=null===(o=l.inputFrame)||void 0===o?void 0:o.height)&&void 0!==r?r:null==i?void 0:i._videoHeight)&&void 0!==n?n:0,_=null!==(s=null!==(a=null===(c=l.inputFrame)||void 0===c?void 0:c.width)&&void 0!==a?a:null==i?void 0:i._videoWidth)&&void 0!==s?s:0,E=null!==(d=null===(u=l.inputFrame)||void 0===u?void 0:u.frameRate)&&void 0!==d?d:0;return p&&(h.A_fhi=p+""),_&&(h.A_fwi=_+""),E&&(h.A_fri=E+""),h}function TI(e){return e>=0&&e<.17?1:e>=.17&&e<.36?2:e>=.36&&e<.59?3:e>=.59&&e<=1?4:e>1?5:0}function gI(e,t){let i,n,r=void 0;switch(t){case US.CHOOSE_SERVER:i=4096,n="choose server";break;case US.CLOUD_PROXY:i=1048576,n="proxy";break;case US.CLOUD_PROXY_5:i=4194304,n="proxy5";break;case US.CLOUD_PROXY_FALLBACK:i=4194310,n="proxy fallback";break;default:throw new EE(_E.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&&(r={code:t.buffer.code,addresses:(t.buffer.edges_services||[]).map(e=>pI(pI({},e),{},{ticket:t.buffer.cert})),server_ts:e.enter_ts,uid:t.buffer.uid,cid:t.buffer.cid,cname:t.buffer.cname,detail:pI(pI({},t.buffer.detail),e.detail),flag:t.buffer.flag,opid:e.opid,cert:t.buffer.cert})}),!r)throw new EE(_E.MULTI_UNILBS_RESPONSE_ERROR,"cannot parse response ".concat(n," from multi unilbs response"),{csIp:e.detail&&e.detail[502]});return r}async function RI(e,t){return await Sl.all(e.addresses.map(async e=>({address:_I(e.ip),tcpport:e.port,udpport:e.port,username:t&&FE("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?t.toString():wE.username,password:t&&FE("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?await Eg(t.toString()):wE.password})))}function II(e,t){const i=t._videoWidth||t.getMediaStreamTrack(!0).getSettings().width;return i||CE.warning("cannot get original video track's width, default scale down 4 times for low stream"),i?i/mI(e.width):4}function vI(e){let{candidateType:t,relayProtocol:i,type:n,address:r,port:o,protocol:s}=e;return"local-candidate"===n?{candidateType:t,relayProtocol:i,protocol:s}:{candidateType:t,relayProtocol:i,address:r,port:o,protocol:s}}function CI(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function yI(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?CI(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):CI(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function AI(e){return window.TextEncoder?(new TextEncoder).encode(e).length:e.length}function OI(e){return new Sl(t=>{window.setTimeout(t,e)})}function bI(e){const t=new EE(_E.TIMEOUT,"timeout");return new Sl((i,n)=>{window.setTimeout(()=>n(t),e)})}function wI(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:7,t=arguments.length>1?arguments[1]:void 0;const i=Math.random().toString(16).substr(2,e).toLowerCase();return i.length===e?"".concat(t).concat(i):"".concat(t).concat(i)+wI(e-i.length,"")}function NI(){return wI(32,"").toUpperCase()}const DI=()=>{};function PI(e){return new Sl((t,i)=>{let n=!1;const r=document.createElement("video");r.setAttribute("autoplay",""),r.setAttribute("muted",""),r.muted=!0,r.autoplay=!0,r.setAttribute("playsinline",""),r.setAttribute("style","position: fixed; top: 0; left: 0; width: 1px; height: 1px"),document.body.appendChild(r);const o=Kh()?"canplay":"playing";r.addEventListener(o,()=>{const e=r.videoWidth,i=r.videoHeight;!e&&Hh()||(n=!0,r.srcObject=null,r.remove(),t([e,i]))}),r.srcObject=new MediaStream([e]),r.play().catch(DI),setTimeout(()=>{n||(r.srcObject=null,r.remove(),t([r.videoWidth,r.videoHeight]))},4e3)})}function LI(e){return Sl.all(e.map(e=>e.then(e=>{throw e},e=>e))).then(e=>{throw e},e=>e)}function kI(e,t){for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];return 0===e.getListeners(t).length?Sl.reject(new EE(_E.UNEXPECTED_ERROR,"can not emit promise")):new Sl((i,r)=>{e.emit(t,...n,i,r)})}function MI(e,t){if(0===e.getListeners(t).length)return Sl.resolve();for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];return kI(e,t,...n)}function UI(e,t){if(0===e.getListeners(t).length)return null;for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];return xI(e,t,...n)}function xI(e,t){let i=null,n=null;for(var r=arguments.length,o=new Array(r>2?r-2:0),s=2;s<r;s++)o[s-2]=arguments[s];if(e.emit(t,...o,e=>{i=e},e=>{n=e}),null!==n)throw n;if(null===i)throw new EE(_E.UNEXPECTED_ERROR,"handler is not sync");return i}function VI(e,t){const i=e.indexOf(t);-1!==i&&e.splice(i,1)}function FI(e){const t=[];return e.forEach(e=>{-1===t.indexOf(e)&&t.push(e)}),t}function jI(e){Sl.resolve().then(e)}function BI(e){return JSON.parse(JSON.stringify(e))}const GI={};function WI(e,t){GI[t]||(GI[t]=!0,e())}function HI(e){const 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 KI(e){let t="";for(let i=0;i<e.length;i+=1)t+=String.fromCharCode(e[i]);return window.btoa(t)}const YI=new class{constructor(){lp(this,"fnMap",new Map)}throttleByKey(e,t,i,n){for(var r=arguments.length,o=new Array(r>4?r-4:0),s=4;s<r;s++)o[s-4]=arguments[s];if(this.fnMap.has(t)){const r=this.fnMap.get(t);if(r.threshold!==i){r.fn(...r.args),clearTimeout(r.timer);const s=window.setTimeout(()=>{const 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:n})}else r.skipFn&&r.skipFn(...r.args),this.fnMap.set(t,yI(yI({},r),{},{fn:e,args:o,skipFn:n}))}else{const r=window.setTimeout(()=>{const e=this.fnMap.get(t);e&&e.fn(...e.args),this.fnMap.delete(t)},i);this.fnMap.set(t,{fn:e,threshold:i,timer:r,args:o,skipFn:n})}}},qI=YI.throttleByKey.bind(YI),JI=async e=>{let{fragementLength:t,referenceList:i,asyncMapHandler:n,allFailedhandler:r,promisesCollector:o}=e,s=0;const a=t;let c,d=0;const u=async()=>{const e=(()=>{const e=s*a,t=e+a;return i.slice(e,t).map(n)})();o&&o.push(...e);try{c=await LI(e)}catch(e){if(d+=a,s++,!(d>=i.length))return void await u();r(e)}e.forEach(e=>e.cancel())};return await u(),c};function XI(e){return"object"==typeof e&&null!==e&&!(e instanceof RegExp)}const zI={[_f.ACCESS_POINT]:{[ff.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[ff.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[ff.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[ff.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[ff.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[ff.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[ff.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[ff.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voice service available",retry:!0},[ff.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[ff.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[ff.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[ff.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[ff.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[ff.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[ff.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[ff.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[ff.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[ff.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[_f.UNILBS]:{[mf.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[mf.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[mf.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[mf.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[mf.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[mf.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[mf.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[mf.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[mf.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[mf.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[mf.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[mf.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1}},[_f.STRING_UID_ALLOCATOR]:{[Ef.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[Ef.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[Ef.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function QI(e){const t=zI[Math.floor(e/1e4)];if(!t)return{desc:"unkonw error",retry:!1};const i=t[e%1e4];if(!i){if(Math.floor(e/1e4)===_f.ACCESS_POINT){const 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}const ZI={[Sf.K_TIMESTAMP_EXPIRED]:{desc:"K_TIMESTAMP_EXPIRED",action:"failed"},[Sf.K_CHANNEL_PERMISSION_INVALID]:{desc:"K_CHANNEL_PERMISSION_INVALID",action:"failed"},[Sf.K_CERTIFICATE_INVALID]:{desc:"K_CERTIFICATE_INVALID",action:"failed"},[Sf.K_CHANNEL_NAME_EMPTY]:{desc:"K_CHANNEL_NAME_EMPTY",action:"failed"},[Sf.K_CHANNEL_NOT_FOUND]:{desc:"K_CHANNEL_NOT_FOUND",action:"failed"},[Sf.K_TICKET_INVALID]:{desc:"K_TICKET_INVALID",action:"failed"},[Sf.K_CHANNEL_CONFLICTED]:{desc:"K_CHANNEL_CONFLICTED",action:"failed"},[Sf.K_SERVICE_NOT_READY]:{desc:"K_SERVICE_NOT_READY",action:"tryNext"},[Sf.K_SERVICE_TOO_HEAVY]:{desc:"K_SERVICE_TOO_HEAVY",action:"tryNext"},[Sf.K_UID_BANNED]:{desc:"K_UID_BANNED",action:"failed"},[Sf.K_IP_BANNED]:{desc:"K_IP_BANNED",action:"failed"},[Sf.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[Sf.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[Sf.WARN_NO_AVAILABLE_CHANNEL]:{desc:"WARN_NO_AVAILABLE_CHANNEL",action:"failed"},[Sf.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:"WARN_LOOKUP_CHANNEL_TIMEOUT",action:"tryNext"},[Sf.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:"WARN_LOOKUP_CHANNEL_REJECTED",action:"failed"},[Sf.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:"WARN_OPEN_CHANNEL_TIMEOUT",action:"tryNext"},[Sf.WARN_OPEN_CHANNEL_REJECTED]:{desc:"WARN_OPEN_CHANNEL_REJECTED",action:"failed"},[Sf.WARN_REQUEST_DEFERRED]:{desc:"WARN_REQUEST_DEFERRED",action:"failed"},[Sf.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:"ERR_DYNAMIC_KEY_TIMEOUT",action:"failed"},[Sf.ERR_NO_AUTHORIZED]:{desc:"ERR_NO_AUTHORIZED",action:"failed"},[Sf.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:"ERR_VOM_SERVICE_UNAVAILABLE",action:"tryNext"},[Sf.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:"ERR_NO_CHANNEL_AVAILABLE_CODE",action:"failed"},[Sf.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:"ERR_MASTER_VOCS_UNAVAILABLE",action:"tryNext"},[Sf.ERR_INTERNAL_ERROR]:{desc:"ERR_INTERNAL_ERROR",action:"tryNext"},[Sf.ERR_NO_ACTIVE_STATUS]:{desc:"ERR_NO_ACTIVE_STATUS",action:"failed"},[Sf.ERR_INVALID_UID]:{desc:"ERR_INVALID_UID",action:"failed"},[Sf.ERR_DYNAMIC_KEY_EXPIRED]:{desc:"ERR_DYNAMIC_KEY_EXPIRED",action:"failed"},[Sf.ERR_STATIC_USE_DYANMIC_KE]:{desc:"ERR_STATIC_USE_DYANMIC_KE",action:"failed"},[Sf.ERR_DYNAMIC_USE_STATIC_KE]:{desc:"ERR_DYNAMIC_USE_STATIC_KE",action:"failed"},[Sf.ERR_NO_VOCS_AVAILABLE]:{desc:"ERR_NO_VOCS_AVAILABLE",action:"tryNext"},[Sf.ERR_NO_VOS_AVAILABLE]:{desc:"ERR_NO_VOS_AVAILABLE",action:"tryNext"},[Sf.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:"ERR_JOIN_CHANNEL_TIMEOUT",action:"tryNext"},[Sf.ERR_JOIN_BY_MULTI_IP]:{desc:"ERR_JOIN_BY_MULTI_IP",action:"recover"},[Sf.ERR_NOT_JOINED]:{desc:"ERR_NOT_JOINED",action:"failed"},[Sf.ERR_REPEAT_JOIN_REQUEST]:{desc:"ERR_REPEAT_JOIN_REQUEST",action:"quit"},[Sf.ERR_REPEAT_JOIN_CHANNEL]:{desc:"ERR_REPEAT_JOIN_CHANNEL",action:"quit"},[Sf.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[Sf.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[Sf.ERR_INVALID_STRINGUID]:{desc:"ERR_INVALID_STRINGUID",action:"failed"},[Sf.ERR_TOO_MANY_USERS]:{desc:"ERR_TOO_MANY_USERS",action:"tryNext"},[Sf.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[Sf.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[Sf.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",action:"success"},[Sf.ERR_PUBLISH_REQUEST_INVALID]:{desc:"ERR_PUBLISH_REQUEST_INVALID",action:"failed"},[Sf.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:"ERR_SUBSCRIBE_REQUEST_INVALID",action:"failed"},[Sf.ERR_NOT_SUPPORTED_MESSAGE]:{desc:"ERR_NOT_SUPPORTED_MESSAGE",action:"failed"},[Sf.ERR_ILLEAGAL_PLUGIN]:{desc:"ERR_ILLEAGAL_PLUGIN",action:"failed"},[Sf.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:"ILLEGAL_CLIENT_ROLE_LEVEL",action:"failed"},[Sf.ERR_REJOIN_TOKEN_INVALID]:{desc:"ERR_REJOIN_TOKEN_INVALID",action:"failed"},[Sf.ERR_REJOIN_USER_NOT_JOINED]:{desc:"ERR_REJOIN_NOT_JOINED",action:"failed"},[Sf.ERR_INVALID_OPTIONAL_INFO]:{desc:"ERR_INVALID_OPTIONAL_INFO",action:"quit"},[Sf.ERR_TEST_RECOVER]:{desc:"ERR_TEST_RECOVER",action:"recover"},[Sf.ERR_TEST_TRYNEXT]:{desc:"ERR_TEST_TRYNEXT",action:"recover"},[Sf.ERR_TEST_RETRY]:{desc:"ERR_TEST_RETRY",action:"recover"},[Sf.ILLEGAL_AES_PASSWORD]:{desc:"ERR_TEST_RETRY",action:"failed"},[Sf.ERR_TOO_MANY_BROADCASTERS]:{desc:"ERR_TOO_MANY_BROADCASTERS",action:"failed"},[Sf.ERR_TOO_MANY_SUBSCRIBERS]:{desc:"ERR_TOO_MANY_SUBSCRIBERS",action:"failed"},[Sf.ERR_LICENSE_ILLEGAL]:{desc:"ERR_LICENSE_ILLEGAL",action:"quit"},[Sf.ERR_LICENSE_MISSING]:{desc:"ERR_LICENSE_MISSING",action:"quit"},[Sf.ERR_LICENSE_EXPIRED]:{desc:"ERR_LICENSE_EXPIRED",action:"quit"},[Sf.ERR_LICENSE_MINUTES_EXCEEDED]:{desc:"ERR_LICENSE_MINUTES_EXCEEDED",action:"quit"},[Sf.ERR_LICENSE_PERIOD_INVALID]:{desc:"ERR_LICENSE_PERIOD_INVALID",action:"quit"},[Sf.ERR_LICENSE_MULTIPLE_SDK_SERVICE]:{desc:"ERR_LICENSE_MULTIPLE_SDK_SERVICE",action:"quit"}};function $I(e){const t=ZI[e];return t||{desc:"UNKNOW_ERROR_".concat(e),action:"failed"}}function ev(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}class tv extends hE{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(jf.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(jf.CONNECTED):"closed"===this._state?this.emit(jf.CLOSED):"failed"===this._state&&this.emit(jf.FAILED))}resetReconnectCount(e){CE.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4?arguments[4]:void 0;super(),lp(this,"connectionID",0),lp(this,"currentURLIndex",0),lp(this,"urls",void 0),lp(this,"_reconnectMode","tryNext"),lp(this,"reconnectReason",void 0),lp(this,"_initMutex",new vg("websocket")),lp(this,"name",void 0),lp(this,"_state","closed"),lp(this,"reconnectInterrupter",void 0),lp(this,"websocket",void 0),lp(this,"retryConfig",void 0),lp(this,"reconnectCount",0),lp(this,"forceCloseTimeout",5e3),lp(this,"onlineReconnectListener",void 0),lp(this,"useCompress",void 0),lp(this,"tryDoubleDomain",!1),lp(this,"wsInflateLength",0),lp(this,"wsDeflateLength",0),lp(this,"closeEstablishingWs",()=>{}),lp(this,"store",void 0),lp(this,"joinChannelServiceRecordIndex",void 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?ev(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):ev(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({},t),this.useCompress=i,this.tryDoubleDomain=n;const{timeout:o,timeoutFactor:s}=t,a=Math.max(300,Math.floor(3*o/5)),c=Math.max(1.2,Math.floor(8*s)/10);CS.ONLINE&&(this.retryConfig.timeout=a,this.retryConfig.timeoutFactor=c),dg.on(yS.NETWORK_STATE_CHANGE,(e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===CS.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;const i=(t,i)=>{this.urls=e;const n=this.urls[this.currentURLIndex];this.state="connecting",this.createWebSocketConnection(n).then(t).catch(i),this.once(jf.CLOSED,()=>i(new EE(_E.WS_DISCONNECT))),this.once(jf.CONNECTED,()=>t())};return this._initMutex.lock().then(e=>new Sl((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;const 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){if(!this.websocket)return void CE.warning("[".concat(this.name,"] can not reconnect, no websocket"));var i;(void 0!==e&&(this.reconnectMode=e),CE.debug("[".concat(this.name,"] reconnect is triggered initiative")),"number"==typeof this.joinChannelServiceRecordIndex)&&(null===(i=this.store)||void 0===i||i.recordJoinChannelService({status:"error",errors:[new Error(t)]},this.joinChannelServiceRecordIndex));const n=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),n&&n.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 EE(_E.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new EE(_E.WS_ERR,"send websocket message error"+e.toString())}}setWsInflateData(e){this.wsDeflateLength=this.wsDeflateLength+e.originLength,this.wsInflateLength=this.wsInflateLength+e.compressedLength}getWsInflateData(){const 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 Sl((i,n)=>{var r;const o=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),CE.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),i()},s=async e=>{if(CE.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");const t=UI(this,jf.WILL_RECONNECT,this.reconnectMode)||this.reconnectMode,r=await this.reconnectWithAction(t);if("closed"===this.state)return void CE.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!r)return n(new EE(_E.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),void this.close(!0);i()}else n(new EE(_E.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close()},a=e=>{this.emit(jf.ON_MESSAGE,e)};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),FE("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=FE("GATEWAY_WSS_ADDRESS")),CE.debug("[".concat(this.name,"] start connect, url: ").concat(e));const c=null===(r=this.store)||void 0===r?void 0:r.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});this.chooseBestWebsocketConnection(e,!!t,c).then(e=>{var t;this.websocket=e,o&&o(e.url),e.onclose=s,e.onmessage=a,null===(t=this.store)||void 0===t||t.recordJoinChannelService({endTs:Date.now(),status:"success"},c),this.joinChannelServiceRecordIndex=c}).catch(e=>{var t;if(null===(t=this.store)||void 0===t||t.recordJoinChannelService({endTs:Date.now(),status:e instanceof EE&&e.code===_E.WS_ABORT?"aborted":"error",errors:[e]},c),"closed"!==this.state){if(e instanceof EE&&e.code===_E.WS_ERR){const t=new EE(_E.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return CE.error("[".concat(this.name,"]").concat(t)),void n(t)}s&&s(e)}else n(new EE(_E.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)return!1;if(!this.urls)return!1;if("closed"===this.state)return!1;this.onlineReconnectListener||dg.networkState!==CS.OFFLINE||(this.onlineReconnectListener=dg.onlineWaiter&&dg.onlineWaiter.then(()=>{this.onlineReconnectListener=void 0}));let i=!0;if(this.reconnectInterrupter=()=>{i=!1},t){const t=fE(this.reconnectCount,this.retryConfig);CE.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await Sl.race([OI(t),this.onlineReconnectListener||new Sl(()=>{})])}if("closed"===this.state||!i)return!1;this.reconnectCount+=1;const n=async(e,t)=>{this.emit(jf.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e){const t=this.urls[this.currentURLIndex];this.emit(jf.RECONNECT_WAITTING_FINISH,e),await n(t,e)}else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return await this.reconnectWithAction("recover",!1);CE.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex));const t=this.urls[this.currentURLIndex];this.emit(jf.RECONNECT_WAITTING_FINISH,e),await n(t,e)}else if("recover"===e){CE.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.emit(jf.RECONNECT_WAITTING_FINISH,e),this.urls=await kI(this,jf.REQUEST_NEW_URLS),this.currentURLIndex=0;const t=this.urls[this.currentURLIndex];await n(t,e)}return!0}catch(i){var r;return CE.error("[".concat(this.name,"] reconnect failed"),i.toString()),null!=i&&null!==(r=i.data)&&void 0!==r&&r.desc&&Array.isArray(i.data.desc)&&i.data.desc.length&&i.data.desc.includes("dynamic key expired")?(this.emit(jf.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):await this.reconnectWithAction(e,t)}}async chooseBestWebsocketConnection(e,t,i){return new Sl((n,r)=>{let o=!1;const s=[];this.closeEstablishingWs=()=>{CE.debug("[choose-best-ws] close establishing websockets"),s.forEach(e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()}),r(new EE(_E.WS_ABORT,"choose best websocket aborted"))};const a=FE("GATEWAY_DOMAINS");let c;const d=e.indexOf("?h="),u=a.find(t=>-1!==d?e.includes(t,d):e.includes(t));CE.debug("[choose-best-ws] currentDomain: ",u,", domains: ",a);let l=!this.tryDoubleDomain||t||!u;if(!l&&u){var h;const t=Date.now();try{a.forEach(t=>{const i=-1===d?e.replace(u,t):e.substr(0,d)+e.substr(d).replace(u,t),n=new WebSocket(i);n.binaryType="arraybuffer",s.push(n),CE.debug("[choose-best-ws] ws is connecting:",n.url)})}catch(e){for(CE.debug("[choose-best-ws] ws create failed, fallback to single url"),s.forEach(e=>e.close());s.length;)s.pop();l=!0}null===(h=this.store)||void 0===h||h.recordJoinChannelService({urls:s.map(e=>e.url),service:"gateway"},i),s.forEach(e=>{e.onopen=()=>{if(o)return;const i=Date.now()-t;CE.debug("[choose-best-ws] ws open cost ".concat(i,"ms")),s.filter(t=>t!==e).forEach(e=>{CE.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()}),o=!0,n(e)},e.onclose=e=>{if(c=e,o)return;s.find(e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING))||(CE.debug("[choose-best-ws] all websocket is closed"),o=!0,r(c))},e.onmessage=t=>{CE.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}}),OI(this.forceCloseTimeout).then(()=>{s.forEach(e=>{e.readyState!==WebSocket.OPEN&&e.close()})})}if(l){var p;let t;CE.debug("[choose-best-ws] use single url: ",e),null===(p=this.store)||void 0===p||p.recordJoinChannelService({urls:[e],service:"gateway"},i);try{t=new WebSocket(e),s.push(t),t.binaryType="arraybuffer"}catch(e){const t=new EE(_E.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return CE.error("[".concat(this.name,"]").concat(t)),void r(t)}t.onopen=()=>{n(t)},t.onclose=e=>{r(e)},t.onmessage=e=>{CE.debug("[choose-best-ws]".concat(t.url," onmessage: ").concat(e.data))},OI(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 iv{constructor(e){lp(this,"input",[]),lp(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:zi(e=this.input).call(e,(e,t)=>e+t)/this.input.length}}class nv extends hE{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===vf.CONNECTED?this.emit(Cf.WS_CONNECTED):e===vf.RECONNECTING?this.emit(Cf.WS_RECONNECTING,this._websocketReconnectReason):e===vf.CLOSED&&this.emit(Cf.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(),lp(this,"_disconnectedReason",void 0),lp(this,"_websocketReconnectReason",void 0),lp(this,"_connectionState",vf.CLOSED),lp(this,"reconnectToken",void 0),lp(this,"websocket",void 0),lp(this,"openConnectionTime",void 0),lp(this,"clientId",void 0),lp(this,"lastMsgTime",Date.now()),lp(this,"uploadCache",[]),lp(this,"uploadCacheInterval",void 0),lp(this,"rttRolling",new iv(5)),lp(this,"pingpongTimer",void 0),lp(this,"wsInflateDataTimer",void 0),lp(this,"pingpongTimeoutCount",0),lp(this,"joinResponse",void 0),lp(this,"multiIpOption",void 0),lp(this,"initError",void 0),lp(this,"spec",void 0),lp(this,"store",void 0),lp(this,"onWebsocketMessage",e=>{if(e.data instanceof ArrayBuffer)return void this.emit(Cf.ON_BINARY_DATA,e.data);const t=JSON.parse(e.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const 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===Of.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===Of.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(gf.UID_BANNED);break;case 15:this.close(gf.IP_BANNED);break;case 16:this.close(gf.CHANNEL_BANNED)}if(t._type===Of.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case Sf.ERR_LICENSE_MISSING:this.close(gf.LICENSE_MISSING);break;case Sf.ERR_LICENSE_EXPIRED:this.close(gf.LICENSE_EXPIRED);break;case Sf.ERR_LICENSE_MINUTES_EXCEEDED:this.close(gf.LICENSE_MINUTES_EXCEEDED);break;case Sf.ERR_LICENSE_PERIOD_INVALID:this.close(gf.LICENSE_PERIOD_INVALID);break;case Sf.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(gf.LICENSE_MULTIPLE_SDK_SERVICE);break;case Sf.ERR_LICENSE_ILLEGAL:this.close(gf.LICENSE_ILLEGAL);break;default:this.close()}}}),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new tv("gateway-".concat(this.clientId),this.spec.retryConfig,!0,!0,t),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===vf.CONNECTED&&this.reconnect("retry",If.OFFLINE)})}async request(e,t,i,n){const r=wI(6,""),o={_id:r,_type:e,_message:t},s=this.websocket.connectionID,a=()=>new Sl((t,i)=>{if(this.connectionState===vf.CONNECTED)return t();const n=()=>{this.off(Cf.WS_CLOSED,r),t()},r=()=>{this.off(Cf.WS_CONNECTED,n),i(new EE(_E.WS_ABORT))};this.once(Cf.WS_CONNECTED,n),this.once(Cf.WS_CLOSED,r),e!==yf.PUBLISH&&e!==yf.SUBSCRIBE&&e!==yf.UNSUBSCRIBE&&e!==yf.UNPUBLISH&&e!==yf.CONTROL&&e!==yf.RESTART_ICE||this.once(Cf.DISCONNECT_P2P,()=>{i(new EE(_E.DISCONNECT_P2P))}),e!==yf.PUBLISH&&e!==yf.RESTART_ICE||this.once(Cf.ABORT_P2P_EXECUTION,()=>{i(new EE(_E.DISCONNECT_P2P))})});if(this.connectionState!==vf.CONNECTING&&this.connectionState!==vf.RECONNECTING||e===yf.JOIN||e===yf.REJOIN||await a(),this.websocket.sendMessage(o,!0),n)return;const c=new Sl((i,n)=>{let o=!1;const a=(n,r)=>{o=!0,i({isSuccess:"success"===n,message:r||{}}),this.off(Cf.WS_CLOSED,c),this.off(Cf.WS_RECONNECTING,c),this.emit(Cf.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{n(new EE(_E.WS_ABORT,"type: ".concat(e))),this.off(Cf.WS_CLOSED,c),this.off(Cf.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(Cf.WS_CLOSED,c),this.once(Cf.WS_RECONNECTING,c),OI(FE("SIGNAL_REQUEST_TIMEOUT")).then(()=>{this.websocket.connectionID!==s||o||(CE.warning("ws request timeout, type: ".concat(e)),this.emit(Cf.REQUEST_TIMEOUT,e,t))})});let d=null;try{d=await c}catch(n){if(this.connectionState===vf.CLOSED||e===yf.LEAVE)throw new EE(_E.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===yf.JOIN||e===yf.REJOIN?null:(await a(),await this.request(e,t))}if(d.isSuccess)return d.message;const u=Number(d.message.error_code||d.message.code),l=$I(u),h=new EE(_E.UNEXPECTED_RESPONSE,"".concat(l.desc,": ").concat(d.message.error_str),{code:u,data:d.message});return"success"===l.action?d.message:(CE.warning("[".concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(u,", message: ").concat(l.desc,", action: ").concat(l.action)),u===Sf.ERR_TOO_MANY_BROADCASTERS?e===yf.JOIN||e===yf.REJOIN?(this.initError=h,this.close(),h.throw()):h.throw():"failed"===l.action?h.throw():"quit"===l.action?(this.initError=h,this.close(),h.throw()):(u===Sf.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,CE.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",If.MULTI_IP)):this.reconnect(l.action,If.SERVER_ERROR),e===yf.JOIN||e===yf.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new Sl(i=>{const n=r=>{(!t||t(r))&&(this.off(e,n),i(r))};this.on(e,n)})}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=FE("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval(()=>{if(this.connectionState!==vf.CONNECTED)return;const 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)},FE("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i)}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 Sl((i,n)=>{this.once(Cf.WS_CONNECTED,()=>i(this.joinResponse)),this.once(Cf.WS_CLOSED,()=>n(this.initError||new EE(_E.WS_ABORT))),this.connectionState=vf.CONNECTING,this.websocket.init(e).catch(n),this.wsInflateDataTimer&&window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=window.setInterval(()=>{this.handleWsInflateData()},2e4),setTimeout(()=>{t&&void 0===this.openConnectionTime&&(CE.debug("[".concat(this.clientId,"] init websocket timeout while join with fallback to proxy")),n(new EE(_E.INIT_WEBSOCKET_TIMEOUT)))},FE("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||gf.LEAVE,this.connectionState=vf.CLOSED,CE.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close(),e===gf.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new tv("gateway-".concat(this.clientId),this.spec.retryConfig,!0,!0,this.store),this.handleWebsocketEvents())}async join(){if(!this.joinResponse){this.emit(Cf.ABORT_P2P_EXECUTION);const e=await kI(this,Cf.REQUEST_JOIN_INFO),t=await this.request(yf.JOIN,e);if(!t)return this.emit(Cf.REPORT_JOIN_GATEWAY,_E.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(Cf.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=vf.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new EE(_E.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=xI(this,Cf.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(yf.REJOIN,e);return!!t&&(this.connectionState=vf.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach(e=>{this.emit(Of.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(Of.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(Of.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(Of.MUTE_AUDIO,{uid:e.uid}):this.emit(Of.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(Of.MUTE_VIDEO,{uid:e.uid}):this.emit(Of.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(Of.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(Of.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(Of.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(Of.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(Of.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){CE.debug("[".concat(this.clientId,"] receive notification: "),e);const t=$I(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(gf.UID_BANNED),void this.close()):void this.reconnect(t.action,If.SERVER_ERROR);CE.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;const e=FE("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(CE.warning("PINGPONG Timeout. Last Socket Message: ".concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>FE("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",If.TIMEOUT):this.request(yf.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),FE("REPORT_STATS")&&this.send(yf.PING_BACK,{pingpongElapse:e})}).catch(e=>{})}handleWsInflateData(){const{wsInflateLength:e,wsDeflateLength:t}=this.websocket.getWsInflateData();0!==e&&0!==t&&this.upload(Af.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(jf.RECONNECT_WAITTING_FINISH,e=>{this.emit(Cf.WS_RECONNECT_WAITTING_FINISH,e)}),this.websocket.on(jf.RECONNECT_CREATE_CONNECTION,e=>{this.emit(Cf.WS_RECONNECT_CREATE_CONNECTION,e)}),this.websocket.on(jf.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(jf.CLOSED,()=>{this.connectionState=vf.CLOSED}),this.websocket.on(jf.FAILED,()=>{this._disconnectedReason=gf.NETWORK_ERROR,this.connectionState=vf.CLOSED}),this.websocket.on(jf.RECONNECTING,e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===vf.CONNECTED?this.connectionState=vf.RECONNECTING:this.connectionState=vf.CONNECTING}),this.websocket.on(jf.WILL_RECONNECT,(e,t)=>{if(xI(this,Cf.IS_P2P_DISCONNECTED)&&"retry"===e)return CE.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit(Cf.NEED_RENEW_SESSION),this.emit(Cf.DISCONNECT_P2P),t("tryNext");"retry"!==e&&(CE.debug("".concat(this.clientId," websockt will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0,this.emit(Cf.NEED_RENEW_SESSION),this.emit(Cf.DISCONNECT_P2P)),t(e)}),this.websocket.on(jf.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch(e=>{CE.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",If.SERVER_ERROR)}):this.join().catch(e=>{if(this.emit(Cf.REPORT_JOIN_GATEWAY,e.message||e.code,this.url||""),e instanceof EE&&e.code===_E.UNEXPECTED_RESPONSE&&e.data.code===Sf.ERR_NO_AUTHORIZED)return CE.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",If.SERVER_ERROR);CE.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",If.SERVER_ERROR):(this.initError=e,this.close())})}),this.websocket.on(jf.REQUEST_NEW_URLS,(e,t)=>{kI(this,Cf.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)}),this.websocket.on(jf.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(Of.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})}}function rv(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}class ov extends hE{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(PS.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(PS.CONNECTED):"closed"===this._state?this.emit(PS.CLOSED):"failed"===this._state&&this.emit(PS.FAILED))}constructor(e,t,i,n){super(),lp(this,"connectionID",0),lp(this,"currentURLIndex",0),lp(this,"reconnectReason",void 0),lp(this,"_reconnectMode","tryNext"),lp(this,"_initMutex",void 0),lp(this,"_name",void 0),lp(this,"_state","closed"),lp(this,"_reconnectInterrupter",void 0),lp(this,"_url",void 0),lp(this,"_retryConfig",void 0),lp(this,"_reconnectCount",0),lp(this,"_forceCloseTimeout",5e3),lp(this,"_onlineReconnectListener",void 0),lp(this,"_closeEstablishingTransmitter",()=>{}),lp(this,"_store",void 0),lp(this,"_joinChannelServiceRecordIndex",void 0),lp(this,"_transmitter",void 0),lp(this,"_useCompress",void 0),lp(this,"_inflateLength",0),lp(this,"_deflateLength",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?rv(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):rv(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({},t),this._useCompress=i}resetReconnectCount(e){CE.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;const 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){if(!this._transmitter)return void CE.warning("[".concat(this._name,"] can not reconnect, no websocket"));var i;(void 0!==e&&(this.reconnectMode=e),CE.debug("[".concat(this._name,"] reconnect is triggered initiative")),"number"==typeof this._joinChannelServiceRecordIndex)&&(null===(i=this._store)||void 0===i||i.recordJoinChannelService({status:"error",errors:[new Error(t)]},this._joinChannelServiceRecordIndex));const n=this._transmitter.onclose;this._transmitter.onclose=null,this._transmitter.close(),n&&n.bind(this._transmitter)({code:9999,reason:t})}getInflateData(){const 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 sv(e,t,i){if("getBigUint64"in DataView.prototype)return e.getBigUint64(t,i);const n=e.getUint32(t,i),r=e.getUint32(t+4,i),o=Number(!!i),s=Number(!i);return BigInt(n*s+r*o)<<BigInt(32)|BigInt(n*o+r*s)}function av(e,t,i,n){if("setBigUint64"in DataView.prototype)return e.setBigUint64(t,i,n);const r=Number(i>>BigInt(32)),o=Number(i&BigInt(4294967295));n?(e.setUint32(t+4,r,n),e.setUint32(t,o,n)):(e.setUint32(t,r,n),e.setUint32(t+4,o,n))}let cv;!function(e){e[e.Default=0]="Default",e[e.Ack=1]="Ack"}(cv||(cv={}));class dv{constructor(e,t,i){lp(this,"version",1),lp(this,"initialRTO",void 0),lp(this,"maxBatchAckCount",void 0),lp(this,"maxRTO",void 0),lp(this,"initialRTT",void 0),lp(this,"ID",void 0),lp(this,"rtt",void 0),lp(this,"packetNumber",1),lp(this,"rtoRatioMap",new Map),lp(this,"timeoutMap",new Map),lp(this,"unorderedPacketQueue",[]),lp(this,"batchAckPacketQueue",[]),lp(this,"lastOrderedPacketNumber",0),lp(this,"batchAckTimer",void 0),lp(this,"sendImpl",void 0),lp(this,"receiveImpl",void 0),this.sendImpl=e,this.receiveImpl=t,this.ID=wI(7,"transmitter-"),this.initialRTO=void 0!==(null==i?void 0:i.initialRTO)?i.initialRTO:FE("TRANSMITTER_INITIAL_RTO"),this.initialRTT=void 0!==(null==i?void 0:i.initialRTT)?i.initialRTT:FE("TRANSMITTER_INITIAL_RTT"),this.rtt=void 0!==(null==i?void 0:i.initialRTT)?i.initialRTT:FE("TRANSMITTER_INITIAL_RTT"),this.maxBatchAckCount=void 0!==(null==i?void 0:i.maxBatchAckCount)?i.maxBatchAckCount:FE("TRANSMITTER_MAX_BATCH_ACK_COUNT"),this.maxRTO=void 0!==(null==i?void 0:i.maxRTO)?i.maxRTO:FE("TRANSMITTER_MAX_RTO")}packetize(e,t){return{type:cv.Default,version:this.version,packetNumber:t,payload:e}}serialize(e){switch(e.type){case cv.Default:{let t;if("string"==typeof e.payload){t=(new TextEncoder).encode(e.payload)}else t=e.payload;const i=new ArrayBuffer(t.length+15),n=new DataView(i);n.setUint16(0,e.version),n.setUint8(2,e.type),n.setUint32(3,e.packetNumber),av(n,7,BigInt(e.sendTs));return new Uint8Array(n.buffer).set(t,15),i}case cv.Ack:{const 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),av(i,8,BigInt(e.ackSendTs)),t}}}deserialize(e){const t=new DataView(e),i=t.getUint16(0),n=t.getUint8(2);switch(n){case cv.Default:{const r=t.getUint32(3),o=sv(t,7),s=e.slice(15),a=(new TextDecoder).decode(s);return{version:i,type:n,packetNumber:r,sendTs:Number(o),payload:a}}case cv.Ack:{const e=t.getUint32(3),r=t.getUint8(7),o=sv(t,8);return{version:i,type:n,maxAckPacketNumber:e,shift:r,ackSendTs:Number(o)}}default:throw CE.error("[".concat(this.ID,"] Unrecognized packet type ").concat(n)),new Error("Unrecognized packet type ".concat(n))}}sendMessage(e){const t=this.packetize(e,this.packetNumber);this.packetNumber=4294967295===this.packetNumber?1:this.packetNumber+1;const i=this.calculateRTO(t),n=window.setTimeout(()=>{this.resendMessage(t)},i);this.timeoutMap.set(t.packetNumber,n),this.sendPacket(t)}onData(e){const t=this.deserialize(e);t.type===cv.Default?this.ack(t):t.type===cv.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){const t=this.calculateRTO(e),i=window.setTimeout(()=>{this.resendMessage(e)},t);this.timeoutMap.set(e.packetNumber,i),this.sendPacket(e)}calculateRTO(e){const t=this.rtoRatioMap.get(e.packetNumber);if(void 0===t)return this.rtoRatioMap.set(e.packetNumber,1),this.initialRTO;{const i=9*this.rtt/8*t;return this.rtoRatioMap.set(e.packetNumber,t+1),i>this.maxRTO?this.maxRTO:i}}updateRTT(e,t){const 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);;){const 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){const t={ackSendTs:e.sendTs,maxAckPacketNumber:e.packetNumber,shift:0,type:cv.Ack,version:this.version};this.sendPacket(t)}else if(e.packetNumber>this.lastOrderedPacketNumber){this.unorderedPacketQueue[e.packetNumber-this.lastOrderedPacketNumber-2]=e;const t={ackSendTs:e.sendTs,maxAckPacketNumber:e.packetNumber,shift:0,type:cv.Ack,version:this.version};this.sendPacket(t)}}batchAck(){window.clearTimeout(this.batchAckTimer),this.batchAckTimer=void 0;const e={ackSendTs:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].sendTs,maxAckPacketNumber:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].packetNumber,shift:this.batchAckPacketQueue.length-1,type:cv.Ack,version:this.version};this.sendPacket(e),this.batchAckPacketQueue=[]}sendPacket(e){e.type===cv.Default&&(e.sendTs=Math.round(performance.now()));const t=this.serialize(e);this.sendImpl(t)}clearRTO(e){for(let t=e.maxAckPacketNumber-e.shift;t<=e.maxAckPacketNumber;t++){const e=this.timeoutMap.get(t);void 0!==e&&window.clearTimeout(e),this.timeoutMap.delete(t),this.rtoRatioMap.delete(t)}}}class uv extends ov{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3?arguments[3]:void 0),lp(this,"_initMutex",void 0),lp(this,"_reconnectInterrupter",void 0),lp(this,"_url",void 0),lp(this,"_transmitter",void 0),lp(this,"_addresses",void 0),lp(this,"_reliableTransmission",void 0),this._initMutex=new vg("datachannel");const{timeout:i,timeoutFactor:n}=t,r=Math.max(300,Math.floor(3*i/5)),o=Math.max(1.2,Math.floor(8*n)/10);CS.ONLINE&&(this._retryConfig.timeout=r,this._retryConfig.timeoutFactor=o),dg.on(yS.NETWORK_STATE_CHANGE,(e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===CS.ONLINE?(this._retryConfig.timeout=r,this._retryConfig.timeoutFactor=o):(this._retryConfig.timeout=i,this._retryConfig.timeoutFactor=n))})}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;const i=(t,i)=>{this._addresses=e,this.currentURLIndex=this._addresses.findIndex(e=>e.fingerprint||FE("FINGERPRINT"));const n=this._addresses[this.currentURLIndex];this.state="connecting",this.createTransmitterConnection(n).then(t).catch(i),this.once(PS.CLOSED,()=>i(new EE(_E.WS_DISCONNECT))),this.once(PS.CONNECTED,()=>t())};return this._initMutex.lock().then(e=>new Sl((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 EE(_E.WS_ABORT,"datachannel is not ready");try{t||(e=JSON.stringify(e)),this._reliableTransmission.sendMessage(e)}catch(e){throw new EE(_E.WS_ERR,"send datachannel signal message error"+e.toString())}}unbindDcCloseEventListener(){this._transmitter&&(this._transmitter.onclose=null)}sendMessageWithJSON(e){const 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 Sl((t,i)=>{var n;const r=()=>{CE.debug("[".concat(this._name,"] datachannel opened:"),this._url),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),t()},o=async e=>{var n;if(null===(n=this._closeEstablishingTransmitter)||void 0===n||n.call(this),CE.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");const n=UI(this,PS.WILL_RECONNECT,this.reconnectMode)||this.reconnectMode,r=await this.reconnectWithAction(n);if("closed"===this.state)return void CE.debug("[".concat(this.connectionID,"] dc is closed, no need to reconnect"));if(!r)return i(new EE(_E.WS_DISCONNECT,"datachannel reconnect failed: ".concat(e.code))),void this.close(!0);t()}else i(new EE(_E.WS_DISCONNECT,"datachannel close: ".concat(e.code))),this.close()},s=e=>{var t;null===(t=this._reliableTransmission)||void 0===t||t.onData(e.data)};this._transmitter&&(this._transmitter.onclose=null,this._transmitter.close()),this._reliableTransmission&&(this._reliableTransmission.close(),this._reliableTransmission=void 0),CE.debug("[".concat(this._name,"] start connect, address: ").concat(JSON.stringify(e)));const a=null===(n=this._store)||void 0===n?void 0:n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"}),c=Date.now();kI(this,PS.TO_CONNECT_DATACHANNEL,e).then(e=>{var t,i;if(!e)throw new Error("transmissonInfo not exist yet");const{transmitter:n,close:d}=e;this._transmitter=n,null===(t=this._store)||void 0===t||t.signalChannelOpen();const u=Date.now()-c;CE.debug("[choose dc] dc open cost ".concat(u,"ms"));this._reliableTransmission=new dv(e=>{var t;this._transmitter&&"open"===this._transmitter.readyState&&(null===(t=this._transmitter)||void 0===t||t.send(e))},e=>{"string"==typeof e&&this.emit(PS.ON_MESSAGE,e)}),this._closeEstablishingTransmitter=()=>{var e;null===(e=this._reliableTransmission)||void 0===e||e.close(),this._reliableTransmission=void 0,d()},r&&r(),n.onclose=o,n.onmessage=s,null===(i=this._store)||void 0===i||i.recordJoinChannelService({endTs:Date.now(),status:"success"},a),this._joinChannelServiceRecordIndex=a}).catch(e=>{var t;if(null===(t=this._store)||void 0===t||t.recordJoinChannelService({endTs:Date.now(),status:e instanceof EE&&e.code===_E.WS_ABORT?"aborted":"error",errors:[e]},a),"closed"!==this.state){if(e instanceof EE&&e.code===_E.WS_ERR){const t=new EE(_E.WS_ERR,"init datachannel failed! Error: ".concat(e.toString()));return CE.error("[".concat(this._name,"]").concat(t)),void i(t)}o&&o(e)}else i(new EE(_E.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)return!1;if(!this._addresses)return!1;if("closed"===this.state)return!1;this._onlineReconnectListener||dg.networkState!==CS.OFFLINE||(this._onlineReconnectListener=dg.onlineWaiter&&dg.onlineWaiter.then(()=>{this._onlineReconnectListener=void 0}));let i=!0;if(this._reconnectInterrupter=()=>{i=!1},t){const t=fE(this._reconnectCount,this._retryConfig);CE.debug("[".concat(this._name,"] wait ").concat(t,"ms to reconnect datachannel, mode: ").concat(e)),await Sl.race([OI(t),this._onlineReconnectListener||new Sl(()=>{})])}if("closed"===this.state||!i)return!1;this._reconnectCount+=1;const n=async(e,t)=>{this.emit(PS.RECONNECT_CREATE_CONNECTION,t),await this.createTransmitterConnection(e)};try{if("retry"===e){const t=this._addresses[this.currentURLIndex];this.emit(PS.RECONNECT_WAITTING_FINISH,e),await n(t,e)}else if("tryNext"===e){this.currentURLIndex+=1;for(let e=this.currentURLIndex;e<this._addresses.length;e++){if(this._addresses[e].fingerprint||FE("FINGERPRINT")){this.currentURLIndex=e;break}this.currentURLIndex+=1}if(this.currentURLIndex>=this._addresses.length)return CE.debug("[".concat(this._name,"] the available addresses are exhausted, change to recover")),await this.reconnectWithAction("recover",!1);CE.debug("[".concat(this._name,"] datachannel url length: ").concat(this._addresses.length," current index: ").concat(this.currentURLIndex));const t=this._addresses[this.currentURLIndex];this.emit(PS.RECONNECT_WAITTING_FINISH,e),await n(t,e)}else"recover"===e&&(CE.debug("[".concat(this._name,"] start to failback to websocket")),this.resetReconnectCount("recover mode"),this.emit(PS.RECONNECT_WAITTING_FINISH,e),this.emit(PS.FAILBACK));return!0}catch(i){var r;return CE.error("[".concat(this._name,"] reconnect failed"),i.toString()),null!=i&&null!==(r=i.data)&&void 0!==r&&r.desc&&Array.isArray(i.data.desc)&&i.data.desc.length&&i.data.desc.includes("dynamic key expired")?(this.emit(PS.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):await this.reconnectWithAction(e,t)}}}class lv extends hE{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===vf.CONNECTED?this.emit(Cf.WS_CONNECTED):e===vf.RECONNECTING?this.emit(Cf.WS_RECONNECTING,this._websocketReconnectReason):e===vf.CLOSED&&this.emit(Cf.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(),lp(this,"_disconnectedReason",void 0),lp(this,"_websocketReconnectReason",void 0),lp(this,"_connectionState",vf.CLOSED),lp(this,"reconnectToken",void 0),lp(this,"websocket",void 0),lp(this,"openConnectionTime",void 0),lp(this,"clientId",void 0),lp(this,"lastMsgTime",Date.now()),lp(this,"uploadCache",[]),lp(this,"uploadCacheInterval",void 0),lp(this,"rttRolling",new iv(5)),lp(this,"pingpongTimer",void 0),lp(this,"inflateDataTimer",void 0),lp(this,"pingpongTimeoutCount",0),lp(this,"joinResponse",void 0),lp(this,"multiIpOption",void 0),lp(this,"initError",void 0),lp(this,"spec",void 0),lp(this,"store",void 0),lp(this,"onWebsocketMessage",e=>{if(e instanceof ArrayBuffer)return void this.emit(Cf.ON_BINARY_DATA,e);const t=JSON.parse(e);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const 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===Of.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===Of.ON_USER_BANNED))switch(t._message.error_code){case 14:this.close(gf.UID_BANNED);break;case 15:this.close(gf.IP_BANNED);break;case 16:this.close(gf.CHANNEL_BANNED)}}),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new uv("gateway-".concat(this.clientId),this.spec.retryConfig,!0,t),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===vf.CONNECTED&&this.reconnect("retry",DS.OFFLINE)})}async request(e,t,i,n){const r=wI(6,""),o={_id:r,_type:e,_message:t},s=this.websocket.connectionID,a=()=>new Sl((t,i)=>{if(this.connectionState===vf.CONNECTED)return t();const n=()=>{this.off(Cf.WS_CLOSED,r),t()},r=()=>{this.off(Cf.WS_CONNECTED,n),i(new EE(_E.WS_ABORT))};this.once(Cf.WS_CONNECTED,n),this.once(Cf.WS_CLOSED,r),e!==yf.PUBLISH&&e!==yf.SUBSCRIBE&&e!==yf.UNSUBSCRIBE&&e!==yf.UNPUBLISH&&e!==yf.CONTROL&&e!==yf.RESTART_ICE||this.once(Cf.DISCONNECT_P2P,()=>{i(new EE(_E.DISCONNECT_P2P))}),e!==yf.PUBLISH&&e!==yf.RESTART_ICE||this.once(Cf.ABORT_P2P_EXECUTION,()=>{i(new EE(_E.DISCONNECT_P2P))})});if(this.connectionState!==vf.CONNECTING&&this.connectionState!==vf.RECONNECTING||e===yf.JOIN||e===yf.REJOIN||await a(),e===yf.LEAVE&&(this.websocket.unbindDcCloseEventListener(),n=!0),this.websocket.sendMessage(o,!0,!1),n)return;const c=new Sl((i,n)=>{let o=!1;const a=(n,r)=>{o=!0,i({isSuccess:"success"===n,message:r||{}}),this.off(Cf.WS_CLOSED,c),this.off(Cf.WS_RECONNECTING,c),this.emit(Cf.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{n(new EE(_E.WS_ABORT,"type: ".concat(e))),this.off(Cf.WS_CLOSED,c),this.off(Cf.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(Cf.WS_CLOSED,c),this.once(Cf.WS_RECONNECTING,c),OI(FE("SIGNAL_REQUEST_TIMEOUT")).then(()=>{this.websocket.connectionID!==s||o||(CE.warning("dc request timeout, type: ".concat(e)),this.emit(Cf.REQUEST_TIMEOUT,e,t))})});let d=null;try{d=await c}catch(n){if(this.connectionState===vf.CLOSED||e===yf.LEAVE)throw new EE(_E.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===yf.JOIN||e===yf.REJOIN?null:(await a(),await this.request(e,t))}if(d.isSuccess)return d.message;const u=Number(d.message.error_code||d.message.code),l=$I(u),h=new EE(_E.UNEXPECTED_RESPONSE,"".concat(l.desc,": ").concat(d.message.error_str),{code:u,data:d.message});return"success"===l.action?d.message:(CE.warning("[".concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(u,", message: ").concat(l.desc,", action: ").concat(l.action)),u===Sf.ERR_TOO_MANY_BROADCASTERS?e===yf.JOIN||e===yf.REJOIN?(this.initError=h,this.close(),h.throw()):h.throw():"failed"===l.action?h.throw():"quit"===l.action?(this.initError=h,this.close(),h.throw()):(u===Sf.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,CE.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",DS.MULTI_IP)):this.reconnect(l.action,DS.SERVER_ERROR),e===yf.JOIN||e===yf.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new Sl(i=>{const n=r=>{(!t||t(r))&&(this.off(e,n),i(r))};this.on(e,n)})}upload(e,t){const i={_type:e,_message:t};try{this.websocket.sendMessage(i)}catch(e){const t=FE("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval(()=>{if(this.connectionState!==vf.CONNECTED)return;const 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)},FE("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){const i={_type:e,_message:t};this.websocket.sendMessage(i)}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 Sl((i,n)=>{this.once(Cf.WS_CONNECTED,()=>i(this.joinResponse)),this.once(Cf.WS_CLOSED,()=>n(this.initError||new EE(_E.WS_ABORT))),this.connectionState=vf.CONNECTING,this.websocket.init(e).catch(n),this.websocket.once(PS.FAILBACK,()=>{void 0===this.openConnectionTime&&n(new EE(_E.INIT_DATACHANNEL_TIMEOUT))}),this.inflateDataTimer&&window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=window.setInterval(()=>{this.handleInflateData()},2e4),setTimeout(()=>{t&&void 0===this.openConnectionTime&&(CE.debug("[".concat(this.clientId,"] init datachannel timeout while join with failback to websocket")),n(new EE(_E.INIT_DATACHANNEL_TIMEOUT)))},FE("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||gf.LEAVE,this.connectionState=vf.CLOSED,CE.debug("[".concat(this.clientId,"] ")+"will close datachannel in signal"),this.websocket.close(),e===gf.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new uv("gateway-".concat(this.clientId),this.spec.retryConfig,!0,this.store),this.handleWebsocketEvents())}async join(){if(!this.joinResponse){this.emit(Cf.ABORT_P2P_EXECUTION);const e=await kI(this,Cf.DATACHANNEL_CONNECTING),t=await this.request(yf.JOIN,e);if(!t)return this.emit(Cf.REPORT_JOIN_GATEWAY,_E.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(Cf.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=vf.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new EE(_E.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=xI(this,Cf.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(yf.REJOIN,e);return!!t&&(this.connectionState=vf.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach(e=>{this.emit(Of.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(Of.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(Of.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(Of.MUTE_AUDIO,{uid:e.uid}):this.emit(Of.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(Of.MUTE_VIDEO,{uid:e.uid}):this.emit(Of.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(Of.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(Of.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(Of.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(Of.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(Of.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){CE.debug("[".concat(this.clientId,"] receive notification: "),e);const t=$I(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(gf.UID_BANNED),void this.close()):void this.reconnect(t.action,DS.SERVER_ERROR);CE.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;const e=FE("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(CE.warning("PINGPONG Timeout. Last Socket Message: ".concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>FE("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",DS.TIMEOUT):this.request(yf.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),FE("REPORT_STATS")&&this.send(yf.PING_BACK,{pingpongElapse:e})}).catch(e=>{})}handleInflateData(){const{inflateLength:e,deflateLength:t}=this.websocket.getInflateData();0!==e&&0!==t&&this.upload(Af.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(PS.RECONNECT_WAITTING_FINISH,e=>{this.emit(Cf.WS_RECONNECT_WAITTING_FINISH,e)}),this.websocket.on(PS.RECONNECT_CREATE_CONNECTION,e=>{this.emit(Cf.WS_RECONNECT_CREATE_CONNECTION,e)}),this.websocket.on(PS.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(PS.CLOSED,()=>{this.connectionState=vf.CLOSED}),this.websocket.on(PS.FAILED,()=>{this._disconnectedReason=gf.NETWORK_ERROR,this.connectionState=vf.CLOSED}),this.websocket.on(PS.RECONNECTING,e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===vf.CONNECTED?this.connectionState=vf.RECONNECTING:this.connectionState=vf.CONNECTING}),this.websocket.on(PS.WILL_RECONNECT,(e,t)=>{if(xI(this,Cf.IS_P2P_DISCONNECTED)&&"retry"===e)return CE.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit(Cf.NEED_RENEW_SESSION),this.emit(Cf.DISCONNECT_P2P),t("tryNext");"retry"!==e&&(CE.debug("".concat(this.clientId," websockt will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0,this.emit(Cf.NEED_RENEW_SESSION),this.emit(Cf.DISCONNECT_P2P)),t(e)}),this.websocket.on(PS.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch(e=>{CE.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",DS.SERVER_ERROR)}):this.join().catch(e=>{if(this.emit(Cf.REPORT_JOIN_GATEWAY,e.message||e.code,this.url||""),e instanceof EE&&e.code===_E.UNEXPECTED_RESPONSE&&e.data.code===Sf.ERR_NO_AUTHORIZED)return CE.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",DS.SERVER_ERROR);CE.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",DS.SERVER_ERROR):(this.initError=e,this.close())})}),this.websocket.on(PS.REQUEST_NEW_URLS,(e,t)=>{kI(this,Cf.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)}),this.websocket.on(PS.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(Of.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}),this.websocket.on(PS.TO_CONNECT_DATACHANNEL,async(e,t,i)=>kI(this,Cf.DATACHANNEL_PRECONNECT,e).then(t).catch(i)),this.websocket.on(PS.FAILBACK,()=>{void 0!==this.openConnectionTime&&this.emit(Cf.DATACHANNEL_FAILBACK)})}}function hv(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function pv(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?hv(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):hv(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}const _v=new Map;class Ev extends hE{get state(){return this._state}set state(e){if(e===this._state)return;const t=this._state;this._state=e,"DISCONNECTED"===e&&this._disconnectedReason?this.emit(nS.CONNECTION_STATE_CHANGE,e,t,this._disconnectedReason):this.emit(nS.CONNECTION_STATE_CHANGE,e,t)}get joinGatewayStartTime(){return this._joinGatewayStartTime}set joinGatewayStartTime(e){CE.debug("[".concat(this.store.clientId,"] set joinGatewayStartTime at ").concat(e)),this._joinGatewayStartTime=e}constructor(e,t){super(),lp(this,"store",void 0),lp(this,"joinInfo",void 0),lp(this,"key",void 0),lp(this,"signal",void 0),lp(this,"role",void 0),lp(this,"inChannelInfo",{joinAt:null,duration:0}),lp(this,"spec",void 0),lp(this,"_state","DISCONNECTED"),lp(this,"_statsCollector",void 0),lp(this,"_disconnectedReason",void 0),lp(this,"isSignalRecover",!1),lp(this,"hasChangeBGPAddress",!1),lp(this,"trafficStatsInterval",void 0),lp(this,"networkQualityInterval",void 0),lp(this,"_joinGatewayStartTime",0),lp(this,"_signalTimeout",!1),lp(this,"_clientRoleOptions",void 0),lp(this,"_isProactiveJoin",!1),this.store=e,this.spec=t,this.signal=this.store.useDataChannel?new lv(pv(pv({},t),{},{retryConfig:t.websocketRetryConfig}),e):new nv(pv(pv({},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 lv){let t=!1;"disabled"!==e.cloudProxyServer?(CE.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?(CE.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)||FE("FINGERPRINT")||(CE.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);const n=Date.now();let r=_v.get(e.cname);if(r||(r=new Map,_v.set(e.cname,r)),this._isProactiveJoin=!0,r.has(e.uid)){const t=new EE(_E.UID_CONFLICT);throw Tg.joinGateway(e.sid,{lts:n,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 lv?"1":"0"}),this._isProactiveJoin=!1,t}r.set(e.uid,!0),this.joinInfo=e,this.key=t;let o=0;this.joinGatewayStartTime=n;const s=e.proxyServer;try{let t;if(CE.debug("[".concat(this.store.clientId,"] use ").concat(this.signal instanceof lv?"datachannel":"websocket"," join uid ").concat(o)),this.signal instanceof lv)t=await this.signal.init(e.apResponse.addresses,i);else{const n=e.proxyServer,r=n?e.gatewayAddrs.map(e=>{const t=e.address.split(":");return"wss://".concat(n,"/ws/?h=").concat(t[0],"&p=").concat(t[1])}):e.gatewayAddrs.map(e=>"wss://".concat(e.address));t=await this.signal.init(r,i)}o=t.uid,CE.debug("[".concat(this.store.clientId,"] ").concat(this.signal instanceof lv?"datachannel":"websocket"," join uid ").concat(o," cost ").concat(Date.now()-this.joinGatewayStartTime))}catch(t){if(t&&t.code===_E.INIT_WEBSOCKET_TIMEOUT)throw CE.warning("[".concat(this.store.clientId,"] User join failed"),t.toString()),t;if(t&&t.code===_E.INIT_DATACHANNEL_TIMEOUT)throw CE.warning("[".concat(this.store.clientId,"] User join datachannel failed"),t.toString()),this.resetSignal(),t;throw CE.error("[".concat(this.store.clientId,"] User join failed"),t.toString()),Tg.joinGateway(e.sid,{lts:n,succ:!1,ec:t.message,addr:this.signal.url,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!s,signalChannel:this.signal instanceof lv?"1":"0"}),this._isProactiveJoin=!1,r.delete(e.uid),this.signal.close(),t}return this.state="CONNECTED",this.inChannelInfo.joinAt=Date.now(),CE.debug("[".concat(this.store.clientId,"] Connected to gateway server")),this.trafficStatsInterval=window.setInterval(()=>{this.updateTrafficStats().catch(e=>{CE.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(nS.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6}):this._signalTimeout?this.emit(nS.NETWORK_QUALITY,{downlinkNetworkQuality:5,uplinkNetworkQuality:5}):"CONNECTED"===this.state&&this._statsCollector.trafficStats?this.emit(nS.NETWORK_QUALITY,{uplinkNetworkQuality:TI(this._statsCollector.trafficStats.B_unq),downlinkNetworkQuality:TI(this._statsCollector.trafficStats.B_dnq)}):this.emit(nS.NETWORK_QUALITY,{uplinkNetworkQuality:0,downlinkNetworkQuality:0})},2e3),this.store.joinGatewayEnd(),o}async leave(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0;if("DISCONNECTED"!==this.state){t!==gf.FALLBACK&&(this.state="DISCONNECTING");try{e||this.signal.connectionState!==vf.CONNECTED||await function(e,t){return t===1/0?e:Sl.race([e,bI(t)])}(this.signal.request(yf.LEAVE,void 0,!0),3e3)}catch(e){CE.warning("[".concat(this.store.clientId,"] leave request failed, ignore"),e)}this.signal.close(t),t!==gf.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}}async publish(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new EE(_E.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const n={state:"offer",p2p_id:this.store.p2pId,ortc:t,mode:this.spec.mode,extend:FE("PUB_EXTEND"),twcc:!!FE("PUBLISH_TWCC")};try{return(await this.signal.request(yf.PUBLISH,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===Sf.ERR_PUBLISH_REQUEST_INVALID)return CE.warning("[".concat(this.store.clientId,"] receive publish error code, retry"),n.toString()),await this.tryUnpubBeforeRepub(e,t),this.publish(e,t,!1);throw n}}async unpublish(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new EE(_E.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await this.signal.request(yf.UNPUBLISH,{stream_id:t,ortc:e},!0)}catch(e){CE.warning("unpublish warning: ",e)}}async subscribe(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new EE(_E.INVALID_OPERATION,"can not subscribe when connection state is ".concat(this.state));const n={stream_id:e,stream_type:t.stream_type,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!FE("SUBSCRIBE_TWCC"),extend:FE("SUB_EXTEND"),ssrcId:t.ssrcId};try{return(await this.signal.request(yf.SUBSCRIBE,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===Sf.ERR_SUBSCRIBE_REQUEST_INVALID)return CE.warning("[".concat(this.store.clientId,"] receiver subscribe error code, retry"),n.toString()),await this.tryUnsubBeforeResub(e,t),await this.subscribe(e,t,!1);throw n}}async subscribeAll(e,t){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new EE(_E.INVALID_OPERATION,"can not massSubscribe when connection state is ".concat(this.state));const i={p2p_id:this.store.p2pId,users:e,dtx:!1};try{return await this.signal.request(yf.SUBSCRIBE_STREAMS,i,!0)}catch(i){if(t&&i.data&&i.data.code===Sf.ERR_SUBSCRIBE_REQUEST_INVALID)return CE.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){const t=function(e){if(!(e.bitrateMax&&e.bitrateMin&&e.frameRate&&e.height&&e.width))return;let t=e.frameRate,i=e.width,n=e.height,r=!0;return"number"!=typeof t&&(t=t.exact||t.ideal||t.max||t.min||0,t||(r=!1)),"number"!=typeof i&&(i=i.exact||i.ideal||i.max||i.min||0,i||(r=!1)),"number"!=typeof n&&(n=n.exact||n.ideal||n.max||n.min||0,t||(r=!1)),r?{stream_type:0,width:i,height:n,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(yf.SET_VIDEO_PROFILE,t);CE.debug("[".concat(this.store.clientId,"] encoder config is not complete, do not report to gateway"))}async unsubscribe(e,t){try{await this.signal.request(yf.UNSUBSCRIBE,{p2p_id:this.store.p2pId,ortc:e,stream_id:t},!0)}catch(e){CE.warning("unsubscribe warning: ",e)}}async massUnsubscribe(e){try{await this.signal.request(yf.UNSUBSCRIBE_STREAMS,e,!0)}catch(e){CE.warning("unsubscribeAll warning: ",e)}}async reconnectPC(e){const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=e;return{gatewayEstablishParams:await this.signal.request(yf.CONNECT_PC,{p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}},!0),gatewayAddress:this.getCurrentGatewayAddress()}}getGatewayInfo(){return this.signal.request(yf.GATEWAY_INFO)}renewToken(e){return this.signal.request(yf.RENEW_TOKEN,e)}async setClientRole(e,t){if(t&&(this._clientRoleOptions=Object.assign({},t)),"CONNECTED"!==this.state)return void(this.role=e);let i=void 0;i="audience"===e?this._clientRoleOptions&&this._clientRoleOptions.level?this._clientRoleOptions.level:2:0,await this.signal.request(yf.SET_CLIENT_ROLE,{role:e,level:i,client_ts:Date.now()}),this.role=e}async setRemoteVideoStreamType(e,t){await this.signal.request(yf.SWITCH_VIDEO_STREAM,{stream_id:e,stream_type:t})}async setDefaultRemoteVideoStreamType(e){await this.signal.request(yf.DEFAULT_VIDEO_STREAM,{stream_type:e})}async setStreamFallbackOption(e,t){await this.signal.request(yf.SET_FALLBACK_OPTION,{stream_id:e,fallback_type:t})}async pickSVCLayer(e,t){await this.signal.request(yf.PICK_SVC_LAYER,{stream_id:e,spatial_layer:t.spatialLayer,temporal_layer:t.temporalLayer})}getInChannelInfo(){return this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt),pv({},this.inChannelInfo)}async getGatewayVersion(){return(await this.signal.request(yf.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){const e=_v.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(){if(!this.joinInfo)return;const e=function(e){let t;return t=e.startsWith("dc")?e.match(/(dc\:\/\/)?([^:]+):(\d+)/):e.match(/(wss\:\/\/)?([^:]+):(\d+)/),t?{username:wE.username,password:wE.password,turnServerURL:t[2],tcpport:parseInt(t[3])+30,udpport:parseInt(t[3])+30,forceturn:!1}:null}(("disabled"===this.joinInfo.cloudProxyServer?this.signal.url:this.joinInfo.gatewayAddrs[this.signal.currentURLIndex].address)||"");this.joinInfo.turnServer.serversFromGateway=[],e&&"off"!==this.joinInfo.turnServer.mode&&"disabled"===this.joinInfo.cloudProxyServer&&this.joinInfo.turnServer.serversFromGateway.push(pv(pv({},wE),{},{turnServerURL:e.turnServerURL,tcpport:e.tcpport,udpport:e.udpport,username:this.joinInfo.uid.toString(),password:this.joinInfo.token}))}async updateTrafficStats(){if("CONNECTED"!==this.state)return;const e=await this.signal.request(yf.TRAFFIC_STATS,void 0,!0);e.timestamp=Date.now(),e.peer_delay.forEach(e=>{const t=this._statsCollector.trafficStats&&this._statsCollector.trafficStats.peer_delay.find(t=>t.peer_uid===e.peer_uid);t&&t.B_st!==e.B_st&&jI(()=>{this.emit(nS.STREAM_TYPE_CHANGE,e.peer_uid,e.B_st)})}),this._statsCollector.updateTrafficStats(e)}getJoinMessage(e){if(!this.joinInfo||!this.key)throw new EE(_E.UNEXPECTED_ERROR,"can not generate join message, no join info");const t=Object.assign({},this.joinInfo.apResponse);let i=FE("REPORT_APP_SCENARIO");if("string"!=typeof i)try{i=JSON.stringify(i)}catch(e){i=void 0}i&&i.length>128&&(i=void 0);const n=pv({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:AE,browser:navigator.userAgent,process_id:FE("PROCESS_ID"),mode:this.spec.mode,codec:this.spec.codec,role:this.role,has_changed_gateway:this.hasChangeBGPAddress,ap_response:t,extend:FE("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:FE("ENABLE_PUBLISHED_USER_LIST"),maxSubscription:FE("MAX_SUBSCRIPTION"),subscribeAudioFilterTopN:"number"==typeof FE("SUBSCRIBE_AUDIO_FILTER_TOPN")?FE("SUBSCRIBE_AUDIO_FILTER_TOPN"):void 0,enablePublishAudioFilter:"boolean"==typeof FE("ENABLE_PUBLISH_AUDIO_FILTER")?FE("ENABLE_PUBLISH_AUDIO_FILTER"):void 0,enableUserLicenseCheck:"boolean"==typeof FE("ENABLE_USER_LICENSE_CHECK")?FE("ENABLE_USER_LICENSE_CHECK"):void 0}},join_ts:this.joinGatewayStartTime},e);return this.joinInfo.stringUid&&(n.string_uid=this.joinInfo.stringUid),this.joinInfo.aesmode&&this.joinInfo.aespassword&&(n.aes_mode=this.joinInfo.aesmode,FE("ENCRYPT_AES")?(n.aes_secret=this.joinInfo.aespassword,n.aes_encrypt=!0):n.aes_secret=this.joinInfo.aespassword,this.joinInfo.aessalt&&(n.aes_salt=this.joinInfo.aessalt)),t.addresses[this.signal.websocket.currentURLIndex]&&(n.ap_response.ticket=t.addresses[this.signal.websocket.currentURLIndex].ticket,delete t.addresses),void 0!==this.joinInfo.defaultVideoStream&&(n.default_video_stream=this.joinInfo.defaultVideoStream),n}getRejoinMessage(){if(!this.joinInfo)throw new EE(_E.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(Cf.WS_RECONNECT_WAITTING_FINISH,e=>{["tryNext","recover"].includes(e)&&this.joinInfo&&Tg.adjustSessionStartTime(this.joinInfo.sid)}),this.signal.on(Cf.WS_RECONNECT_CREATE_CONNECTION,e=>{this.joinGatewayStartTime=Date.now()}),this.signal.on(Cf.WS_RECONNECTING,e=>{this.joinInfo&&Tg.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:e||If.NETWORK_ERROR}),this.joinInfo&&(this.state="RECONNECTING",Tg.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(Cf.WS_CLOSED,e=>{let t;switch(e){case gf.LEAVE:t=If.LEAVE;break;case gf.UID_BANNED:case gf.IP_BANNED:case gf.CHANNEL_BANNED:case gf.SERVER_ERROR:t=If.SERVER_ERROR;break;case gf.FALLBACK:t=If.FALLBACK;break;case gf.LICENSE_MISSING:case gf.LICENSE_EXPIRED:case gf.LICENSE_MINUTES_EXCEEDED:case gf.LICENSE_PERIOD_INVALID:case gf.LICENSE_MULTIPLE_SDK_SERVICE:case gf.LICENSE_ILLEGAL:t=e;break;default:t=If.NETWORK_ERROR}CE.debug("[signal] websocket closed, reason: ".concat(t||"undefined -> "+If.NETWORK_ERROR)),this.joinInfo&&Tg.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:e===gf.LEAVE?1:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:t}),this._disconnectedReason=e,e!==gf.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}),this.signal.on(Cf.WS_CONNECTED,()=>{if(this.updateTurnConfigFromSignal(),this.state="CONNECTED",this.joinInfo&&("audience"===this.role&&this._clientRoleOptions&&this._clientRoleOptions.level&&(CE.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)),Tg.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 lv?"1":"0"}),this._isProactiveJoin=!1,this.joinInfo.useLocalAccessPoint&&1===this.joinInfo.setLocalAPVersion)){const e=this.signal.url&&this.signal.url.match(/wss\:\/\/([^:]+):(\d+)/);if(!e)return void CE.error("[".concat(this.store.clientId,"] set local access point after joined failed: ").concat(e));VE("EVENT_REPORT_DOMAIN",e[1]),VE("EVENT_REPORT_BACKUP_DOMAIN",e[1]),VE("LOG_UPLOAD_SERVER","".concat(e[1],":6444"))}}),this.signal.on(Of.ON_UPLINK_STATS,e=>{this._statsCollector.updateUplinkStats(e)}),this.signal.on(Cf.REQUEST_RECOVER,(e,t,i)=>{if(!this.joinInfo)return i(new EE(_E.UNEXPECTED_ERROR,"gateway: can not recover, no join info"));e&&(this.joinInfo.multiIP=e,this.hasChangeBGPAddress=!0),this.isSignalRecover=!0,kI(this,nS.REQUEST_NEW_GATEWAY_LIST).then(t).catch(i)}),this.signal.on(Cf.REQUEST_JOIN_INFO,async e=>{var t;this.updateTurnConfigFromSignal();const{iceParameters:i,dtlsParameters:n,rtpCapabilities:r}=await kI(this,nS.REQUEST_P2P_CONNECTION_PARAMS,{turnServer:null===(t=this.joinInfo)||void 0===t?void 0:t.turnServer});e(this.getJoinMessage({ortc:{iceParameters:i,dtlsParameters:n,rtpCapabilities:r,version:"2"}}))}),this.signal.on(Cf.REQUEST_REJOIN_INFO,e=>{e(this.getRejoinMessage())}),this.signal.on(Cf.REPORT_JOIN_GATEWAY,(e,t)=>{this.joinInfo&&(Tg.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 lv?"1":"0"}),this._isProactiveJoin=!1)}),this.signal.on(Cf.IS_P2P_DISCONNECTED,e=>{e(xI(this,nS.IS_P2P_DISCONNECTED))}),this.signal.on(Cf.DISCONNECT_P2P,()=>{this.emit(nS.DISCONNECT_P2P)}),this.signal.on(Cf.NEED_RENEW_SESSION,()=>{this.emit(nS.NEED_RENEW_SESSION)}),this.signal.on(Cf.REQUEST_SUCCESS,()=>{this._signalTimeout=!1}),this.signal.on(Cf.REQUEST_TIMEOUT,()=>{this._signalTimeout=!0}),this.signal.on(Cf.JOIN_RESPONSE,e=>{const t=this.getCurrentGatewayAddress();this.emit(nS.JOIN_RESPONSE,e,t)}),this.signal.on(Cf.DATACHANNEL_PRECONNECT,async(e,t,i)=>{this.updateTurnConfigFromSignal();const n=this.getCurrentGatewayAddress();return kI(this,nS.DATACHANNEL_PRECONNECT,e,n).then(t).catch(i)}),this.signal.on(Cf.DATACHANNEL_CONNECTING,async e=>{const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=await kI(this,nS.REQUEST_DC_CONNECTION_PARAMS);e(this.getJoinMessage({ortc:{iceParameters:t,dtlsParameters:i,rtpCapabilities:n,version:"2"}}))}),this.signal.on(Cf.DATACHANNEL_FAILBACK,()=>{CE.warning("[".concat(this.store.clientId,"] User join datachannel failed")),this.reset(),this.resetSignal(),this.emit(nS.DATACHANNEL_FAILBACK)})}async tryUnsubBeforeResub(e,t){try{await this.signal.request(yf.UNSUBSCRIBE,{p2p_id:this.store.p2pId,stream_id:e,ortc:[t]},!0)}catch(e){throw CE.warning("unsubscribe warning",e),e}}async tryUnpubBeforeRepub(e,t){try{await this.signal.request(yf.UNPUBLISH,{stream_id:e,ortc:t},!0)}catch(e){throw CE.warning("unpublish warning: ",e),e}}async tryMassUnsubBeforeResub(e){const t={users:e.map(e=>({stream_id:e.stream_id,stream_type:e.stream_type}))};try{await this.signal.request(yf.UNSUBSCRIBE_STREAMS,t,!0)}catch(e){throw CE.warning("massUnsubscribe warning",e),e}}async muteLocal(e,t){const i={action:e.find(e=>e.stream_type===iS.Audio)?"mute_local_audio":"mute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(yf.CONTROL,i,!0,!0)}catch(e){throw CE.warning("gateway unmuteLocal warning: ",e),e}}async unmuteLocal(e,t){const i={action:e.find(e=>e.stream_type===iS.Audio)?"unmute_local_audio":"unmute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(yf.CONTROL,i,!0,!0)}catch(e){throw CE.warning("gateway muteLocal warning: ",e),e}}uploadStats(e,t){this.signal.upload(e,t)}getSignalRTT(){return this.signal.rtt}async restartICE(e){const t={p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:e};try{return await this.signal.request(yf.RESTART_ICE,t,!0)}catch(e){throw CE.warning("P2PChannel.restartICE warning: ",e),e}}reconnect(){"CONNECTED"===this.state&&this.signal.reconnect(void 0,If.P2P_FAILED)}getCurrentGatewayAddress(){var e;if(!FE("GATEWAY_WSS_ADDRESS"))return null!==(e=this.joinInfo)&&void 0!==e&&e.gatewayAddrs?this.joinInfo.gatewayAddrs[this.signal.currentURLIndex]:void 0}async setPublishAudioFilterEnabled(e){await this.signal.request(yf.SET_PARAMETER,{enablePublishAudioFilter:e})}resetSignal(){this.signal&&(this.signal.removeAllListeners(),this.signal.close(gf.FALLBACK)),this.store.useDataChannel=!1,this.signal=new nv(pv(pv({},this.spec),{},{retryConfig:this.spec.websocketRetryConfig}),this.store),this.handleSignalEvents(),this.emit(nS.RESET_SIGNAL,oS.websocket)}}
|
||
/*! formdata-polyfill. MIT License. Jimmy W?rting <https://jimmy.warting.se/opensource> */!function(){var e;function i(e){var t=0;return function(){return t<e.length?{done:!1,value:e[t++]}:{done:!0}}}var n="function"==typeof Object.defineProperties?Object.defineProperty:function(e,t,i){return e==Array.prototype||e==Object.prototype||(e[t]=i.value),e};var r,o=function(e){e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof t&&t];for(var i=0;i<e.length;++i){var n=e[i];if(n&&n.Math==Math)return n}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(e){return(e={next:e})[Symbol.iterator]=function(){return this},e}function c(e){var t="undefined"!=typeof Symbol&&Symbol.iterator&&e[Symbol.iterator];return t?t.call(e):{next:i(e)}}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 new TypeError("Symbol is not a constructor");return new t(i+(n||"")+"_"+r++,n)}})),s("Symbol.iterator",(function(e){if(e)return e;e=Symbol("Symbol.iterator");for(var t="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),r=0;r<t.length;r++){var s=o[t[r]];"function"==typeof s&&"function"!=typeof s.prototype[e]&&n(s.prototype,e,{configurable:!0,writable:!0,value:function(){return a(i(this))}})}return e})),"function"==typeof Object.setPrototypeOf)r=Object.setPrototypeOf;else{var d;e:{var u={};try{u.__proto__={a:!0},d=u.a;break e}catch(e){}d=!1}r=d?function(e,t){if(e.__proto__=t,e.__proto__!==t)throw new TypeError(e+" is not extensible");return e}:null}var l=r;function h(){this.m=!1,this.j=null,this.v=void 0,this.h=1,this.u=this.C=0,this.l=null}function p(e){if(e.m)throw new TypeError("Generator is already running");e.m=!0}function _(e,t){return e.h=3,{value:t}}function E(e){this.g=new h,this.G=e}function m(e,t,i,n){try{var r=t.call(e.g.j,i);if(!(r instanceof Object))throw new TypeError("Iterator result "+r+" is not an object");if(!r.done)return e.g.m=!1,r;var o=r.value}catch(t){return e.g.j=null,e.g.s(t),f(e)}return e.g.j=null,n.call(e.g,o),f(e)}function f(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 S(e){this.next=function(t){return e.o(t)},this.throw=function(t){return e.s(t)},this.return=function(t){return function(e,t){p(e.g);var i=e.g.j;return i?m(e,"return"in i?i.return:function(e){return{value:e,done:!0}},t,e.g.return):(e.g.return(t),f(e))}(e,t)},this[Symbol.iterator]=function(){return this}}function T(e,t){return t=new S(new E(t)),l&&e.prototype&&l(t,e.prototype),t}if(h.prototype.o=function(e){this.v=e},h.prototype.s=function(e){this.l={D:e,F:!0},this.h=this.C||this.u},h.prototype.return=function(e){this.l={return:e},this.h=this.u},E.prototype.o=function(e){return p(this.g),this.g.j?m(this,this.g.j.next,e,this.g.o):(this.g.o(e),f(this))},E.prototype.s=function(e){return p(this.g),this.g.j?m(this,this.g.j.throw,e,this.g.o):(this.g.s(e),f(this))},s("Array.prototype.entries",(function(e){return e||function(){return function(e,t){e instanceof String&&(e+="");var i=0,n=!1,r={next:function(){if(!n&&i<e.length){var r=i++;return{value:t(r,e[r]),done:!1}}return n=!0,{done:!0,value:void 0}}};return r[Symbol.iterator]=function(){return r},r}(this,(function(e,t){return[e,t]}))}})),"undefined"!=typeof Blob&&("undefined"==typeof FormData||!FormData.prototype.keys)){var g=function(e,t){for(var i=0;i<e.length;i++)t(e[i])},R=function(e){return e.replace(/\r?\n|\r/g,"\r\n")},I=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)]},v=function(e,t){if(e.length<t)throw new TypeError(t+" argument required, but only "+e.length+" present.")},C="object"==typeof globalThis?globalThis:"object"==typeof window?window:"object"==typeof self?self:this,y=C.FormData,A=C.XMLHttpRequest&&C.XMLHttpRequest.prototype.send,O=C.Request&&C.fetch,b=C.navigator&&C.navigator.sendBeacon,w=C.Element&&C.Element.prototype,N=C.Symbol&&Symbol.toStringTag;N&&(Blob.prototype[N]||(Blob.prototype[N]="Blob"),"File"in C&&!File.prototype[N]&&(File.prototype[N]="File"));try{new File([],"")}catch(e){C.File=function(e,t,i){return e=new Blob(e,i||{}),Object.defineProperties(e,{name:{value:t},lastModified:{value:+(i&&void 0!==i.lastModified?new Date(i.lastModified):new Date)},toString:{value:function(){return"[object File]"}}}),N&&Object.defineProperty(e,N,{value:"File"}),e}}var D=function(e){return e.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22")},P=function(e){this.i=[];var t=this;e&&g(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"})];g(i,(function(i){t.append(e.name,i)}))}else"select-multiple"===e.type||"select-one"===e.type?g(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?R(e.value):e.value,t.append(e.name,i))}))};if((e=P.prototype).append=function(e,t,i){v(arguments,2),this.i.push(I(e,t,i))},e.delete=function(e){v(arguments,1);var t=[];e=String(e),g(this.i,(function(i){i[0]!==e&&t.push(i)})),this.i=t},e.entries=function e(){var t,i=this;return T(e,(function(e){if(1==e.h&&(t=0),3!=e.h)return t<i.i.length?e=_(e,i.i[t]):(e.h=0,e=void 0),e;t++,e.h=2}))},e.forEach=function(e,t){v(arguments,1);for(var i=c(this),n=i.next();!n.done;n=i.next()){var r=c(n.value);n=r.next().value,r=r.next().value,e.call(t,r,n,this)}},e.get=function(e){v(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},e.getAll=function(e){v(arguments,1);var t=[];return e=String(e),g(this.i,(function(i){i[0]===e&&t.push(i[1])})),t},e.has=function(e){v(arguments,1),e=String(e);for(var t=0;t<this.i.length;t++)if(this.i[t][0]===e)return!0;return!1},e.keys=function e(){var t,i,n,r,o=this;return T(e,(function(e){if(1==e.h&&(t=c(o),i=t.next()),3!=e.h)return i.done?void(e.h=0):(n=i.value,r=c(n),_(e,r.next().value));i=t.next(),e.h=2}))},e.set=function(e,t,i){v(arguments,2),e=String(e);var n=[],r=I(e,t,i),o=!0;g(this.i,(function(t){t[0]===e?o&&(o=!n.push(r)):n.push(t)})),o&&n.push(r),this.i=n},e.values=function e(){var t,i,n,r,o=this;return T(e,(function(e){if(1==e.h&&(t=c(o),i=t.next()),3!=e.h)return i.done?void(e.h=0):(n=i.value,(r=c(n)).next(),_(e,r.next().value));i=t.next(),e.h=2}))},P.prototype._asNative=function(){for(var e=new y,t=c(this),i=t.next();!i.done;i=t.next()){var n=c(i.value);i=n.next().value,n=n.next().value,e.append(i,n)}return e},P.prototype._blob=function(){var e="----formdata-polyfill-"+Math.random(),t=[],i="--"+e+'\r\nContent-Disposition: form-data; name="';return this.forEach((function(e,n){return"string"==typeof e?t.push(i+D(R(n))+'"\r\n\r\n'+R(e)+"\r\n"):t.push(i+D(R(n))+'"; filename="'+D(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})},P.prototype[Symbol.iterator]=function(){return this.entries()},P.prototype.toString=function(){return"[object FormData]"},w&&!w.matches&&(w.matches=w.matchesSelector||w.mozMatchesSelector||w.msMatchesSelector||w.oMatchesSelector||w.webkitMatchesSelector||function(e){for(var t=(e=(this.document||this.ownerDocument).querySelectorAll(e)).length;0<=--t&&e.item(t)!==this;);return-1<t}),N&&(P.prototype[N]="FormData"),A){var L=C.XMLHttpRequest.prototype.setRequestHeader;C.XMLHttpRequest.prototype.setRequestHeader=function(e,t){L.call(this,e,t),"content-type"===e.toLowerCase()&&(this.B=!0)},C.XMLHttpRequest.prototype.send=function(e){e instanceof P?(e=e._blob(),this.B||this.setRequestHeader("Content-Type",e.type),A.call(this,e)):A.call(this,e)}}O&&(C.fetch=function(e,t){return t&&t.body&&t.body instanceof P&&(t.body=t.body._blob()),O.call(this,e,t)}),b&&(C.navigator.sendBeacon=function(e,t){return t instanceof P&&(t=t._asNative()),b.call(this,e,t)}),C.FormData=P}}();const mv=()=>{const e=FE("AREAS");0===e.length&&e.push(hS.GLOBAL);return zi(e).call(e,(e,t,i)=>{const n=fv(t);return n?0===i?n:"".concat(e,",").concat(n):e},"")},fv=e=>e===hS.OVERSEA?"".concat(mS.ASIA,",").concat(mS.EUROPE,",").concat(mS.AFRICA,",").concat(mS.NORTH_AMERICA,",").concat(mS.SOUTH_AMERICA,",").concat(mS.OCEANIA):mS[e],Sv=e=>{const 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=>{const i=fS[e],n=Object.keys(i);n&&n.map(e=>{"CODE"!==e&&(t[e]=t[e].concat(i[e]))})}),t},Tv={GLOBAL:{ASIA:[hS.CHINA,hS.JAPAN,hS.INDIA,hS.KOREA,hS.HKMC],EUROPE:[],NORTH_AMERICA:[hS.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}},gv=Object.keys(Tv[hS.GLOBAL]),Rv=[hS.CHINA,hS.NORTH_AMERICA,hS.EUROPE,hS.ASIA,hS.JAPAN,hS.INDIA,hS.OCEANIA,hS.SOUTH_AMERICA,hS.AFRICA,hS.KOREA,hS.HKMC,hS.US],Iv=function(e,t){let i=[];if(e.includes(hS.GLOBAL)){const o=[hS.GLOBAL,hS.OVERSEA],s=Object.keys(fS);if(t===hS.GLOBAL)throw new EE(_E.INVALID_PARAMS,"GLOBAL is an invalid excludedArea value");if(t===hS.CHINA)i=[hS.OVERSEA];else if(r=t,gv.includes(r)){const e=(n=t,Tv[hS.GLOBAL][n]||[]),r=[...o,t,...e];i=s.filter(e=>!r.includes(e))}else if(function(e){let t=!1;return gv.forEach(i=>{Tv[hS.GLOBAL][i].includes(e)&&(t=!0)}),t}(t)){const e=function(e){let t;return gv.forEach(i=>{Tv[hS.GLOBAL][i].includes(e)&&(t=i)}),t}(t),n=[...o,e,t];i=s.filter(e=>!n.includes(e))}else i=e;i=function(e){const t=[];return Rv.forEach(i=>{e.includes(i)&&t.push(i)}),t.concat(e.filter(e=>!Rv.includes(e)))}(i)}else i=e;var n,r;return i};function vv(e){if(!e&&FE("AREAS").includes(hS.EXTENSIONS))return CE.debug("update area from ap : reset"),void Cv(bE,!0);if(!FE("AREAS").includes(hS.GLOBAL)||!e)return;let t=fS.EXTENSIONS;t&&(t={CODE:fv(hS.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")]},CE.debug("update area from ap success: ".concat(e,",config is "),t),VE("AREAS",[hS.EXTENSIONS],!0),Object.keys(t).map(e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){VE(e,t[e][0])}else VE(e,t[e])}))}function Cv(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=Tg.reportApiInvoke(null,{name:uf.SET_AREA,options:e,tag:lf.TRACER});try{let n=[];if("string"==typeof e&&(n=[e]),Array.isArray(e)&&(e.forEach(e=>{if(!ES.includes(e))throw new EE(_E.INVALID_PARAMS,"invalid area code")}),n=e),"[object Object]"===Object.prototype.toString.call(e)){const{areaCode:t,excludedArea:i}=e;if(!t)throw new EE(_E.INVALID_PARAMS,"area code is needed");let r=t;"string"==typeof t&&(r=[t]),n=i?Iv(r,i):r}if(!t){if(BE.AREAS){const e=new EE(_E.PROHIBITED_OPERATION,"setArea is prohibited because of config-distribute");return i.onError(e),void CE.warning("setArea is prohibited because of config-distribute")}if(n.includes(hS.GLOBAL)&&FE("AREAS")===hS.EXTENSIONS){const e=new EE(_E.PROHIBITED_OPERATION,"setArea is prohibited because of ap extensions");return i.onError(e),void CE.warning("setArea is prohibited because of ap extensions")}}VE("AREAS",n,t);const r=Sv(n);Object.keys(r).map(e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){VE(e,r[e][0])}else VE(e,r[e])}),CE.debug("set area success:",n.join(","))}catch(e){throw i.onError(e),e}i.onSuccess()}function yv(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function Av(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?yv(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):yv(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let Ov=1;function bv(e,t,i,n,r){Ov+=1;const o={sid:i.sid,command:"convergeAllocateEdge",uid:"666",appId:i.appId,ts:Math.floor(Date.now()/1e3),seq:Ov,requestId:Ov,version:AE,cname:i.cname},s={service_name:t,json_body:JSON.stringify(o)};let a,c,d=e[0];return SE(async()=>{a=Date.now();const e=await ag(d,{data:s,cancelToken:n,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"}});if(c=Date.now()-a,0!==e.code){const t=new EE(_E.UNEXPECTED_RESPONSE,"live streaming ap error, code"+e.code,{retry:!0,responseTime:c});throw CE.error(t.toString()),t}const i=JSON.parse(e.json_body);if(200!==i.code){const e=new EE(_E.UNEXPECTED_RESPONSE,"live streaming app center error, code: ".concat(i.code,", reason: ").concat(i.reason),{code:i.code,responseTime:c});throw CE.error(e.toString()),e}if(!i.servers||0===i.servers.length){const e=new EE(_E.UNEXPECTED_RESPONSE,"live streaming app center empty server",{code:i.code,responseTime:c});throw CE.error(e.toString()),e}const r=function(e,t){return{addressList:e.servers.map(e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(FE("WORKER_DOMAIN"),":").concat(e.wss,"?serviceName=").concat(encodeURIComponent(t))),workerToken:e.workerToken,vid:e.vid}}(i,t);return FE("LIVE_STREAMING_ADDRESS")&&(r.addressList=FE("LIVE_STREAMING_ADDRESS")instanceof Array?FE("LIVE_STREAMING_ADDRESS"):[FE("LIVE_STREAMING_ADDRESS")]),Av(Av({},r),{},{responseTime:c})},(n,r)=>(Tg.apworkerEvent(i.sid,{success:!0,sc:200,serviceName:t,responseDetail:JSON.stringify(n.addressList),firstSuccess:0===r,responseTime:c,serverIp:e[r%e.length]}),!1),(n,r)=>(Tg.apworkerEvent(i.sid,{success:!1,sc:n.data&&n.data.code||200,serviceName:t,responseTime:c,serverIp:e[r%e.length]}),!!(n.code!==_E.OPERATION_ABORTED&&n.code!==_E.UNEXPECTED_RESPONSE||n.data&&n.data.retry)&&(d=e[(r+1)%e.length],!0)),r)}let wv=1;function Nv(e,t,i,n){let{url:r,areaCode:o}=e;const s=Date.now();let a;const[c,d]=Mv(t,o,[US.CHOOSE_SERVER]);let u=dg.networkState;return SE(async()=>{u&&dg.networkState===CS.OFFLINE&&dg.onlineWaiter&&await Sl.race([dg.onlineWaiter,OI(n&&n.maxRetryTimeout||mE.maxRetryTimeout)]),u=dg.networkState;const{data:e,headers:o}=await ag(r,{data:c,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);a="1"===o.http3?1:-1,Tg.reportResourceTiming(r,t.sid),Pv(e,r,t,s,[US.CHOOSE_SERVER],a);const d=gI(e,US.CHOOSE_SERVER);return Lv(d),EI(d,r)},e=>(e&&Tg.joinChooseServer(t.sid,{lts:s,succ:!0,csAddr:r,opid:d,serverList:e.gatewayAddrs.map(e=>e.address),ec:null,cid:e.cid.toString(),uid:e.uid.toString(),csIp:e.csIp,unilbsServerIds:[US.CHOOSE_SERVER].toString(),isHttp3:a}),!1),e=>e.code!==_E.OPERATION_ABORTED&&(e.code===_E.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(Tg.joinChooseServer(t.sid,{lts:s,succ:!1,csAddr:r,serverList:null,opid:d,ec:e.code,csIp:e.data&&e.data.csIp,unilbsServerIds:[US.CHOOSE_SERVER].toString(),extend:JSON.stringify({networkState:u}),isHttp3:a}),CE.warning("[".concat(t.clientId,"] Choose server network error, retry"),e),!0)),n)}function Dv(e,t,i,n){let r,{url:o,areaCode:s,serviceIds:a}=e;const c=Date.now(),[d,u]=Mv(t,s,a);let l=void 0;return SE(async()=>{l&&dg.networkState===CS.OFFLINE&&dg.onlineWaiter&&await Sl.race([dg.onlineWaiter,OI(n&&n.maxRetryTimeout||mE.maxRetryTimeout)]),l=dg.networkState;const{data:e,headers:s}=await ag(o,{data:d,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);r="1"===s.http3?1:-1,Tg.reportResourceTiming(o,t.sid),Pv(e,o,t,c,a,r);const u=gI(e,US.CHOOSE_SERVER),h=gI(e,"proxy5"===t.cloudProxyServer?US.CLOUD_PROXY_5:"proxy3"===t.cloudProxyServer||"proxy4"===t.cloudProxyServer?US.CLOUD_PROXY:US.CLOUD_PROXY_FALLBACK);return Lv(u),{gatewayInfo:EI(u,o),proxyInfo:h,url:o}},e=>(e.gatewayInfo&&Tg.joinChooseServer(t.sid,{lts:c,succ:!0,csAddr:o,serverList:e.gatewayInfo.gatewayAddrs.map(e=>e.address),ec:null,opid:u,cid:e.gatewayInfo.cid.toString(),uid:e.gatewayInfo.uid.toString(),csIp:e.gatewayInfo.csIp,unilbsServerIds:a.toString(),isHttp3:r}),e.proxyInfo&&Tg.joinWebProxyAP(t.sid,{lts:c,sucess:1,apServerAddr:o,turnServerAddrList:e.proxyInfo.addresses.map(e=>e.ip).join(","),errorCode:null,eventType:t.cloudProxyServer,unilbsServerIds:a.toString()}),!1),e=>e.code!==_E.OPERATION_ABORTED&&(e.code===_E.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(Tg.joinWebProxyAP(t.sid,{lts:c,sucess:0,apServerAddr:o,turnServerAddrList:null,errorCode:e.code,eventType:t.cloudProxyServer,unilbsServerIds:a.toString(),extend:JSON.stringify({networkState:l})}),CE.warning("[".concat(t.clientId,"] multi unilbs network error, retry"),e),!0)),n)}const Pv=(e,t,i,n,r,o)=>{const s=[],a=s=>{4096===s.flag?Tg.joinChooseServer(i.sid,{lts:n,succ:!1,csAddr:t,opid:e.opid,serverList:null,ec:s.error.message,csIp:s.error.data&&s.error.data.csIp,unilbsServerIds:r.toString(),isHttp3:o}):1048576!==s.flag&&4194304!==s.flag&&4194310!==s.flag||Tg.joinWebProxyAP(i.sid,{lts:n,sucess:0,apServerAddr:t,turnServerAddrList:null,errorCode:s.error.code,eventType:i.cloudProxyServer,unilbsServerIds:r.toString()})};if(e.response_body.forEach(t=>{const i=t.buffer.code;if(23===t.uri&&0===i&&!t.buffer.edges_services)if(4194310===t.buffer.flag)CE.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers"),t.buffer.edges_services=[];else{const i={error:new EE(_E.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:!0,csIp:e.detail[502]}),flag:t.buffer.flag};s.push(i),a(i)}if(0!==i){const n=QI(i),r={error:new EE(_E.CAN_NOT_GET_GATEWAY_SERVER,n.desc,{desc:n.desc,retry:n.retry,csIp:e.detail[502]}),flag:t.buffer.flag};4194310===t.buffer.flag?CE.warning(r.error.toString()):s.push(r),a(r)}}),s.length)throw CE.warning("[".concat(i.clientId,"] multi unilbs ").concat(t," failed, ").concat(s.map(e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message,", retry: ").concat(e.error.data.retry)).join(" | "))),new EE(_E.CAN_NOT_GET_GATEWAY_SERVER,s.map(e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message)).join(" | "),{retry:!!s.find(e=>e.error.data.retry),csIp:e.detail[502],desc:[...new Set(s.map(e=>{var t,i;return null==e||null===(t=e.error)||void 0===t||null===(i=t.data)||void 0===i?void 0:i.desc}).filter(e=>!!e))]})},Lv=e=>{var t,i,n,r;if(e.addresses&&0===e.addresses.length&&0===e.code)throw new EE(_E.CAN_NOT_GET_GATEWAY_SERVER,"void gateway address",{retry:!0,csIp:e.detail&&e.detail[502]});if(null!==(t=e.detail)&&void 0!==t&&t[23]&&"string"==typeof(null===(i=e.detail)||void 0===i?void 0:i[23])?vv(e.detail[23].toLowerCase()):vv(),null!==(n=e.detail)&&void 0!==n&&n[19]&&"string"==typeof(null===(r=e.detail)||void 0===r?void 0:r[19])){const t=e.detail[19],i=null==t?void 0:t.split(";");for(let t=0;t<i.length;t++){var o;const n=mh(o=i[t]).call(o);e.addresses[t]&&i&&(e.addresses[t].fingerprint=n)}}if(FE("GATEWAY_ADDRESS")&&FE("GATEWAY_ADDRESS").length>0){CE.debug("assign gateway address to",FE("GATEWAY_ADDRESS"));const t=FE("GATEWAY_ADDRESS").map(t=>{var i,n;const r=null!==(i=null===(n=e.addresses.find(e=>e.ip===t.ip&&e.port===t.port))||void 0===n?void 0:n.fingerprint)&&void 0!==i?i:"";return{ip:t.ip,port:t.port,ticket:e.addresses[0]&&e.addresses[0].ticket,fingerprint:r}});e.addresses=t}},kv=(e,t)=>{if(e.response_body&&e.response_body.length){const t=e.response_body[0];if(0!==t.buffer.code){const e=QI(t.buffer.code);throw new EE(_E.UPDATE_TICKET_FAILED,"[".concat(t.buffer.code,"]: ").concat(e.desc),{retry:e.retry})}return t.buffer.ticket}throw CE.debug("update ticket request received ap response without response body:",t),new EE(_E.UPDATE_TICKET_FAILED,"cannot find response body from ap response",{retry:!1})},Mv=(e,t,i)=>{const n=Math.floor(Math.random()*10**12),r={appid:e.appId,client_ts:Date.now(),opid:n,sid:e.sid,request_bodies:[{uri:22,buffer:{cname:e.cname,detail:{6:e.stringUid,11:t,12:FE("USE_NEW_TOKEN")?"1":void 0,22:t},key:e.token,service_ids:i,uid:e.uid||0}}]};r.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]}))});const o=new FormData;return o.append("request",JSON.stringify(r)),[o,n]},Uv=(e,t)=>{const i=Math.floor(Math.random()*10**12),n={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}))}}]},r=new FormData;return r.append("request",JSON.stringify(n)),[r,i]};let xv=0;async function Vv(e,t,i,n){const r=async function(e,t,i,n){let r=null;const o=[],s=async()=>{const r=FE("WEBCS_DOMAIN").slice(0,FE("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:mv()})),s=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map(e=>e.url)}),a=await JI({fragementLength:FE("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(CE.debug("[".concat(e.clientId,"] Connect to choose_server:"),n.url),Nv(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},s),e[0]},promisesCollector:o});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},s),a},a=async()=>{if(await OI(1e3),null!==r)return r;const s=FE("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:mv()})),a=n.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:s.map(e=>e.url)}),c=await JI({fragementLength:FE("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:n=>(CE.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),n.url),Nv(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},a),e[0]},promisesCollector:o});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},a),c};try{return r=await LI([s(),a()]),o.length&&o.forEach(e=>e.cancel&&"function"==typeof e.cancel&&e.cancel()),r}catch(e){throw e[0]}}(e,t,i,n);return{gatewayInfo:await r}}async function Fv(e,t,i,n,r){const o=e.cloudProxyServer;if("disabled"===o){if(!n)return;if(e.useLocalAccessPoint)return await Vv(e,t,i,r);if(FE("JOIN_WITH_FALLBACK_MEDIA_PROXY")){const{gatewayInfo:n,proxyInfo:o}=await Gv(e,t,i,r);return e.turnServer&&"auto"!==e.turnServer.mode||(e.turnServer={mode:"manual",servers:o.map(e=>({turnServerURL:e.address,tcpport:e.tcpport||wE.tcpport,udpport:e.udpport||wE.udpport,username:e.username||wE.username,password:e.password||wE.password,forceturn:FE("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE"),security:!0}))}),{gatewayInfo:n}}return await Vv(e,t,i,r)}const{proxyInfo:s,gatewayInfo:a}=await Gv(e,t,i,r),c={gatewayInfo:a};return e.turnServer={mode:"manual",servers:s.map(e=>({turnServerURL:e.address,tcpport:"proxy3"===o?void 0:e.tcpport?e.tcpport:wE.tcpport,udpport:"proxy4"===o?void 0:e.udpport?e.udpport:wE.udpport,username:e.username||wE.username,password:e.password||wE.password,forceturn:"proxy4"!==o,security:"proxy5"===o}))},CE.debug("[".concat(e.clientId,"] set proxy server: ").concat(e.proxyServer,", mode: ").concat(o)),c}async function jv(e,t,i,n,r){const o=FE("ACCOUNT_REGISTER").slice(0,FE("AJAX_REQUEST_CONCURRENT"));let s=[];s=t.proxyServer?o.map(e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1")):o.map(e=>"https://".concat(e,"/api/v1"));const a=null==r?void 0:r.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"stringUID",urls:s});try{const o=await async function(e,t,i,n,r){const o=Date.now(),s={sid:i.sid,opid:10,appid:i.appId,string_uid:t};let a=e[0];const c=await SE(()=>ag(a+"".concat(-1===a.indexOf("?")?"?":"&","action=stringuid"),{data:s,cancelToken:n,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}}),(i,n)=>{if(0===i.code){if(i.uid<=0||i.uid>=Math.pow(2,32))throw CE.error("Invalid Uint Uid ".concat(t," => ").concat(i.uid),i),Tg.reqUserAccount(s.sid,{lts:o,success:!1,serverAddr:a,stringUid:s.string_uid,uid:i.uid,errorCode:_E.INVALID_UINT_UID_FROM_STRING_UID,extend:s}),new EE(_E.INVALID_UINT_UID_FROM_STRING_UID);return Tg.reqUserAccount(s.sid,{lts:o,success:!0,serverAddr:a,stringUid:s.string_uid,uid:i.uid,errorCode:null,extend:s}),!1}const r=QI(i.code);return r.retry&&(a=e[(n+1)%e.length]),Tg.reqUserAccount(s.sid,{lts:o,success:!1,serverAddr:a,stringUid:s.string_uid,uid:i.uid,errorCode:r.desc,extend:s}),r.retry},(t,i)=>t.code!==_E.OPERATION_ABORTED&&(Tg.reqUserAccount(s.sid,{lts:o,success:!1,serverAddr:a,stringUid:s.string_uid,uid:null,errorCode:t.code,extend:s}),a=e[(i+1)%e.length],!0),r);if(0!==c.code){const e=QI(c.code);throw new EE(_E.UNEXPECTED_RESPONSE,e.desc)}return c}(s,e,t,i,n);return null==r||r.recordJoinChannelService({status:"success",endTs:Date.now()},a),o.uid}catch(e){throw null==r||r.recordJoinChannelService({status:"error",endTs:Date.now(),errors:[e]},a),e}}async function Bv(e,t,i){const n=FE("CDS_AP").slice(0,FE("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(n=>function(e,t,i,n){const r=Mh(),o={flag:64,cipher_method:0,features:{device:r.name,system:r.os,system_general:navigator.userAgent,vendor:t.appId,version:AE,cname:t.cname,sid:t.sid,session_id:t.sid,detail:"",proxyServer:t.proxyServer}};return SE(()=>ag(e,{data:o,timeout:1e3,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":54}}),void 0,e=>e.code!==_E.OPERATION_ABORTED,n)}(n,e,t,i));let r=null,o=null,s={};try{r=await LI(n)}catch(e){if(e.code===_E.OPERATION_ABORTED)throw e;o=e}n.forEach(e=>e.cancel());if(Tg.reportApiInvoke(e.sid,{name:uf.REQUEST_CONFIG_DISTRIBUTE,options:{error:o,res:r}}).onSuccess(),r&&r.test_tags)try{s=function(e){if(!e.test_tags)return{};const t=e.test_tags,i=Object.keys(t),n={};return i.forEach(e=>{var i;const r=mh(i=e.slice(4)).call(i),o=JSON.parse(t[e])[1];n[r]=o}),n}(r)}catch(e){}return s}async function Gv(e,t,i,n){const r=FE("PROXY_SERVER_TYPE3"),o=(e,t,i)=>{let n=i||r;return Array.isArray(n)&&(n=t%2==0?r[1]:r[0]),"https://".concat(n,"/ap/?url=").concat(e)};let s=null;const a=[],c=async()=>{const r=FE("WEBCS_DOMAIN").slice(0,FE("AJAX_REQUEST_CONCURRENT")).map((t,i)=>{let n;return n="disabled"===e.cloudProxyServer&&e.proxyServer?o("".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"):o("".concat(t,"/api/v2/transpond/webrtc?v=2"),i),{url:n,areaCode:mv(),serviceIds:[US.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?US.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?US.CLOUD_PROXY:US.CLOUD_PROXY_FALLBACK]}}),s=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map(e=>e.url)}),c=await JI({fragementLength:FE("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(CE.debug("[".concat(e.clientId,"] Connect to choose_server:"),n.url),Dv(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},s),e[0]},promisesCollector:a});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},s),c},d=async()=>{if(await OI(1e3),null!==s)return s;const r=FE("WEBCS_DOMAIN_BACKUP_LIST").map((t,i)=>{let n;return n="disabled"===e.cloudProxyServer&&e.proxyServer?o("".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"):o("".concat(t,"/api/v2/transpond/webrtc?v=2"),i),{url:n,areaCode:mv(),serviceIds:[US.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?US.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?US.CLOUD_PROXY:US.CLOUD_PROXY_FALLBACK]}}),c=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map(e=>e.url)}),d=await JI({fragementLength:FE("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(CE.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),n.url),Dv(n,e,t,i)),allFailedhandler:e=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},c),e[0]},promisesCollector:a});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},c),d};let u,l,h;try{({gatewayInfo:u,proxyInfo:l,url:h}=await LI([c(),d()]))}catch(e){throw e[0]}if(a.length&&a.forEach(e=>e.cancel&&"function"==typeof e.cancel&&e.cancel()),!u||!l)throw new EE(_E.UNEXPECTED_ERROR,"missing gateway or proxy response").print();if(e.apUrl=h,"disabled"!==e.cloudProxyServer&&Array.isArray(r)&&h){const t=/^https?:\/\/(.+?)(\/.*)?$/.exec(h)[1];r.includes(t)&&(e.proxyServer=t,CE.setProxyServer(t),Tg.setProxyServer(t))}return s={gatewayInfo:u,proxyInfo:await RI(l,u.uid)},s}async function Wv(e,t,i,n){const r=FE("UAP_AP").slice(0,FE("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 bv(r,e,t,i,n)}async function Hv(e,t,i){const n=FE("UAP_AP").slice(0,FE("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(n=>function(e,t,i,n){const r={command:"convergeAllocateEdge",sid:t.sid,appId:t.appId,token:t.token,ts:Date.now(),version:AE,cname:t.cname,uid:t.uid.toString(),requestId:wv,seq:wv};wv+=1;const o={service_name:"tele_channel",json_body:JSON.stringify(r)};return SE(async()=>{const t=await ag(e,{data:o,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":61}});if(0!==t.code){const e=new EE(_E.UNEXPECTED_RESPONSE,"cross channel ap error, code"+t.code,{retry:!0});throw CE.error(e.toString()),e}const n=JSON.parse(t.json_body);if(200!==n.code){const e=new EE(_E.UNEXPECTED_RESPONSE,"cross channel app center error, code: ".concat(n.code,", reason: ").concat(n.reason));throw CE.error(e.toString()),e}if(!n.servers||0===n.servers.length){const e=new EE(_E.UNEXPECTED_RESPONSE,"cross channel app center empty server");throw CE.error(e.toString()),e}return{vid:n.vid,workerToken:n.workerToken,addressList:(FE("CHANNEL_MEDIA_RELAY_SERVERS")||n.servers).map(e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(FE("WORKER_DOMAIN"),":").concat(e.wss))}},void 0,e=>!!(e.code!==_E.OPERATION_ABORTED&&e.code!==_E.UNEXPECTED_RESPONSE||e.data&&e.data.retry),n)}(n,e,t,i));try{const e=await LI(n);return n.forEach(e=>e.cancel()),e}catch(e){throw e[0]}}async function Kv(e,t,i){let n=null;const r=[],o=async o=>{const s=FE(o?"WEBCS_DOMAIN_BACKUP_LIST":"WEBCS_DOMAIN").map(t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2"));return o&&(await OI(1e3),null!==n)?n:await JI({fragementLength:FE("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:n=>(CE.debug("[".concat(e.clientId,"] update ticket, Connect to ").concat(o?"backup":""," choose_server:"),n),function(e,t,i,n){const[r]=Uv(t,[US.CHOOSE_SERVER]);let o=dg.networkState;return SE(async()=>{o&&dg.networkState===CS.OFFLINE&&dg.onlineWaiter&&await Sl.race([dg.onlineWaiter,OI(n&&n.maxRetryTimeout||mE.maxRetryTimeout)]),o=dg.networkState;const t=await ag(e,{data:r,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0);return kv(t,e)},()=>!1,e=>e.code!==_E.OPERATION_ABORTED&&(e.code===_E.UPDATE_TICKET_FAILED?e.data.retry:(CE.warning("[".concat(t.clientId,"] update ticket network error, retry"),e),!0)),n)}(n,e,t,i)),allFailedhandler:e=>{throw e[0]},promisesCollector:r})};try{return n=await LI([o(!1),o(!0)]),r.length&&r.forEach(e=>e.cancel&&"function"==typeof e.cancel&&e.cancel()),n}catch(e){throw e[0]}}function Yv(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function qv(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Yv(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Yv(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class Jv extends hE{constructor(){super(),lp(this,"configs",void 0),lp(this,"joinInfo",void 0),lp(this,"cancelToken",void 0),lp(this,"retryConfig",{timeout:3e3,timeoutFactor:1.5,maxRetryCount:1,maxRetryTimeout:1e4}),lp(this,"interval",void 0),lp(this,"mutex",new vg("config-distribute")),lp(this,"mutableParamsRead",!1)}startGetConfigDistribute(e,t){this.joinInfo=e,this.cancelToken=t,this.interval&&this.stopGetConfigDistribute(),FE("ENABLE_CONFIG_DISTRIBUTE")&&(this.updateConfigDistribute(),this.interval=window.setInterval(()=>{this.updateConfigDistribute()},FE("CONFIG_DISTRIBUTE_INTERVAL")))}stopGetConfigDistribute(){this.interval&&clearInterval(this.interval),this.interval=void 0,this.joinInfo=void 0,this.cancelToken=void 0}async awaitConfigDistributeComplete(){if(!this.mutex.isLocked)return;(await this.mutex.lock())()}async updateConfigDistribute(){if(!this.mutableParamsRead){this.mutableParamsRead=!0;Tg.reportApiInvoke(null,{options:void 0,name:uf.LOAD_CONFIG_FROM_LOCALSTORAGE,tag:lf.TRACER}).onSuccess(JSON.stringify(BE))}if(!this.joinInfo||!this.cancelToken||!this.retryConfig)return void CE.debug("[config-distribute] get config distribute interrupted have no joininfo");let e;const t=await this.mutex.lock();try{e=await Bv(this.joinInfo,this.cancelToken,this.retryConfig),CE.debug("[config-distribute] get config distribute",JSON.stringify(e)),e.limit_bitrate&&this.handleBitrateLimit(e.limit_bitrate),this.cacheGlobalParameterConfig(e),this.configs=e}catch(e){const t=new EE(_E.NETWORK_RESPONSE_ERROR,e);CE.warning("[config-distribute] ".concat(t.toString()))}finally{t()}}getBitrateLimit(){return this.configs?this.configs.limit_bitrate:void 0}handleBitrateLimit(e){var t;(t=e)&&t.uplink&&t.id&&void 0!==t.uplink.max_bitrate&&void 0!==t.uplink.min_bitrate&&(this.configs&&this.configs.limit_bitrate?this.configs&&this.configs.limit_bitrate&&this.configs.limit_bitrate.id!==e.id&&this.emit(SS.UPDATE_BITRATE_LIMIT,e):this.emit(SS.UPDATE_BITRATE_LIMIT,e))}getLowStreamConfigDistribute(){return this.configs&&this.configs.limit_bitrate&&qv({},this.configs.limit_bitrate.low_stream_uplink)}cacheGlobalParameterConfig(e){var t;const i=jm(t=Object.keys(e).filter(e=>/^webrtc_ng_global_parameter/.test(e))).call(t);for(let t=0;t<i.length;t++)for(let n=i.length-1;n>t;n--){const t=i[n];if("number"==typeof e[t].__priority){const r=e[t].__priority,o=i[n-1];if("number"==typeof e[o].__priority){if(!(r>e[o].__priority))continue;{const e=t;i[n]=i[n-1],i[n-1]=e}}else{const e=t;i[n]=i[n-1],i[n-1]=e}}}const n={};i.forEach(t=>{const i=e[t],r=i.__expires;Object.keys(i).forEach(e=>{"__priority"===e||"__expires"===e||Object.prototype.hasOwnProperty.call(n,e)||(n[e]=qv({value:i[e]},r&&{expires:r}))})});try{const e=JSON.stringify(n),t=window.btoa(e);window.localStorage.setItem("websdk_ng_global_parameter",t),CE.debug("Caching global parameters ".concat(e))}catch(e){CE.error("Error caching global parameters:",e.message)}}}function Xv(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function zv(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Xv(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Xv(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class Qv extends hE{constructor(e,t,i,n){super(),lp(this,"spec",void 0),lp(this,"token",void 0),lp(this,"websocket",void 0),lp(this,"pingpongTimer",void 0),lp(this,"reconnectMode","retry"),lp(this,"serviceMode",void 0),lp(this,"reqId",0),lp(this,"commandReqId",0),lp(this,"handleWebSocketOpen",()=>{this.reconnectMode="retry",this.startPingPong()}),lp(this,"handleWebSocketMessage",e=>{if(!e.data)return;const t=JSON.parse(e.data);t.requestId?this.emit("@".concat(t.requestId,"-").concat(t.sid),t):this.serviceMode===Bf.INJECT?this.emit(Jf.INJECT_STREAM_STATUS,t):(Tg.workerEvent(this.spec.sid,{actionType:"status",serverCode:t.code,workerType:this.serviceMode===Bf.TRANSCODE?1:2}),this.emit(Jf.PUBLISH_STREAM_STATUS,t))}),this.spec=t,this.token=e,this.serviceMode=n,this.websocket=new tv("live-streaming",i),this.websocket.on(jf.CONNECTED,this.handleWebSocketOpen),this.websocket.on(jf.ON_MESSAGE,this.handleWebSocketMessage),this.websocket.on(jf.REQUEST_NEW_URLS,(e,t)=>{kI(this,Jf.REQUEST_NEW_ADDRESS).then(e).catch(t)}),this.websocket.on(jf.RECONNECTING,()=>{this.websocket.reconnectMode=this.reconnectMode})}init(e){return this.websocket.init(e)}async request(e,t,i,n){this.reqId+=1,"request"===e&&(this.commandReqId+=1);const r=this.commandReqId,o=this.reqId;if(!o||!this.websocket)throw new EE(_E.UNEXPECTED_ERROR);const s=zv({command:e,sdkVersion:"4.17.0"===AE?"0.0.1":AE,seq:o,requestId:o,allocate:i,cname:this.spec.cname,appId:this.spec.appId,sid:this.spec.sid,uid:this.spec.uid.toString(),ts:Math.floor(Date.now()/1e3)},t);if("closed"===this.websocket.state)throw new EE(_E.WS_DISCONNECT);const a=()=>new Sl((e,t)=>{this.websocket.once(jf.CLOSED,()=>t(new EE(_E.WS_ABORT))),this.websocket.once(jf.CONNECTED,e)});"connected"!==this.websocket.state&&await a(),s.clientRequest&&(s.clientRequest.workerToken=this.token);const c=new Sl((e,t)=>{const i=()=>{t(new EE(_E.WS_ABORT))};this.websocket.once(jf.RECONNECTING,i),this.websocket.once(jf.CLOSED,i),this.once("@".concat(o,"-").concat(this.spec.sid),t=>{e(t)})});n&&Tg.workerEvent(this.spec.sid,zv(zv({},n),{},{requestId:r,actionType:"request",payload:JSON.stringify(t.clientRequest),serverCode:0,code:0}));const d=Date.now();this.websocket.sendMessage(s);let u=null;try{u=await c}catch(n){if("closed"===this.websocket.state)throw n;return await a(),await this.request(e,t,i)}return n&&Tg.workerEvent(this.spec.sid,zv(zv({},n),{},{requestId:r,actionType:"response",payload:JSON.stringify(u.serverResponse),serverCode:u.code,success:200===u.code,responseTime:Date.now()-d})),200!==u.code&&this.handleResponseError(u),u}tryNextAddress(){this.reconnectMode="tryNext",this.websocket.reconnect("tryNext")}close(){const e="4.17.0"===AE?"0.0.1":AE;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 zf.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void CE.warning("live stream response already exists stream");case zf.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case zf.LIVE_STREAM_RESPONSE_BAD_STREAM:case zf.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return new EE(_E.LIVE_STREAMING_INVALID_ARGUMENT,"",{code:e.code}).throw();case zf.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if("UnpublishStream"===e.serverResponse.command||"UninjectStream"===e.serverResponse.command)return;throw new EE(_E.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case zf.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new EE(_E.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:e.code}).throw();case zf.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const t=new EE(_E.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(Jf.WARNING,t,e.serverResponse.url)}case zf.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:{const t=new EE(_E.LIVE_STREAMING_WARN_FREQUENT_REQUEST);return this.emit(Jf.WARNING,t,e.serverResponse.url)}case zf.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new EE(_E.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case zf.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new EE(_E.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:e.code}).throw();case zf.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{const t=new EE(_E.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT);return this.emit(Jf.WARNING,t,e.serverResponse.url)}case zf.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return new EE(_E.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code}).throw();case zf.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new EE(_E.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream resource limit",{retry:!0,changeAddress:!0});case zf.LIVE_STREAM_RESPONSE_WORKER_LOST:case zf.LIVE_STREAM_RESPONSE_WORKER_QUIT:if("UnpublishStream"===e.serverResponse.command||"UninjectStream"===e.serverResponse.command)return;throw new EE(_E.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case zf.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 EE(_E.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:e.code}).throw();throw new EE(_E.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case zf.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case zf.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case zf.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case zf.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return new EE(_E.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(DI)},6e3)}}function Zv(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function $v(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Zv(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Zv(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class eC extends hE{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:mE,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:mE;super(),lp(this,"onLiveStreamWarning",void 0),lp(this,"onLiveStreamError",void 0),lp(this,"onInjectStatusChange",void 0),lp(this,"spec",void 0),lp(this,"retryTimeout",1e4),lp(this,"connection",void 0),lp(this,"httpRetryConfig",void 0),lp(this,"wsRetryConfig",void 0),lp(this,"streamingTasks",new Map),lp(this,"isStartingStreamingTask",!1),lp(this,"taskMutex",new vg("live-streaming")),lp(this,"cancelToken",uE.CancelToken.source()),lp(this,"transcodingConfig",void 0),lp(this,"injectConfig",$v({},qf)),lp(this,"injectLoopTimes",0),lp(this,"uapResponse",void 0),lp(this,"lastTaskId",1),lp(this,"statusError",new Map),this.spec=e,this.httpRetryConfig=i,this.wsRetryConfig=t}async setTranscodingConfig(e){const t=$v($v({},Yf),e);66!==t.videoCodecProfile&&77!==t.videoCodecProfile&&100!==t.videoCodecProfile&&(CE.debug("[".concat(this.spec.clientId,"] set transcoding config, fix video codec profile: ").concat(t.videoCodecProfile," -> 100")),t.videoCodecProfile=100),t.transcodingUsers||(t.transcodingUsers=t.userConfigs),t.transcodingUsers&&(t.transcodingUsers=t.transcodingUsers.map(e=>$v($v($v({},Wf),e),{},{zOrder:e.zOrder?e.zOrder+1:1}))),function(e){Xm(e.width)||Wm(e.width,"config.width",0,1e4),Xm(e.height)||Wm(e.height,"config.height",0,1e4),Xm(e.videoBitrate)||Wm(e.videoBitrate,"config.videoBitrate",1,1e6),Xm(e.videoFrameRate)||Wm(e.videoFrameRate,"config.videoFrameRate"),Xm(e.lowLatency)||Bm(e.lowLatency,"config.lowLatency"),Xm(e.audioSampleRate)||Gm(e.audioSampleRate,"config.audioSampleRate",[32e3,44100,48e3]),Xm(e.audioBitrate)||Wm(e.audioBitrate,"config.audioBitrate",1,128),Xm(e.audioChannels)||Gm(e.audioChannels,"config.audioChannels",[1,2,3,4,5]),Xm(e.videoGop)||Wm(e.videoGop,"config.videoGop"),Xm(e.videoCodecProfile)||Gm(e.videoCodecProfile,"config.videoCodecProfile",[66,77,100]),Xm(e.userCount)||Wm(e.userCount,"config.userCount",0,17),Xm(e.backgroundColor)||Wm(e.backgroundColor,"config.backgroundColor",0,16777215),Xm(e.userConfigExtraInfo)||Km(e.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1),e.transcodingUsers&&!Xm(e.transcodingUsers)&&(Ym(e.transcodingUsers,"config.transcodingUsers"),e.transcodingUsers.forEach((e,t)=>{Jm(e.uid),Xm(e.x)||Wm(e.x,"transcodingUser[".concat(t,"].x"),0,1e4),Xm(e.y)||Wm(e.y,"transcodingUser[".concat(t,"].y"),0,1e4),Xm(e.width)||Wm(e.width,"transcodingUser[".concat(t,"].width"),0,1e4),Xm(e.height)||Wm(e.height,"transcodingUser[".concat(t,"].height"),0,1e4),Xm(e.zOrder)||Wm(e.zOrder-1,"transcodingUser[".concat(t,"].zOrder"),0,100),Xm(e.alpha)||Wm(e.alpha,"transcodingUser[".concat(t,"].alpha"),0,1,!1)})),Xm(e.watermark)||Kf(e.watermark,"watermark"),Xm(e.backgroundImage)||Kf(e.backgroundImage,"backgroundImage"),e.images&&!Xm(e.images)&&(Ym(e.images,"config.images"),e.images.forEach((e,t)=>{Kf(e,"images[".concat(t,"]"))}))}(t);const i=[];t.images&&i.push(...t.images.map(e=>$v($v($v({},Hf),e),{},{zOrder:255}))),t.backgroundImage&&(i.push($v($v($v({},Hf),t.backgroundImage),{},{zOrder:0})),delete t.backgroundImage),t.watermark&&(i.push($v($v($v({},Hf),t.watermark),{},{zOrder:255})),delete t.watermark),t.images=i,t.transcodingUsers&&(t.userConfigs=t.transcodingUsers.map(e=>$v({},e)),t.userCount=t.transcodingUsers.length,delete t.transcodingUsers);const n=(t.userConfigs||[]).map(e=>"number"==typeof e.uid?Sl.resolve(e.uid):jv(e.uid,this.spec,this.cancelToken.token,this.httpRetryConfig));if((await Sl.all(n)).forEach((e,i)=>{t.userConfigs&&t.userConfigs[i]&&(t.userConfigs[i].uid=e)}),this.transcodingConfig=t,this.connection)try{var r;const e=await this.connection.request("request",{clientRequest:{command:"UpdateTranscoding",transcodingConfig:this.transcodingConfig}},!1,{command:"UpdateTranscoding",workerType:1,requestByUser:!0,tid:Array.from(HR(r=this.streamingTasks).call(r)).map(e=>e.taskId).join("#")});CE.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=>{CE.warning("[".concat(this.spec.clientId,"] live streaming receive error"),e.toString(),"try to republish",t.url),this.startLiveStreamingTask(t.url,t.mode,e).then(()=>{CE.debug("[".concat(this.spec.clientId,"] live streaming republish ").concat(t.url," success"))}).catch(e=>{CE.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 n;if(Array.from(HR(n=this.streamingTasks).call(n)).find(e=>e.mode===Bf.INJECT)&&t===Bf.INJECT)return new EE(_E.LIVE_STREAMING_TASK_CONFLICT,"inject stream over limit").throw();if(!this.transcodingConfig&&t===Bf.TRANSCODE)throw new EE(_E.INVALID_OPERATION,"[LiveStreaming] no transcoding config found, can not start transcoding streaming task");let r={command:"PublishStream",ts:Date.now(),url:e,uid:this.spec.uid.toString(),autoDestroyTime:100,acceptImageTimeout:!0};CE.debug("[".concat(this.spec.clientId,"] start live streaming ").concat(e,", mode: ").concat(t));const o=await this.taskMutex.lock();if(!this.connection&&i)return void o();if(this.streamingTasks.get(e)&&!i)return o(),new EE(_E.LIVE_STREAMING_TASK_CONFLICT).throw();try{this.connection||(this.connection=await this.connect(t))}catch(e){throw o(),e}switch(t){case Bf.TRANSCODE:r.transcodingConfig=$v({},this.transcodingConfig);break;case Bf.RAW:break;case Bf.INJECT:r={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&&(r.vid=this.uapResponse.vid),this.isStartingStreamingTask=!0;const s=this.lastTaskId++;try{const n=new Sl((t,n)=>{OI(this.retryTimeout).then(()=>{if(i)return n(i);const t=this.statusError.get(e);return t?(this.statusError.delete(e),n(t)):void 0})}),a=await Sl.race([this.connection.request("request",{clientRequest:r},!0,{url:e,command:"PublishStream",workerType:t===Bf.TRANSCODE?1:2,requestByUser:!i,tid:s.toString()}),n]);this.isStartingStreamingTask=!1,CE.debug("[".concat(this.spec.clientId,"] live streaming started, code: ").concat(a.code)),this.streamingTasks.set(e,{clientRequest:r,mode:t,url:e,taskId:s}),o()}catch(n){if(o(),this.isStartingStreamingTask=!1,!n.data||!n.data.retry||i)throw n;return n.data.changeAddress?(this.connection.tryNextAddress(),await this.startLiveStreamingTask(e,t,n)):await this.startLiveStreamingTask(e,t,n)}}stopLiveStreamingTask(e){return new Sl((t,i)=>{const n=this.streamingTasks.get(e);if(!n||!this.connection)return new EE(_E.UNEXPECTED_ERROR,"can not find streaming task to stop").throw();const r=n.mode;n.abortTask=()=>{CE.debug("[".concat(this.spec.clientId,"] stop live streaming success(worker exception)")),this.streamingTasks.delete(e),t()},this.connection.request("request",{clientRequest:{command:r===Bf.INJECT?"UninjectStream":"UnpublishStream",url:n.url}},!1,{url:e,command:"UnPublishStream",workerType:r===Bf.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then(i=>{CE.debug("[".concat(this.spec.clientId,"] stop live streaming success, code: ").concat(i.code)),this.streamingTasks.delete(e),0===this.streamingTasks.size&&r!==Bf.INJECT&&(this.connection&&this.connection.close(),this.connection=void 0),t(),r===Bf.INJECT&&this.onInjectStatusChange&&this.onInjectStatusChange(Gf.INJECT_STREAM_STATUS_STOP_SUCCESS,this.spec.uid,e)}).catch(i)})}async controlInjectStream(e,t,i,n){const r=this.streamingTasks.get(e);if(!r||!this.connection||r.mode!==Bf.INJECT)throw new EE(_E.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:n}})).serverResponse}resetAllTask(){var e;const t=Array.from(HR(e=this.streamingTasks).call(e));this.terminate();for(const e of 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=uE.CancelToken.source(),this.uapResponse=void 0,this.connection&&this.connection.close(),this.connection=void 0}async connect(e){if(this.connection)throw new EE(_E.UNEXPECTED_ERROR,"live streaming connection has already connected");const t=await kI(this,Xf.REQUEST_WORKER_MANAGER_LIST,e);return this.uapResponse=t,this.connection=new Qv(t.workerToken,this.spec,this.wsRetryConfig,e),this.connection.on(Jf.WARNING,(e,t)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e)),this.connection.on(Jf.PUBLISH_STREAM_STATUS,e=>this.handlePublishStreamServer(e)),this.connection.on(Jf.INJECT_STREAM_STATUS,e=>this.handleInjectStreamServerStatus(e)),this.connection.on(Jf.REQUEST_NEW_ADDRESS,(t,i)=>{if(!this.connection)return i(new EE(_E.UNEXPECTED_ERROR,"can not get new live streaming address list"));kI(this,Xf.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){const t=e.serverStatus&&e.serverStatus.url||"empty_url",i=this.streamingTasks.get(t),n=e.reason;switch(e.code){case zf.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case zf.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case zf.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case zf.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:{const n=new EE(_E.LIVE_STREAMING_CDN_ERROR,"",{code:e.code});if(i)return CE.error(n.toString()),this.onLiveStreamError&&this.onLiveStreamError(t,n);if(!this.isStartingStreamingTask)return;this.statusError.set(t,n)}case zf.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const e=new EE(_E.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,n);return this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e)}case zf.LIVE_STREAM_RESPONSE_WORKER_LOST:case zf.LIVE_STREAM_RESPONSE_WORKER_QUIT:{var r;if(!this.connection)return;this.connection.tryNextAddress();const t=Array.from(HR(r=this.streamingTasks).call(r));for(const i of t)i.abortTask?i.abortTask():(CE.warning("[".concat(this.spec.clientId,"] publish stream status code"),e.code,"try to republish",i.url),this.startLiveStreamingTask(i.url,i.mode,new EE(_E.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code})).then(()=>{CE.debug("[".concat(this.spec.clientId,"] republish live stream success"),i.url)}).catch(e=>{CE.error(e.toString()),this.onLiveStreamError&&this.onLiveStreamError(i.url,e)}));return}}}handleInjectStreamServerStatus(e){const t=Number(e.uid),i=e.serverStatus&&e.serverStatus.url;switch(e.code){case 200:return void(this.onInjectStatusChange&&this.onInjectStatusChange(Gf.INJECT_STREAM_STATUS_START_SUCCESS,t,i));case 451:return this.onInjectStatusChange&&this.onInjectStatusChange(Gf.INJECT_STREAM_STATUS_START_ALREADY_EXISTS,t,i),void this.streamingTasks.delete(i);case 453:return this.onInjectStatusChange&&this.onInjectStatusChange(Gf.INJECT_STREAM_STATUS_START_UNAUTHORIZED,t,i),void this.streamingTasks.delete(i);case 470:return this.onInjectStatusChange&&this.onInjectStatusChange(Gf.INJECT_STREAM_STATUS_BROKEN,t,i),void this.streamingTasks.delete(i);case 499:return this.onInjectStatusChange&&this.onInjectStatusChange(Gf.INJECT_STREAM_STATUS_START_TIMEOUT,t,i),void this.streamingTasks.delete(i);default:return void CE.debug("inject stream server status",e)}}hasUrl(e){return this.streamingTasks.has(e)}}class tC{constructor(){lp(this,"destChannelMediaInfos",new Map),lp(this,"srcChannelMediaInfo",void 0)}setSrcChannelInfo(e){pS(e),this.srcChannelMediaInfo=e}addDestChannelInfo(e){pS(e),this.destChannelMediaInfos.set(e.channelName,e)}removeDestChannelInfo(e){qm(e),this.destChannelMediaInfos.delete(e)}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo}getDestChannelMediaInfo(){return this.destChannelMediaInfos}}function iC(e){if(!(e instanceof tC)){return new EE(_E.INVALID_PARAMS,"Config should be instance of [ChannelMediaRelayConfiguration]").throw()}const t=e.getSrcChannelMediaInfo(),i=e.getDestChannelMediaInfo();if(!t){return new EE(_E.INVALID_PARAMS,"srcChannelMediaInfo should not be empty").throw()}if(0===i.size){return new EE(_E.INVALID_PARAMS,"destChannelMediaInfo should not be empty").throw()}}class nC extends hE{constructor(e,t,i){super(),lp(this,"ws",void 0),lp(this,"requestId",1),lp(this,"heartBeatTimer",void 0),lp(this,"joinInfo",void 0),lp(this,"clientId",void 0),lp(this,"onOpen",()=>{this.emit("open"),this.startHeartBeatCheck()}),lp(this,"onClose",e=>{this.emit("close"),this.dispose()}),lp(this,"onMessage",e=>{const 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 tv("cross-channel-".concat(this.clientId),i),this.ws.on(jf.RECONNECTING,()=>{this.ws.reconnectMode="retry",this.emit("reconnecting")}),this.ws.on(jf.CONNECTED,this.onOpen),this.ws.on(jf.ON_MESSAGE,this.onMessage),this.ws.on(jf.CLOSED,this.onClose)}isConnect(){return"connected"===this.ws.state}sendMessage(e){const t=this.requestId++;return e.requestId=t,e.seq=t,this.ws.sendMessage(e),t}waitStatus(e){return new Sl((t,i)=>{const n=window.setTimeout(()=>{i(new EE(_E.TIMEOUT,"wait status timeout, status: ".concat(e)))},5e3);this.once(e,r=>{window.clearTimeout(n),r.state&&0!==r.state?i(new EE(_E.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(e))):t(void 0)}),this.once("dispose",()=>{window.clearTimeout(n),i(new EE(_E.WS_ABORT))})})}async request(e){if("closed"===this.ws.state)throw new EE(_E.WS_DISCONNECT);const t=()=>new Sl((e,t)=>{this.ws.once(jf.CLOSED,()=>t(new EE(_E.WS_ABORT))),this.ws.once(jf.CONNECTED,e)});"connected"!==this.ws.state&&await t();const i=this.sendMessage(e),n=new Sl((e,t)=>{const n=()=>{t(new EE(_E.WS_ABORT))};this.ws.once(jf.RECONNECTING,n),this.ws.once(jf.CLOSED,n),this.once("req_".concat(i),e),OI(3e3).then(()=>{this.removeAllListeners("req_".concat(i)),this.ws.off(jf.RECONNECTING,n),this.ws.off(jf.CLOSED,n),t(new EE(_E.TIMEOUT,"cross channel ws request timeout"))})}),r=await n;if(!r||200!==r.code)throw new EE(_E.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(JSON.stringify(r)));return r}async connect(e){this.ws.removeAllListeners(jf.REQUEST_NEW_URLS),this.ws.on(jf.REQUEST_NEW_URLS,t=>{t(e)}),await this.ws.init(e)}dispose(){this.clearHeartBeatCheck(),this.emit("dispose"),this.removeAllListeners(),this.ws.close()}sendPing(e){const 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 rC extends hE{set state(e){e!==this._state&&(e!==eS.RELAY_STATE_FAILURE&&(this.errorCode=tS.RELAY_OK),this.emit("state",e,this.errorCode),this._state=e)}get state(){return this._state}constructor(e,t,i,n){super(),lp(this,"joinInfo",void 0),lp(this,"sid",void 0),lp(this,"clientId",void 0),lp(this,"cancelToken",uE.CancelToken.source()),lp(this,"workerToken",void 0),lp(this,"requestId",0),lp(this,"signal",void 0),lp(this,"prevChannelMediaConfig",void 0),lp(this,"httpRetryConfig",void 0),lp(this,"_state",eS.RELAY_STATE_IDLE),lp(this,"errorCode",tS.RELAY_OK),lp(this,"onStatus",e=>{CE.debug("[".concat(this.clientId,"] ChannelMediaStatus: ").concat(JSON.stringify(e))),e&&e.command&&("onAudioPacketReceived"===e.command&&this.emit("event",$f.PACKET_RECEIVED_AUDIO_FROM_SRC),"onVideoPacketReceived"===e.command&&this.emit("event",$f.PACKET_RECEIVED_VIDEO_FROM_SRC),"onSrcTokenPrivilegeDidExpire"===e.command&&(this.errorCode=tS.SRC_TOKEN_EXPIRED,this.state=eS.RELAY_STATE_FAILURE),"onDestTokenPrivilegeDidExpire"===e.command&&(this.errorCode=tS.DEST_TOKEN_EXPIRED,this.state=eS.RELAY_STATE_FAILURE))}),lp(this,"onReconnect",async()=>{CE.debug("[".concat(this.clientId,"] ChannelMediaSocket disconnect, reconnecting")),this.emit("event",$f.NETWORK_DISCONNECTED),this.state=eS.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch(e=>{this.state!==eS.RELAY_STATE_IDLE&&(CE.error("auto restart channel media relay failed",e.toString()),this.errorCode=tS.SERVER_CONNECTION_LOST,this.state=eS.RELAY_STATE_FAILURE)})}),this.joinInfo=e,this.clientId=t,this.sid=NI(),this.signal=new nC(this.joinInfo,this.clientId,i),this.httpRetryConfig=n}async startChannelMediaRelay(e){if(this.state!==eS.RELAY_STATE_IDLE)throw new EE(_E.INVALID_OPERATION);this.state=eS.RELAY_STATE_CONNECTING,await this.connect(),CE.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 EE(_E.CROSS_CHANNEL_FAILED_JOIN_SRC);if(e.data&&e.data.serverResponse&&"SetDestChannelStatus"===e.serverResponse.command)throw new EE(_E.CROSS_CHANNEL_FAILED_JOIN_DEST);if(e.data&&e.data.serverResponse&&"StartPacketTransfer"===e.serverResponse.command)throw new EE(_E.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST);throw e}this.prevChannelMediaConfig=e}async updateChannelMediaRelay(e){if(this.state!==eS.RELAY_STATE_RUNNING)throw new EE(_E.INVALID_OPERATION);await this.sendUpdateMessage(e),this.prevChannelMediaConfig=e}async stopChannelMediaRelay(){await this.sendStopRelayMessage(),CE.debug("[".concat(this.clientId,"] stopChannelMediaRelay: send stop message success")),this.state=eS.RELAY_STATE_IDLE,this.dispose()}dispose(){CE.debug("[".concat(this.clientId,"] disposeChannelMediaRelay")),this.cancelToken.cancel(),this.cancelToken=uE.CancelToken.source(),this.state=eS.RELAY_STATE_IDLE,this.emit("dispose"),this.signal.dispose(),this.prevChannelMediaConfig=void 0}async connect(){const e=await Hv(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=e.workerToken,await this.signal.connect(e.addressList),this.emit("event",$f.NETWORK_CONNECTED),this.signal.on("status",this.onStatus),this.signal.on("reconnecting",this.onReconnect)}async sendStartRelayMessage(e){const t=this.genMessage(Zf.StopPacketTransfer);await this.signal.request(t),await this.signal.waitStatus("Normal Quit"),CE.debug("[".concat(this.clientId,"] startChannelMediaRelay: StopPacketTransfer success"));const i=this.genMessage(Zf.SetSdkProfile,e);await this.signal.request(i),CE.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));const n=this.genMessage(Zf.SetSourceChannel,e);await this.signal.request(n),await this.signal.waitStatus("SetSourceChannelStatus"),this.emit("event",$f.PACKET_JOINED_SRC_CHANNEL),CE.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));const r=this.genMessage(Zf.SetSourceUserId,e);await this.signal.request(r),CE.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));const o=this.genMessage(Zf.SetDestChannel,e);await this.signal.request(o),await this.signal.waitStatus("SetDestChannelStatus"),this.emit("event",$f.PACKET_JOINED_DEST_CHANNEL),CE.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetDestChannel success"));const s=this.genMessage(Zf.StartPacketTransfer,e);await this.signal.request(s),this.emit("event",$f.PACKET_SENT_TO_DEST_CHANNEL),this.state=eS.RELAY_STATE_RUNNING,CE.debug("[".concat(this.clientId,"] startChannelMediaRelay: StartPacketTransfer success"))}async sendUpdateMessage(e){const t=this.genMessage(Zf.UpdateDestChannel,e);await this.signal.request(t),this.emit("event",$f.PACKET_UPDATE_DEST_CHANNEL),CE.debug("[".concat(this.clientId,"] sendUpdateMessage: UpdateDestChannel success"))}async sendStopRelayMessage(){const e=this.genMessage(Zf.StopPacketTransfer);await this.signal.request(e),CE.debug("[".concat(this.clientId,"] sendStopRelayMessage: StopPacketTransfer success"))}genMessage(e,t){const i=[],n=[],r=[];this.requestId+=1;const o={appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sdkVersion:AE,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};"4.17.0"===o.sdkVersion&&(o.sdkVersion="0.0.1");let s=null,a=null;switch(e){case Zf.SetSdkProfile:return o.clientRequest={command:"SetSdkProfile",type:"multi_channel"},o;case Zf.SetSourceChannel:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new EE(_E.UNEXPECTED_ERROR,"can not find source config");return o.clientRequest={command:"SetSourceChannel",uid:"0",channelName:a.channelName,token:a.token||this.joinInfo.appId},o;case Zf.SetSourceUserId:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new EE(_E.UNEXPECTED_ERROR,"can not find source config");return o.clientRequest={command:"SetSourceUserId",uid:a.uid+""},o;case Zf.SetDestChannel:if(s=t&&t.getDestChannelMediaInfo(),!s)throw new EE(_E.UNEXPECTED_ERROR,"can not find dest config");return s.forEach(e=>{i.push(e.channelName),n.push(e.uid+""),r.push(e.token||this.joinInfo.appId)}),o.clientRequest={command:"SetDestChannel",channelName:i,uid:n,token:r},o;case Zf.StartPacketTransfer:return o.clientRequest={command:"StartPacketTransfer"},o;case Zf.Reconnect:return o.clientRequest={command:"Reconnect"},o;case Zf.StopPacketTransfer:return o.clientRequest={command:"StopPacketTransfer"},o;case Zf.UpdateDestChannel:if(s=t&&t.getDestChannelMediaInfo(),!s)throw new EE(_E.UNEXPECTED_ERROR,"can not find dest config");return s.forEach(e=>{i.push(e.channelName),n.push(e.uid+""),r.push(e.token||this.joinInfo.appId)}),o.clientRequest={command:"UpdateDestChannel",channelName:i,uid:n,token:r},o}return o}}const oC=e=>{const t=document.createElement("canvas");return t.width=2,t.height=2,new Sl((i,n)=>{t.toBlob(async e=>{if(t.remove(),e){const n=await sC(e);i({buffer:n,width:t.width,height:t.height})}else n(new EE(_E.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))},e,1)})},sC=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t)};function aC(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function cC(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?aC(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):aC(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class dC{get videoElementStatus(){return this._videoElementStatus}set videoElementStatus(e){e!==this._videoElementStatus&&(CE.debug("[".concat(this.trackId,"] video-element-status change ").concat(this._videoElementStatus," => ").concat(e)),this._videoElementStatus=e)}constructor(e){lp(this,"trackId",void 0),lp(this,"config",void 0),lp(this,"onFirstVideoFrameDecoded",void 0),lp(this,"freezeTimeCounterList",[]),lp(this,"renderFreezeAccTime",0),lp(this,"timeUpdatedCount",0),lp(this,"freezeTime",0),lp(this,"playbackTime",0),lp(this,"lastTimeUpdatedTime",0),lp(this,"autoplayFailed",!1),lp(this,"videoTrack",void 0),lp(this,"container",void 0),lp(this,"videoElement",void 0),lp(this,"cacheVideoElement",void 0),lp(this,"videoElementCheckInterval",void 0),lp(this,"_videoElementStatus",tf.NONE),lp(this,"slot",void 0),lp(this,"isGettingVideoDimensions",!1),lp(this,"handleVideoEvents",e=>{switch(e.type){case"play":case"playing":this.startGetVideoDimensions(),this.videoElementStatus=tf.PLAYING;break;case"loadeddata":if(this.onFirstVideoFrameDecoded&&this.onFirstVideoFrameDecoded(),this.cacheVideoElement){try{this.container&&this.container.removeChild(this.cacheVideoElement)}catch(e){}this.cacheVideoElement=void 0}break;case"canplay":this.videoElementStatus=tf.CANPLAY;break;case"stalled":this.videoElementStatus=tf.STALLED;break;case"suspend":this.videoElementStatus=tf.SUSPEND;break;case"pause":this.videoElementStatus=tf.PAUSED,Kh()||Zh()||Wh()&&this.autoplayFailed||!this.videoElement||!this.videoTrack||"live"!==this.videoTrack.readyState||(CE.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=tf.WAITING;break;case"abort":this.videoElementStatus=tf.ABORT;break;case"ended":this.videoElementStatus=tf.ENDED;break;case"emptied":this.videoElementStatus=tf.EMPTIED;break;case"error":{var t;this.videoElementStatus=tf.ERROR;const e=null===(t=this.videoElement)||void 0===t?void 0:t.error;e&&CE.error("[".concat(this.trackId,"] media error, code: ").concat(e.code,", message: ").concat(e.message));break}case"timeupdate":{const e=performance.now();if(this.timeUpdatedCount+=1,this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);const t=e-this.lastTimeUpdatedTime,i=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,lI.lastVisibleTime<lI.lastHiddenTime||i<lI.lastHiddenTime||i<lI.lastVisibleTime)return;for(t>FE("VIDEO_FREEZE_DURATION")&&(this.freezeTime+=t),this.playbackTime+=t;this.playbackTime>=6e3;){this.playbackTime-=6e3;const e=Math.min(6e3,this.freezeTime);this.freezeTimeCounterList.push(e),this.freezeTime=Math.max(0,this.freezeTime-6e3)}break}}}),lp(this,"startGetVideoDimensions",()=>{const e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement&&this.videoElement.videoWidth*this.videoElement.videoHeight>4)return CE.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(e,500)};!this.isGettingVideoDimensions&&e()}),lp(this,"autoResumeAfterInterruption",()=>{this.videoElement&&this.videoTrack&&"live"===this.videoTrack.readyState&&"running"===wg.curState&&(Qh()?(CE.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()):zh()?(CE.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()):Xh()&&(CE.debug("[track-".concat(this.trackId,"] video element paused, auto resume for iOS 15.0")),this.videoElement.pause(),this.videoElement.play()))}),lp(this,"autoResumeAfterInterruptionOnIOS15",()=>{this.videoElement&&this.videoTrack&&"live"===this.videoTrack.readyState&&(Qh()?(CE.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()):zh()?(CE.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()):Xh()&&(CE.debug("[track-".concat(this.trackId,"] video element paused, auto resume for iOS 15.0")),this.videoElement.pause(),this.videoElement.play()))}),this.slot=e.element,this.trackId=e.trackId,this.updateConfig(e),wg.on(Rg.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),wg.on(Rg.IOS_15_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15)}updateConfig(e){this.config=e,this.trackId=e.trackId;const 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){if(this.videoElement){const t=this.videoElement.play();t&&t.catch&&t.catch(t=>{e&&Tg.autoplayFailed(e,"video",t.message,this.trackId),"NotAllowedError"===t.name?(CE.warning("detected video element autoplay failed",t),this.autoplayFailed=!0,this.handleAutoPlayFailed()):CE.warning("[".concat(this.trackId,"] play warning: "),t)});const i=Mh();if(("Safari"===i.name&&15===Number(i.version)||Jh())&&t&&t.then&&t.catch){const e=()=>{this.config.mirror&&this.videoElement&&(this.videoElement.style.transform="rotateY(180deg)")};t.then(e).catch(e)}}}getCurrentFrame(){if(!this.videoElement)return new ImageData(2,2);const e=document.createElement("canvas");e.width=this.videoElement.videoWidth,e.height=this.videoElement.videoHeight;const t=e.getContext("2d");if(!t)return CE.error("create canvas context failed!"),new ImageData(2,2);t.drawImage(this.videoElement,0,0,e.width,e.height);const 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;if(!this.videoElement)return await oC(e);const i=document.createElement("canvas");i.width=this.videoElement.videoWidth,i.height=this.videoElement.videoHeight;const n=i.getContext("2d");return n?(n.drawImage(this.videoElement,0,0,i.width,i.height),new Sl((n,r)=>{i.toBlob(async e=>{if(i.remove(),e){const t=await sC(e);n({buffer:t,width:i.width,height:i.height})}else r(new EE(_E.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))},e,t<0?.1:t>1?1:t)})):await oC(e)}destroy(){if(wg.off(Rg.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),wg.off(Rg.IOS_15_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15),this.videoElement&&(this.videoElement.srcObject=null,this.videoElement.remove(),this.videoElement=void 0),this.container){try{this.container.remove(),this.slot.removeChild(this.container)}catch(e){}this.container=void 0}this.freezeTimeCounterList=[]}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",FE("KEEP_LAST_FRAME")&&this.resetVideoElement(),this.createVideoElement(),this.container.appendChild(this.videoElement)):this.removeVideoElement(),this.slot.appendChild(this.container)}createVideoElement(){if(!this.videoElement&&(this.videoElementStatus=tf.INIT,this.videoElement=document.createElement("video"),this.container&&this.container.appendChild(this.videoElement),uC.forEach(e=>{this.videoElement&&this.videoElement.addEventListener(e,this.handleVideoEvents)}),this.videoElementCheckInterval=window.setInterval(()=>{!document.getElementById("video_".concat(this.trackId))&&this.videoElement&&(this.videoElementStatus=tf.DESTROYED)},1e3),FE("ENABLE_VIDEO_FRAME_CALLBACK"))){var e,t;let i;const n=(e,t)=>{if(this.videoElementStatus===tf.PLAYING){if(i){const e=t.presentationTime-i.presentationTime;e>FE("VIDEO_FREEZE_DURATION")&&lI.lastVisibleTime>=lI.lastHiddenTime&&i.timestamp>lI.lastVisibleTime&&i.timestamp>lI.lastHiddenTime&&(this.renderFreezeAccTime+=e)}i=cC(cC({},t),{},{timestamp:e})}var r,o;FE("ENABLE_VIDEO_FRAME_CALLBACK")&&(null===(r=this.videoElement)||void 0===r||null===(o=r.requestVideoFrameCallback)||void 0===o||o.call(r,n))};null===(e=(t=this.videoElement).requestVideoFrameCallback)||void 0===e||e.call(t,n)}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.controls=!1,this.videoElement.setAttribute("playsinline",""),this.videoElement.style.left="0",this.videoElement.style.top="0",ip()&&(this.videoElement.poster="noposter");const i=Mh();if("Safari"===i.name&&15===Number(i.version)||Jh()||!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,Hh()&&this.videoElement.load())}else this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,Hh()&&this.videoElement.load();const n=this.videoElement.play();void 0!==n&&n.catch(e=>{CE.debug("[".concat(this.trackId,"] playback interrupted"),e.toString())})}removeVideoElement(){if(this.videoElement){uC.forEach(e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents)}),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0);try{this.container&&this.container.removeChild(this.videoElement)}catch(e){}this.videoElement=void 0,this.videoElementStatus=tf.NONE}}resetVideoElement(){this.videoElement&&(uC.forEach(e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents)}),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.cacheVideoElement=this.videoElement,this.videoElement=void 0,this.videoElementStatus=tf.NONE)}handleAutoPlayFailed(){if(this.videoElement){const e=t=>{t.preventDefault(),this.videoElement&&(this.videoElement.play().then(()=>{CE.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))}).catch(e=>{CE.error(e)}),this.autoplayFailed=!1,np()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0)))};np()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),hg()}}getVideoElement(){return this.videoElement}getContainerElement(){return this.container}}const uC=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];function lC(e){const t={};e.facingMode&&(t.facingMode=e.facingMode),e.cameraId&&(t.deviceId={exact:e.cameraId});const i=LE(e.encoderConfig);return t.width=i.width,t.height=i.height,!ep()&&i.frameRate&&(t.frameRate=i.frameRate),Mh().name===Nh.EDGE&&"object"==typeof t.frameRate&&(t.frameRate.max=60),Hh()&&(t.frameRate={ideal:30,max:30}),t}function hC(e){const t={};e.screenSourceType&&(t.mediaSource=e.screenSourceType),e.extensionId&&Gh()&&(t.extensionId=e.extensionId),e.electronScreenSourceId&&(t.sourceId=e.electronScreenSourceId);const i=e.encoderConfig?kE(e.encoderConfig):null;return t.mandatory={chromeMediaSource:"desktop",maxWidth:i?i.width:void 0,maxHeight:i?i.height:void 0},i&&i.frameRate&&("number"==typeof i.frameRate?(t.mandatory.maxFrameRate=i.frameRate,t.mandatory.minFrameRate=i.frameRate):(t.mandatory.maxFrameRate=i.frameRate.max||i.frameRate.ideal||i.frameRate.exact||void 0,t.mandatory.minFrameRate=i.frameRate.min||i.frameRate.ideal||i.frameRate.exact||void 0),t.frameRate=i.frameRate),i&&i.width&&(t.width=i.width),i&&i.height&&(t.height=i.height),t}function pC(e){const t={};if(ep()||(void 0!==e.AGC&&(t.autoGainControl=e.AGC),void 0!==e.AEC&&(t.echoCancellation=e.AEC),void 0!==e.ANS&&(t.noiseSuppression=e.ANS,Gh()&&e.ANS&&(t.googHighpassFilter=e.ANS))),e.encoderConfig){const i=xE(e.encoderConfig);t.channelCount=i.stereo?2:1,t.sampleRate=i.sampleRate,t.sampleSize=i.sampleSize}return e.microphoneId&&(t.deviceId={exact:e.microphoneId}),ip()&&(t.sampleRate=void 0),t}var _C,EC;!function(e){e.COVERED="COVERED",e.POSITION="POSITION",e.SIZE="SIZE",e.STYLE="STYLE"}(_C||(_C={})),function(e){e.UNMOUNTED="UNMOUNTED",e.INVALID_HTML_ELEMENT="INVALID_HTML_ELEMENT"}(EC||(EC={}));var mC,fC,SC,TC,gC,RC,IC,vC,CC,yC,AC,OC,bC,wC,NC,DC,PC,LC,kC,MC,UC,xC,VC,FC,jC,BC,GC,WC,HC,KC,YC,qC,JC=new class{constructor(){lp(this,"_clientSize",null),lp(this,"getClientWidth",()=>document.documentElement?document.documentElement.clientWidth:document.body.clientWidth),lp(this,"getClientHeight",()=>document.documentElement?document.documentElement.clientHeight:document.body.clientHeight),lp(this,"getStyle",e=>window.getComputedStyle(e,null)),lp(this,"checkCssVisibleProperty",e=>{let t=!0;const i=this.getStyle(e),{display:n,visibility:r,opacity:o,filter:s}=i;if(("none"===n||["hidden","collapse"].includes(r)||Number(o)<.1)&&(t=!1),!t)return!1;if(s){s.split(" ").filter(e=>{const t=e.split("(")[0];return["brightness","blur","opacity"].includes(t)}).map(e=>{const[t,i]=e.split(/\(|\)/);return[t,Number(i.match(/^[0-9\.]+/))]}).forEach(e=>{const[i,n]=e;switch(i){case"brightness":(n<.1||n>3)&&(t=!1);break;case"blur":n>3&&(t=!1);break;case"opacity":n<.1&&(t=!1)}})}return t}),lp(this,"checkPropertyUpToAllParentNodes",(e,t)=>{let i=!0,n=!0;const r=e=>t(e);let o=e;for(;o&&n;){r(o)||(i=!1,n=!1),o=o.parentElement,o||(n=!1)}return i}),lp(this,"checkActualCssVisibleIncludeInherit",e=>this.checkPropertyUpToAllParentNodes(e,this.checkCssVisibleProperty)),lp(this,"getSizeAboutClient",e=>{const{width:t,height:i,left:n,right:r,top:o,bottom:s}=e.getBoundingClientRect(),a=this.getClientWidth(),c=this.getClientHeight();return{width:t,height:i,left:n,right:r,top:o,bottom:s,clientWidth:a,clientHeight:c,clientMin:Math.min(a,c)}}),lp(this,"checkActualSize",()=>{const{width:e,height:t,clientMin:i}=this._clientSize;return this.checkSizeIsVisible(e,t,i)}),lp(this,"elementFromPoint",(e,t)=>document.elementFromPoint?document.elementFromPoint(e,t):null),lp(this,"checkCoverForAPoint",(e,t,i)=>{const n=this.elementFromPoint(e,t);return null!==n&&n!==i}),lp(this,"getPointPositionList",()=>{const{width:e,height:t,left:i,top:n}=this._clientSize,r=e/6,o=t/6,s=[],a=10**6;for(let e=0;e<5;e++)for(let t=0;t<5;t++){const c=(i*a+(0===e?.1:4===e?(r*e*a-1e5)/a:r*e)*a)/a,d=(n*a+(0===t?.1:4===t?(o*t*a-1e5)/a:o*t)*a)/a;s.push({x:c,y:d})}return[...s]}),lp(this,"checkElementCover",e=>this.getPointPositionList().map(t=>this.checkCoverForAPoint(t.x,t.y,e)).filter(e=>!!e).length>6),lp(this,"checkSizeIsVisible",(e,t,i)=>(e>50||i/e<=10)&&(t>50||i/t<=10)),lp(this,"checkSizeOfPartInClient",()=>{const{left:e,right:t,top:i,bottom:n,clientHeight:r,clientWidth:o,clientMin:s}=this._clientSize;let a,c,d,u;if(e<0)a=0;else{if(!(e<o))return!1;a=e}if(t<0)return!1;if(c=t<o?t:o,i<0)d=0;else{if(!(i<r))return!1;d=i}if(n<0)return!1;u=n<r?n:r;const l=c-a,h=u-d;return this.checkSizeIsVisible(l,h,s)}),lp(this,"returnHiddenResult",e=>(this._clientSize=null,{visible:!1,reason:e})),lp(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(_C.COVERED);{const e=this.checkActualSize(),t=this.checkSizeOfPartInClient();return e&&!t?this.returnHiddenResult(_C.POSITION):e?(this._clientSize=null,{visible:!0}):this.returnHiddenResult(_C.SIZE)}}return this.returnHiddenResult(_C.STYLE)}return this.returnHiddenResult(EC.UNMOUNTED)}return this.returnHiddenResult(EC.INVALID_HTML_ELEMENT)}),lp(this,"checkElementIsMountedOnDom",e=>this.checkPropertyUpToAllParentNodes(e,e=>"HTML"!==e.nodeName.toUpperCase()?null!==e.parentElement:!!document.documentElement))}};function XC(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function zC(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?XC(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):XC(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let QC=(mC=Sg({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:"HTMLElement",i]}),fC=$g(),SC=Sg({argsMap:e=>[e.getTrackId()]}),TC=Cg("LocalVideoTrack","_enabledMutex"),gC=Sg({argsMap:(e,t)=>[e.getTrackId(),t]}),RC=$g(),IC=Cg("LocalVideoTrack","_enabledMutex"),vC=Sg({argsMap:(e,t)=>[e.getTrackId(),t]}),CC=$g(),yC=$g(),AC=Sg({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),OC=$g(),bC=$g(),wC=$g(),NC=$g(),DC=$g(),PC=$g(),LC=$g(),kC=Sg({argsMap:(e,t)=>[e.getTrackId(),t.name]}),MC=Sg({argsMap:e=>[e.getTrackId()]}),UC=Sg({argsMap:e=>[e.getTrackId()]}),xC=Sg({argsMap:(e,t,i)=>[e.getTrackId(),t.label,i]}),JT((VC=class e extends yg{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==tf.PLAYING)}get __className__(){return"LocalVideoTrack"}constructor(e,t,i,n,r,o){super(e,r),lp(this,"trackMediaType","video"),lp(this,"_player",void 0),lp(this,"_videoVisibleTimer",null),lp(this,"_previousVideoVisibleStatus",void 0),lp(this,"_clearPreviousVideoVisibleStatus",()=>this._previousVideoVisibleStatus=void 0),lp(this,"_encoderConfig",void 0),lp(this,"_scalabiltyMode",{numSpatialLayers:1,numTemporalLayers:1}),lp(this,"_optimizationMode",void 0),lp(this,"_videoHeight",void 0),lp(this,"_videoWidth",void 0),lp(this,"_forceBitrateLimit",void 0),lp(this,"_enabled",!0),lp(this,"processorDestination",void 0),lp(this,"processorContext",void 0),this.updateMediaStreamTrackResolution(),this._encoderConfig=t,this._scalabiltyMode=i,this._optimizationMode=n,this._hints=o||[],-1===this._hints.indexOf(aS.SCREEN_TRACK)&&this.updateBitrateFromProfile(),this.processorContext=new JR(this.getTrackId(),"local"),this.processorDestination=new qR(this.processorContext),this.bindProcessorDestinationEvents()}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e){const t=document.getElementById(e);t?e=t:(CE.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}CE.debug("[".concat(this.getTrackId(),"] start video playback"),JSON.stringify(t));const i=zC(zC(zC({},this._getDefaultPlayerConfig()),t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(this._player=new dC(i),this._player.updateVideoTrack(this._mediaStreamTrack)),this._player.play(),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval(()=>{try{const e=this.getVideoElementVisibleStatus();this.emit(uS.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}},FE("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,CE.debug("[".concat(this.getTrackId(),"] stop video playback")))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(CE.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){this._originMediaStreamTrack.enabled=!1;try{await MI(this,sS.NEED_DISABLE_TRACK,this)}catch(e){throw CE.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}return t||(this._enabled=!1),void CE.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}this._originMediaStreamTrack.enabled=!0;try{await MI(this,sS.NEED_ENABLE_TRACK,this)}catch(e){throw CE.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}CE.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,CE.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await MI(this,sS.NEED_MUTE_TRACK,this):await MI(this,sS.NEED_UNMUTE_TRACK,this))}getStats(){WI(()=>{CE.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")},"localVideoTrackGetStatsWarning");const e=UI(this,sS.GET_STATS);return e||zC({},Uf)}async setBeautyEffect(e){CE.error("LocalVideoTrack.setBeautyEffect was deprecated, please migrate to agora-extension-beauty-effect https://docs-beta.agora.io/en/video-calling/develop/image-enhancement?platform=web ")}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 oC(e)}clone(t,i,n,r){const o=this._mediaStreamTrack.clone();return new e(o,t,i,n,r)}async setBitrateLimit(e){if(CE.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 MI(this,sS.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw()}}}async setOptimizationMode(e){if("motion"!==e&&"detail"!==e&&"balanced"!==e)return void CE.error(_E.INVALID_PARAMS,"optimization mode must be motion, detail or balanced");const t=this._optimizationMode;try{this._optimizationMode=e,await MI(this,sS.SET_OPTIMIZATION_MODE,this)}catch(e){throw this._optimizationMode=t,CE.error("[".concat(this.getTrackId(),"] set optimization mode failed"),e.toString()),e}CE.info("[".concat(this.getTrackId(),"] set optimization mode success (").concat(e,")"))}setScalabiltyMode(e){if(1===e.numSpatialLayers&&1!==e.numTemporalLayers)return CE.error(_E.INVALID_PARAMS,"scalability mode currently not supported, no SVC."),void(this._scalabiltyMode={numSpatialLayers:1,numTemporalLayers:1});this._scalabiltyMode=e,CE.info("[".concat(this.getTrackId(),"] set scalability mode success (").concat(e,")"))}updateMediaStreamTrackResolution(){PI(this._originMediaStreamTrack).then(e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t}).catch(DI)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:"contain"}}updateBitrateFromProfile(){if(!this._encoderConfig)return;const{width:e,height:t,frameRate:i}=this.getMediaStreamTrackSettings();if(!e||!t||!i)return;const[n,r]=function(e,t,i){const n=FE("BITRATE_ADAPTER_TYPE");let r;const o=200*Math.pow(i/15,.6)*Math.pow(e*t/640/360,.75),s=o;if("STANDARD_BITRATE"===n)r=4*o;else{if("COMPATIABLE_BITRATE"!==n)return;r=2*o}return[Math.floor(r),Math.floor(s)]}(e,t,i)||[void 0,void 0];this._encoderConfig.bitrateMin||this._encoderConfig.bitrateMax||(this._encoderConfig.bitrateMin=r,this._encoderConfig.bitrateMax=n,CE.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(e,", h: ").concat(t,", fps: ").concat(i,"] => [brMax: ").concat(n,", brMin: ").concat(r,"]")))}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:r,slot:o}=n;if(this.isPlaying&&r instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=JC.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=Tg.reportApiInvoke(null,{tag:lf.TRACER,name:uf.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 EE(_E.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}async renewMediaStreamTrack(e){}pipe(e){if(this.processor===e)return e;if(e._source)throw new EE(_E.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;const 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 EE(_E.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if("video"!==e.kind)throw new EE(_E.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(e,t,!0),this.updateMediaStreamTrackResolution()}bindProcessorDestinationEvents(){this.processorDestination.on(AS.ON_TRACK,async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),await MI(this,sS.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await MI(this,sS.NEED_REPLACE_TRACK,this))})}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(AS.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(OS.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(OS.REQUEST_CONSTRAINTS)}}).prototype,"play",[mC,fC],Object.getOwnPropertyDescriptor(VC.prototype,"play"),VC.prototype),JT(VC.prototype,"stop",[SC],Object.getOwnPropertyDescriptor(VC.prototype,"stop"),VC.prototype),JT(VC.prototype,"setEnabled",[TC,gC,RC],Object.getOwnPropertyDescriptor(VC.prototype,"setEnabled"),VC.prototype),JT(VC.prototype,"setMuted",[IC,vC,CC],Object.getOwnPropertyDescriptor(VC.prototype,"setMuted"),VC.prototype),JT(VC.prototype,"getStats",[yC],Object.getOwnPropertyDescriptor(VC.prototype,"getStats"),VC.prototype),JT(VC.prototype,"setBeautyEffect",[AC,OC],Object.getOwnPropertyDescriptor(VC.prototype,"setBeautyEffect"),VC.prototype),JT(VC.prototype,"getCurrentFrameData",[bC],Object.getOwnPropertyDescriptor(VC.prototype,"getCurrentFrameData"),VC.prototype),JT(VC.prototype,"getCurrentFrameImage",[wC],Object.getOwnPropertyDescriptor(VC.prototype,"getCurrentFrameImage"),VC.prototype),JT(VC.prototype,"setBitrateLimit",[NC],Object.getOwnPropertyDescriptor(VC.prototype,"setBitrateLimit"),VC.prototype),JT(VC.prototype,"setOptimizationMode",[DC],Object.getOwnPropertyDescriptor(VC.prototype,"setOptimizationMode"),VC.prototype),JT(VC.prototype,"setScalabiltyMode",[PC],Object.getOwnPropertyDescriptor(VC.prototype,"setScalabiltyMode"),VC.prototype),JT(VC.prototype,"updateMediaStreamTrackResolution",[LC],Object.getOwnPropertyDescriptor(VC.prototype,"updateMediaStreamTrackResolution"),VC.prototype),JT(VC.prototype,"pipe",[kC],Object.getOwnPropertyDescriptor(VC.prototype,"pipe"),VC.prototype),JT(VC.prototype,"unpipe",[MC],Object.getOwnPropertyDescriptor(VC.prototype,"unpipe"),VC.prototype),JT(VC.prototype,"close",[UC],Object.getOwnPropertyDescriptor(VC.prototype,"close"),VC.prototype),JT(VC.prototype,"replaceTrack",[xC],Object.getOwnPropertyDescriptor(VC.prototype,"replaceTrack"),VC.prototype),VC),ZC=(FC=Sg({argsMap:(e,t)=>[e.getTrackId(),t]}),jC=$g(),BC=Cg("CameraVideoTrack","_enabledMutex"),GC=Sg({argsMap:(e,t)=>[e.getTrackId(),t]}),WC=$g(),HC=Sg({argsMap:(e,t)=>[e.getTrackId(),t]}),KC=$g(),YC=Sg({argsMap:e=>[e.getTrackId()]}),JT((qC=class extends QC{get __className__(){return"CameraVideoTrack"}constructor(e,t,i,n,r,o){super(e,LE(t.encoderConfig),n,r,o),lp(this,"_config",void 0),lp(this,"_originalConstraints",void 0),lp(this,"_constraints",void 0),lp(this,"_enabled",!0),lp(this,"_deviceName","default"),lp(this,"tryResumeVideoForIOS15WeChat",async()=>{Jh()&&!Qh()&&$h()&&this._enabled&&!this._isClosed&&(CE.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=LE(this._config.encoderConfig),wg.on(Rg.IOS_15_INTERRUPTION_END,this.tryResumeVideoForIOS15WeChat),wg.on(Rg.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15WeChat),this.bindProcessorContextEvents()}async setDevice(e){if(CE.info("[".concat(this.getTrackId(),"] set device to ").concat(e)),this._enabled)try{const t=await zg.getDeviceById(e),i={};i.video=zC({},this._constraints),i.video.deviceId={exact:e},i.video.facingMode=void 0,this._originMediaStreamTrack.stop();let n=null;try{n=await Yg(i,this.getTrackId())}catch(e){throw CE.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),n=await Yg({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(n.getVideoTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(n.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution(),this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw CE.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await zg.getDeviceById(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw CE.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}CE.info("[".concat(this.getTrackId(),"] setDevice success"))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(CE.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{const e=await Yg({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1)}await MI(this,sS.NEED_ENABLE_TRACK,this)}catch(e){throw CE.error("[".concat(this.getTrackId(),"] setEnabled true error"),e.toString()),e}this.updateMediaStreamTrackResolution(),CE.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 MI(this,sS.NEED_DISABLE_TRACK,this)}catch(e){throw CE.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}CE.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new EE(_E.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");e=LE(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);const i=BI(this._config);i.encoderConfig=e;const n=lC(i);(Wh()||Kh()||Zh())&&(n.deviceId=void 0),CE.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(n));try{await this._originMediaStreamTrack.applyConstraints(n),this.updateMediaStreamTrackResolution()}catch(e){const t=new EE(_E.UNEXPECTED_ERROR,e.toString());throw CE.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}this._config=i,this._constraints=n,this._originalConstraints=n,this._encoderConfig=e,-1===this._hints.indexOf(aS.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await MI(this,sS.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw()}}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((Kh()||Zh())&&this._enabled&&!this._isClosed&&wg.duringInterruption){const e=async()=>{wg.off(Rg.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(CE.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};wg.on(Rg.IOS_INTERRUPTION_END,e)}else CE.debug("[".concat(this.getTrackId(),"] track ended")),this.emit(uS.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=zg.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId={exact:i}),this._enabled){const e=await Yg({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),wg.off(Rg.IOS_15_INTERRUPTION_END,this.tryResumeVideoForIOS15WeChat),wg.off(Rg.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15WeChat)}bindProcessorContextEvents(){this.processorContext.on(OS.REQUEST_UPDATE_CONSTRAINTS,async(e,t,i)=>{try{const i=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(i),t()}catch(e){i(e)}}),this.processorContext.on(OS.REQUEST_CONSTRAINTS,async e=>{e(this._originMediaStreamTrack.getSettings())})}}).prototype,"setDevice",[FC,jC],Object.getOwnPropertyDescriptor(qC.prototype,"setDevice"),qC.prototype),JT(qC.prototype,"setEnabled",[BC,GC,WC],Object.getOwnPropertyDescriptor(qC.prototype,"setEnabled"),qC.prototype),JT(qC.prototype,"setEncoderConfiguration",[HC,KC],Object.getOwnPropertyDescriptor(qC.prototype,"setEncoderConfiguration"),qC.prototype),JT(qC.prototype,"close",[YC],Object.getOwnPropertyDescriptor(qC.prototype,"close"),qC.prototype),qC);class $C{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){lp(this,"uid",void 0),lp(this,"_uintid",void 0),lp(this,"_trust_in_room_",!0),lp(this,"_trust_audio_enabled_state_",!0),lp(this,"_trust_video_enabled_state_",!0),lp(this,"_trust_audio_mute_state_",!0),lp(this,"_trust_video_mute_state_",!0),lp(this,"_audio_muted_",!1),lp(this,"_video_muted_",!1),lp(this,"_audio_enabled_",!0),lp(this,"_video_enabled_",!0),lp(this,"_audio_added_",!1),lp(this,"_video_added_",!1),lp(this,"_trust_video_stream_added_state_",!0),lp(this,"_trust_audio_stream_added_state_",!0),lp(this,"_audioTrack",void 0),lp(this,"_videoTrack",void 0),lp(this,"_audioSSRC",void 0),lp(this,"_videoSSRC",void 0),lp(this,"_audioOrtc",void 0),lp(this,"_videoOrtc",void 0),lp(this,"_cname",void 0),lp(this,"_rtxSsrcId",void 0),this.uid=e,this._uintid=t}}var ey=fl,ty=pd,iy=Rd;Ii({target:"Promise",stat:!0},{try:function(e){var t=ty.f(this),i=iy(e);return(i.error?t.reject:t.resolve)(i.value),t.promise}});var ny=ey,ry=Ii,oy=h,sy=i,ay=VS,cy=q,dy=Fe,uy=wi,ly=ZE,hy=YS,py=OT,_y=ae,Ey=rt("isConcatSpreadable"),my=9007199254740991,fy="Maximum allowed index exceeded",Sy=oy.TypeError,Ty=_y>=51||!sy((function(){var e=[];return e[Ey]=!1,e.concat()[0]!==e})),gy=py("concat"),Ry=function(e){if(!cy(e))return!1;var t=e[Ey];return void 0!==t?!!t:ay(e)};ry({target:"Array",proto:!0,forced:!Ty||!gy},{concat:function(e){var t,i,n,r,o,s=dy(this),a=hy(s,0),c=0;for(t=-1,n=arguments.length;t<n;t++)if(Ry(o=-1===t?s:arguments[t])){if(c+(r=uy(o))>my)throw Sy(fy);for(i=0;i<r;i++,c++)i in o&&ly(a,c,o[i])}else{if(c>=my)throw Sy(fy);ly(a,c++,o)}return a.length=c,a}});var Iy={},vy=k,Cy=K,yy=Pn.f,Ay=rm,Oy="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];Iy.f=function(e){return Oy&&"Window"==vy(e)?function(e){try{return yy(e)}catch(e){return Ay(Oy)}}(e):yy(Cy(e))};var by={},wy=rt;by.f=wy;var Ny=J,Dy=Ge,Py=by,Ly=Ht.f,ky=function(e){var t=Ny.Symbol||(Ny.Symbol={});Dy(t,e)||Ly(t,e,{value:Py.f(e)})},My=Ii,Uy=h,xy=$,Vy=f,Fy=v,jy=d,By=g,Gy=ue,Wy=i,Hy=Ge,Ky=VS,Yy=S,qy=q,Jy=u,Xy=fe,zy=zt,Qy=Fe,Zy=K,$y=Et,eA=No,tA=N,iA=Pr,nA=hr,rA=Pn,oA=Iy,sA=Zn,aA=T,cA=Ht,dA=dr,uA=C,lA=pc,hA=xs,pA=Ne.exports,_A=Gn,EA=qe,mA=rt,fA=by,SA=ky,TA=ta,gA=ws,RA=eT.forEach,IA=pn("hidden"),vA="Symbol",CA=mA("toPrimitive"),yA=gA.set,AA=gA.getterFor(vA),OA=Object.prototype,bA=Uy.Symbol,wA=bA&&bA.prototype,NA=Uy.TypeError,DA=Uy.QObject,PA=xy("JSON","stringify"),LA=aA.f,kA=cA.f,MA=oA.f,UA=uA.f,xA=jy([].push),VA=pA("symbols"),FA=pA("op-symbols"),jA=pA("string-to-symbol-registry"),BA=pA("symbol-to-string-registry"),GA=pA("wks"),WA=!DA||!DA.prototype||!DA.prototype.findChild,HA=By&&Wy((function(){return 7!=iA(kA({},"a",{get:function(){return kA(this,"a",{value:7}).a}})).a}))?function(e,t,i){var n=LA(OA,t);n&&delete OA[t],kA(e,t,i),n&&e!==OA&&kA(OA,t,n)}:kA,KA=function(e,t){var i=VA[e]=iA(wA);return yA(i,{type:vA,tag:e,description:t}),By||(i.description=t),i},YA=function(e,t,i){e===OA&&YA(FA,t,i),zy(e);var n=$y(t);return zy(i),Hy(VA,n)?(i.enumerable?(Hy(e,IA)&&e[IA][n]&&(e[IA][n]=!1),i=iA(i,{enumerable:tA(0,!1)})):(Hy(e,IA)||kA(e,IA,tA(1,{})),e[IA][n]=!0),HA(e,n,i)):kA(e,n,i)},qA=function(e,t){zy(e);var i=Zy(t),n=nA(i).concat(QA(i));return RA(n,(function(t){By&&!Fy(JA,i,t)||YA(e,t,i[t])})),e},JA=function(e){var t=$y(e),i=Fy(UA,this,t);return!(this===OA&&Hy(VA,t)&&!Hy(FA,t))&&(!(i||!Hy(this,t)||!Hy(VA,t)||Hy(this,IA)&&this[IA][t])||i)},XA=function(e,t){var i=Zy(e),n=$y(t);if(i!==OA||!Hy(VA,n)||Hy(FA,n)){var r=LA(i,n);return!r||!Hy(VA,n)||Hy(i,IA)&&i[IA][n]||(r.enumerable=!0),r}},zA=function(e){var t=MA(Zy(e)),i=[];return RA(t,(function(e){Hy(VA,e)||Hy(_A,e)||xA(i,e)})),i},QA=function(e){var t=e===OA,i=MA(t?FA:Zy(e)),n=[];return RA(i,(function(e){!Hy(VA,e)||t&&!Hy(OA,e)||xA(n,VA[e])})),n};(Gy||(hA(wA=(bA=function(){if(Jy(wA,this))throw NA("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?eA(arguments[0]):void 0,t=EA(e),i=function(e){this===OA&&Fy(i,FA,e),Hy(this,IA)&&Hy(this[IA],t)&&(this[IA][t]=!1),HA(this,t,tA(1,e))};return By&&WA&&HA(OA,t,{configurable:!0,set:i}),KA(t,e)}).prototype,"toString",(function(){return AA(this).tag})),hA(bA,"withoutSetter",(function(e){return KA(EA(e),e)})),uA.f=JA,cA.f=YA,dA.f=qA,aA.f=XA,rA.f=oA.f=zA,sA.f=QA,fA.f=function(e){return KA(mA(e),e)},By&&kA(wA,"description",{configurable:!0,get:function(){return AA(this).description}})),My({global:!0,wrap:!0,forced:!Gy,sham:!Gy},{Symbol:bA}),RA(nA(GA),(function(e){SA(e)})),My({target:vA,stat:!0,forced:!Gy},{for:function(e){var t=eA(e);if(Hy(jA,t))return jA[t];var i=bA(t);return jA[t]=i,BA[i]=t,i},keyFor:function(e){if(!Xy(e))throw NA(e+" is not a symbol");if(Hy(BA,e))return BA[e]},useSetter:function(){WA=!0},useSimple:function(){WA=!1}}),My({target:"Object",stat:!0,forced:!Gy,sham:!By},{create:function(e,t){return void 0===t?iA(e):qA(iA(e),t)},defineProperty:YA,defineProperties:qA,getOwnPropertyDescriptor:XA}),My({target:"Object",stat:!0,forced:!Gy},{getOwnPropertyNames:zA,getOwnPropertySymbols:QA}),My({target:"Object",stat:!0,forced:Wy((function(){sA.f(1)}))},{getOwnPropertySymbols:function(e){return sA.f(Qy(e))}}),PA)&&My({target:"JSON",stat:!0,forced:!Gy||Wy((function(){var e=bA();return"[null]"!=PA([e])||"{}"!=PA({a:e})||"{}"!=PA(Object(e))}))},{stringify:function(e,t,i){var n=lA(arguments),r=t;if((qy(t)||void 0!==e)&&!Xy(e))return Ky(t)||(t=function(e,t){if(Yy(r)&&(t=Fy(r,this,e,t)),!Xy(t))return t}),n[1]=t,Vy(PA,null,n)}});if(!wA[CA]){var ZA=wA.valueOf;hA(wA,CA,(function(e){return Fy(ZA,this)}))}TA(bA,vA),_A[IA]=!0,ky("asyncIterator"),ky("hasInstance"),ky("isConcatSpreadable"),ky("iterator"),ky("match"),ky("matchAll"),ky("replace"),ky("search"),ky("species"),ky("split"),ky("toPrimitive"),ky("toStringTag"),ky("unscopables"),ta(h.JSON,"JSON",!0);var $A=J.Symbol;ky("asyncDispose"),ky("dispose"),ky("matcher"),ky("metadata"),ky("observable"),ky("patternMatch"),ky("replaceAll");var eO=$A,tO=by.f("asyncIterator"),iO=tO;function nO(e){this.wrapped=e}function rO(e){var t,i;function n(t,i){try{var o=e[t](i),s=o.value,a=s instanceof nO;ny.resolve(a?s.wrapped:s).then((function(e){a?n("return"===t?"return":"next",e):r(o.done?"return":"normal",e)}),(function(e){n("throw",e)}))}catch(e){r("throw",e)}}function r(e,r){switch(e){case"return":t.resolve({value:r,done:!0});break;case"throw":t.reject(r);break;default:t.resolve({value:r,done:!1})}(t=t.next)?n(t.key,t.arg):i=null}this._invoke=function(e,r){return new ny((function(o,s){var a={key:e,arg:r,resolve:o,reject:s,next:null};i?i=i.next=a:(t=i=a,n(e,r))}))},"function"!=typeof e.return&&(this.return=void 0)}function oO(e){return function(){return new rO(e.apply(this,arguments))}}function sO(e){return new nO(e)}rO.prototype["function"==typeof eO&&iO||"@@asyncIterator"]=function(){return this},rO.prototype.next=function(e){return this._invoke("next",e)},rO.prototype.throw=function(e){return this._invoke("throw",e)},rO.prototype.return=function(e){return this._invoke("return",e)};var aO=by.f("iterator");function cO(e,t){var i={},n=!1;function r(i,r){return n=!0,r=new ny((function(t){t(e[i](r))})),{done:!1,value:t(r)}}return i[void 0!==eO&&aO||"@@iterator"]=function(){return this},i.next=function(e){return n?(n=!1,e):r("next",e)},"function"==typeof e.throw&&(i.throw=function(e){if(n)throw n=!1,e;return r("throw",e)}),"function"==typeof e.return&&(i.return=function(e){return n?(n=!1,e):r("return",e)}),i}var dO=tO,uO={exports:{}};function lO(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function hO(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?lO(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):lO(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function pO(e,t,i,n,r,o,s){let a=[],c=[],d=[],u=[],l=!1,h=!1;if(uO.exports.parse(e).mediaDescriptions.forEach(e=>{s&&s!==e.attributes.direction||("video"!==e.media.mediaType||l||(c=e.attributes.payloads,u=e.attributes.extmaps,l=!0),"audio"!==e.media.mediaType||h||(a=e.attributes.payloads,d=e.attributes.extmaps,h=!0))}),!u||0===c.length)throw new Error("Cannot get video capabilities from SDP.");if(!d||0===a.length)throw new Error("Cannot get audio capabilities from SDP.");return c.forEach(e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate))}),a.forEach(e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&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?void 0:t.encodingName.toLowerCase())}),c=c.filter(e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?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?void 0:t.encodingName)||"")})),n&&(a=a.filter(e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")})),r&&(null==r?void 0:r.length)>0&&(a=a.filter(e=>{var t;return r.includes((null===(t=e.rtpMap)||void 0===t?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?void 0:t.encodingName.toLowerCase())||"")})),{audioCodecs:a,videoCodecs:c,audioExtensions:d,videoExtensions:u}}function _O(e){const t=uO.exports.parse(e);let i,n;for(const e of t.mediaDescriptions){if(!i){const t=e.attributes.iceUfrag,n=e.attributes.icePwd;if(!t||!n)throw new Error("Cannot get iceUfrag or icePwd from SDP.");i={iceUfrag:t,icePwd:n}}if(!n){const t=e.attributes.fingerprints;t.length>0&&(n={fingerprints:t})}}if(!n&&t.attributes.fingerprints.length>0&&(n={fingerprints:t.attributes.fingerprints}),!n||!i)throw new Error("Cannot get iceParameters or dtlsParameters from SDP.");return{iceParameters:i,dtlsParameters:n}}function EO(e,t){const i=[],n=e.attributes.ssrcGroups.filter(e=>"FID"===e.semantic),r=e.attributes.ssrcGroups.find(e=>"SIM"===e.semantic),o=e.attributes.ssrcs;if(r)r.ssrcIds.forEach(e=>{var r;const o=null===(r=n.find(t=>t.ssrcIds[0]===e))||void 0===r?void 0:r.ssrcIds[1];i.push({ssrcId:e,rtx:t?o:void 0})});else if(n.length>0){const e=n[0].ssrcIds[0],r=n[0].ssrcIds[1];i.push({ssrcId:e,rtx:t?r:void 0})}else{if(0===o.length)throw new Error("No ssrcs found on local media description.");i.push({ssrcId:o[0].ssrcId})}return i}function mO(e,t){const{cname:i}=e;let n;t&&t.ip&&"number"==typeof t.port?(n=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:t.ip,port:t.port.toString(),type:"host",extension:{}}],CE.debug("Using remote candidate from AP ".concat(t.ip,":").concat(t.port)),t.ip6&&(n.push({foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:t.ip6,port:t.port.toString(),type:"host",extension:{}}),CE.debug("Using IPV6 remote candidate from AP ".concat(t.ip6,":").concat(t.port)))):n=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:{}}));const r={fingerprints:e.dtlsParameters.fingerprints.map(e=>({hashFunction:e.algorithm,fingerprint:e.fingerprint}))},o={iceUfrag:e.iceParameters.iceUfrag,icePwd:e.iceParameters.icePwd};let s;switch(e.dtlsParameters.role){case"server":s="passive";break;case"client":s="active";break;case"auto":s="actpass"}return{dtlsParameters:r,iceParameters:o,candidates:n,rtpCapabilities:AO(e.rtpCapabilities),setup:s,cname:i}}function fO(e,t,i){const n=[],r=[];return e.forEach(e=>{let{ssrcId:o,rtx:s}=e;const a=wI(8,"track-"),c={ssrcId:o,attributes:hO({label:a,mslabel:i=i||wI(10,""),msid:"".concat(i," ").concat(a)},t&&{cname:t})};if(n.push(c),void 0!==s){const e={ssrcId:s,attributes:hO({label:a,mslabel:i,msid:"".concat(i," ").concat(a)},t&&{cname:t})};n.push(e),r.push({semantic:"FID",ssrcIds:[o,s]})}}),e.length>1&&r.push({semantic:"SIM",ssrcIds:e.map(e=>{let{ssrcId:t}=e;return t})}),{ssrcs:n,ssrcGroups:r}}function SO(e,t){t instanceof tI&&e.attributes.payloads.forEach(e=>{var i;const n=null===(i=e.rtpMap)||void 0===i?void 0:i.encodingName.toLowerCase();if(!n||-1===["opus","pcmu","pcma","g722"].indexOf(n))return;e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.minptime="10",e.fmtp.parameters.useinbandfec="1";const r=t._encoderConfig;r&&"pcmu"!==n&&"pcma"!==n&&"g722"!==n&&(r.bitrate&&!Hh()&&(e.fmtp.parameters.maxaveragebitrate="".concat(Math.floor(1e3*r.bitrate))),r.sampleRate&&(e.fmtp.parameters.maxplaybackrate="".concat(r.sampleRate),e.fmtp.parameters["sprop-maxcapturerate"]="".concat(r.sampleRate)),r.stereo&&(e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1"))})}function TO(e){const t=e.attributes.unrecognized.findIndex(e=>"x-google-flag"===e.attField&&"conference"===e.attValue);-1!==t&&e.attributes.unrecognized.splice(t,1)}function gO(e,t){if(!(t instanceof QC&&t._encoderConfig&&-1===t._hints.indexOf(aS.SCREEN_TRACK)))return;const i=t._encoderConfig;MS().supportMinBitrate&&i.bitrateMin&&e.attributes.payloads.forEach(e=>{var t;["h264","vp8","vp9","av1"].includes((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-min-bitrate"]="".concat(i.bitrateMin))}),MS().supportMinBitrate&&!t._hints.includes(aS.LOW_STREAM)&&i.bitrateMax&&e.attributes.payloads.forEach(e=>{var t;["h264","vp8","vp9","av1"].includes((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-start-bitrate"]="".concat(FE("X_GOOGLE_START_BITRATE")||Math.floor(i.bitrateMax)))})}function RO(e){if("video"!==e.media.mediaType)return;const t=Mh();if(t.name!==Nh.SAFARI&&t.os!==wh.IOS)return;const i=e.attributes.extmaps.findIndex(e=>/video-orientation/g.test(e.extensionName));-1!==i&&e.attributes.extmaps.splice(i,1)}function IO(e,t,i){if(!t)return;let n,r;if("video"===e.media.mediaType?(n=i.videoExtensions,r=i.videoCodecs):(n=i.audioExtensions,r=i.audioCodecs),!0===t.twcc){const t=n.find(e=>"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e.extensionName);if(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"});(function(e,t){return t.filter(t=>!!e.find(e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find(e=>"transport-cc"===e.type)))})(r,e.attributes.payloads).forEach(e=>{e.rtcpFeedbacks.find(e=>"transport-cc"===e.type)||e.rtcpFeedbacks.push({type:"transport-cc"})})}}else if(!1===t.twcc){const 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=>{const t=e.rtcpFeedbacks.findIndex(e=>"transport-cc"===e.type);-1!==t&&e.rtcpFeedbacks.splice(t,1)})}if(!0===t.remb){const t=n.find(e=>"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e.extensionName);if(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"});(function(e,t){return t.filter(t=>!!e.find(e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find(e=>"goog-remb"===e.type)))})(r,e.attributes.payloads).forEach(e=>{e.rtcpFeedbacks.find(e=>"goog-remb"===e.type)||e.rtcpFeedbacks.push({type:"goog-remb"})})}}else if(!1===t.remb){const 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=>{const t=e.rtcpFeedbacks.findIndex(e=>"goog-remb"===e.type);-1!==t&&e.rtcpFeedbacks.splice(t,1)})}}function vO(e,t,i){if(Hh())return;if("video"!==e.media.mediaType)return;if(!(t instanceof QC))return;if("vp9"!==i&&"vp8"!==i)return;if("vp8"===i&&!FE("SIMULCAST"))return;if(void 0===t._scalabiltyMode||t._scalabiltyMode.numSpatialLayers<=1)return;const n="vp8"===i?2:t._scalabiltyMode.numSpatialLayers,r=e.attributes.ssrcs[0],o=e.attributes.ssrcGroups.find(e=>"FID"===e.semantic&&e.ssrcIds[0]===r.ssrcId),s={semantic:"SIM",ssrcIds:[r.ssrcId]};for(let t=1;t<n;t++)e.attributes.ssrcs.push({ssrcId:r.ssrcId+t,attributes:BI(r.attributes)}),s.ssrcIds.push(r.ssrcId+t),o&&(e.attributes.ssrcs.push({ssrcId:o.ssrcIds[1]+t,attributes:BI(r.attributes)}),e.attributes.ssrcGroups.push({semantic:"FID",ssrcIds:[r.ssrcId+t,o.ssrcIds[1]+t]}));e.attributes.ssrcGroups.unshift(s)}async function CO(e,t,i,n,r){const o=new RTCPeerConnection;o.addTransceiver("video",{direction:"sendonly"}),o.addTransceiver("audio",{direction:"sendonly"}),o.addTransceiver("video",{direction:"recvonly"}),o.addTransceiver("audio",{direction:"recvonly"});const s=(await o.createOffer()).sdp,a=pO(s,e,t,i,n,r,"sendonly"),c=pO(s,e,t,i,n,r,"recvonly"),d={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},u={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},l={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(yO(a,c,"videoExtensions",d,u,l),yO(a,c,"videoCodecs",d,u,l),yO(a,c,"audioExtensions",d,u,l),yO(a,c,"audioCodecs",d,u,l),FE("RAISE_H264_BASELINE_PRIORITY")){const e=l.videoCodecs.findIndex(e=>{var t,i;return"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&"42001f"===(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"])});if(-1!==e){const t=l.videoCodecs.findIndex(e=>{var t;return"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())});if(t<e){CE.debug("raising H264 baseline profile priority");const i=l.videoCodecs[e];l.videoCodecs.splice(e,1),l.videoCodecs.splice(t,0,i)}-1!==t&&(u.videoCodecs=u.videoCodecs.filter(e=>{var t,i;return!("h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&"42001f"!==(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"]))})),-1!==t&&FE("FILTER_SEND_H264_BASELINE")&&(d.videoCodecs=d.videoCodecs.filter(e=>{var t,i;return!("h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&"42001f"!==(null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"]))}))}}try{o.close()}catch(e){}return{send:d,recv:u,sendrecv:l}}function yO(e,t,i,n,r,o){if("videoExtensions"===i||"audioExtensions"===i){const 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):n[i].push(e)}),void t[i].forEach((e,t)=>{-1===s.indexOf(t)&&r[i].push(e)})}if("videoCodecs"===i||"audioCodecs"===i){const 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):n[i].push(e)}),void t[i].forEach((e,t)=>{-1===s.indexOf(t)&&r[i].push(e)})}}function AO(e){const{send:t,recv:i,sendrecv:n}=e;if(!n){if(!t||!i)throw new Error("cannot merge rtp capabilities because one of send or recv is empty!");return{send:t,recv:i}}let r,o;return t?(r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r.audioCodecs=[...t.audioCodecs,...n.audioCodecs],r.videoCodecs=[...t.videoCodecs,...n.videoCodecs],r.audioExtensions=[...t.audioExtensions,...n.audioExtensions],r.videoExtensions=[...t.videoExtensions,...n.videoExtensions]):r=n,i?(o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},o.audioCodecs=[...i.audioCodecs,...n.audioCodecs],o.videoCodecs=[...i.videoCodecs,...n.videoCodecs],o.audioExtensions=[...i.audioExtensions,...n.audioExtensions],o.videoExtensions=[...i.videoExtensions,...n.videoExtensions]):o=n,{send:r,recv:o}}function OO(e){if("audio"!==e.media.mediaType)return;e.attributes.payloads.filter(e=>{var t;return"opus"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())}).forEach(e=>{e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1"})}!function(e,t){e.exports=(()=>{var e={8:(e,t,i)=>{i.r(t),i.d(t,{Parser:()=>I,Printer:()=>O,parse:()=>D,print:()=>P});const n="\n",r="".concat("\r").concat(n),o=" ";let s;function a(e){return e>="0"&&e<="9"}function c(e){return e>="!"&&e<="~"}function d(e){return c(e)||e>=""&&e<="ÿ"}function u(e){return"!"===e||e>="#"&&e<="'"||e>="*"&&e<="+"||e>="-"&&e<="."||e>="0"&&e<="9"||e>="A"&&e<="Z"||e>="^"&&e<="~"}function l(e){return e>="1"&&e<="9"}function h(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function p(e){return"d"===e||"h"===e||"m"===e||"s"===e}function _(e){return e>""&&e<"\t"||e>"\v"&&e<"\f"||e>""&&e<"ÿ"}function E(e){return h(e)||a(e)||"+"===e||"/"===e}function m(e){return a(e)||h(e)||"+"===e||"/"===e||"-"===e||"_"===e}function f(e){return h(e)||a(e)||"+"===e||"/"===e}function S(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function T(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?S(Object(i),!0).forEach((function(t){g(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):S(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function g(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}!function(e){e.VERSION="v",e.ORIGIN="o",e.SESSION_NAME="s",e.INFORMATION="i",e.URI="u",e.EMAIL="e",e.PHONE="p",e.CONNECTION="c",e.BANDWIDTH="b",e.TIME="t",e.REPEAT="r",e.ZONE_ADJUSTMENTS="z",e.KEY="k",e.ATTRIBUTE="a",e.MEDIA="m"}(s||(s={}));class R{consumeText(e,t){let i=t;for(;i<e.length;){const t=e[i];if("\0"===t||"\r"===t||t===n)break;i+=1}if(i-t==0)throw new Error("Invalid text, at ".concat(e));return i}consumeUnicastAddress(e,t,i){return this.consumeTill(e,t,o)}consumeOneOrMore(e,t,i){let n=t;for(;i(e[n]);)n++;if(n-t==0)throw new Error("Invalid rule at ".concat(t,"."));return n}consumeSpace(e,t){if(e[t]===o)return t+1;throw new 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 new Error("Invalid IP4 address.");i++}return i}consumeDecimalUChar(e,t){let i=t;for(let t=0;t<3&&a(e[i]);t++,i++);if(i-t==0)throw new Error("Invalid decimal uchar.");const n=parseInt(e.slice(t,i));if(n>=0&&n<=255)return i;throw new Error("Invalid decimal uchar")}consumeIP6Address(e,t){let i=this.consumeHexpart(e,t);return":"===e[i]?(i+=1,i=this.consumeIP4Address(e,i),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}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){let i=0;for(;i<4;i++)if(!((n=e[t+i])>="0"&&n<="9"||n>="a"&&n<="f"||n>="A"&&n<="F")){if(0===i)throw new Error("Invalid hex 4");break}var n;return t+i}consumeFQDN(e,t){let i=t;for(;a(e[i])||h(e[i])||"-"===e[i]||"."===e[i];)i+=1;if(i-t<4)throw new Error("Invalid FQDN");return i}consumeExtnAddr(e,t){return this.consumeOneOrMore(e,t,d)}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){const i=this.consumeHexpart(e,t);return"/"===e[i]?this.consumeInteger(e,i+1):i}consumeIP4MulticastAddress(e,t){let i=t+3;const n=e.slice(t,i),r=parseInt(n);if(r<224||r>239)throw new 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 new 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)),i}consumeInteger(e,t){if(!l(e[t]))throw new Error("Invalid integer.");for(t+=1;a(e[t]);)t+=1;return t}consumeTTL(e,t){if("0"===e[t])return t+1;if(!l(e[t]))throw new Error("Invalid TTL.");t+=1;for(let i=0;i<2&&a(e[t]);i++)t+=1;return t}consumeToken(e,t){return this.consumeOneOrMore(e,t,u)}consumeTime(e,t){let i=t;if("0"===e[i])return i+1;for(l(e[i])&&(i+=1);a(e[i]);)i++;if(i-t<10)throw new Error("Invalid time");return i}consumeAddress(e,t){return this.consumeTill(e,t,o)}consumeTypedTime(e,t){let i=t;return i=this.consumeOneOrMore(e,i,a),p(e[i])?i+1:i}consumeRepeatInterval(e,t){if(!l(e[t]))throw new Error("Invalid repeat interval");for(t+=1;a(e[t]);)t+=1;return p(e[t])&&(t+=1),t}consumePort(e,t){return this.consumeOneOrMore(e,t,a)}consume(e,t,i){for(let n=0;n<i.length;n++){if(t+n>=e.length)throw new Error("consume exceeding value length");if(e[t+n]!==i[n])throw new Error("consume ".concat(i," failed at ").concat(n))}return t+i.length}consumeTill(e,t,i){let n=t;for(;n<e.length&&("string"!=typeof i||e[n]!==i)&&("function"!=typeof i||!i(e[n]));)n++;return n}}class I extends R{constructor(){super(),g(this,"records",[]),g(this,"currentLine",0)}parse(e){const t=this.probeEOL(e);this.records=e.split(t).filter(e=>!!e.trim()).map(this.parseLine),this.currentLine=0;const i=this.parseVersion(),n=this.parseOrigin(),r=this.parseSessionName(),o=this.parseInformation(),s=this.parseUri(),a=this.parseEmail(),c=this.parsePhone(),d=this.parseConnection(),u=this.parseBandWidth(),l=this.parseTimeFields(),h=this.parseKey(),p=this.parseSessionAttribute(),_=this.parseMediaDescription();if(this.currentLine!==this.records.length)throw new Error("parsing failed, non exhaustive sdp lines.");return{version:i,origin:n,sessionName:r,information:o,uri:s,emails:a,phones:c,connection:d,bandwidths:u,timeFields:l,key:h,attributes:p,mediaDescriptions:_}}getCurrentRecord(){const e=this.records[this.currentLine];if(!e)throw new Error("Record doesn't exit.");return e}probeEOL(e){for(let t=0;t<e.length;t++)if(e[t]===n)return"\r"===e[t-1]?r:n;throw new Error("Invalid newline character.")}parseLine(e,t){if(e.length<2)throw new Error("Invalid sdp line, sdp line should be of form <type>=<value>.");const i=e[0];if("="!==e[1])throw new 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(){const e=new C;for(;this.currentLine<this.records.length;){const t=this.getCurrentRecord();if(t.type!==s.ATTRIBUTE)break;const i={attField:this.extractOneOrMore(t,e=>u(e)&&":"!==e),_cur:0};":"===t.value[t.cur]&&(t.cur+=1,i.attValue=this.extractOneOrMore(t,_)),e.parse(i),this.currentLine++}return e.digest()}parseMediaAttributes(e){const t=new y(e);for(;this.currentLine<this.records.length;){const e=this.getCurrentRecord();if(e.type!==s.ATTRIBUTE)break;const i={attField:this.extractOneOrMore(e,e=>u(e)&&":"!==e),_cur:0};":"===e.value[e.cur]&&(e.cur+=1,i.attValue=this.extractOneOrMore(e,_)),t.parse(i),this.currentLine++}return t.digest()}parseKey(){const e=this.getCurrentRecord();if(e.type===s.KEY){if("prompt"===e.value||"clear:"===e.value||"base64:"===e.value||"uri:"===e.value)return e.value;throw this.currentLine++,new Error("Invalid key.")}}parseZone(){const e=this.getCurrentRecord();if(e.type===s.ZONE_ADJUSTMENTS){const t=[];for(;;)try{const i=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);let n=!1;"-"===e.value[e.cur]&&(n=!0,e.cur+=1);const r=this.extract(e,this.consumeTypedTime);t.push({time:i,typedTime:r,back:n})}catch(e){break}if(0===t.length)throw new Error("Invalid zone adjustments");return this.currentLine++,t}return[]}parseRepeat(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==s.REPEAT)break;{const i=this.extract(t,this.consumeRepeatInterval),n=this.parseTypedTime(t);e.push({repeatInterval:i,typedTimes:n}),this.currentLine++}}return e}parseTypedTime(e){const t=[];for(;;)try{this.consumeSpaceForRecord(e),t.push(this.extract(e,this.consumeTypedTime))}catch(e){break}if(0===t.length)throw new Error("Invalid typed time.");return t}parseTime(){const e=this.getCurrentRecord(),t=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);const i=this.extract(e,this.consumeTime);return this.currentLine++,{startTime:t,stopTime:i}}parseBandWidth(){const e=[];for(;this.currentLine<this.records.length;){const t=this.getCurrentRecord();if(t.type!==s.BANDWIDTH)break;{const i=this.extractOneOrMore(t,u);if(":"!==t.value[t.cur])throw new Error("Invalid bandwidth field.");t.cur++;const n=this.extractOneOrMore(t,a);e.push({bwtype:i,bandwidth:n}),this.currentLine++}}return e}parseVersion(){const e=this.getCurrentRecord();if(e.type!==s.VERSION)throw new Error("first sdp record must be version");const t=e.value.slice(0,this.consumeOneOrMore(e.value,0,a));if(t.length!==e.value.length)throw new Error('invalid proto version, "v='.concat(e.value,'"'));return this.currentLine++,t}parseOrigin(){const e=this.getCurrentRecord();if(e.type!==s.ORIGIN)throw new Error("second line of sdp must be origin");const t=this.extractOneOrMore(e,d);this.consumeSpaceForRecord(e);const i=this.extractOneOrMore(e,a);this.consumeSpaceForRecord(e);const n=this.extractOneOrMore(e,a);this.consumeSpaceForRecord(e);const r=this.extractOneOrMore(e,u);this.consumeSpaceForRecord(e);const o=this.extractOneOrMore(e,u);this.consumeSpaceForRecord(e);const c=this.extract(e,this.consumeUnicastAddress);return this.currentLine++,{username:t,sessId:i,sessVersion:n,nettype:r,addrtype:o,unicastAddress:c}}parseSessionName(){const e=this.getCurrentRecord();if(e.type===s.SESSION_NAME){const t=this.extract(e,this.consumeText);return this.currentLine++,t}}parseInformation(){const e=this.getCurrentRecord();if(e.type!==s.INFORMATION)return;const t=this.extract(e,this.consumeText);return this.currentLine++,t}parseUri(){const e=this.getCurrentRecord();if(e.type===s.URI)return this.currentLine++,e.value}parseEmail(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==s.EMAIL)break;e.push(t.value),this.currentLine++}return e}parsePhone(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==s.PHONE)break;e.push(t.value),this.currentLine++}return e}parseConnection(){const e=this.getCurrentRecord();if(e.type===s.CONNECTION){const t=this.extractOneOrMore(e,u);this.consumeSpaceForRecord(e);const i=this.extractOneOrMore(e,u);this.consumeSpaceForRecord(e);const n=this.extract(e,this.consumeAddress);return this.currentLine++,{nettype:t,addrtype:i,address:n}}}parseMedia(){const 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);const n=[];for(n.push(this.extract(e,this.consumeToken));"/"===e.value[e.cur];)e.cur+=1,n.push(this.extract(e,this.consumeToken));if(0===n.length)throw new Error("Invalid proto");const r=this.parseFmt(e);return this.currentLine++,{mediaType:t,port:i,protos:n,fmts:r}}parseTimeFields(){const e=[];for(;this.getCurrentRecord().type===s.TIME;){const t=this.parseTime(),i=this.parseRepeat(),n=this.parseZone();e.push({time:t,repeats:i,zones:n})}return e}parseMediaDescription(){const e=[];for(;this.currentLine<this.records.length&&this.getCurrentRecord().type===s.MEDIA;){const t=this.parseMedia(),i=this.parseInformation(),n=this.parseConnections(),r=this.parseBandWidth(),o=this.parseKey(),s=this.parseMediaAttributes(t);e.push({media:t,information:i,connections:n,bandwidths:r,key:o,attributes:s})}return e}parseConnections(){const e=[];for(;this.currentLine<this.records.length&&this.getCurrentRecord().type===s.CONNECTION;)e.push(this.parseConnection());return e}parseFmt(e){const t=[];for(;;)try{this.consumeSpaceForRecord(e),t.push(this.extract(e,this.consumeToken))}catch(e){break}if(0===t.length)throw new Error("Invalid fmts");return t}extract(e,t,...i){const n=t.call(this,e.value,e.cur,...i),r=e.value.slice(e.cur,n);return e.cur=n,r}extractOneOrMore(e,t){const i=this.consumeOneOrMore(e.value,e.cur,t),n=e.value.slice(e.cur,i);return e.cur=i,n}consumeSpaceForRecord(e){if(e.value[e.cur]!==o)throw new Error("Invalid space at ".concat(e.cur,"."));e.cur+=1}}class v extends R{constructor(...e){super(...e),g(this,"attributes",void 0),g(this,"digested",!1)}extractOneOrMore(e,t,i){const n=this.consumeOneOrMore(e.attValue,e._cur,t),r=e.attValue.slice(e._cur,n),[o,s]=i||[];if("number"==typeof o&&r.length<o)throw new Error("error in length, should be more or equal than ".concat(o," characters."));if("number"==typeof s&&r.length>s)throw new Error("error in length, should be less or equal than ".concat(s," characters."));return e._cur=n,r}consumeAttributeSpace(e){if(e.attValue[e._cur]!==o)throw new Error("Invalid space at ".concat(e._cur,"."));e._cur+=1}extract(e,t,...i){if(!e.attValue)throw new Error("Nothing to extract from attValue.");const n=t.call(this,e.attValue,e._cur,...i),r=e.attValue.slice(e._cur,n);return e._cur=n,r}atEnd(e){if(!e.attValue)throw new Error;return e._cur>=e.attValue.length}peekChar(e){if(!e.attValue)throw new Error;return e.attValue[e._cur]}peek(e,t){if(!e.attValue)throw new 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 new Error("Invalid ice-ufrag, should be only a single line if 'a=ice-ufrag'");this.attributes.iceUfrag=this.extractOneOrMore(e,E,[4,256])}parseIcePwd(e){if(this.attributes.icePwd)throw new Error("Invalid ice-pwd, should be only a single line if 'a=ice-pwd'");this.attributes.icePwd=this.extractOneOrMore(e,E,[22,256])}parseIceOptions(e){if(this.attributes.iceOptions)throw new Error("Invalid ice-options, should be only one 'ice-options' line");const t=[];for(;!this.atEnd(e);){t.push(this.extractOneOrMore(e,E));try{this.consumeAttributeSpace(e)}catch(t){if(this.atEnd(e))break;throw t}}this.attributes.iceOptions=t}parseFingerprint(e){const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill);this.attributes.fingerprints.push({hashFunction:t,fingerprint:i})}parseExtmap(e){const t=this.extractOneOrMore(e,a);let i;"/"===this.peekChar(e)&&(this.extract(e,this.consume,"/"),i=this.extract(e,this.consumeToken)),this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeTill,o),r=T(T({entry:parseInt(t,10)},i&&{direction:i}),{},{extensionName:n});this.peekChar(e)===o&&(this.consumeAttributeSpace(e),r.extensionAttributes=this.extract(e,this.consumeTill)),this.attributes.extmaps.push(r)}parseSetup(e){if(this.attributes.setup)throw new Error("must only be one single 'a=setup' line.");const t=this.extract(e,this.consumeTill);if("active"!==t&&"passive"!==t&&"actpass"!==t&&"holdconn"!==t)throw new Error("role must be one of 'active', 'passive', 'actpass', 'holdconn'.");this.attributes.setup=t}}class C extends v{constructor(...e){super(...e),g(this,"attributes",{unrecognized:[],groups:[],extmaps:[],fingerprints:[],identities:[]})}parse(e){if(this.digested)throw new 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 new Error("attribute parsing error")}digest(){return this.digested=!0,this.attributes}parseGroup(e){const t=this.extract(e,this.consumeToken),i=[];for(;!this.atEnd(e)&&this.peekChar(e)===o;)this.consumeAttributeSpace(e),i.push(this.extract(e,this.consumeToken));this.attributes.groups.push({semantic:t,identificationTag:i})}parseIceLite(){if(this.attributes.iceLite)throw new 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 new Error("must be only one tld-id line");this.attributes.tlsId=this.extractOneOrMore(e,m)}parseIdentity(e){const t=this.extractOneOrMore(e,f),i=[];for(;!this.atEnd(e)&&this.peekChar(e)===o;){this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeToken);this.extract(e,this.consume,"=");const n=this.extractOneOrMore(e,e=>e!==o&&_(e));i.push({name:t,value:n})}this.attributes.identities.push({assertionValue:t,extensions:i})}parseMsidSemantic(e){this.peekChar(e)===o&&this.consumeAttributeSpace(e);const 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}{const i=this.extract(e,this.consumeTill,o);t.identifierList.push(i)}}this.attributes.msidSemantic=t}}class y extends v{constructor(e){super(),g(this,"attributes",void 0),-1!==e.protos.indexOf("RTP")||e.protos.indexOf("rtp"),this.attributes={unrecognized:[],candidates:[],extmaps:[],fingerprints:[],imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[]}}parse(e){if(this.digested)throw new 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 new Error("attribute parsing error")}parseCandidate(e){const t=this.extractOneOrMore(e,E,[1,32]);this.consumeAttributeSpace(e);const i=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const r=this.extractOneOrMore(e,a,[1,10]);this.consumeAttributeSpace(e);const s=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);const d=this.extract(e,this.consumePort);this.consumeAttributeSpace(e),this.extract(e,this.consume,"typ"),this.consumeAttributeSpace(e);const u={foundation:t,componentId:i,transport:n,priority:r,connectionAddress:s,port:d,type:this.extract(e,this.consumeToken),extension:{}};for(this.peek(e," raddr")&&(this.extract(e,this.consume," raddr"),this.consumeAttributeSpace(e),u.relAddr=this.extract(e,this.consumeAddress)),this.peek(e," rport")&&(this.extract(e,this.consume," rport"),this.consumeAttributeSpace(e),u.relPort=this.extract(e,this.consumePort));this.peekChar(e)===o;){this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e),u.extension[t]=this.extractOneOrMore(e,c)}this.attributes.candidates.push(u)}parseRemoteCandidate(e){const t=[];for(;;){const i=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);const r=this.extract(e,this.consumePort);t.push({componentId:i,connectionAddress:n,port:r});try{this.consumeAttributeSpace(e)}catch(e){break}}this.attributes.remoteCandidatesList.push(t)}parseEndOfCandidates(){if(this.attributes.endOfCandidates)throw new Error("must be only one line of end-of-candidates");this.attributes.endOfCandidates=!0}parseRtpmap(e){const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,"/");this.extract(e,this.consume,"/");const n={encodingName:i,clockRate:this.extractOneOrMore(e,a)};this.atEnd(e)||"/"!==this.peekChar(e)||(this.extract(e,this.consume,"/"),n.encodingParameters=parseInt(this.extract(e,this.consumeTill),10));const r=this.attributes.payloads.find(e=>e.payloadType===parseInt(t,10));r?r.rtpMap=n:this.attributes.payloads.push({payloadType:parseInt(t,10),rtpMap:n,rtcpFeedbacks:[]})}parsePtime(e){if(this.attributes.ptime)throw new Error("must be only one line of ptime");this.attributes.ptime=this.extract(e,this.consumeTill)}parseMaxPtime(e){if(this.attributes.maxPtime)throw new Error("must be only one line of ptime");this.attributes.maxPtime=this.extract(e,this.consumeTill)}parseDirection(e){if(this.attributes.direction)throw new Error("must be only one line of direction info");this.attributes.direction=e.attField}parseSSRC(e){const t=this.extractOneOrMore(e,a);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,":");let n;":"===this.peekChar(e)&&(this.extract(e,this.consume,":"),n=this.extract(e,this.consumeTill));const r=this.attributes.ssrcs.find(e=>e.ssrcId===parseInt(t,10));r?r.attributes[i]=n:this.attributes.ssrcs.push({ssrcId:parseInt(t,10),attributes:{[i]:n}})}parseFmtp(e){const t=this.extract(e,this.consumeTill,o);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill),n={};i.split(";").forEach(e=>{let[t,i]=e.split("=");t=t.trim();const r="string"==typeof i?i.trim():null;"string"==typeof t&&t.length>0&&(n[t]=r)});const r=this.attributes.payloads.find(e=>e.payloadType===parseInt(t,10));r?r.fmtp={parameters:n}:this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[],fmtp:{parameters:n}})}parseFmtParameters(e){const t={},i=this.extract(e,this.consumeTill,"=");e._cur++;const n=this.extract(e,this.consumeTill,";");for(t[i]=n;";"===e.attValue[e._cur];){const i=this.extract(e,this.consumeTill,"=");e._cur++;const n=this.extract(e,this.consumeTill,";");t[i]=n}return t}parseRtcpFb(e){let t="";t="*"===this.peekChar(e)?this.extract(e,this.consume,"*"):this.extract(e,this.consumeTill,o),this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,o);let n;switch(i){case"trr-int":n={type:i,interval:this.extract(e,this.consumeTill)};break;case"ack":case"nack":default:{const t={type:i};this.peekChar(e)===o&&(this.consumeAttributeSpace(e),t.parameter=this.extract(e,this.consumeToken),this.peekChar(e)===o&&(t.additional=this.extract(e,this.consumeTill))),n=t}}if("*"===t)this.attributes.rtcpFeedbackWildcards.push(n);else{const e=this.attributes.payloads.find(e=>e.payloadType===parseInt(t,10));e?e.rtcpFeedbacks.push(n):this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[n]})}}parseRTCPMux(){if(this.attributes.rtcpMux)throw new Error("must be single line of rtcp-mux");this.attributes.rtcpMux=!0}parseRTCPMuxOnly(){if(this.attributes.rtcpMuxOnly)throw new Error("must be single line of rtcp-only");this.attributes.rtcpMuxOnly=!0}parseRTCPRsize(){if(this.attributes.rtcpRsize)throw new Error("must be single line of rtcp-rsize");this.attributes.rtcpRsize=!0}parseRTCP(e){if(this.attributes.rtcp)throw new Error("must be single line of rtcp");const t={port:this.extract(e,this.consumePort)};this.peekChar(e)===o&&(this.consumeAttributeSpace(e),t.netType=this.extractOneOrMore(e,u),this.consumeAttributeSpace(e),t.addressType=this.extractOneOrMore(e,u),this.consumeAttributeSpace(e),t.address=this.extract(e,this.consumeAddress)),this.attributes.rtcp=t}parseMsid(e){const t={id:this.extractOneOrMore(e,u,[1,64])};this.peekChar(e)===o&&(this.consumeAttributeSpace(e),t.appdata=this.extractOneOrMore(e,u,[1,64])),this.attributes.msids.push(t)}parseImageAttr(e){this.attributes.imageattr.push(e.attValue)}parseRid(e){const t=this.extractOneOrMore(e,e=>h(e)||a(e)||"_"===e||"-"===e);this.consumeAttributeSpace(e);const i={id:t,direction:this.extract(e,this.consumeToken),params:[]};if(this.peekChar(e)===o){if(this.consumeAttributeSpace(e),this.peek(e,"pt=")){this.extract(e,this.consume,"pt=");const t=[];for(;;){const i=this.extract(e,this.consumeToken);t.push(i);try{this.extract(e,this.consume,",")}catch(e){break}}i.payloads=t,this.peekChar(e)===o&&this.extract(e,this.consume,o)}for(;;){const t=this.extract(e,this.consumeToken);switch(t){case"depend":{const n={type:t,rids:this.extract(e,this.consume,"=").split(",")};i.params.push(n);break}case"max-width":case"height-width":case"max-fps":case"max-fs":case"max-br":case"max-pps":case"max-bpp":default:{const n={type:t};"="===this.peekChar(e)&&(this.extract(e,this.consume,"="),n.val=this.extract(e,this.consumeTill,";")),i.params.push(n)}}try{this.extract(e,this.consume,";")}catch(e){break}}}this.attributes.rids.push(i)}parseSimulcast(e){if(this.attributes.simulcast)throw new Error("must be single line of simulcast");this.attributes.simulcast=e.attValue,this.extract(e,this.consumeTill)}parseSctpPort(e){this.attributes.sctpPort=this.extractOneOrMore(e,a,[1,5])}parseMaxMessageSize(e){this.attributes.maxMessageSize=this.extractOneOrMore(e,a,[1,void 0])}digest(){return this.digested=!0,this.attributes}parseMid(e){this.attributes.mid=this.extract(e,this.consumeToken)}parseSSRCGroup(e){const t=this.extract(e,this.consumeToken),i=[];for(;;)try{this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeInteger);i.push(parseInt(t,10))}catch(e){break}this.attributes.ssrcGroups.push({semantic:t,ssrcIds:i})}}function A(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}class O{constructor(){A(this,"eol",r)}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.key),i+=this.printSessionAttributes(e.attributes),i+=this.printMediaDescription(e.mediaDescriptions),i}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(const i of e)t+="e=".concat(i).concat(this.eol);return t}printPhone(e){let t="";for(const 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(const i of e)t+="b=".concat(i.bwtype,":").concat(i.bandwidth).concat(this.eol);return t}printTimeFields(e){let t="";for(const i of e){t+="t=".concat(i.time.startTime," ").concat(i.time.startTime).concat(this.eol);for(const e of 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(const i of e)t+="a=".concat(i.attField).concat(i.attValue?":".concat(i.attValue):"").concat(this.eol);return t}printMediaDescription(e){let t="";for(const 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(const 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 w(this.eol).print(e)}printMediaAttributes(e){return new N(this.eol).print(e)}}class b{constructor(e){A(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(o)).concat(this.eol)}printFingerprints(e){return e.length>0?e.map(e=>"a=fingerprint:".concat(e.hashFunction).concat(o).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(o).concat(e.extensionName).concat(e.extensionAttributes?"".concat(o).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 w extends b{print(e){let t="";return t+=this.printGroups(e.groups),t+=this.printMsidSemantic(e.msidSemantic),t+=this.printIceLite(e.iceLite),t+=this.printIceUfrag(e.iceUfrag),t+=this.printIcePwd(e.icePwd),t+=this.printIceOptions(e.iceOptions),t+=this.printFingerprints(e.fingerprints),t+=this.printSetup(e.setup),t+=this.printTlsId(e.tlsId),t+=this.printIdentity(e.identities),t+=this.printExtmap(e.extmaps),t+=this.printUnrecognized(e.unrecognized),t}printGroups(e){let t="";return e.length>0&&(t+=e.map(e=>"a=group:".concat(e.semantic).concat(e.identificationTag.map(e=>"".concat(o).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(o).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(o,"*"):e.identifierList.length>0&&(t+=e.identifierList.map(e=>"".concat(o).concat(e))),t+this.eol}}class N extends b{print(e){const t=e.attributes;let i="";return 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),i}printCandidates(e){return e.map(e=>"a=candidate:".concat(e.foundation).concat(o).concat(e.componentId).concat(o).concat(e.transport).concat(o).concat(e.priority).concat(o).concat(e.connectionAddress).concat(o).concat(e.port).concat(o,"typ").concat(o).concat(e.type).concat(e.relAddr?"".concat(o,"raddr").concat(o).concat(e.relAddr):"").concat(e.relPort?"".concat(o,"rport").concat(o).concat(e.relPort):"").concat(Object.keys(e.extension).map(t=>"".concat(o).concat(t).concat(o).concat(e.extension[t])).join("")).concat(this.eol)).join("")}printRemoteCandidatesList(e){return e.map(e=>"a=remote-candidates:".concat(e.join(o)).concat(this.eol)).join("")}printEndOfCandidates(e){return void 0===e?"":"a=end-of-candidates"+this.eol}printRTPRelated(e){if(!e.payloads)return"";const t=e.payloads;let i="";i+=e.rtcpFeedbackWildcards.map(e=>this.printRTCPFeedback("*",e)).join("");for(const e of t)i+=this.printRtpMap(e.payloadType,e.rtpMap),i+=this.printFmtp(e.payloadType,e.fmtp),i+=e.rtcpFeedbacks.map(t=>this.printRTCPFeedback(e.payloadType,t)).join("");return i}printFmtp(e,t){if(!t)return"";const i=Object.keys(t.parameters);return 1===i.length&&null===t.parameters[i[0]]?"a=fmtp:".concat(e).concat(o).concat(i[0]).concat(this.eol):"a=fmtp:".concat(e).concat(o).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(o).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(o),n=t;switch(n.type){case"trr-int":i+="ttr-int".concat(o).concat(n.interval);break;case"ack":case"nack":default:n=n,i+="".concat(n.type),n.parameter&&(i+="".concat(o).concat(n.parameter),n.additional&&(i+="".concat(o).concat(n.additional)))}return 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(o).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(o).concat(e.netType)),e.addressType&&(t+="".concat(o).concat(e.addressType)),e.address&&(t+="".concat(o).concat(e.address)),t+this.eol}printMSId(e){return e.map(e=>"a=msid:".concat(e.id).concat(e.appdata?"".concat(o).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(o).concat(e.direction);return e.payloads&&(t+="".concat(o,"pt=").concat(e.payloads.join(","))),e.params.length>0&&(t+="".concat(o).concat(e.params.map(e=>"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(o).concat(e.toString(10))).join("")).concat(this.eol)).join("")}}function D(e){return(new I).parse(e)}function P(e,t){return(new O).print(e,t)}}},t={};function i(n){if(t[n])return t[n].exports;var r=t[n]={exports:{}};return e[n](r,r.exports,i),r.exports}return i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},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)})()}(uO);class bO{constructor(e){lp(this,"sessionDesc",void 0),lp(this,"localCapabilities",void 0),lp(this,"rtpCapabilities",void 0),lp(this,"candidates",void 0),lp(this,"iceParameters",void 0),lp(this,"dtlsParameters",void 0),lp(this,"setup",void 0),lp(this,"currentMidIndex",void 0),lp(this,"cname",void 0),e=BI(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,remoteSetup:o,localCapabilities:s,sdkCodec:a,cname:c}=e,d=uO.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=r,this.candidates=n,this.iceParameters=t,this.dtlsParameters=i,this.setup=o,this.localCapabilities=s,this.cname=c;for(let e=0;e<d.mediaDescriptions.length;e++){const s=d.mediaDescriptions[e];if(s.attributes.iceUfrag=t.iceUfrag,s.attributes.icePwd=t.icePwd,s.attributes.fingerprints=i.fingerprints,s.attributes.candidates=n,s.attributes.setup=o,"video"===s.media.mediaType){s.media.fmts=r.videoCodecs.map(e=>e.payloadType.toString(10));const e=r.videoCodecs.filter(e=>{var t;return null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase().includes(a)});if(0===e.length)throw new Error("Codec ".concat(a," not supported by remote SDP."));s.attributes.payloads=e,s.attributes.extmaps=r.videoExtensions}"audio"===s.media.mediaType&&(s.media.fmts=r.audioCodecs.map(e=>e.payloadType.toString(10)),s.attributes.payloads=r.audioCodecs,s.attributes.extmaps=r.audioExtensions),d.mediaDescriptions[e]=this.mungMediaDesc(s)}this.sessionDesc=d,this.currentMidIndex=d.mediaDescriptions.length-1}toString(){return uO.exports.print(this.sessionDesc)}send(e,t,i){const{ssrcs:n,ssrcGroups:r}=fO(t,this.cname),o=this.sessionDesc.mediaDescriptions.find(t=>e===gS.VIDEO?"video"===t.media.mediaType:"audio"===t.media.mediaType),s=n[0].attributes.label,a=n[0].attributes.mslabel;return o.attributes.ssrcs=o.attributes.ssrcs.concat(n),o.attributes.ssrcGroups=o.attributes.ssrcGroups.concat(r),{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=>{const i=[],n=[],r=[];t.attributes.ssrcs.forEach(t=>{e.includes(t.attributes.label||"")?r.push(t):i.push(t)}),t.attributes.ssrcGroups.forEach(e=>{r.map(e=>e.ssrcId).includes(e.ssrcIds[0])||n.push(e)}),t.attributes.ssrcs=i,t.attributes.ssrcGroups=n})}mute(e){const t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new 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)=>{const i=e._mediaStreamTrack,n=this.sessionDesc.mediaDescriptions.findIndex(e=>e.attributes.mid===i.kind),r=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],e);this.sessionDesc.mediaDescriptions[n]=r})}stopReceiving(e){}restartICE(e){e=BI(e),this.iceParameters=e,this.sessionDesc.mediaDescriptions.forEach(t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd})}predictReceivingMids(e){const t=[];for(let i=0;i<e;i++)t.push((this.currentMidIndex+i+1).toString(10));return t}mungRecvMediaDsec(e,t){const i=BI(e);return SO(i,t),gO(i,t),i}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex(t=>t.attributes.mid===e);if(-1!==i){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],t);this.sessionDesc.mediaDescriptions[i]=e}}bumpMid(e){this.currentMidIndex+=e}updateTrackLabel(e,t,i){const n=this.sessionDesc.mediaDescriptions.find(t=>e===gS.VIDEO?"video"===t.attributes.mid:"audio"===t.attributes.mid);if(n){const e=n.attributes.ssrcs.find(e=>e.attributes.label===t);var r;if(e)e.attributes.label=i,null===(r=e.attributes.msid)||void 0===r||r.replace(t,i)}}mungMediaDesc(e){const t=BI(e);return TO(t),function(e){const 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=>{const t=e.rtcpFeedbacks.findIndex(e=>"transport-cc"===e.type);-1!==t&&e.rtcpFeedbacks.splice(t,1)})}(t),t}getSSRC(e){for(const t of this.sessionDesc.mediaDescriptions)for(const i of t.attributes.ssrcs)if(i.attributes.label===e)return[i]}}function wO(e){if(Array.isArray(e))return e.map(e=>e);if(!NO(e))return e;const t={};for(const i in e)NO(e[i])||Array.isArray(e[i])?t[i]=wO(e[i]):t[i]=e[i];return t}function NO(e){return!("object"!=typeof e||Array.isArray(e)||!e)}function DO(){const e=navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]*/i);return e&&e[0]?Number(e[0].split("/")[1]):null}function PO(e){if(!window.RTCStatsReport)return!1;return e.getStats()instanceof Sl}class LO{constructor(e){lp(this,"input",[]),lp(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}}const kO={address:"unknown",candidateType:"unknown",id:"unknown",port:0,priority:0,protocol:"unknown",type:"unknown"},MO={timestamp:0,bitrate:{actualEncoded:0,transmit:0},sendPacketLossRate:0,recvPacketLossRate:0,videoRecv:[],videoSend:[],audioRecv:[],audioSend:[],selectedCandidatePair:{id:"unknown",localCandidate:kO,remoteCandidate:kO}},UO={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},xO={firsCount:0,nacksCount:0,plisCount:0,frameCount:0,bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,qpSumPerFrame:0},VO={bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0},FO={jitterBufferMs:0,jitterMs:0,bytes:0,packetsLost:0,packetLostRate:0,packets:0,ssrc:0,receivedFrames:0,droppedFrames:0,concealedSamples:0};class jO{constructor(e,t){lp(this,"onFirstVideoReceived",void 0),lp(this,"onFirstVideoDecoded",void 0),lp(this,"onFirstAudioReceived",void 0),lp(this,"onFirstVideoDecodedTimeout",void 0),lp(this,"onFirstAudioDecoded",void 0),lp(this,"onSelectedLocalCandidateChanged",void 0),lp(this,"onSelectedRemoteCandidateChanged",void 0),lp(this,"videoIsReady",!1),lp(this,"videoIsReady2",{}),lp(this,"pc",void 0),lp(this,"options",void 0),lp(this,"intervalTimer",void 0),lp(this,"stats",wO(MO)),lp(this,"isFirstVideoReceived",{}),lp(this,"isFirstVideoDecoded",{}),lp(this,"isFirstAudioReceived",{}),lp(this,"isFirstAudioDecoded",{}),lp(this,"isFirstVideoDecodedTimeout",{}),lp(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);const t=this.lossRateWindowStats.length,i=["videoSend","audioSend","videoRecv","audioRecv"];let n=0,r=0,o=0,s=0;for(const a of i)e[a].forEach((e,i)=>{if(!this.lossRateWindowStats[t-1][a][i]||!this.lossRateWindowStats[0][a][i])return;const c=this.lossRateWindowStats[t-1][a][i].packets-this.lossRateWindowStats[0][a][i].packets,d=this.lossRateWindowStats[t-1][a][i].packetsLost-this.lossRateWindowStats[0][a][i].packetsLost;"videoSend"===a||"audioSend"===a?(n+=c,o+=d):(r+=c,s+=d),Number.isNaN(c)||Number.isNaN(c)?e.packetLostRate=0:e.packetLostRate=c<=0||d<=0?0:d/(c+d)});e.sendPacketLossRate=n<=0||o<=0?0:o/(n+o),e.recvPacketLossRate=r<=0||s<=0?0:s/(r+s)}}function BO(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function GO(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?BO(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):BO(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class WO extends jO{constructor(){super(...arguments),lp(this,"_stats",MO),lp(this,"lastDecodeVideoReceiverStats",new Map)}async updateStats(){const e=await this._getStats(),t=this.statsResponsesToObjects(e);this._stats=wO(MO);const i=t.filter(e=>"ssrc"===e.type);this.processSSRCStats(i);const n=t.find(e=>"VideoBwe"===e.type);n&&this.processBandwidthStats(n),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=>{const t=e.id.includes("send");switch("".concat(e.mediaType,"_").concat(t?"send":"recv")){case"video_send":{const t=wO(xO);t.codec=e.googCodecName,t.adaptionChangeReason="none",e.googCpuLimitedResolution&&(t.adaptionChangeReason="cpu"),e.googBandwidthLimitedResolution&&(t.adaptionChangeReason="bandwidth"),t.avgEncodeMs=Number(e.googAvgEncodeMs),t.inputFrame={width:Number(e.googFrameWidthInput)||Number(e.googFrameWidthSent),height:Number(e.googFrameHeightInput)||Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},t.sentFrame={width:Number(e.googFrameWidthSent),height:Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},t.firsCount=Number(e.googFirReceived),t.nacksCount=Number(e.googNacksReceived),t.plisCount=Number(e.googPlisReceived),t.frameCount=Number(e.framesEncoded),t.bytes=Number(e.bytesSent),t.packets=Number(e.packetsSent),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.rttMs=Number(e.googRtt||0),this._stats.videoSend.push(t),this._stats.rtt=t.rttMs;break}case"video_recv":{const t=wO(UO),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){const n=i.stats,r=Date.now()-i.lts;t.framesDecodeFreezeTime=n.framesDecodeFreezeTime,t.framesDecodeInterval=n.framesDecodeInterval,t.framesDecodeCount>n.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(i.lts=Date.now(),t.framesDecodeInterval=r,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:GO({},t),lts:Date.now()}),this._stats.videoRecv.push(t);break}case"audio_recv":{const t=wO(FO);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.push(t);break}case"audio_send":{const t=wO(VO);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);break}}})}_getStats(){return new Sl((e,t)=>{this.pc.getStats(e,t)})}statsResponsesToObjects(e){const t=[];return e.result().forEach(e=>{const 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 HO(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function KO(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?HO(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):HO(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class YO extends jO{constructor(){super(...arguments),lp(this,"_stats",MO),lp(this,"report",void 0),lp(this,"lastDecodeVideoReceiverStats",new Map),lp(this,"lastVideoFramesRecv",new Map),lp(this,"lastVideoFramesSent",new Map),lp(this,"lastVideoFramesDecode",new Map),lp(this,"lastVideoJBDelay",new Map),lp(this,"lastAudioJBDelay",new Map),lp(this,"mediaBytesSent",new Map),lp(this,"mediaBytesRetransmit",new Map),lp(this,"mediaBytesTargetEncode",new Map),lp(this,"lastEncoderMs",new Map)}async updateStats(){this.report=await this.pc.getStats(),this._stats=wO(MO),this.report.forEach(e=>{switch(e.type){case Lh.OUTBOUND:"audio"===e.mediaType?this.processAudioOutboundStats(e):"video"===e.mediaType&&this.processVideoOutboundStats(e);break;case Lh.INBOUND:"audio"===e.mediaType?this.processAudioInboundStats(e):"video"===e.mediaType&&this.processVideoInboundStats(e);break;case Lh.TRANSPORT:{const t=this.report.get(e.selectedCandidatePairId);t&&this.processCandidatePairStats(t);break}case Lh.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=>{!t.rttMs&&e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime)}),this._stats.audioSend.forEach(t=>{!t.rttMs&&e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime)}),this._stats.selectedCandidatePair.id=e.id,e.localCandidateId){const t=this.report.get(e.localCandidateId);t&&this.processCandidateStats(t)}if(e.remoteCandidateId){const t=this.report.get(e.remoteCandidateId);t&&this.processCandidateStats(t)}}processCandidateStats(e){let t;e.type===Lh.LOCAL_CANDIDATE&&(t=this._stats.selectedCandidatePair.localCandidate),e.type===Lh.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===Lh.LOCAL_CANDIDATE&&this.stats.selectedCandidatePair.localCandidate.id!==t.id&&this.onSelectedLocalCandidateChanged&&this.onSelectedLocalCandidateChanged(KO({},t),KO({},this.stats.selectedCandidatePair.localCandidate)),e.type===Lh.REMOTE_CANDIDATE&&this.stats.selectedCandidatePair.remoteCandidate.id!==t.id&&this.onSelectedRemoteCandidateChanged&&this.onSelectedRemoteCandidateChanged(KO({},t),KO({},this.stats.selectedCandidatePair.remoteCandidate)))}processAudioInboundStats(e){let t=this._stats.audioRecv.find(t=>t.ssrc===e.ssrc);t||(t=wO(FO),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=wO(UO),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;const i=this.lastDecodeVideoReceiverStats.get(t.ssrc),n=this.lastVideoFramesDecode.get(t.ssrc),r=Date.now();if(t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]){const 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){const n=i.stats,o=r-i.lts;t.framesDecodeFreezeTime=n.framesDecodeFreezeTime,t.framesDecodeInterval=n.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>n.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<n.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))}n&&r-n.lts>=800?(t.decodeFrameRate=Math.round((t.framesDecodeCount-n.count)/((r-n.lts)/1e3)),this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:r,rate:t.decodeFrameRate})):n?t.decodeFrameRate=n.rate:this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:r,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:KO({},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=wO(xO),this._stats.videoSend.push(t));const i=this.mediaBytesSent.get(e.ssrc);if(i)i.add(e.bytesSent);else{const t=new LO(10);t.add(e.bytesSent),this.mediaBytesSent.set(e.ssrc,t)}if(void 0!==e.retransmittedBytesSent){const t=this.mediaBytesRetransmit.get(e.ssrc);if(t)t.add(e.retransmittedBytesSent);else{const t=new LO(10);t.add(e.retransmittedBytesSent),this.mediaBytesRetransmit.set(e.ssrc,t)}}if(e.totalEncodedBytesTarget){const t=this.mediaBytesTargetEncode.get(e.ssrc);if(t)t.add(e.totalEncodedBytesTarget);else{const t=new LO(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){const i=this.lastEncoderMs.get(e.ssrc);if(!i||i.lastFrameCount>e.framesEncoded)t.avgEncodeMs=1e3*e.totalEncodeTime/e.framesEncoded;else{const n=e.framesEncoded-i.lastFrameCount,r=e.totalEncodeTime-i.lastEncoderTime;t.avgEncodeMs=1e3*r/n}}if(e.framesEncoded&&e.qpSum){const 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)}if(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{const i=this.findRemoteStatsId(e.ssrc,Lh.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t)}}processAudioOutboundStats(e){let t=this._stats.audioSend.find(t=>t.ssrc===e.ssrc);if(t||(t=wO(VO),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{const i=this.findRemoteStatsId(e.ssrc,Lh.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t)}}findRemoteStatsId(e,t){var i;const n=Array.from(HR(i=this.report).call(i)).find(i=>i.type===t&&i.ssrc===e);return n?n.id:null}processVideoMediaSource(e,t){const 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){const i=this.report.get(e);i&&(t.inputLevel=i.audioLevel)}processVideoTrackSenderStats(e,t,i){var n,r,o;const s=t?this.report.get(t):void 0,a=null!==(n=null==s?void 0:s.framesSent)&&void 0!==n?n:e.framesSent;let c=null!==(r=null==s?void 0:s.frameWidth)&&void 0!==r?r:e.frameWidth,d=null!==(o=null==s?void 0:s.frameHeight)&&void 0!==o?o:e.frameHeight;if("number"!=typeof a)return;0!==a||"number"==typeof c&&"number"==typeof d||(c=0,d=0);let u=0;const l=Date.now(),h=this.lastVideoFramesSent.get(i.ssrc);h&&l-h.lts>=800?(u=Math.round((a-h.count)/((l-h.lts)/1e3)),this.lastVideoFramesSent.set(i.ssrc,{count:a,lts:l,rate:u})):h?u=h.rate:this.lastVideoFramesSent.set(i.ssrc,{count:a,lts:l,rate:0}),i.sentFrame={width:c,height:d,frameRate:Math.max(0,u)}}processVideoTrackReceiverStats(e,t,i){var n,r,o,s,a;const c=t?this.report.get(t):void 0,d=null!==(n=null==c?void 0:c.framesReceived)&&void 0!==n?n:e.framesReceived,u=null!==(r=null==c?void 0:c.frameWidth)&&void 0!==r?r:e.frameWidth,l=null!==(o=null==c?void 0:c.frameHeight)&&void 0!==o?o:e.frameHeight,h=null!==(s=null==c?void 0:c.jitterBufferDelay)&&void 0!==s?s:e.jitterBufferDelay,p=null!==(a=null==c?void 0:c.jitterBufferEmittedCount)&&void 0!==a?a:e.jitterBufferEmittedCount;if("number"==typeof d){const e=this.lastVideoFramesRecv.get(i.ssrc),t=Date.now();i.framesReceivedCount=d;let n=0;e&&t-e.lts>=800?(n=Math.round((d-e.count)/((t-e.lts)/1e3)),this.lastVideoFramesRecv.set(i.ssrc,{count:d,lts:t,rate:n})):e?n=e.rate:this.lastVideoFramesRecv.set(i.ssrc,{count:d,lts:t,rate:0}),i.receivedFrame={width:u||0,height:l||0,frameRate:n||0},i.decodedFrame={width:u||0,height:l||0,frameRate:i.decodeFrameRate||0},i.outputFrame={width:u||0,height:l||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});const t=1e3*(h-e.jitterBufferDelay)/(p-e.jitterBufferEmittedCount);i.jitterBufferMs=t,i.currentDelayMs=Math.round(t)}}processAudioTrackSenderStats(e,t,i){var n,r,o,s;const a=t?this.report.get(t):void 0,c=null!==(n=null!==(r=null==a?void 0:a.echoReturnLoss)&&void 0!==r?r:e.echoReturnLoss)&&void 0!==n?n:0,d=null!==(o=null!==(s=null==a?void 0:a.echoReturnLossEnhancement)&&void 0!==s?s:e.echoReturnLossEnhancement)&&void 0!==o?o:0;i.aecReturnLoss=c,i.aecReturnLossEnhancement=d}processAudioTrackReceiverStats(e,t,i){var n,r,o,s,a,c,d;const u=t?this.report.get(t):void 0,l=null!==(n=null==u?void 0:u.removedSamplesForAcceleration)&&void 0!==n?n:e.removedSamplesForAcceleration,h=null!==(r=null==u?void 0:u.totalSamplesReceived)&&void 0!==r?r:e.totalSamplesReceived,p=null!==(o=null==u?void 0:u.jitterBufferDelay)&&void 0!==o?o:e.jitterBufferDelay,_=null!==(s=null==u?void 0:u.jitterBufferEmittedCount)&&void 0!==s?s:e.jitterBufferEmittedCount,E=null!==(a=null==u?void 0:u.audioLevel)&&void 0!==a?a:null==e?void 0:e.audioLevel,m=null!==(c=null==u?void 0:u.totalSamplesDuration)&&void 0!==c?c:null==e?void 0:e.totalSamplesDuration,f=null!==(d=null==u?void 0:u.concealedSamples)&&void 0!==d?d:e.concealedSamples;if(l&&h&&(i.accelerateRate=l/h),p&&_){let e=this.lastAudioJBDelay.get(i.ssrc);this.lastAudioJBDelay.set(i.ssrc,{jitterBufferDelay:p,jitterBufferEmittedCount:_}),e||(e={jitterBufferDelay:0,jitterBufferEmittedCount:0});const t=1e3*(p-e.jitterBufferDelay)/(_-e.jitterBufferEmittedCount);i.jitterBufferMs=Math.round(t)}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){const i=this.report.get(e);i&&(t.packetsLost=i.packetsLost,i.roundTripTime&&(t.rttMs=1e3*i.roundTripTime))}getCodecFromCodecStats(e){const t=this.report.get(e);if(!t)return"";const i=t.mimeType.match(/\/(.*)$/);return i&&i[1]?i[1]:""}updateSendBitrate(){let e=0,t=null,i=null;this.mediaBytesSent.forEach(t=>{e+=t.diffMean()}),this.mediaBytesRetransmit.forEach(e=>{t=null===t?e.diffMean():t+e.diffMean()}),this.mediaBytesTargetEncode.forEach(e=>{i=null===i?e.diffMean():i+e.diffMean()});const n=null!==t?e-t:e;this._stats.bitrate={actualEncoded:8*n/(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 qO extends jO{updateStats(){return Sl.resolve()}}function JO(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:250,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:8,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:500,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1e4;const o=DO();return o?o<76?new WO(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new YO(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):PO(e)?new YO(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new qO(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r})}var XO;function zO(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function QO(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?zO(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):zO(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let ZO=(JT((XO=class e extends LS{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),lp(this,"store",void 0),lp(this,"peerConnection",void 0),lp(this,"remoteSDP",void 0),lp(this,"initialOffer",void 0),lp(this,"statsFilter",void 0),lp(this,"useRTX",!1),lp(this,"localCapabilities",void 0),lp(this,"localCandidateCount",0),lp(this,"allCandidatesReceived",!1),lp(this,"establishPromise",void 0),lp(this,"mutex",new vg("P2PConnection-mutex")),this.store=i,this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.statsFilter=JO(this.peerConnection,void 0,void 0,Hh()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}async establish(){try{const e=await this.peerConnection.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=_O(e.sdp),i=pO(e.sdp,!this.useRTX,FE("FILTER_VIDEO_FEC"),FE("FILTER_AUDIO_FEC"),["opus"]);return this.localCapabilities=i,this.initialOffer=e,QO(QO({},t),{},{rtpCapabilities:{send:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},recv:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},sendrecv:i},offerSDP:e.sdp})}catch(e){throw new EE(_E.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e,t,i,n,r,o){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.remoteSDP=new bO({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:n.send,remoteSetup:r,localCapabilities:this.localCapabilities,sdkCodec:this.store.codec,cname:o});const s=this.remoteSDP.toString();await this.peerConnection.setLocalDescription(this.initialOffer),await this.peerConnection.setRemoteDescription({type:"answer",sdp:s})}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}send(e,t){var i=this;return oO((function*(){const n=yield sO(i.mutex.lock());try{if(!i.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const r=e.map(e=>i.peerConnection.addTrack(e._mediaStreamTrack)),o=yield sO(i.peerConnection.createOffer()),s=uO.exports.parse(o.sdp),a=e.map(e=>{const t=e._mediaStreamTrack,n=s.mediaDescriptions.find(e=>e.attributes.mid===t.kind);if(!n)throw new Error("Cannot extract ssrc from mediaDescription.");return function(e,t,i){const n=e.attributes.ssrcs.filter(e=>e.attributes.label===t),r=e.attributes.ssrcGroups;if(0===n.length)throw new Error("Cannot extract ssrc from plan-b SDP.");if(r&&n.length>1){const e=r.find(e=>-1!==e.ssrcIds.indexOf(n[0].ssrcId));return e?[{ssrcId:e.ssrcIds[0],rtx:i?e.ssrcIds[1]:void 0}]:[{ssrcId:n[0].ssrcId}]}return[{ssrcId:n[0].ssrcId}]}(n,t.id,i.useRTX)});let c;try{c=yield a}catch(e){throw r.forEach(e=>{Wh()&&e.replaceTrack(null),i.peerConnection.removeTrack(e)}),e}const d=i.mungSendOfferSDP(o.sdp,e);i.remoteSDP.receive(e,t,c);const u=i.remoteSDP.toString();return yield sO(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield sO(i.applySendEncodings(r,e)),yield sO(i.peerConnection.setRemoteDescription({type:"answer",sdp:u})),e.map((e,t)=>{const i=e._mediaStreamTrack.id;return{localSSRC:a[t],id:i}})}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{n()}}))()}async stopSending(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getSenders().filter(t=>{var i;return-1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||"")});if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");t.map(e=>{Wh()&&e.replaceTrack(null),this.peerConnection.removeTrack(e)});const i=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(i),this.remoteSDP.stopReceiving(e);const n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{id:i,mslabel:r}=this.remoteSDP.send(e,t,n),o=new Sl((t,n)=>{const o=setTimeout(()=>{n(new Error("Cannot receive track, id: ".concat(i)))},1e4),s=n=>{const a=Mh();if(("Safari"===a.name&&11===Number(a.version)||Kh())&&n.track.id!==i&&n.streams[0].id===r){var c;const r=n.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(e,i,n.track.id),this.peerConnection.removeEventListener("track",s),clearTimeout(o),void t(r)}if(n.track.id===i)return this.peerConnection.removeEventListener("track",s),clearTimeout(o),void t(n.track)};this.peerConnection.addEventListener("track",s)}),s=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:s});const a=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(a);return{track:await o,id:i}}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(i)}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){}async unmuteRemote(e){}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getSenders().filter(t=>{var i;return-1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||"")});if(t.length!==e.length)throw new Error("sender' length doesn't match mids' length.");t.map(e=>{if(Wh()&&e.track)e.track.enabled=!1;else{const t=e.getParameters();t.encodings.forEach(e=>e.active=!1),e.setParameters(t)}})}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getSenders().filter(t=>{var i;return-1!==e.indexOf((null===(i=t.track)||void 0===i?void 0:i.id)||"")});if(t.length!==e.length)throw new Error("Senders' length doesn't match mids' length.");t.map(async e=>{if(Wh()&&e.track)e.track.enabled=!0;else{const t=e.getParameters();t.encodings.forEach(e=>e.active=!0),await e.setParameters(t)}});const i=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(i);const n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(){var e=this;return oO((function*(){const t=yield sO(e.mutex.lock("From P2PConnection.restartICE"));try{const i=yield sO(e.peerConnection.createOffer({iceRestart:!0}));if(!i.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const n=_O(i.sdp),{remoteIceParameters:r}=yield n.iceParameters;if(!e.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");e.remoteSDP.restartICE(r);const o=e.remoteSDP.toString();yield sO(e.peerConnection.setLocalDescription(i)),yield sO(e.peerConnection.setRemoteDescription({type:"answer",sdp:o}))}catch(e){CE.warning("restart ICE failed, abort operation",e)}finally{t()}}))()}close(){var e;this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||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 new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const e=await this.peerConnection.createOffer(),i=this.mungSendOfferSDP(e.sdp,[t]);this.remoteSDP.updateRecvMedia(t._mediaStreamTrack.kind,t);const n=this.remoteSDP.toString();await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const i=this.peerConnection.getSenders().filter(t=>{var i;return(null===(i=t.track)||void 0===i?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){const i=this.peerConnection.getSenders().find(e=>{var i;return(null===(i=e.track)||void 0===i?void 0:i.id)===t});i&&await i.replaceTrack(e._mediaStreamTrack)}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,CE.debug("[pc-".concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,CE.debug("[pc-".concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))},FE("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){const i={iceServers:[],sdpSemantics:"plan-b"};return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(Pf(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),FE("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||[]).forEach(e=>{e.forceturn&&(i.iceTransportPolicy="relay")}))),i}static turnServerConfigToIceServers(e){const 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(!MS().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let n=0;n<e.length;n++){var i;const r=e[n],o=t[n];if(!o)continue;const s={},a={};if(o instanceof QC)switch(o._optimizationMode){case"motion":s.degradationPreference="maintain-framerate";break;case"detail":s.degradationPreference="maintain-resolution";break;default:s.degradationPreference="balanced"}if(FE("DSCP_TYPE")&&tp()){const e=FE("DSCP_TYPE");["very-low","low","medium","high"].includes(e)&&(a.networkPriority=e)}const c=r.getParameters(),d=null===(i=c.encodings)||void 0===i?void 0:i[0];d&&Object.assign(d,a),Object.assign(c,s),await r.setParameters(c)}}catch(e){CE.debug("Apply RTPSendEncodings failed.")}}mungSendOfferSDP(e,t){const i=uO.exports.parse(e);return t.forEach((e,t)=>{const n=e._mediaStreamTrack,r=i.mediaDescriptions.find(e=>e.attributes.mid===n.kind);r&&SO(r,e)}),uO.exports.print(i)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||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 new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const t=this.remoteSDP.batchSend(e).map((t,i)=>{let{id:n,mslabel:r}=t;const{kind:o}=e[i];return new Sl((e,t)=>{const i=setTimeout(()=>{t(new Error("Cannot receive track, id: ".concat(n)))},1e4),s=t=>{const a=Mh();if("Safari"===a.name&&11===Number(a.version)&&t.track.id!==n&&t.streams[0].id===r){var c;const r=t.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(o,n,t.track.id),this.peerConnection.removeEventListener("track",s),clearTimeout(i),void e({track:r,id:n})}if(t.track.id===n)return this.peerConnection.removeEventListener("track",s),clearTimeout(i),void e({track:t.track,id:n})};this.peerConnection.addEventListener("track",s)})}),i=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:i});const n=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(n),await Sl.all(t)}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId}setConfiguration(t){if(MS().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}}}).prototype,"connect",[$O],Object.getOwnPropertyDescriptor(XO.prototype,"connect"),XO.prototype),JT(XO.prototype,"stopSending",[$O],Object.getOwnPropertyDescriptor(XO.prototype,"stopSending"),XO.prototype),JT(XO.prototype,"receive",[$O],Object.getOwnPropertyDescriptor(XO.prototype,"receive"),XO.prototype),JT(XO.prototype,"stopReceiving",[$O],Object.getOwnPropertyDescriptor(XO.prototype,"stopReceiving"),XO.prototype),JT(XO.prototype,"muteRemote",[$O],Object.getOwnPropertyDescriptor(XO.prototype,"muteRemote"),XO.prototype),JT(XO.prototype,"unmuteRemote",[$O],Object.getOwnPropertyDescriptor(XO.prototype,"unmuteRemote"),XO.prototype),JT(XO.prototype,"muteLocal",[$O],Object.getOwnPropertyDescriptor(XO.prototype,"muteLocal"),XO.prototype),JT(XO.prototype,"unmuteLocal",[$O],Object.getOwnPropertyDescriptor(XO.prototype,"unmuteLocal"),XO.prototype),JT(XO.prototype,"close",[$O],Object.getOwnPropertyDescriptor(XO.prototype,"close"),XO.prototype),JT(XO.prototype,"updateEncoderConfig",[$O],Object.getOwnPropertyDescriptor(XO.prototype,"updateEncoderConfig"),XO.prototype),JT(XO.prototype,"updateSendParameters",[$O],Object.getOwnPropertyDescriptor(XO.prototype,"updateSendParameters"),XO.prototype),JT(XO.prototype,"replaceTrack",[$O],Object.getOwnPropertyDescriptor(XO.prototype,"replaceTrack"),XO.prototype),JT(XO.prototype,"getRemoteSSRC",[$O],Object.getOwnPropertyDescriptor(XO.prototype,"getRemoteSSRC"),XO.prototype),XO);function $O(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("Locking from P2PConnection.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return await n.apply(this,o)}finally{i()}},i}const eb="9",tb=4e4;class ib{get localCapabilities(){return BI(this._localCapabilities)}get rtpCapabilities(){return BI(this._rtpCapabilities)}get candidates(){return BI(this._candidates)}get iceParameters(){return BI(this._iceParameters)}get dtlsParameters(){return BI(this._dtlsParameters)}constructor(e){lp(this,"sessionDesc",void 0),lp(this,"_localCapabilities",void 0),lp(this,"_rtpCapabilities",void 0),lp(this,"_candidates",void 0),lp(this,"_iceParameters",void 0),lp(this,"_dtlsParameters",void 0),lp(this,"setup",void 0),lp(this,"currentMidIndex",void 0),lp(this,"cname",void 0),lp(this,"firefoxSsrcMidMap",new Map),e=BI(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,remoteSetup:o,localCapabilities:s,cname:a}=e,c=uO.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=r,this._candidates=n,this._iceParameters=t,this._dtlsParameters=i,this._localCapabilities=s,this.setup=o,this.cname=a;const d=this.rtpCapabilities.send;for(const e of c.mediaDescriptions){if(e.attributes.iceUfrag=t.iceUfrag,e.attributes.icePwd=t.icePwd,e.attributes.fingerprints=i.fingerprints,e.attributes.candidates=n,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,FE("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=fO([{ssrcId:tb,rtx:FE("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,OO(e),FE("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=fO([{ssrcId:2e4}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}}this.sessionDesc=c,this.currentMidIndex=c.mediaDescriptions.length-1}preloadRemoteMedia(){const e=FE("PRELOAD_MEDIA_COUNT");this.rtpCapabilities;const t=this.candidates,i=this.dtlsParameters,n=this.iceParameters,r=this.rtpCapabilities.send;for(let o=1;o<e;o++){const e=2*o+2e4,s=2*o+tb,{ssrcs:a,ssrcGroups:c}=fO([{ssrcId:e}],this.cname),{ssrcs:d,ssrcGroups:u}=fO([{ssrcId:s,rtx:FE("USE_RTX")?s+1:void 0}],this.cname);this.sessionDesc.mediaDescriptions.push({media:{mediaType:"video",port:eb,protos:["UDP","TLS","RTP","SAVPF"],fmts:r.videoCodecs.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.videoExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:d,ssrcGroups:u,rtcpFeedbackWildcards:[],payloads:r.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:eb,protos:["UDP","TLS","RTP","SAVPF"],fmts:r.audioCodecs.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.audioExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:a,ssrcGroups:c,rtcpFeedbackWildcards:[],payloads:r.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 uO.exports.print(this.sessionDesc)}send(e,t,i,n){const{ssrcs:r,ssrcGroups:o}=fO(t,this.cname,FE("AV_SYNC")?i:void 0),s=this.findPreloadMediaDesc(r);if(s){if(Hh()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,s.attributes.mid),n&&(n.twcc||n.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(s);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(s,n),{mid:s.attributes.mid,needExchangeSDP:!0}}return{mid:s.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,r);let i;return-1===t||1===t&&(Wh()||Yh())||qh()?(i=this.createOrRecycleSendMedia(e,r,o,"sendonly",n),this.updateBundleMids()):(i=BI(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=r,i.attributes.ssrcGroups=o,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,n)),Hh()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,i.attributes.mid),{mid:i.attributes.mid,needExchangeSDP:!0}}}batchSend(e){const t=e.map(e=>{let{kind:t,ssrcMsg:i,mslabel:n}=e;return this.send(t,i,n)}),i=[];let n=!1;return t.forEach(e=>{let{mid:t,needExchangeSDP:r}=e;r&&(n=!0),i.push(t)}),{mids:i,needExchangeSDP:n}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach(e=>{"0"===e.attributes.mid||Hh()||qh()?e.attributes.ssrcs=[]:(e.attributes.ssrcs=[],e.attributes.direction="inactive",e.media.port="0")}),this.updateBundleMids()}mute(e){const t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly"}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>e.includes(t.attributes.mid||""));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(e=>{e.attributes.direction="inactive"})}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>e.includes(t.attributes.mid||""));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(e=>{e.attributes.direction="recvonly"})}receive(e,t,i,n){e.forEach((e,r)=>{this.createOrRecycleRecvMedia(e,[],"recvonly",t,i,n[r])}),this.updateBundleMids()}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>-1!==e.indexOf(t.attributes.mid));if(t.length!==e.length)throw new 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=BI(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach(t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd})}predictReceivingMids(e){const 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=>{const n=i.media.mediaType===e&&"0"!==i.media.port&&("sendonly"===i.attributes.direction||"sendrecv"===i.attributes.direction)&&0===i.attributes.ssrcs.length;if(Hh()){if(n){const 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 n})}createOrRecycleRecvMedia(e,t,i,n,r,o){const s=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,c=this.localCapabilities.send;let d=[];if(s===gS.VIDEO){var u,l;if(FE("H264_PROFILE_LEVEL_ID")&&"h264"===n&&(d=a.videoCodecs.filter(e=>{var t,i;return((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"").includes(n)&&(null==e||null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"])===FE("H264_PROFILE_LEVEL_ID")})),!d||0===(null===(u=d)||void 0===u?void 0:u.length)){const e=c.videoCodecs.filter(e=>{var t;return((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"").includes(n)});0!==e.length&&(d=a.videoCodecs.filter(t=>e.some(e=>e.payloadType===t.payloadType)))}if(FE("USE_RTX")){const e=d.map(e=>e.payloadType.toString()),t=a.videoCodecs.filter(t=>{var i,n;return"rtx"===(null===(i=t.rtpMap)||void 0===i?void 0:i.encodingName)&&e.includes((null===(n=t.fmtp)||void 0===n?void 0:n.parameters.apt)||"")});d=[...d,...t]}if(0===d.length)CE.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: ").concat(null===(l=a.videoCodecs[0].rtpMap)||void 0===l?void 0:l.encodingName)),d=a.videoCodecs}else d=a.audioCodecs.filter(e=>{var t;return((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"").includes(r)}),0===d.length&&(CE.warning("codec ".concat(r," not included in rtpCapabilities, fallback to opus")),d=a.audioCodecs.filter(e=>{var t;return((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"").includes("opus")}));const h=s===gS.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const p="".concat(this.currentMidIndex);let _={media:{mediaType:s,port:eb,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);const E=this.findFirstClosedMedia(s);if(E){const e=this.sessionDesc.mediaDescriptions.indexOf(E);this.sessionDesc.mediaDescriptions[e]=_}else this.sessionDesc.mediaDescriptions.push(_);return _}createOrRecycleSendMedia(e,t,i,n,r){const o=this.rtpCapabilities.send,s=e===gS.VIDEO?o.videoCodecs:o.audioCodecs,a=e===gS.VIDEO?o.videoExtensions:o.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:eb,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:n,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(c)}};d=this.mungSendMediaDesc(d,r);const u=this.findFirstClosedMedia(e);if(u){const e=this.sessionDesc.mediaDescriptions.indexOf(u);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){const n=BI(e);return TO(n),SO(n,t),gO(n,t),RO(n),IO(n,i,this.localCapabilities.send),n}mungSendMediaDesc(e,t){const i=BI(e);return IO(i,t,this.localCapabilities.recv),OO(i),i}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex(t=>t.attributes.mid===e);if(-1!==i){const 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=>Hh()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port)}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find(t=>{var i,n;return(null===(i=t.attributes)||void 0===i||null===(n=i.ssrcs[0])||void 0===n?void 0:n.ssrcId)===e[0].ssrcId})}getSSRC(e){var t;return null===(t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e))||void 0===t?void 0:t.attributes.ssrcs}}var nb;function rb(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function ob(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?rb(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):rb(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let sb=(JT((nb=class e extends LS{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),lp(this,"store",void 0),lp(this,"peerConnection",void 0),lp(this,"remoteSDP",void 0),lp(this,"initialOffer",void 0),lp(this,"transportEventReceiver",void 0),lp(this,"statsFilter",void 0),lp(this,"useRTX",FE("USE_RTX")),lp(this,"localCapabilities",void 0),lp(this,"localCandidateCount",0),lp(this,"allCandidatesReceived",!1),lp(this,"establishPromise",void 0),lp(this,"mutex",new vg("P2PConnection-mutex")),this.store=i,this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.statsFilter=JO(this.peerConnection,void 0,void 0,Hh()?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"});const e=await this.peerConnection.createOffer();if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=_O(e.sdp),i=await CO(!this.useRTX,FE("FILTER_VIDEO_FEC"),FE("FILTER_AUDIO_FEC"));return this.localCapabilities=AO(i),this.initialOffer=e,ob(ob({},t),{},{rtpCapabilities:i,offerSDP:e.sdp})}catch(e){throw new EE(_E.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e,t,i,n,r,o){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.remoteSDP=new ib({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:n,remoteSetup:r,localCapabilities:this.localCapabilities,cname:o});const s=this.remoteSDP.toString(),a=uO.exports.parse(this.initialOffer.sdp),c=a.mediaDescriptions.find(e=>"audio"===e.media.mediaType);c&&OO(c);const d=uO.exports.print(a),u=this.logSDPExchange(d||"","offer","local","connect");await this.peerConnection.setLocalDescription({type:"offer",sdp:d}),null==u||u(s),await this.peerConnection.setRemoteDescription({type:"answer",sdp:s});const l=this.peerConnection.getTransceivers()[0];if(null!=l&&l.receiver&&this.tryBindTransportEvents(l.receiver),FE("PRELOAD_MEDIA_COUNT")>0){this.remoteSDP.preloadRemoteMedia();const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t)}}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}send(e,t,i){var n=this;return oO((function*(){const r=yield sO(n.mutex.lock("From P2PConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const o=[];e.forEach(e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});o.push(t)}),Hh()&&!0===FE("SIMULCAST")&&(yield sO(n.applySimulcastForFirefox(o,e)));const s=yield sO(n.peerConnection.createOffer()),a=n.remoteSDP.predictReceivingMids(e.length),c=n.mungSendOfferSDP(s.sdp,e,a),d=uO.exports.parse(c),u=a.map(e=>{const t=d.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return EO(t,n.useRTX)});let l;try{l=yield u}catch(r){l=[],n.remoteSDP.receive(e,t,i,l);const o=n.remoteSDP.toString();throw yield sO(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield sO(n.peerConnection.setRemoteDescription({type:"answer",sdp:o})),yield sO(n.stopSending(a,!0)),r}n.remoteSDP.receive(e,t,i,l);const h=n.remoteSDP.toString(),p=n.logSDPExchange(c,"offer","local","send");return yield sO(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield sO(n.applySimulcastEncodings(o,e)),yield sO(n.applySendEncodings(o,e)),null==p||p(h),yield sO(n.peerConnection.setRemoteDescription({type:"answer",sdp:h})),o.map((e,t)=>{const i=a[t];return{localSSRC:u[t],id:i,transceiver:e}})}catch(e){throw e instanceof EE?e:new EE(_E.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{r()}}))()}async stopSending(e,t){const i=t?void 0:await this.mutex.lock("From P2PConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter(t=>-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new 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)||void 0===t||t.call(e)});const n=await this.peerConnection.createOffer(),r=this.logSDPExchange(n.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const o=this.remoteSDP.toString();null==r||r(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}finally{i&&i()}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{mid:r,needExchangeSDP:o}=this.remoteSDP.send(e,t,i,n);if(o){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","receive");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer(),o=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(o||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:o}),CE.debug("[P2PConnection] receive ".concat(e," by exchanging SDP."))}else CE.debug("[P2PConnection] receive ".concat(e," no need to exchange SDP."));const s=this.peerConnection.getTransceivers().find(e=>e.mid===r);if(!s)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:s.receiver.track,id:r}}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const{mids:t,needExchangeSDP:i}=this.remoteSDP.batchSend(e);if(i){const e=this.remoteSDP.toString(),t=this.logSDPExchange(e,"offer","remote","receive");await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const i=await this.peerConnection.createAnswer();null==t||t(i.sdp||""),await this.peerConnection.setLocalDescription(i),CE.debug("[P2PConnection] batchReceive by exchanging SDP.")}else CE.debug("[P2PConnection] batchReceive no need to exchange SDP.");return t.map(e=>{const t=this.peerConnection.getTransceivers().find(t=>t.mid===e);if(!t)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:t.receiver.track,id:e}})}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.mute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"P2PConnection.muteRemote failed; ".concat(e.toString()))}}async unmuteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.unmute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteRemote failed; ".concat(e.toString()))}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter(t=>t.mid&&-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map(e=>{e.direction="inactive"});const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter(t=>t.mid&&-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map(async(e,t)=>{e.direction="sendonly"});const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(){var e=this;return oO((function*(){const t=yield sO(e.mutex.lock("From P2PConnection.restartICE"));try{const i=yield sO(e.peerConnection.createOffer({iceRestart:!0}));if(!i.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const n=_O(i.sdp),{remoteIceParameters:r}=yield n.iceParameters;if(!e.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");e.remoteSDP.restartICE(r);const o=e.remoteSDP.toString(),s=e.logSDPExchange(i.sdp||"","offer","local","restartICE");yield sO(e.peerConnection.setLocalDescription(i)),null==s||s(o),yield sO(e.peerConnection.setRemoteDescription({type:"answer",sdp:o}))}catch(e){CE.warning("restart ICE failed, abort operation",e)}finally{t()}}))()}close(){var e;this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||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 new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),o=this.logSDPExchange(n,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==o||o(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const i=this.peerConnection.getTransceivers().filter(t=>t.mid===e);1===i.length&&(this.isVP8Simulcast(t)?Hh()||await this.applySimulcastEncodings(i,[t]):await this.applySendEncodings(i,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const 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)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,CE.debug("[pc-".concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,CE.debug("[pc-".concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))},FE("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){const i={iceServers:[]};return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(Pf(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),FE("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),FE("FORCE_TURN_TCP")?i.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach(e=>{e.forceturn&&(i.iceTransportPolicy="relay")}))),i}static turnServerConfigToIceServers(e){const t=[];return e.forEach(e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(_I(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!FE("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)&&void 0!==t&&t.state&&(null===(i=this.onDTLSTransportStateChange)||void 0===i||i.call(this,e.transport.state))},e.transport.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,e.error)},e.transport.iceTransport&&(e.transport.iceTransport.onstatechange=()=>{var t,i,n;null!==(t=e.transport)&&void 0!==t&&t.iceTransport.state&&(null===(i=this.onICETransportStateChange)||void 0===i||i.call(this,null===(n=e.transport)||void 0===n?void 0:n.iceTransport.state))}))}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(!MS().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let c=0;c<e.length;c++){const d=e[c],u=t[c];if(u&&u instanceof QC){var i,n;if(this.isVP8Simulcast(u))continue;const e={},t={};switch(u._optimizationMode){case"motion":e.degradationPreference="maintain-framerate";break;case"detail":e.degradationPreference="maintain-resolution";break;default:e.degradationPreference="balanced"}var r,o,s,a;if(null!==(i=u._encoderConfig)&&void 0!==i&&i.bitrateMax)t.maxBitrate=1e3*(null===(r=u._encoderConfig)||void 0===r?void 0:r.bitrateMax);if(u._hints.includes(aS.LOW_STREAM))null!==(o=u._encoderConfig)&&void 0!==o&&o.frameRate&&(t.maxFramerate=mI(u._encoderConfig.frameRate)),null!==(s=u._encoderConfig)&&void 0!==s&&s.scaleResolutionDownBy&&(null===(a=u._encoderConfig)||void 0===a?void 0:a.scaleResolutionDownBy)>1&&(t.scaleResolutionDownBy=u._encoderConfig.scaleResolutionDownBy);if(FE("DSCP_TYPE")&&tp()){const e=FE("DSCP_TYPE");["very-low","low","medium","high"].includes(e)&&(t.networkPriority=e)}const c=d.sender.getParameters(),l=null===(n=c.encodings)||void 0===n?void 0:n[0];Hh()&&!l&&(e.encodings=[t]),l&&Object.assign(l,t),Object.assign(c,e),await d.sender.setParameters(c)}}}catch(e){CE.debug("Apply RTPSendEncodings failed.")}}mungSendOfferSDP(e,t,i){const n=uO.exports.parse(e);return t.forEach((e,t)=>{const r=i[t],o=n.mediaDescriptions.find(e=>e.attributes.mid===r);o&&(SO(o,e),vO(o,e,this.store.codec))}),uO.exports.print(n)}mungReceiveAnswerSDP(e,t,i){const n=uO.exports.parse(e),r=n.mediaDescriptions.find(e=>e.attributes.mid===t);return r&&i===gS.AUDIO&&"audio"===r.media.mediaType&&OO(r),uO.exports.print(n)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||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,n,r,o;const a=e[s],c=t[s];if(c instanceof QC&&!c._hints.includes(aS.LOW_STREAM)&&null!==(i=c._encoderConfig)&&void 0!==i&&i.bitrateMax&&(null===(n=c._encoderConfig)||void 0===n?void 0:n.bitrateMax)>200&&null!==(r=c._scalabiltyMode)&&void 0!==r&&r.numSpatialLayers&&(null===(o=c._scalabiltyMode)||void 0===o?void 0:o.numSpatialLayers)>1&&"vp8"===this.store.codec){const 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}];const i=a.sender.getParameters();await a.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!Hh()&&e.length===t.length)for(let i=0;i<e.length;i++){const n=t[i];if(n instanceof QC&&this.isVP8Simulcast(n)){const t=e[i],r={},o={high:1e3*(n._encoderConfig.bitrateMax-50),medium:5e4};r.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}];const s=t.sender.getParameters();await t.sender.setParameters(Object.assign(s,r))}}}isVP8Simulcast(e){var t,i,n,r;return!!(e instanceof QC&&FE("SIMULCAST")&&"vp8"===this.store.codec&&!e._hints.includes(aS.LOW_STREAM)&&null!==(t=e._encoderConfig)&&void 0!==t&&t.bitrateMax&&(null===(i=e._encoderConfig)||void 0===i?void 0:i.bitrateMax)>200&&null!==(n=e._scalabiltyMode)&&void 0!==n&&n.numSpatialLayers&&(null===(r=e._scalabiltyMode)||void 0===r?void 0:r.numSpatialLayers)>1)}logSDPExchange(e,t,i,n){if(FE("SDP_LOGGING"))return CE.upload("exchanging ".concat(i," ").concat(t," SDP during P2PConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n)}:void 0}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId}setConfiguration(t){if(MS().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}}}).prototype,"connect",[ab],Object.getOwnPropertyDescriptor(nb.prototype,"connect"),nb.prototype),JT(nb.prototype,"receive",[ab],Object.getOwnPropertyDescriptor(nb.prototype,"receive"),nb.prototype),JT(nb.prototype,"batchReceive",[ab],Object.getOwnPropertyDescriptor(nb.prototype,"batchReceive"),nb.prototype),JT(nb.prototype,"stopReceiving",[ab],Object.getOwnPropertyDescriptor(nb.prototype,"stopReceiving"),nb.prototype),JT(nb.prototype,"muteRemote",[ab],Object.getOwnPropertyDescriptor(nb.prototype,"muteRemote"),nb.prototype),JT(nb.prototype,"unmuteRemote",[ab],Object.getOwnPropertyDescriptor(nb.prototype,"unmuteRemote"),nb.prototype),JT(nb.prototype,"muteLocal",[ab],Object.getOwnPropertyDescriptor(nb.prototype,"muteLocal"),nb.prototype),JT(nb.prototype,"unmuteLocal",[ab],Object.getOwnPropertyDescriptor(nb.prototype,"unmuteLocal"),nb.prototype),JT(nb.prototype,"close",[ab],Object.getOwnPropertyDescriptor(nb.prototype,"close"),nb.prototype),JT(nb.prototype,"updateEncoderConfig",[ab],Object.getOwnPropertyDescriptor(nb.prototype,"updateEncoderConfig"),nb.prototype),JT(nb.prototype,"updateSendParameters",[ab],Object.getOwnPropertyDescriptor(nb.prototype,"updateSendParameters"),nb.prototype),JT(nb.prototype,"replaceTrack",[ab],Object.getOwnPropertyDescriptor(nb.prototype,"replaceTrack"),nb.prototype),JT(nb.prototype,"getRemoteSSRC",[ab],Object.getOwnPropertyDescriptor(nb.prototype,"getRemoteSSRC"),nb.prototype),nb);function ab(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From P2PConnection.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return await n.apply(this,o)}finally{i()}},i}function cb(e,t){let i=document.createElement("video"),n=document.createElement("canvas");i.setAttribute("style","display:none"),n.setAttribute("style","display:none"),i.setAttribute("muted",""),i.muted=!0,i.setAttribute("autoplay",""),i.autoplay=!0,i.setAttribute("playsinline",""),n.width=mI(t.width),n.height=mI(t.height);const r=mI(t.framerate||15);document.body.append(i),document.body.append(n);let o=e._mediaStreamTrack;i.srcObject=new MediaStream([o]),i.play();const s=n.getContext("2d");if(!s)throw new EE(_E.UNEXPECTED_ERROR,"can not get canvas context");const a=MS(),c=n.captureStream(a.supportRequestFrame?0:r).getVideoTracks()[0],d=kg(()=>(()=>{if(i.paused&&i.play(),i.videoHeight>2&&i.videoWidth>2){const e=i.videoWidth,t=i.videoHeight/e,r=n.width*t;Math.abs(r-n.height)>=2&&(CE.debug("adjust low stream resolution","".concat(n.width,"x").concat(n.height," -> ").concat(n.width,"x").concat(r)),n.height=r)}s.drawImage(i,0,0,n.width,n.height),c.requestFrame&&c.requestFrame(),o!==e._mediaStreamTrack&&(o=e._mediaStreamTrack,i.srcObject=new MediaStream([o]))})(),r),u=c.stop;return c.stop=()=>{u.call(c),d(),i&&(i.remove(),i=null),n&&(n.width=0,n.remove(),n=null),CE.debug("clean low stream renderer")},c}var db,ub,lb,hb,pb,_b,Eb,mb,fb,Sb,Tb,gb;function Rb(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function Ib(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Rb(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Rb(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class vb extends gg{getUserId(){return this._userId}constructor(e,t,i,n){super(e,"track-".concat(e.kind,"-").concat(t,"-").concat(n.clientId,"_").concat(wI(5,""))),lp(this,"_userId",void 0),lp(this,"_uintId",void 0),lp(this,"_isDestroyed",!1),lp(this,"store",void 0),lp(this,"processor",void 0),lp(this,"processorContext",void 0),this._userId=t,this._uintId=i,this.store=n}_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,CE.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}let Cb=(db=Sg({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:"HTMLElement",i]}),ub=Sg({argsMap:e=>[e.getTrackId()]}),lb=Sg({argsMap:(e,t)=>[e.getTrackId(),t.name]}),hb=Sg({argsMap:e=>[e.getTrackId()]}),JT((pb=class extends vb{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==tf.PLAYING)}get __className__(){return"RemoteVideoTrack"}constructor(e,t,i,n){super(e,t,i,n),lp(this,"_videoVisibleTimer",null),lp(this,"_previousVideoVisibleStatus",void 0),lp(this,"_clearPreviousVideoVisibleStatus",()=>this._previousVideoVisibleStatus=void 0),lp(this,"trackMediaType","video"),lp(this,"_videoWidth",void 0),lp(this,"_videoHeight",void 0),lp(this,"_player",void 0),lp(this,"processorDestination",void 0),lp(this,"processorContext",void 0),this.updateMediaStreamTrackResolution(),this.processorContext=new JR(this.getTrackId(),"remote"),this.processorDestination=new qR(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){WI(()=>{CE.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")},"remoteVideoTrackGetStatsWarning");return UI(this,sS.GET_STATS)||Ib({},Ff)}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e){const t=document.getElementById(e);t?e=t:(CE.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}CE.debug("[".concat(this.getTrackId(),"] start video playback"),JSON.stringify(t));const i=Ib(Ib({fit:"cover"},t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(this._player=new dC(i),this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.emit(lS.FIRST_FRAME_DECODED)}),this._player.play(this.store.sessionId||void 0),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval(()=>{try{const e=this.getVideoElementVisibleStatus();this.emit(lS.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}},FE("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,CE.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){PI(this._originMediaStreamTrack).then(e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t}).catch(DI)}_updatePlayerSource(){CE.debug("[".concat(this.getTrackId(),"] update player source track")),this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}getVideoElementVisibleStatus(){try{var e,t;const i=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),n={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==i?void 0:i.parentElement},{element:r,slot:o}=n;if(this.isPlaying&&r instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=JC.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=Tg.reportApiInvoke(null,{tag:lf.TRACER,name:uf.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 EE(_E.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}pipe(e){if(this.processor===e)return e;if(e._source)throw new EE(_E.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;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(AS.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(AS.ON_TRACK)}_destroy(){super._destroy(),this.unbindProcessorDestinationEvents()}}).prototype,"play",[db],Object.getOwnPropertyDescriptor(pb.prototype,"play"),pb.prototype),JT(pb.prototype,"stop",[ub],Object.getOwnPropertyDescriptor(pb.prototype,"stop"),pb.prototype),JT(pb.prototype,"pipe",[lb],Object.getOwnPropertyDescriptor(pb.prototype,"pipe"),pb.prototype),JT(pb.prototype,"unpipe",[hb],Object.getOwnPropertyDescriptor(pb.prototype,"unpipe"),pb.prototype),pb),yb=(_b=Sg({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),Eb=Sg({argsMap:(e,t)=>[e.getTrackId(),t]}),mb=Sg({argsMap:e=>[e.getTrackId()]}),fb=Sg({argsMap:e=>[e.getTrackId()]}),Sb=Sg({argsMap:(e,t)=>[e.getTrackId(),t.name]}),Tb=Sg({argsMap:e=>[e.getTrackId()]}),JT((gb=class extends vb{get isPlaying(){return this._useAudioElement?Zg.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}constructor(e,t,i,n){super(e,t,i,n),lp(this,"trackMediaType","audio"),lp(this,"_source",void 0),lp(this,"_useAudioElement",!0),lp(this,"_volume",100),lp(this,"processorContext",void 0),lp(this,"processorDestination",void 0),lp(this,"_played",!1),lp(this,"_bypassWebAudio",!1),FE("DISABLE_WEBAUDIO")?(this._source=new QR,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new xg(e,!0),FE("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once(wf.RECEIVE_TRACK_BUFFER,()=>{this.emit(lS.FIRST_FRAME_DECODED)}),this.processorContext=new zR(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new XR(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(wf.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(wf.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(wf.ON_AUDIO_BUFFER),this._source.on(wf.ON_AUDIO_BUFFER,t=>e(t))}setVolume(e){this._volume=e,this._useAudioElement?Zg.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement)throw new EE(_E.NOT_SUPPORTED,"your browser does not support setting the audio output device");await Zg.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getStats(){WI(()=>{CE.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")},"remoteAudioTrackGetStatsWarning");return UI(this,sS.GET_STATS)||Ib({},xf)}play(){CE.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement?(CE.debug("[".concat(this.getTrackId(),"] use audio element to play")),Zg.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):this._source.play()}stop(){CE.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?Zg.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];CE.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&Zg.updateTrack(this.getTrackId(),this._mediaStreamTrack)}pipe(e){if(this._bypassWebAudio)throw new EE(_E.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new EE(_E.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 EE(_E.NOT_SUPPORTED,"can not unpipe extension when WebAudio disabled");if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(AS.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(AS.ON_NODE,e=>{this._source.processedNode=e;const t=!e;this._useAudioElement!==t&&(this._played?(this.stop(),this._useAudioElement=t,this.play()):this._useAudioElement=t)})}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(AS.ON_TRACK),this.processorDestination.removeAllListeners(AS.ON_NODE)}}).prototype,"setVolume",[_b],Object.getOwnPropertyDescriptor(gb.prototype,"setVolume"),gb.prototype),JT(gb.prototype,"setPlaybackDevice",[Eb],Object.getOwnPropertyDescriptor(gb.prototype,"setPlaybackDevice"),gb.prototype),JT(gb.prototype,"play",[mb],Object.getOwnPropertyDescriptor(gb.prototype,"play"),gb.prototype),JT(gb.prototype,"stop",[fb],Object.getOwnPropertyDescriptor(gb.prototype,"stop"),gb.prototype),JT(gb.prototype,"pipe",[Sb],Object.getOwnPropertyDescriptor(gb.prototype,"pipe"),gb.prototype),JT(gb.prototype,"unpipe",[Tb],Object.getOwnPropertyDescriptor(gb.prototype,"unpipe"),gb.prototype),gb);function Ab(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function Ob(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Ab(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Ab(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class bb extends hE{constructor(){super(),lp(this,"uplinkStatsUploadInterval",void 0),lp(this,"uplinkStatsUploadSlowInterval",void 0),lp(this,"uplinkRelatedStatsUploadInterval",void 0),lp(this,"uplinkDenoiserStatsUploadInterval",void 0),lp(this,"transportStatsUploadInterval",void 0),lp(this,"uplinkExtensionStatsUploadInterval",void 0),lp(this,"downlinkExtensionStatsUploadInterval",void 0),lp(this,"extensionUsageStatsUploadInterval",void 0),lp(this,"downlinkStatsUploadInterval",void 0),lp(this,"downlinkStatsUploadSlowInterval",void 0),lp(this,"downlinkRelatedStatsUploadInterval",void 0),lp(this,"lastStats",void 0),lp(this,"uploadUnplinkStarted",!1),lp(this,"uploadDownlinkStarted",!1),lp(this,"uploadTransportStarted",!1),lp(this,"uploadExtensionUsageStarted",!1),lp(this,"requestStats",void 0),lp(this,"requestLocalMedia",void 0),lp(this,"requestRemoteMedia",void 0),lp(this,"requestAllTracks",void 0),lp(this,"requestVideoIsReady",void 0),lp(this,"requestUpload",void 0)}startUploadTransportStats(){this.uploadTransportStarted||(this.uploadTransportStarted=!0,this.transportStatsUploadInterval&&window.clearInterval(this.transportStatsUploadInterval),this.transportStatsUploadInterval=window.setInterval(()=>{var e;const t=null===(e=this.requestStats)||void 0===e?void 0:e.call(this);t&&this.uploadTransportStats(t)},6e3))}startUploadExtensionUsageStats(){if(this.uploadExtensionUsageStarted)return;this.uploadExtensionUsageStarted=!0,this.extensionUsageStatsUploadInterval&&window.clearInterval(this.extensionUsageStatsUploadInterval);const e=new Map;this.extensionUsageStatsUploadInterval=window.setInterval(async()=>{var t,i,n;const r=Date.now(),o={connectionInterval:FE("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3,details:[],lts:r};let s=[];const a=(null===(t=this.requestAllTracks)||void 0===t?void 0:t.call(this))||[];for(const e of a)!e.muted&&e.enabled&&(s=s.concat(await e.getProcessorUsage()));const c=(null===(i=this.requestRemoteMedia)||void 0===i?void 0:i.call(this))||[];for(const[e,t]of c)t.has(gS.VIDEO)&&e.videoTrack&&(s=s.concat(await e.videoTrack.getProcessorUsage())),t.has(gS.AUDIO)&&e.audioTrack&&(s=s.concat(await e.audioTrack.getProcessorUsage()));if(0===s.length)return;o.details=function(e,t){const i={};for(const{id:s,value:a,level:c,direction:d}of e){var n;const e=null!==(n=t.get(s))&&void 0!==n?n:0,u=2===a?e+FE("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3:e;var r,o;t.set(s,u),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!==(r=t.get(s))&&void 0!==r?r:0):i[s]={value:a,level:c,remoteUidCount:"local"===d?0:1,totalTs:null!==(o=t.get(s))&&void 0!==o?o:0}}return Object.keys(i).map(e=>{const{level:t,value:n,totalTs:r}=i[e];return{id:e,level:t,value:n,totalTs:r}})}(s,e);const d=Date.now(),u=d>r?d:r+1;null===(n=this.requestUpload)||void 0===n||n.call(this,Af.EXTENSION_USAGE_STATS,{usageStats:o,sendTs:u})},FE("EXTENSION_USAGE_UPLOAD_INTERVAL"))}startUploadUplinkStats(){this.uploadUnplinkStarted||(this.uploadUnplinkStarted=!0,this.uplinkStatsUploadInterval&&window.clearInterval(this.uplinkStatsUploadInterval),this.uplinkStatsUploadInterval=window.setInterval(()=>{var e;const t=null===(e=this.requestStats)||void 0===e?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;const t=null===(e=this.requestStats)||void 0===e?void 0:e.call(this);t&&this.uploadSlowUplinkStats(t)},6e4),this.uplinkRelatedStatsUploadInterval&&window.clearInterval(this.uplinkRelatedStatsUploadInterval),this.uplinkRelatedStatsUploadInterval=window.setInterval(()=>{var e;const t=null===(e=this.requestStats)||void 0===e?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;const t=null===(e=this.requestAllTracks)||void 0===e?void 0:e.call(this);t&&this.uploadDenoiserStats(t)},2e3),this.uplinkExtensionStatsUploadInterval&&window.clearInterval(this.uplinkExtensionStatsUploadInterval),this.uplinkExtensionStatsUploadInterval=window.setInterval(()=>{var e;const t=null===(e=this.requestAllTracks)||void 0===e?void 0:e.call(this);t&&this.uploadExtensionStats(t)},2e3))}uploadTransportStats(e){jI(()=>{var t;null===(t=this.requestUpload)||void 0===t||t.call(this,Af.TRANSPORT_STATS,function(e){const t={connectionType:100};if("relay"===e.selectedCandidatePair.localCandidate.candidateType){const 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?void 0:t.call(this))||[]).forEach(t=>{let[i,{track:n,ssrcs:r}]=t;switch(i){case RS.LocalVideoLowTrack:case RS.LocalVideoTrack:{const t=function(e,t,i){var n;const r=t.videoSend.find(t=>t.ssrc===e);if(!r)return null;const o={id:wI(10,""),timestamp:new Date(t.timestamp).toISOString(),mediaType:"video",type:"ssrc",ssrc:r.ssrc.toString()};switch(o.A_vstd=i._originMediaStreamTrack&&!i._originMediaStreamTrack.enabled||i._mediaStreamTrack&&!i._mediaStreamTrack.enabled?"1":"0",r.sentFrame&&(o.A_fhs=r.sentFrame.height.toString(),o.A_frs=r.sentFrame.frameRate.toString(),o.A_fws=r.sentFrame.width.toString()),r.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=nf[i._player?i._player.videoElementStatus:"uninit"].toString(),o.A_nr=null===(n=r.nacksCount)||void 0===n?void 0:n.toString(),r.avgEncodeMs&&(o.A_aem=r.avgEncodeMs.toFixed(0).toString()),o}(r[0].ssrcId,e,n),o=i===RS.LocalVideoTrack?SI(r[0].ssrcId,e,n):null;t&&jI(()=>{var e;return null===(e=this.requestUpload)||void 0===e?void 0:e.call(this,Af.PUBLISH_STATS,{stream_type:i===RS.LocalVideoLowTrack?"low":"high",stats:Ob(Ob({},t),o)})});const s=function(e){const 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?void 0:e.call(this,Af.PUBLISH_STATS,{stream_type:i===RS.LocalVideoLowTrack?"low":"high",stats:s})},1e3);break}case RS.LocalAudioTrack:{const t=function(e,t,i){const n=t.audioSend.find(t=>t.ssrc===e);if(!n)return null;const r={id:wI(10,""),timestamp:new Date(t.timestamp).toISOString(),mediaType:"audio",type:"ssrc",ssrc:n.ssrc.toString()};return r.A_astd=i._originMediaStreamTrack.enabled&&i._mediaStreamTrack.enabled?"0":"1",n.inputLevel?r.A_ail=Math.round(100*n.inputLevel).toString():r.A_ail=Math.round(100*i._source.getAccurateVolumeLevel()).toString(),r.A_apil=Math.round(100*i._source.getAccurateVolumeLevel()).toString(),n.aecReturnLoss&&(r.A_ecrl=Math.round(n.aecReturnLoss).toString()),n.aecReturnLossEnhancement&&(r.A_ecrle=Math.round(n.aecReturnLossEnhancement).toString()),r}(r[0].ssrcId,e,n);t&&jI(()=>{var e;return null===(e=this.requestUpload)||void 0===e?void 0:e.call(this,Af.PUBLISH_STATS,{stream_type:"high",stats:t})});break}}})}uploadSlowUplinkStats(e){var t;((null===(t=this.requestLocalMedia)||void 0===t?void 0:t.call(this))||[]).filter(e=>{let[t]=e;return t===RS.LocalVideoLowTrack||t===RS.LocalVideoTrack}).forEach(t=>{let[i,{ssrcs:n}]=t;const r=SI(n[0].ssrcId,e);r&&jI(()=>{var e;return null===(e=this.requestUpload)||void 0===e?void 0:e.call(this,Af.PUBLISH_STATS,{stream_type:i===RS.LocalVideoLowTrack?"low":"high",stats:r})})})}uploadRelatedUplinkStats(e,t){var i;((null===(i=this.requestLocalMedia)||void 0===i?void 0:i.call(this))||[]).filter(e=>{let[t]=e;return t===RS.LocalVideoLowTrack||t===RS.LocalVideoTrack}).forEach(t=>{let[i,{ssrcs:n}]=t;const r=function(e,t){const 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}(n[0].ssrcId,e);r&&jI(()=>{var e;null===(e=this.requestUpload)||void 0===e||e.call(this,Af.PUBLISH_RELATED_STATS,{stream_type:i===RS.LocalVideoLowTrack?"low":"high",stats:r})})})}uploadDenoiserStats(e){for(let r=0;r<e.length;r++){const o=e[r];if(o instanceof iI){var t,i,n;const e=null===(t=(i=o._external).getDenoiserStats)||void 0===t?void 0:t.call(i);return void(e&&(null===(n=this.requestUpload)||void 0===n||n.call(this,Af.DENOISER_STATS,e)))}}}uploadExtensionStats(e){for(let t=0;t<e.length;t++){e[t].getProcessorStats().forEach(e=>{var t;null===(t=this.requestUpload)||void 0===t||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(){if(this.uploadDownlinkStarted)return;let e;this.uploadDownlinkStarted=!0,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval);let t=!1;this.downlinkStatsUploadInterval=window.setInterval(()=>{var i;const n=null===(i=this.requestStats)||void 0===i?void 0:i.call(this);n&&(this.uploadDownlinkStats(n,t,e),e=n),t=!t},3e3),this.downlinkStatsUploadSlowInterval&&window.clearInterval(this.downlinkStatsUploadSlowInterval),this.downlinkStatsUploadSlowInterval=window.setInterval(()=>{var e;const t=null===(e=this.requestStats)||void 0===e?void 0:e.call(this);t&&this.uploadSlowDownlinkStats(t)},6e4),this.downlinkRelatedStatsUploadInterval&&window.clearInterval(this.downlinkRelatedStatsUploadInterval),this.downlinkRelatedStatsUploadInterval=window.setInterval(()=>{var e;const t=null===(e=this.requestStats)||void 0===e?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;const t=null===(e=this.requestRemoteMedia)||void 0===e?void 0:e.call(this);t&&this.uploadDownlinkExtensionStats(t)},2e3)}uploadDownlinkStats(e,t,i){var n;((null===(n=this.requestRemoteMedia)||void 0===n?void 0:n.call(this))||[]).forEach(n=>{let[r,o]=n;if(o.has(gS.VIDEO)&&r.videoTrack){const n=r.videoTrack?function(e,t,i,n,r){const o=t.videoRecv.find(t=>t.ssrc===e);if(!o)return null;const s={id:wI(10,""),timestamp:new Date(t.timestamp).toISOString(),mediaType:"video",type:"ssrc",ssrc:o.ssrc.toString()};var a,c;if(s.bytesReceived=o.bytes.toString(),s.packetsLost=o.packetsLost.toString(),s.packetsReceived=o.packets.toString(),o.framesRateFirefox&&(s.A_frr=o.framesRateFirefox.toString()),o.receivedFrame?(s.A_frr=o.receivedFrame.frameRate.toString(),s.A_fhr=o.receivedFrame.height.toString(),s.A_fwr=o.receivedFrame.width.toString()):(s.A_fhr=null===(a=n._videoHeight)||void 0===a?void 0:a.toString(),s.A_fwr=null===(c=n._videoWidth)||void 0===c?void 0:c.toString()),s.A_frd=o.decodeFrameRate.toString(),o.outputFrame&&(s.A_fro=o.outputFrame.frameRate.toString()),void 0!==o.jitterBufferMs&&(s.A_jbm=Math.floor(o.jitterBufferMs).toString()),void 0!==o.currentDelayMs&&(s.A_cdm=Math.floor(o.currentDelayMs).toString()),s.A_fs=o.firsCount.toString(),s.A_ns=o.nacksCount.toString(),s.A_ps=o.plisCount.toString(),n&&(s.A_vrtd=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?"0":"1"),n._player&&n._player.freezeTimeCounterList.length>0&&(s.A_vrft=Math.round(n._player.freezeTimeCounterList.splice(0,1)[0]).toString()),r&&n._player&&"visible"===lI.visibility){const e=Math.min(6e3,n._player.renderFreezeAccTime);s.A_vrrft=Math.round(e).toString(),n._player.renderFreezeAccTime=Math.max(0,n._player.renderFreezeAccTime-e)}if(s.A_rvps=nf[n._player?n._player.videoElementStatus:"uninit"].toString(),i){const t=i.videoRecv.find(t=>t.ssrc===e);if(t&&void 0!==o.totalInterFrameDelay&&void 0!==o.totalSquaredInterFrameDelay&&void 0!==t.totalInterFrameDelay&&void 0!==t.totalSquaredInterFrameDelay){const e=o.totalInterFrameDelay-t.totalInterFrameDelay,i=o.totalSquaredInterFrameDelay-t.totalSquaredInterFrameDelay,n=o.framesDecodeCount-t.framesDecodeCount,r=e/n*1e3,a=Math.round(1e3*Math.sqrt((i-Math.pow(e,2)/n)/n));!isNaN(a)&&r+a>Math.max(3*r,r+150)&&(s.A_ifdsd=a.toString())}}return s}(r._videoSSRC,e,i,r.videoTrack,t):void 0;n&&jI(()=>{var e;return null===(e=this.requestUpload)||void 0===e?void 0:e.call(this,Af.SUBSCRIBE_STATS,{stream_id:r.uid,stats:n})})}if(o.has(gS.AUDIO)&&r.audioTrack){const t=r.audioTrack?function(e,t,i,n){const r=t.audioRecv.find(t=>t.ssrc===e);if(!r)return null;const o={id:wI(10,""),timestamp:new Date(t.timestamp).toISOString(),mediaType:"audio",type:"ssrc",ssrc:r.ssrc.toString()};if(o.bytesReceived=r.bytes.toString(),o.packetsLost=r.packetsLost.toString(),o.packetsReceived=r.packets.toString(),r.outputLevel?o.A_aol=Math.round(100*r.outputLevel).toString():o.A_aol=Math.round(100*n._source.getAccurateVolumeLevel()).toString(),o.A_apol=Math.round(100*n._source.getAccurateVolumeLevel()).toString(),n&&(o.A_artd=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?"0":"1"),o.A_jr=r.jitterMs.toString(),o.A_jbm=Math.floor(r.jitterBufferMs).toString(),o.A_cdm=Math.floor(r.jitterBufferMs).toString(),o.A_raps=nf[Zg.getPlayerState(n.getTrackId())].toString(),i){const t=i.audioRecv.find(t=>t.ssrc===e);if(t){const e=r.concealedSamples-t.concealedSamples;e>0&&(o.A_cs=Math.round(e).toString())}}return o}(r._audioSSRC,e,i,r.audioTrack):void 0;t&&jI(()=>{var e;return null===(e=this.requestUpload)||void 0===e?void 0:e.call(this,Af.SUBSCRIBE_STATS,{stream_id:r.uid,stats:t})})}})}uploadSlowDownlinkStats(e){}uploadRelatedDownlinkStats(e,t){var i;((null===(i=this.requestRemoteMedia)||void 0===i?void 0:i.call(this))||[]).forEach(i=>{let[n,r]=i;if(r.has(gS.VIDEO)&&n.videoTrack){var o;const i=!0===(n._videoSSRC&&(null===(o=this.requestVideoIsReady)||void 0===o?void 0:o.call(this,n._videoSSRC))||!1),r=function(e,t,i,n,r,o){const s=i.videoRecv.find(t=>t.ssrc===e),a=r?r.videoRecv.find(t=>t.ssrc===e):void 0;if(!s)return null;const c=uI.isRemoteVideoFreeze(o,s,a)&&t,d={mediaType:"video",isVideoMute:!1,peerId:n,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}(n._videoSSRC,i,e,n.uid,t,n.videoTrack);r&&jI(()=>{var e;null===(e=this.requestUpload)||void 0===e||e.call(this,Af.SUBSCRIBE_RELATED_STATS,{stream_id:n.uid,stats:r})})}if(r.has(gS.AUDIO)&&n.audioTrack){const t=function(e,t,i,n){const r=t.audioRecv.find(t=>t.ssrc===e);if(!r)return null;const o=uI.isRemoteAudioFreeze(n);return{mediaType:"audio",isAudioMute:!1,peerId:i,googJitterReceived:r.jitterMs.toString(),isFreeze:o,bytesReceived:r.bytes.toString(),packetsReceived:r.packets.toString(),packetsLost:r.packetsLost.toString(),frameReceived:r.receivedFrames.toString(),frameDropped:r.droppedFrames.toString()}}(n._audioSSRC,e,n.uid,n.audioTrack);t&&jI(()=>{var e;null===(e=this.requestUpload)||void 0===e||e.call(this,Af.SUBSCRIBE_RELATED_STATS,{stream_id:n.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;if(i.has(gS.VIDEO)&&t.videoTrack){t.videoTrack.getProcessorStats().forEach(e=>{var t;null===(t=this.requestUpload)||void 0===t||t.call(this,e.type,e.stats)})}if(i.has(gS.AUDIO)&&t.audioTrack){t.audioTrack.getProcessorStats().forEach(e=>{var t;null===(t=this.requestUpload)||void 0===t||t.call(this,e.type,e.stats)})}})}}const wb="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",Nb="9",Db=2e4,Pb=4e4;class Lb{get localCapabilities(){return BI(this._localCapabilities)}get rtpCapabilities(){return BI(this._rtpCapabilities)}get candidates(){return BI(this._candidates)}get iceParameters(){return BI(this._iceParameters)}get dtlsParameters(){return BI(this._dtlsParameters)}constructor(e){lp(this,"sessionDesc",void 0),lp(this,"_localCapabilities",void 0),lp(this,"_rtpCapabilities",void 0),lp(this,"_candidates",void 0),lp(this,"_iceParameters",void 0),lp(this,"_dtlsParameters",void 0),lp(this,"setup",void 0),lp(this,"currentMidIndex",void 0),lp(this,"cname",void 0),lp(this,"firefoxSsrcMidMap",new Map),e=BI(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,remoteSetup:o,localCapabilities:s,cname:a}=e,c=uO.exports.parse(wb);this._rtpCapabilities=r,this._candidates=n,this._iceParameters=t,this._dtlsParameters=i,this._localCapabilities=s,this.setup=o,this.cname=a;const d=this.rtpCapabilities.send;for(const e of c.mediaDescriptions){if(e.attributes.iceUfrag=t.iceUfrag,e.attributes.icePwd=t.icePwd,e.attributes.fingerprints=i.fingerprints,e.attributes.candidates=n,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,FE("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=fO([{ssrcId:Pb,rtx:FE("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,OO(e),FE("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=fO([{ssrcId:Db}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}}this.sessionDesc=c,this.currentMidIndex=c.mediaDescriptions.length-1}updateRemoteRTPCapabilities(e){const t=uO.exports.parse(wb);this._rtpCapabilities=e;const i=this.rtpCapabilities.send;for(const 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,FE("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=fO([{ssrcId:Pb,rtx:FE("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,FE("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=fO([{ssrcId:Db}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}}this.sessionDesc=t,this.currentMidIndex=t.mediaDescriptions.length-1}preloadRemoteMedia(e){this.rtpCapabilities;const t=this.candidates,i=this.dtlsParameters,n=this.iceParameters,r=this.rtpCapabilities.send;for(let o=1;o<e;o++){const e=2*o+Db,s=2*o+Pb,{ssrcs:a,ssrcGroups:c}=fO([{ssrcId:e}],this.cname),{ssrcs:d,ssrcGroups:u}=fO([{ssrcId:s,rtx:FE("USE_RTX")?s+1:void 0}],this.cname);this.sessionDesc.mediaDescriptions.push({media:{mediaType:"video",port:Nb,protos:["UDP","TLS","RTP","SAVPF"],fmts:r.videoCodecs.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.videoExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:d,ssrcGroups:u,rtcpFeedbackWildcards:[],payloads:r.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:Nb,protos:["UDP","TLS","RTP","SAVPF"],fmts:r.audioCodecs.map(e=>e.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:n.iceUfrag,icePwd:n.icePwd,unrecognized:[],candidates:t,extmaps:r.audioExtensions,fingerprints:i.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:a,ssrcGroups:c,rtcpFeedbackWildcards:[],payloads:r.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 uO.exports.print(this.sessionDesc)}send(e,t,i,n){const{ssrcs:r,ssrcGroups:o}=fO(t,this.cname,FE("AV_SYNC")?i:void 0),s=this.findPreloadMediaDesc(r);if(s){if(Hh()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,s.attributes.mid),n&&(n.twcc||n.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(s);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(s,n),{mid:s.attributes.mid,needExchangeSDP:!0}}return{mid:s.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,r);let i;return-1===t||Wh()||Kh()||Yh()?(i=this.createOrRecycleSendMedia(e,r,o,"sendonly",n),this.updateBundleMids()):(i=BI(this.sessionDesc.mediaDescriptions[t]),i.attributes.direction="sendonly",i.attributes.ssrcs=r,i.attributes.ssrcGroups=o,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(i,n)),Hh()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,i.attributes.mid),{mid:i.attributes.mid,needExchangeSDP:!0}}}batchSend(e){const t=e.map(e=>{let{kind:t,ssrcMsg:i,mslabel:n}=e;return this.send(t,i,n)}),i=[];let n=!1;return t.forEach(e=>{let{mid:t,needExchangeSDP:r}=e;r&&(n=!0),i.push(t)}),{mids:i,needExchangeSDP:n}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach(e=>{"0"===e.attributes.mid||Hh()||Wh()||Kh()?e.attributes.ssrcs=[]:(e.attributes.ssrcs=[],e.attributes.direction="inactive",e.media.port="0")}),this.updateBundleMids()}mute(e){const t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly"}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>e.includes(t.attributes.mid||""));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(e=>{e.attributes.direction="inactive"})}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>e.includes(t.attributes.mid||""));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(e=>{e.attributes.direction="recvonly"})}receive(e,t,i,n){e.forEach((e,r)=>{this.createOrRecycleRecvMedia(e,[],"recvonly",t,i,n[r])}),this.updateBundleMids()}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter(t=>-1!==e.indexOf(t.attributes.mid));if(t.length!==e.length)throw new 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=BI(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach(t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd})}predictReceivingMids(e){const 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=>{const n=i.media.mediaType===e&&"0"!==i.media.port&&("sendonly"===i.attributes.direction||"sendrecv"===i.attributes.direction)&&0===i.attributes.ssrcs.length;if(Hh()){if(n){const 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 n})}createOrRecycleRecvMedia(e,t,i,n,r,o){const s=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,c=this.localCapabilities.send;let d=[];if(s===gS.VIDEO){var u,l;if(FE("H264_PROFILE_LEVEL_ID")&&"h264"===n&&(d=a.videoCodecs.filter(e=>{var t,i;return((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"").includes(n)&&(null==e||null===(i=e.fmtp)||void 0===i?void 0:i.parameters["profile-level-id"])===FE("H264_PROFILE_LEVEL_ID")})),!d||0===(null===(u=d)||void 0===u?void 0:u.length)){const e=c.videoCodecs.filter(e=>{var t;return((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"").includes(n)});0!==e.length&&(d=a.videoCodecs.filter(t=>e.some(e=>e.payloadType===t.payloadType)))}if(FE("USE_RTX")){const e=d.map(e=>e.payloadType.toString()),t=a.videoCodecs.filter(t=>{var i,n;return"rtx"===(null===(i=t.rtpMap)||void 0===i?void 0:i.encodingName)&&e.includes((null===(n=t.fmtp)||void 0===n?void 0:n.parameters.apt)||"")});d=[...d,...t]}if(0===d.length)CE.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: ").concat(null===(l=a.videoCodecs[0].rtpMap)||void 0===l?void 0:l.encodingName)),d=a.videoCodecs}else d=a.audioCodecs.filter(e=>{var t;return((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"").includes(r)}),0===d.length&&(CE.warning("codec ".concat(r," not included in rtpCapabilities, fallback to opus")),d=a.audioCodecs.filter(e=>{var t;return((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"").includes("opus")}));const h=s===gS.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const p="".concat(this.currentMidIndex);let _={media:{mediaType:s,port:Nb,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);const E=this.findFirstClosedMedia(s);if(E){const e=this.sessionDesc.mediaDescriptions.indexOf(E);this.sessionDesc.mediaDescriptions[e]=_}else this.sessionDesc.mediaDescriptions.push(_);return _}createOrRecycleSendMedia(e,t,i,n,r){const o=this.rtpCapabilities.send,s=e===gS.VIDEO?o.videoCodecs:o.audioCodecs,a=e===gS.VIDEO?o.videoExtensions:o.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:Nb,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:n,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(c)}};d=this.mungSendMediaDesc(d,r);const u=this.findFirstClosedMedia(e);if(u){const e=this.sessionDesc.mediaDescriptions.indexOf(u);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){const n=BI(e);return TO(n),SO(n,t),gO(n,t),RO(n),IO(n,i,this.localCapabilities.send),n}mungSendMediaDesc(e,t){const i=BI(e);return IO(i,t,this.localCapabilities.recv),OO(i),i}updateRecvMedia(e,t){const i=this.sessionDesc.mediaDescriptions.findIndex(t=>t.attributes.mid===e);if(-1!==i){const 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=>Hh()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port)}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find(t=>{var i,n;return(null===(i=t.attributes)||void 0===i||null===(n=i.ssrcs[0])||void 0===n?void 0:n.ssrcId)===e[0].ssrcId})}getSSRC(e){var t;return null===(t=this.sessionDesc.mediaDescriptions.find(t=>t.attributes.mid===e))||void 0===t?void 0:t.attributes.ssrcs}}var kb;function Mb(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function Ub(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Mb(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Mb(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let xb=(JT((kb=class e extends LS{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),lp(this,"store",void 0),lp(this,"peerConnection",void 0),lp(this,"remoteSDP",void 0),lp(this,"initialOffer",void 0),lp(this,"transportEventReceiver",void 0),lp(this,"statsFilter",void 0),lp(this,"useRTX",FE("USE_RTX")),lp(this,"localCapabilities",void 0),lp(this,"localCandidateCount",0),lp(this,"allCandidatesReceived",!1),lp(this,"establishPromise",void 0),lp(this,"mutex",new vg("NVExtentionsConnection-mutex")),lp(this,"rtcMedia",void 0),this.store=t,this.peerConnection=i,this.statsFilter=JO(this.peerConnection,void 0,void 0,Hh()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}async establish(e){try{const e=await this.peerConnection.createOffer();if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=_O(e.sdp),i=await CO(!this.useRTX,FE("FILTER_VIDEO_FEC"),FE("FILTER_AUDIO_FEC"));return this.localCapabilities=i,this.initialOffer=e,Ub(Ub({},t),{},{rtpCapabilities:i,offerSDP:e.sdp})}catch(e){throw new EE(_E.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e,t,i,n,r,o){try{if(!this.initialOffer)throw new Error("Cannot establish NVConnection without initial offer.");this.remoteSDP=new Lb({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:n,remoteSetup:r,localCapabilities:AO(this.localCapabilities),cname:o});const s=this.remoteSDP.toString(),a=uO.exports.parse(this.initialOffer.sdp),c=a.mediaDescriptions.find(e=>"audio"===e.media.mediaType);c&&OO(c);const d=uO.exports.print(a),u=this.logSDPExchange(d||"","offer","local","connect");await this.peerConnection.setLocalDescription({type:"offer",sdp:d}),null==u||u(s),await this.peerConnection.setRemoteDescription({type:"answer",sdp:s})}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"NV.connect failed; ".concat(e.toString()))}}async updateRemoteConnect(e){var t,i,n;null===(t=this.remoteSDP)||void 0===t||t.updateRemoteRTPCapabilities(e),null===(i=this.remoteSDP)||void 0===i||i.preloadRemoteMedia(2);const r=null===(n=this.remoteSDP)||void 0===n?void 0:n.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:r});const o=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(o),CE.debug("[NVExtentionsConnection] updateRemoteRTPCapabilities by exchanging SDP.")}send(e,t,i){var n=this;return oO((function*(){const r=yield sO(n.mutex.lock("From NVExtentionsConnection.send"));try{if(!n.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.send before remote SDP created");const o=[];e.forEach(e=>{const t=n.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});o.push(t)}),Hh()&&!0===FE("SIMULCAST")&&(yield sO(n.applySimulcastForFirefox(o,e)));const s=yield sO(n.peerConnection.createOffer()),a=n.remoteSDP.predictReceivingMids(e.length),c=n.mungSendOfferSDP(s.sdp,e,a),d=uO.exports.parse(c),u=a.map(e=>{const t=d.mediaDescriptions.find(t=>t.attributes.mid===e);if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return EO(t,n.useRTX)});let l;try{l=yield u}catch(r){l=[],n.remoteSDP.receive(e,t,i,l);const o=n.remoteSDP.toString();throw yield sO(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield sO(n.peerConnection.setRemoteDescription({type:"answer",sdp:o})),yield sO(n.stopSending(a,!0)),r}n.remoteSDP.receive(e,t,i,l);const h=n.remoteSDP.toString(),p=n.logSDPExchange(c,"offer","local","send");return yield sO(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield sO(n.applySimulcastEncodings(o,e)),yield sO(n.applySendEncodings(o,e)),null==p||p(h),yield sO(n.peerConnection.setRemoteDescription({type:"answer",sdp:h})),o.map((e,t)=>{const i=a[t];return{localSSRC:u[t],id:i,transceiver:e}})}catch(e){throw e instanceof EE?e:new EE(_E.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.send failed; ".concat(e.toString()))}finally{r()}}))()}async stopSending(e,t){const i=t?void 0:await this.mutex.lock("From NVExtentionsConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter(t=>-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new 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)||void 0===t||t.call(e)});const n=await this.peerConnection.createOffer(),r=this.logSDPExchange(n.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const o=this.remoteSDP.toString();null==r||r(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.stopSending failed; ".concat(e.toString()))}finally{i&&i()}}async receive(e,t,i,n){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.receive ".concat(e," before remoteSDP created."));const{mid:r,needExchangeSDP:o}=this.remoteSDP.send(e,t,i,n);if(o){const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","receive");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer(),o=this.mungReceiveAnswerSDP(n.sdp,r,e);null==i||i(o||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:o}),CE.debug("[NVExtentionsConnection] receive ".concat(e," by exchanging SDP."))}else CE.debug("[NVExtentionsConnection] receive ".concat(e," no need to exchange SDP."));const s=this.peerConnection.getTransceivers().find(e=>e.mid===r);if(!s)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:s.receiver.track,id:r}}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.receive failed; ".concat(e.toString()))}}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.batchReceive before remoteSDP created.");const{mids:t,needExchangeSDP:i}=this.remoteSDP.batchSend(e);if(i){const e=this.remoteSDP.toString(),t=this.logSDPExchange(e,"offer","remote","receive");await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const i=await this.peerConnection.createAnswer();null==t||t(i.sdp||""),await this.peerConnection.setLocalDescription(i),CE.debug("[NVExtentionsConnection] batchReceive by exchanging SDP.")}else CE.debug("[NVExtentionsConnection] batchReceive no need to exchange SDP.");return t.map(e=>{const t=this.peerConnection.getTransceivers().find(t=>t.mid===e);if(!t)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:t.receiver.track,id:e}})}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"NVExtentionsConnection stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.muteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.mute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.muteRemote failed; ".concat(e.toString()))}}async unmuteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.unmuteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.unmute(e);const t=this.remoteSDP.toString(),i=this.logSDPExchange(t,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();null==i||i(n.sdp||""),await this.peerConnection.setLocalDescription(n)}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.unmuteRemote failed; ".concat(e.toString()))}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter(t=>t.mid&&-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map(e=>{e.direction="inactive"});const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter(t=>t.mid&&-1!==e.indexOf(t.mid));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map(async(e,t)=>{e.direction="sendonly"});const i=await this.peerConnection.createOffer(),n=this.logSDPExchange(i.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(e);const r=this.remoteSDP.toString();null==n||n(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(){var e=this;return oO((function*(){const t=yield sO(e.mutex.lock("From NVExtentionsConnection.restartICE"));try{const i=yield sO(e.peerConnection.createOffer({iceRestart:!0}));if(!i.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const n=_O(i.sdp),{remoteIceParameters:r}=yield n.iceParameters;if(!e.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");e.remoteSDP.restartICE(r);const o=e.remoteSDP.toString(),s=e.logSDPExchange(i.sdp||"","offer","local","restartICE");yield sO(e.peerConnection.setLocalDescription(i)),null==s||s(o),yield sO(e.peerConnection.setRemoteDescription({type:"answer",sdp:o}))}catch(e){CE.warning("restart ICE failed, abort operation",e)}finally{t()}}))()}close(){var e;null===(e=this.onConnectionStateChange)||void 0===e||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 new Error("Cannot call NVExtentionsConnection.updateEncoderConfig before remote SDP created.");const i=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(i.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),o=this.logSDPExchange(n,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),null==o||o(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new EE(_E.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const i=this.peerConnection.getTransceivers().filter(t=>t.mid===e);1===i.length&&(this.isVP8Simulcast(t)?Hh()||await this.applySimulcastEncodings(i,[t]):await this.applySendEncodings(i,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const 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)||void 0===e||!e.sdp||!this.localCapabilities)throw new Error;return Ub(Ub({},_O(this.peerConnection.currentLocalDescription.sdp)),{},{rtpCapabilities:this.localCapabilities})}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,CE.debug("[pc-".concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,CE.debug("[pc-".concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))},FE("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){const i={iceServers:[]};return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(Pf(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),FE("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),FE("FORCE_TURN_TCP")?i.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach(e=>{e.forceturn&&(i.iceTransportPolicy="relay")}))),i}static turnServerConfigToIceServers(e){const t=[];return e.forEach(e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(_I(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!FE("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(!MS().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let c=0;c<e.length;c++){const d=e[c],u=t[c];if(u&&u instanceof QC){var i,n;if(this.isVP8Simulcast(u))continue;const e={},t={};switch(u._optimizationMode){case"motion":e.degradationPreference="maintain-framerate";break;case"detail":e.degradationPreference="maintain-resolution";break;default:e.degradationPreference="balanced"}var r,o,s,a;if(null!==(i=u._encoderConfig)&&void 0!==i&&i.bitrateMax)t.maxBitrate=1e3*(null===(r=u._encoderConfig)||void 0===r?void 0:r.bitrateMax);if(u._hints.includes(aS.LOW_STREAM))null!==(o=u._encoderConfig)&&void 0!==o&&o.frameRate&&(t.maxFramerate=mI(u._encoderConfig.frameRate)),null!==(s=u._encoderConfig)&&void 0!==s&&s.scaleResolutionDownBy&&(null===(a=u._encoderConfig)||void 0===a?void 0:a.scaleResolutionDownBy)>1&&(t.scaleResolutionDownBy=u._encoderConfig.scaleResolutionDownBy);if(FE("DSCP_TYPE")&&tp()){const e=FE("DSCP_TYPE");["very-low","low","medium","high"].includes(e)&&(t.networkPriority=e)}const c=d.sender.getParameters(),l=null===(n=c.encodings)||void 0===n?void 0:n[0];Hh()&&!l&&(e.encodings=[t]),l&&Object.assign(l,t),Object.assign(c,e),await d.sender.setParameters(c)}}}catch(e){CE.debug("Apply RTPSendEncodings failed.")}}mungSendOfferSDP(e,t,i){const n=uO.exports.parse(e);return t.forEach((e,t)=>{const r=i[t],o=n.mediaDescriptions.find(e=>e.attributes.mid===r);o&&(SO(o,e),vO(o,e,this.store.codec))}),uO.exports.print(n)}mungReceiveAnswerSDP(e,t,i){const n=uO.exports.parse(e),r=n.mediaDescriptions.find(e=>e.attributes.mid===t);return r&&i===gS.AUDIO&&"audio"===r.media.mediaType&&OO(r),uO.exports.print(n)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,i)=>{var n;null===(n=this.onFirstVideoDecoded)||void 0===n||n.call(this,e,t,i)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedLocalCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var i;null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i||i.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||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,n,r,o;const a=e[s],c=t[s];if(c instanceof QC&&!c._hints.includes(aS.LOW_STREAM)&&null!==(i=c._encoderConfig)&&void 0!==i&&i.bitrateMax&&(null===(n=c._encoderConfig)||void 0===n?void 0:n.bitrateMax)>200&&null!==(r=c._scalabiltyMode)&&void 0!==r&&r.numSpatialLayers&&(null===(o=c._scalabiltyMode)||void 0===o?void 0:o.numSpatialLayers)>1&&"vp8"===this.store.codec){const 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}];const i=a.sender.getParameters();await a.sender.setParameters(Object.assign(i,e))}}}async applySimulcastEncodings(e,t){if(!Hh()&&e.length===t.length)for(let i=0;i<e.length;i++){const n=t[i];if(n instanceof QC&&this.isVP8Simulcast(n)){const t=e[i],r={},o={high:1e3*(n._encoderConfig.bitrateMax-50),medium:5e4};r.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}];const s=t.sender.getParameters();await t.sender.setParameters(Object.assign(s,r))}}}isVP8Simulcast(e){var t,i,n,r;return!!(e instanceof QC&&FE("SIMULCAST")&&"vp8"===this.store.codec&&!e._hints.includes(aS.LOW_STREAM)&&null!==(t=e._encoderConfig)&&void 0!==t&&t.bitrateMax&&(null===(i=e._encoderConfig)||void 0===i?void 0:i.bitrateMax)>200&&null!==(n=e._scalabiltyMode)&&void 0!==n&&n.numSpatialLayers&&(null===(r=e._scalabiltyMode)||void 0===r?void 0:r.numSpatialLayers)>1)}logSDPExchange(e,t,i,n){if(FE("SDP_LOGGING"))return CE.upload("exchanging ".concat(i," ").concat(t," SDP during NVExtentionsConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n)}:void 0}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId}setConfiguration(t){if(MS().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}}}).prototype,"connect",[Vb],Object.getOwnPropertyDescriptor(kb.prototype,"connect"),kb.prototype),JT(kb.prototype,"updateRemoteConnect",[Vb],Object.getOwnPropertyDescriptor(kb.prototype,"updateRemoteConnect"),kb.prototype),JT(kb.prototype,"receive",[Vb],Object.getOwnPropertyDescriptor(kb.prototype,"receive"),kb.prototype),JT(kb.prototype,"batchReceive",[Vb],Object.getOwnPropertyDescriptor(kb.prototype,"batchReceive"),kb.prototype),JT(kb.prototype,"stopReceiving",[Vb],Object.getOwnPropertyDescriptor(kb.prototype,"stopReceiving"),kb.prototype),JT(kb.prototype,"muteRemote",[Vb],Object.getOwnPropertyDescriptor(kb.prototype,"muteRemote"),kb.prototype),JT(kb.prototype,"unmuteRemote",[Vb],Object.getOwnPropertyDescriptor(kb.prototype,"unmuteRemote"),kb.prototype),JT(kb.prototype,"muteLocal",[Vb],Object.getOwnPropertyDescriptor(kb.prototype,"muteLocal"),kb.prototype),JT(kb.prototype,"unmuteLocal",[Vb],Object.getOwnPropertyDescriptor(kb.prototype,"unmuteLocal"),kb.prototype),JT(kb.prototype,"close",[Vb],Object.getOwnPropertyDescriptor(kb.prototype,"close"),kb.prototype),JT(kb.prototype,"updateEncoderConfig",[Vb],Object.getOwnPropertyDescriptor(kb.prototype,"updateEncoderConfig"),kb.prototype),JT(kb.prototype,"updateSendParameters",[Vb],Object.getOwnPropertyDescriptor(kb.prototype,"updateSendParameters"),kb.prototype),JT(kb.prototype,"replaceTrack",[Vb],Object.getOwnPropertyDescriptor(kb.prototype,"replaceTrack"),kb.prototype),JT(kb.prototype,"getRemoteSSRC",[Vb],Object.getOwnPropertyDescriptor(kb.prototype,"getRemoteSSRC"),kb.prototype),kb);function Vb(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From NVExtentionsConnection.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return await n.apply(this,o)}finally{i()}},i}var Fb;function jb(e){var t,i,n,r=2;for("undefined"!=typeof Symbol&&(i=dO,n=Symbol.iterator);r--;){if(i&&null!=(t=e[i]))return t.call(e);if(n&&null!=(t=e[n]))return new Bb(t.call(e));i="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function Bb(e){function t(e){if(Object(e)!==e)return Sl.reject(new TypeError(e+" is not an object."));var t=e.done;return Sl.resolve(e.value).then((function(e){return{value:e,done:t}}))}return(Bb=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?Sl.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?Sl.reject(e):t(i.apply(this.s,arguments))}},new Bb(e)}let Gb=(JT((Fb=class e extends LS{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),lp(this,"store",void 0),lp(this,"peerConnection",void 0),lp(this,"cname",void 0),lp(this,"mutex",new vg("DataChannelConnection-mutex")),lp(this,"dataChannel",void 0),lp(this,"_p2pConnection",void 0),lp(this,"establishPromise",void 0),lp(this,"_nvMedia",void 0),this.store=i,this.store.dcId=this.store.dcId+1,this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.dataChannel=this.peerConnection.createDataChannel("agora-signal",{ordered:!1,maxPacketLifeTime:50}),this.dataChannel.binaryType="arraybuffer",this._p2pConnection=new xb(t,i,this.peerConnection),this.bindPCEvents(),this.establishPromise=this._p2pConnection.establishPromise}async establish(){var e;const t=null===(e=this._nvMedia)||void 0===e?void 0:e.getLocalRtpCapabilities();return await this._p2pConnection.establish(t)}getP2PConnectionParams(){return this._p2pConnection.getP2PConnectionParams()}async connect(e,t,i,n,r,o){return this.cname=o,await this._p2pConnection.connect(e,t,i,n,r,o),await new Sl((e,t)=>{const n=setTimeout(()=>{this.closeSignal(),t(new EE(_E.DATACHANNEL_CONNECTION_TIMEOUT,"Datachannel connection timed out, candidates: ".concat(JSON.stringify(i))))},2e3);this.dataChannel.onopen=()=>{if("open"===this.dataChannel.readyState)return clearTimeout(n),void e()},this.dataChannel.onerror=e=>{this.closeSignal(),t(e)}}),{transmitter:this.dataChannel,close:this.closeSignal.bind(this)}}send(e,t,i){var n=this;return oO((function*(){const r=yield sO(n.mutex.lock("From DataChannelConnection.send"));try{return yield*cO(jb(n._p2pConnection.send(e,t,i)),sO)}finally{r()}}))()}async stopSending(e,t){return this._p2pConnection.stopSending(e,t)}async receive(e,t,i,n){return this._nvMedia?(CE.debug("[DataChannelConnection] receive ".concat(e," by DataChannel.")),await this._nvMedia.reveiveByRTCMedia(e,t,this.cname)):(CE.debug("[DataChannelConnection] receive ".concat(e," by WebRTC.")),await this._p2pConnection.receive(e,t,i,n))}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 oO((function*(){return yield*cO(jb(e._p2pConnection.restartICE()),sO)}))()}close(){var e;null===(e=this._nvMedia)||void 0===e||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)||void 0===t||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,n){if(FE("SDP_LOGGING"))return CE.upload("exchanging ".concat(i," ").concat(t," SDP during DataChannelConnection.").concat(n,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===i?"remote":"local",n)}:void 0}static resolvePCConfiguration(t){const i={iceServers:[]};return t.iceServers?i.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(Pf(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),FE("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),FE("FORCE_TURN_TCP")?i.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach(e=>{e.forceturn&&(i.iceTransportPolicy="relay")}))),i}static turnServerConfigToIceServers(e){const t=[];return e.forEach(e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(_I(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!FE("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?void 0:t.call(this,e)},this._p2pConnection.onConnectionStateChange=e=>{var t;return null===(t=this.onConnectionStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onDTLSTransportStateChange=e=>{var t;return null===(t=this.onDTLSTransportStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onDTLSTransportError=e=>{var t;return null===(t=this.onDTLSTransportError)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onICETransportStateChange=e=>{var t;return null===(t=this.onICETransportStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstAudioReceived=e=>{var t;return null===(t=this.onFirstAudioReceived)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoReceived=e=>{var t;return null===(t=this.onFirstVideoReceived)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstAudioDecoded=e=>{var t;return null===(t=this.onFirstAudioDecoded)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoDecoded=(e,t,i)=>{var n;return null===(n=this.onFirstVideoDecoded)||void 0===n?void 0:n.call(this,e,t,i)},this._p2pConnection.onFirstVideoDecodedTimeout=e=>{var t;return null===(t=this.onFirstVideoDecodedTimeout)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onSelectedLocalCandidateChanged=(e,t)=>{var i;return null===(i=this.onSelectedLocalCandidateChanged)||void 0===i?void 0:i.call(this,e,t)},this._p2pConnection.onSelectedRemoteCandidateChanged=(e,t)=>{var i;return null===(i=this.onSelectedRemoteCandidateChanged)||void 0===i?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)}}).prototype,"connect",[Wb],Object.getOwnPropertyDescriptor(Fb.prototype,"connect"),Fb.prototype),JT(Fb.prototype,"receive",[Wb],Object.getOwnPropertyDescriptor(Fb.prototype,"receive"),Fb.prototype),JT(Fb.prototype,"stopReceiving",[Wb],Object.getOwnPropertyDescriptor(Fb.prototype,"stopReceiving"),Fb.prototype),JT(Fb.prototype,"muteRemote",[Wb],Object.getOwnPropertyDescriptor(Fb.prototype,"muteRemote"),Fb.prototype),JT(Fb.prototype,"unmuteRemote",[Wb],Object.getOwnPropertyDescriptor(Fb.prototype,"unmuteRemote"),Fb.prototype),JT(Fb.prototype,"muteLocal",[Wb],Object.getOwnPropertyDescriptor(Fb.prototype,"muteLocal"),Fb.prototype),JT(Fb.prototype,"unmuteLocal",[Wb],Object.getOwnPropertyDescriptor(Fb.prototype,"unmuteLocal"),Fb.prototype),JT(Fb.prototype,"close",[Wb],Object.getOwnPropertyDescriptor(Fb.prototype,"close"),Fb.prototype),JT(Fb.prototype,"updateEncoderConfig",[Wb],Object.getOwnPropertyDescriptor(Fb.prototype,"updateEncoderConfig"),Fb.prototype),JT(Fb.prototype,"updateSendParameters",[Wb],Object.getOwnPropertyDescriptor(Fb.prototype,"updateSendParameters"),Fb.prototype),JT(Fb.prototype,"replaceTrack",[Wb],Object.getOwnPropertyDescriptor(Fb.prototype,"replaceTrack"),Fb.prototype),JT(Fb.prototype,"getRemoteSSRC",[Wb],Object.getOwnPropertyDescriptor(Fb.prototype,"getRemoteSSRC"),Fb.prototype),Fb);function Wb(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From DataChannelConnection.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return await n.apply(this,o)}finally{i()}},i}var Hb;function Kb(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function Yb(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Kb(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Kb(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function qb(e){var t,i,n,r=2;for("undefined"!=typeof Symbol&&(i=dO,n=Symbol.iterator);r--;){if(i&&null!=(t=e[i]))return t.call(e);if(n&&null!=(t=e[n]))return new Jb(t.call(e));i="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function Jb(e){function t(e){if(Object(e)!==e)return Sl.reject(new TypeError(e+" is not an object."));var t=e.done;return Sl.resolve(e.value).then((function(e){return{value:e,done:t}}))}return(Jb=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?Sl.resolve({value:e,done:!0}):t(i.apply(this.s,arguments))},throw:function(e){var i=this.s.return;return void 0===i?Sl.reject(e):t(i.apply(this.s,arguments))}},new Jb(e)}let Xb=(JT((Hb=class extends hE{get state(){return this._state}set state(e){const t=this._state;this._state=e,this.emit(vS.StateChange,t,this._state)}constructor(e,t){super(),lp(this,"store",void 0),lp(this,"statsUploader",void 0),lp(this,"connection",void 0),lp(this,"localTrackMap",new Map),lp(this,"remoteUserMap",new Map),lp(this,"pendingLocalTracks",[]),lp(this,"pendingRemoteTracks",[]),lp(this,"statsCollector",void 0),lp(this,"isPlanB",!1),lp(this,"shouldForwardP2PCreation",void 0),lp(this,"iceFailedCount",0),lp(this,"dtlsFailedCount",0),lp(this,"mutex",new vg("P2PChannel-mutex")),lp(this,"_state",IS.Disconnected),lp(this,"handleMuteLocalTrack",async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleMuteLocalTrack");try{if(!this.connection||this.state!==IS.Connected)return void i(new EE(_E.INVALID_OPERATION,"Cannot call P2PChannel.handleMuteLocalTrack before connection established."));const r=this.filterTobeMutedTracks(e);if(0===r.length)return void t();const o=r.find(e=>"videoLowTrack"===e[0]);if(o){o[1].track._originMediaStreamTrack.stop()}await this.connection.muteLocal(r.map(e=>{let[,{id:t}]=e;return t}));const s=this.createMuteMessage(r);await MI(this,vS.RequestMuteLocal,s),t()}catch(e){i(e)}finally{n()}}),lp(this,"handleUnmuteLocalTrack",async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleUnmuteLocalTrack");try{if(!this.connection||this.state!==IS.Connected)return void i(new EE(_E.INVALID_OPERATION,"Cannot call P2PChannel.handleUnmuteLocalTrack before connection established."));const r=this.filterTobeUnmutedTracks(e);if(0===r.length)return void t();const o=r.find(e=>"videoLowTrack"===e[0]);if(o){const t=o[1];if(t.track._originMediaStreamTrack.stop(),MS().supportDualStreamEncoding){const i=e._mediaStreamTrack.clone();t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}else{const i=cb(e,xI(this,vS.RequestLowStreamParameter));t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}await new Sl((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)})}await this.connection.unmuteLocal(r.map(e=>{let[,{id:t}]=e;return t}));const s=this.createUnmuteMessage(r);await MI(this,vS.RequestUnmuteLocal,s),t()}catch(e){i(e)}finally{n()}}),lp(this,"handleUpdateVideoEncoder",async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleSetVideoEncoder");try{const i=this.localTrackMap.get(RS.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==IS.Connected)return void t();const{id:r,track:o}=i;await this.connection.updateSendParameters(r,o),await this.connection.updateEncoderConfig(r,o),this.emit(vS.UpdateVideoEncoder,o),t()}catch(e){i(e)}finally{n()}}),lp(this,"handleSetOptimizationMode",async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleSetOptimizationMode");try{const i=this.localTrackMap.get(RS.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==IS.Connected)return;const{id:r,track:o}=i;await this.connection.updateSendParameters(r,o),t()}catch(e){i(e)}finally{n()}}),lp(this,"handleReplaceTrack",async(e,t,i,n)=>{let r;CE.debug("P2PChannel handleReplaceTrack for [track-id-".concat(e.getTrackId(),"]")),"boolean"==typeof n&&n||(r=await this.mutex.lock("From P2PChannel.handleReplaceTrack"));try{var o;const i=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i});if(!this.connection||!i||this.state!==IS.Connected)return void t();if(await(null===(o=this.connection)||void 0===o?void 0:o.replaceTrack(e,i[1].id)),this.isPlanB){const t=i[1];t.id=e._mediaStreamTrack.id,this.localTrackMap.set(i[0],t)}if(i[0]===RS.LocalVideoTrack&&MS().supportDualStreamEncoding){const t=this.localTrackMap.get(RS.LocalVideoLowTrack);if(t){const i=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i,await new Sl((e,i)=>{this.handleReplaceTrack(t.track,e,i,!0)})}}t()}catch(e){i(e)}finally{var s;null===(s=r)||void 0===s||s()}}),lp(this,"handleGetLocalVideoStats",e=>{e(this.statsCollector.getLocalVideoTrackStats())}),lp(this,"handleGetLocalAudioStats",e=>{e(this.statsCollector.getLocalAudioTrackStats())}),lp(this,"handleGetRemoteVideoStats",e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid]),lp(this,"handleGetRemoteAudioStats",e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid]),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new bb,this.bindStatsUploaderEvents(),this.isPlanB=!MS().supportUnifiedPlan||FE("CHROME_FORCE_PLAN_B")&&tp(),this.shouldForwardP2PCreation=FE("FORWARD_P2P_CREATION")&&MS().supportPCSetConfiguration,this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new Gb({},this.store):this.isPlanB?new ZO({},this.store):new sb({},this.store),this.bindConnectionEvents(this.connection))}async startP2PConnection(e,t){if(this.state=IS.New,this.shouldForwardP2PCreation||(this.connection=this.store.useDataChannel?new Gb(e,this.store):this.isPlanB?new ZO(e,this.store):new sb(e,this.store),this.bindConnectionEvents(this.connection)),!this.connection)throw new EE(_E.UNEXPECTED_ERROR,"Cannot P2PChannel.startConnection before P2PConnection initialization .");return this.connection.setConfiguration(e),this.connection.establishPromise}async connect(e,t,i,n,r,o){if(!this.connection)throw new EE(_E.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");this.connection instanceof Gb?this.connection.updateRemoteConnect(n):(this.store.peerConnectionStart(),await this.connection.connect(e,t,i,n,r,o),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=IS.Connected)}async preConnect(e,t,i,n,r,o){if(!this.connection)throw new EE(_E.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");this.store.peerConnectionStart();const s=await this.connection.connect(e,t,i,n,r,o);return this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=IS.Connected,s}getEstablishParams(){if(this.connection instanceof Gb)return this.connection.getP2PConnectionParams();throw new Error("Only DataChannelConnection needs to obtain establishParams")}publish(e,t,i){var n=this;return oO((function*(){const r=yield sO(n.mutex.lock("From P2PChannel.publish"));try{if(!n.connection||n.state!==IS.Connected){if(n.state===IS.Disconnected)throw new EE(_E.UNEXPECTED_ERROR,"PeerConnection already disconnected.");n.throwIfTrackTypeNotMatch(e);const t=e.filter(e=>-1===n.pendingLocalTracks.indexOf(e));return void(n.pendingLocalTracks=n.pendingLocalTracks.concat(t))}n.store.pubId=n.store.pubId+1,aI.markPublishStart(n.store.clientId,n.store.pubId);const o=n.filterTobePublishedTracks(e,t,i);if(0===o.length)return void(yield sO(n.tryToUnmuteAudio(e)));yield*cO(qb(n.doPublish(n.connection,o)),sO)}finally{r()}}))()}doPublish(e,t){var i=this;return oO((function*(){t.forEach(e=>{let{track:t,type:n}=e;const r=Date.now();i.store.publish(t.getTrackId(),n===RS.LocalAudioTrack?"audio":"video",r)}),i.bindLocalTrackEvents(t);const n=yield sO(e.send(t.map(e=>{let{track:t}=e;return t}),i.store.codec,i.store.audioCodec)),r=(yield sO(n.next())).value,o=i.createGatewayPublishMessage(t,r);let s;try{s=yield o}catch(e){throw n.throw(e),(null==e?void 0:e.code)===_E.WS_ABORT&&t.forEach(e=>{let{track:t}=e;-1===i.pendingLocalTracks.indexOf(t)&&i.pendingLocalTracks.push(t)}),i.unbindLocalTrackEvents(t),e}const a=i.mapPubResToRemoteConfig(o,s),c=(yield sO(n.next(a))).value;t.forEach(e=>{let{type:t}=e;i.statsCollector.addLocalStats(t)}),i.assignLocalTracks(t,c),i.statsUploader.startUploadUplinkStats(),t.forEach(e=>{let{track:t,type:n}=e;const r=Date.now();i.store.publish(t.getTrackId(),n===RS.LocalAudioTrack?"audio":"video",void 0,r)})}))()}publishLowStream(e){var t=this;return oO((function*(){if(!t.connection||t.state!==IS.Connected)return;const i=yield sO(t.mutex.lock("Locking from P2PChannel.publishLowStream"));try{const r=t.localTrackMap.get(RS.LocalVideoTrack);if(!r)throw new EE(_E.UNEXPECTED_ERROR,"Could not find high stream");if(t.localTrackMap.has(RS.LocalVideoLowTrack))throw new EE(_E.UNEXPECTED_ERROR,"[".concat(t.store.clientId,"] Can't publish low stream when stream already publish"));const o=[{track:t.getLowVideoTrack(r.track,e),type:RS.LocalVideoLowTrack}];if(yield*cO(qb(t.doPublish(t.connection,o)),sO),r.track.muted||!r.track.enabled){var n;const e=null===(n=t.localTrackMap.get(RS.LocalVideoLowTrack))||void 0===n?void 0:n.id;void 0!==e&&(yield sO(t.connection.muteLocal([e])))}}finally{i()}}))()}async republish(){this.pendingLocalTracks.length>0&&(CE.debug("Emit P2PChannelEvents.RequestRePublish to republish tracks."),await kI(this,vS.RequestRePublish,this.pendingLocalTracks),this.emit(vS.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[])}async reSubscribe(e){for(let e=this.pendingRemoteTracks.length-1;e>=0;e--){const{user:t,kind:i}=this.pendingRemoteTracks[e];(i!==gS.AUDIO||t._audio_added_&&t._audioSSRC)&&(i!==gS.VIDEO||t._video_added_&&t._videoSSRC)||this.pendingRemoteTracks.splice(e,1)}if(e)await kI(this,vS.RequestReSubscribe,this.pendingRemoteTracks);else for(const{user:e,kind:t}of this.pendingRemoteTracks)await this.subscribe(e,t,t===gS.VIDEO?e._videoSSRC:e._audioSSRC);this.pendingRemoteTracks.forEach(e=>{let{user:t}=e;this.emit(vS.MediaReconnectEnd,t.uid)}),this.pendingRemoteTracks=[]}async unpublish(e){if(!this.connection||this.state!==IS.Connected)return void e.forEach(e=>{const t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1)});const t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;const i=t.find(e=>"videoLowTrack"===e[0]);if(i){i[1].track.close()}return this.doUnpublish(this.connection,t)}async unpublishLowStream(){if(!this.connection||this.state!==IS.Connected)return;const e=this.localTrackMap.get(RS.LocalVideoLowTrack);if(!e)return;e.track.close();const t=[[RS.LocalVideoLowTrack,e]];return this.doUnpublish(this.connection,t)}async doUnpublish(e,t){const 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,n,r){var o;if(!this.connection||this.state!==IS.Connected)throw new EE(_E.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");if(null!==(o=this.remoteUserMap.get(e))&&void 0!==o&&o.has(t))return;let s,a;if(r){const i=r.find(e=>{let{stream_type:i}=e;return i===t});if(!i)throw new EE(_E.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,"."));const n=await this.connection.receive(t,i.ssrcs,String(e._uintid),i.attributes);s=n.track,a=n.id}else{const r=await this.connection.receive(t,[{ssrcId:i,rtx:n}],String(e._uintid),void 0);s=r.track,a=r.id}t===gS.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(s):(e._audioTrack=new yb(s,e.uid,e._uintid,this.store),CE.info("[".concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(s):(e._videoTrack=new Cb(s,e.uid,e._uintid,this.store),CE.info("[".concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId()))),this.bindRemoteTrackEvents(e,e._videoTrack));const c=this.remoteUserMap.get(e);c?c.set(t,a):this.remoteUserMap.set(e,new Map([[t,a]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadDownlinkStats();const d=this.pendingRemoteTracks.findIndex(i=>{let{user:n,kind:r}=i;return n.uid===e.uid&&t===r});-1!==d&&(this.pendingRemoteTracks.splice(d,1),this.emit(vS.MediaReconnectEnd,e.uid))}async massSubscribe(e){return this.massSubscribeNoLock(e)}async massSubscribeNoLock(e){if(!this.connection||this.state!==IS.Connected)throw new EE(_E.INVALID_OPERATION,"Cannot subscribeAll remote users when peerConnection disconnected.");e=e.filter(e=>{var t;let{user:i,mediaType:n}=e;return!(null!==(t=this.remoteUserMap.get(i))&&void 0!==t&&t.has(n))});const t=await this.connection.batchReceive(e.map(e=>{let{user:t,mediaType:i,ssrcId:n,rtxSsrcId:r}=e;return{kind:i,ssrcMsg:[{ssrcId:n,rtx:r}],mslabel:String(t._uintid)}}));e.forEach((e,i)=>{let{user:n,mediaType:r}=e;const{track:o,id:s}=t[i];r===gS.AUDIO?(n._audioTrack?n._audioTrack._updateOriginMediaStreamTrack(o):(n._audioTrack=new yb(o,n.uid,n._uintid,this.store),CE.info("[".concat(this.store.p2pId,"] create remote audio track: ").concat(n._audioTrack.getTrackId()))),this.bindRemoteTrackEvents(n,n._audioTrack)):(n._videoTrack?n._videoTrack._updateOriginMediaStreamTrack(o):(n._videoTrack=new Cb(o,n.uid,n._uintid,this.store),CE.info("[".concat(this.store.p2pId,"] create remote video track: ").concat(n._videoTrack.getTrackId()))),this.bindRemoteTrackEvents(n,n._videoTrack));const a=this.remoteUserMap.get(n);a?a.set(r,s):this.remoteUserMap.set(n,new Map([[r,s]])),this.statsCollector.addRemoteStats(n.uid),this.statsUploader.startUploadDownlinkStats();const c=this.pendingRemoteTracks.findIndex(e=>{let{user:t,kind:i}=e;return t.uid===n.uid&&r===i});-1!==c&&(this.pendingRemoteTracks.splice(c,1),this.emit(vS.MediaReconnectEnd,n.uid))})}async unsubscribe(e,t,i){const n=this.pendingRemoteTracks.filter(i=>{let{user:n,kind:r}=i;return void 0!==t?n.uid===e.uid&&t===r:n.uid===e.uid});if(n.forEach(e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)}),this.connection&&this.state===IS.Connected||i||n.forEach(t=>{let{kind:i}=t;var n;if(i===gS.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===gS.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0}}),!this.connection||this.state!==IS.Connected)return;const r=this.filterTobeUnSubscribedTracks(e,t);if(0===r.length)return;await this.connection.stopReceiving(r.map(e=>{let[,{id:t}]=e;return t}));const o=this.createUnsubscribeMessage(r);return this.withdrawRemoteTracks(r),0===this.remoteUserMap.size&&this.statsUploader.stopUploadDownlinkStats(),r.forEach(e=>{let[t,{kind:n}]=e;var r,o;n===gS.VIDEO&&t._videoSSRC&&(null===(r=this.connection)||void 0===r||r.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(n===gS.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),i||(null===(o=t._videoTrack)||void 0===o||o._destroy(),t._videoTrack=void 0);else if(n===gS.AUDIO){var s;if(this.unbindRemoteTrackEvents(t._audioTrack),!i)null===(s=t._audioTrack)||void 0===s||s._destroy(),t._audioTrack=void 0}}),o}async massUnsubscribe(e){return this.massUnsubscribeNoLock(e)}async massUnsubscribeNoLock(e){let t=[];for(const{user:i,mediaType:n}of e){const e=this.pendingRemoteTracks.filter(e=>{let{user:t,kind:r}=e;return void 0!==n?t.uid===i.uid&&n===r:t.uid===i.uid});e.forEach(e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)}),t=t.concat(e)}if(!this.connection||this.state!==IS.Connected)return void t.forEach(e=>{let{user:t,kind:i}=e;var n;if(i===gS.AUDIO)null===(n=t._audioTrack)||void 0===n||n._destroy(),t._audioTrack=void 0;else if(i===gS.VIDEO){var r;null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0}});const i=zi(e).call(e,(e,t)=>{let{user:i,mediaType:n}=t;const r=this.filterTobeUnSubscribedTracks(i,n);return e.concat(r)},[]);if(0===i.length)return;await this.connection.stopReceiving(i.map(e=>{let[,{id:t}]=e;return t}));const n=this.createUnsubscribeAllMessage(i);return this.withdrawRemoteTracks(i),0===this.remoteUserMap.size&&this.statsUploader.stopUploadDownlinkStats(),i.forEach(e=>{let[t,{kind:i}]=e;var n,r;i===gS.VIDEO&&t._videoSSRC&&(null===(n=this.connection)||void 0===n||n.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(i===gS.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0;else if(i===gS.AUDIO){var o;this.unbindRemoteTrackEvents(t._audioTrack),null===(o=t._audioTrack)||void 0===o||o._destroy(),t._audioTrack=void 0}}),n}async muteRemote(e,t){if(!this.connection)return;const i=this.remoteUserMap.get(e);if(!i)return void CE.warning("P2PChannel.muteRemote has no remote user ".concat(e.uid,"."));if(!i.get(t))return void CE.warning("P2PChannel.muteRemote has no remote user ".concat(e.uid," media type ").concat(t,"."));const n=t===gS.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==n&&this.connection.setStatsRemoteVideoIsReady(n,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.connection)return;const i=this.remoteUserMap.get(e);if(!i)return void CE.warning("P2PChannel.unmuteRemote has no remote user ".concat(e.uid,"."));i.get(t)||CE.warning("P2PChannel.unmuteRemote has no remote user ".concat(e.uid," media type ").concat(t,"."))}getAllTracks(e){const t=this.localTrackMap.get(RS.LocalAudioTrack);if((null==t?void 0:t.track)instanceof rI){const i=t.track;return Array.from(this.localTrackMap.entries()).filter(e=>{let[t]=e;return t!==RS.LocalAudioTrack}).filter(t=>{let[i]=t;return!(e&&i===RS.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===RS.LocalVideoLowTrack)}).map(e=>{let[,{track:t}]=e;return t})}reportPublishEvent(e,t,i,n,r){if(e){const i=this.localTrackMap.get(RS.LocalAudioTrack),o=n?this.localTrackMap.get(RS.LocalVideoLowTrack):this.localTrackMap.get(RS.LocalVideoTrack);Tg.publish(this.store.sessionId,{eventElapse:aI.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(aS.SCREEN_TRACK)),audio:!!i,video:!!o,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var o;i||(i=[]);const s=i.find(e=>e instanceof tI),a=n?null===(o=this.localTrackMap.get(RS.LocalVideoTrack))||void 0===o?void 0:o.track:i.find(e=>e instanceof QC);Tg.publish(this.store.sessionId,{eventElapse:aI.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(aS.SCREEN_TRACK)),audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,i,n){const r=n===gS.VIDEO?i._videoSSRC:i._audioSSRC;r&&Tg.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===gS.VIDEO,audio:n===gS.AUDIO,peerid:i.uid,subscribeRequestid:n===gS.VIDEO?i._videoSSRC:i._audioSSRC,p2pid:this.store.p2pId,eventElapse:aI.measureFromSubscribeStart(this.store.clientId,r)})}reset(){CE.debug("P2PChannel.reset"),this.mutex=new vg("P2PChannel-mutex"),this.connection&&(this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new Gb({},this.store):this.isPlanB?new ZO({},this.store):new sb({},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=IS.Disconnected}getStats(){var e;return null===(e=this.connection)||void 0===e?void 0:e.getStats()}getRemoteVideoIsReady(e){var t;return(null===(t=this.connection)||void 0===t?void 0:t.getRemoteVideoIsReady(e))||!1}getLocalAudioVolume(){const e=this.localTrackMap.get(RS.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(RS.LocalVideoTrack);if(e)return{width:e.track._videoWidth||0,height:e.track._videoHeight||0}}getEncoderConfig(e){const t=this.localTrackMap.get(e);return t&&t.track instanceof QC||t&&t.track instanceof tI?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;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(e);return!!i&&(!t||i.has(t))}getRemoteMedia(e){var t;const i=Array.from(ig(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}});const t=this.localTrackMap.get(RS.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=jm(e).call(e,(e,t)=>e.level-t.level),e}async disconnectForReconnect(){this.connection&&(CE.debug("P2PChannel.disconnectForReconnect closing P2PConnection"),this.state=IS.Reconnecting,FE("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach(e=>{var t,i,n,r;let[o]=e;null===(t=o._videoTrack)||void 0===t||null===(i=t._player)||void 0===i||null===(n=i.getVideoElement())||void 0===n||n.pause(),null===(r=o._videoTrack)||void 0===r||r._originMediaStreamTrack.stop()}),this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0,this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new Gb({},this.store):this.isPlanB?new ZO({},this.store):new sb({},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 RS.LocalVideoTrack:i._hints.includes(aS.LOW_STREAM)?i.close():this.pendingLocalTracks.push(i);break;case RS.LocalAudioTrack:i instanceof rI?this.pendingLocalTracks=this.pendingLocalTracks.concat(i.trackList):this.pendingLocalTracks.push(i);break;case RS.LocalVideoLowTrack:}}),this.emit(vS.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(ig(i).call(i)).forEach(e=>{this.setPendingRemoteMedia(t,e)}),this.emit(vS.MediaReconnectStart,t.uid)}),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),this.statsUploader.stopUploadUplinkStats(),this.statsUploader.stopUploadDownlinkStats(),this.statsUploader.stopUploadTransportStats(),CE.debug("P2PChannel disconnected, waiting to reconnect."))}hasPendingRemoteMedia(e,t){for(const i of this.pendingRemoteTracks){const{user:n,kind:r}=i;if((e instanceof $C?e.uid:e)===n.uid&&t===r)return!0}return!1}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t})}restartICE(){var e=this;return oO((function*(){if(!e.connection||e.state!==IS.Connected||e.connection instanceof Gb)return;const t=yield sO(e.mutex.lock("From P2PChannel.restartICE"));try{yield*cO(qb(e.connection.restartICE()),sO)}finally{t()}}))()}getUplinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats(),t=this.localTrackMap.get(RS.LocalVideoTrack),i=this.localTrackMap.get(RS.LocalAudioTrack),n=e.videoSend.find(e=>e.ssrc===(null==t?void 0:t.ssrcs[0].ssrcId)),r=e.audioSend.find(e=>e.ssrc===(null==i?void 0:i.ssrcs[0].ssrcId));if(!n||!r)return 1;const o=UI(this,vS.NeedSignalRTT),s=n?n.rttMs:void 0,a=r?r.rttMs:void 0,c=s&&a?(s+a)/2:s||a,d=(c&&o?(c+o)/2:c||o)||0,u=100*e.sendPacketLossRate*.7/50+.3*d/1500,l=u<.17?1:u<.36?2:u<.59?3:u<.1?4:5,h=null==t?void 0:t.track;if(h&&h._encoderConfig&&-1===h._hints.indexOf(aS.SCREEN_TRACK)){const t=h._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return YE[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][l]}}return l}getDownlinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach(i=>{let[n]=i;const r=n._audioSSRC,o=n._videoSSRC,s=e.audioRecv.find(e=>e.ssrc===r),a=e.videoRecv.find(e=>e.ssrc===o);if(!s&&!a)return void(t+=1);const c=UI(this,vS.NeedSignalRTT),d=e.rtt,u=(d&&c?(d+c)/2:d||c)||0,l=s?s.jitterMs:void 0,h=e.recvPacketLossRate;let p=.7*h*100/50+.3*u/1500;l&&(p=.6*h*100/50+.2*u/1500+.2*l/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 Sl((t,i)=>{this.handleMuteLocalTrack(e,t,i)})}filterTobePublishedTracks(e,t,i){const n=[],r=MS(),o=this.getAllTracks();e=FI(e=e.filter(e=>-1===o.indexOf(e)));let s=!1,a=!1;for(const o of e){if(o instanceof QC&&(this.localTrackMap.has(RS.LocalVideoTrack)||s?new EE(_E.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(n.push({track:o,type:RS.LocalVideoTrack}),s=!0),t)){const e=this.getLowVideoTrack(o,i);n.push({track:e,type:RS.LocalVideoLowTrack})}if(o instanceof tI){const e=this.localTrackMap.get(RS.LocalAudioTrack);if(e){if(!(e.track instanceof rI))throw new EE(_E.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(o._bypassWebAudio)throw new EE(_E.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(o),this.bindLocalAudioTrackEvents(o,!0)}else if(a){const e=n.find(e=>{let{type:t}=e;return t===RS.LocalAudioTrack});if(!(e.track instanceof rI))throw new EE(_E.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(o._bypassWebAudio)throw new EE(_E.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(o)}else{if(!r.webAudioMediaStreamDest||o instanceof rI||o._bypassWebAudio)n.push({track:o,type:RS.LocalAudioTrack});else{const e=new rI;e.addAudioTrack(o),n.push({track:e,type:RS.LocalAudioTrack})}a=!0}}}return n}filterTobeUnpublishedTracks(e){const t=[],i=this.getAllTracks();e=FI(e=e.filter(e=>-1!==i.indexOf(e)));for(const i of e){if(i instanceof tI){const e=this.localTrackMap.get(RS.LocalAudioTrack);if(!e)continue;e.track instanceof rI?(e.track.removeAudioTrack(i),this.unbindLocalAudioTrackEvents(i),0===e.track.trackList.length&&(t.push([RS.LocalAudioTrack,e]),e.track.close())):t.push([RS.LocalAudioTrack,e])}if(i instanceof QC){const e=this.localTrackMap.get(RS.LocalVideoTrack);if(!e)continue;t.push([RS.LocalVideoTrack,e]);const i=this.localTrackMap.get(RS.LocalVideoLowTrack);i&&t.push([RS.LocalVideoLowTrack,i])}}return t}bindLocalTrackEvents(e){e.forEach(e=>{let{track:t,type:i}=e;switch(i){case RS.LocalVideoTrack:t.addListener(sS.GET_STATS,this.handleGetLocalVideoStats),t.addListener(sS.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(sS.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(sS.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(sS.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.addListener(sS.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(sS.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(sS.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case RS.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);break;case RS.LocalVideoLowTrack:}})}bindLocalAudioTrackEvents(e,t){e instanceof rI?e.trackList.forEach(e=>{e.addListener(sS.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(sS.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(sS.GET_STATS,this.handleGetLocalAudioStats),e.addListener(sS.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(sS.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)}):(e.addListener(sS.GET_STATS,this.handleGetLocalAudioStats),e.addListener(sS.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(sS.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(sS.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(sS.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||e.addListener(sS.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 RS.LocalVideoTrack:t.off(sS.GET_STATS,this.handleGetLocalVideoStats),t.off(sS.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(sS.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(sS.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(sS.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.off(sS.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(sS.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(sS.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case RS.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);break;case RS.LocalVideoLowTrack:}})}unbindLocalAudioTrackEvents(e){e instanceof rI?e.trackList.forEach(e=>{e.off(sS.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(sS.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(sS.GET_STATS,this.handleGetLocalAudioStats),e.off(sS.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(sS.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)}):(e.off(sS.GET_STATS,this.handleGetLocalAudioStats),e.off(sS.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(sS.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(sS.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(sS.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(sS.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof Cb&&t.addListener(sS.GET_STATS,t=>{t(this.handleGetRemoteVideoStats(e))}),t instanceof yb&&t.addListener(sS.GET_STATS,t=>{t(this.handleGetRemoteAudioStats(e))})}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(sS.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t,i]=e;i.has(gS.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(gS.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack)})}createGatewayPublishMessage(e,t){return e.map((e,i)=>{let n,r,{track:o,type:s}=e;switch(s){case RS.LocalAudioTrack:n=iS.Audio,r={dtx:o instanceof iI&&o._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case RS.LocalVideoTrack:n=o._hints.includes(aS.SCREEN_TRACK)?iS.Screen:iS.High,r=Yb(Yb({},fI(o)),{},{codec:this.store.codec});break;case RS.LocalVideoLowTrack:n=iS.Low,r=Yb(Yb({},fI(o)),{},{codec:this.store.codec})}return{stream_type:n,attributes:r,ssrcs:t[i]}})}createGatewayUnpublishMessage(e){return e.map(e=>{let t,[i,{track:n,ssrcs:r,id:o}]=e;switch(i){case RS.LocalVideoTrack:t=n._hints.includes(aS.SCREEN_TRACK)?iS.Screen:iS.High;break;case RS.LocalAudioTrack:t=iS.Audio;break;case RS.LocalVideoLowTrack:t=iS.Low}return{stream_type:t,ssrcs:r,mid:o}})}assignLocalTracks(e,t){e.forEach((e,i)=>{let{track:n,type:r}=e;this.localTrackMap.set(r,{track:n,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(CE.info("[p2pId: ".concat(this.store.p2pId,"]: P2PConnection.onConnectionStateChange(").concat(t,")")),this.emit(vS.PeerConnectionStateChange,t),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),"disconnected"===t&&"disconnected"===e.iceConnectionState)return setTimeout(()=>{if("disconnected"===e.iceConnectionState&&FE("ICE_RESTART")){"CONNECTED"===UI(this,vS.QueryClientConnectionState)&&this.emit(vS.RequestRestartICE)}},800),void setTimeout(()=>{"disconnected"===e.peerConnectionState&&(CE.debug("P2PConnection disconnected timeout 4000ms, force reconnect"),setTimeout(()=>this.emit(vS.P2PLost),0),this.iceFailedCount+=1,this.requestReconnect())},4e3);"failed"===t&&(CE.debug("P2PConnection state failed, force reconnect"),setTimeout(()=>this.emit(vS.P2PLost),0),this.iceFailedCount+=1,await this.requestReconnect())},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),CE.info("[p2pId: ".concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),Tg.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:lf.TRACER}).onSuccess(),this.emit(vS.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{CE.info("[p2pId: ".concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{CE.info("[p2pId: ".concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{CE.info("[p2pId: ".concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},e.onFirstAudioDecoded=e=>{var t;const i=Array.from(ig(t=this.remoteUserMap).call(t)).find(t=>t._audioSSRC===e);var n;i&&(this.store.subscribe(i.uid,"audio",void 0,void 0,void 0,Date.now()),null===(n=i.audioTrack)||void 0===n||n.emit(lS.FIRST_FRAME_DECODED),Tg.firstRemoteFrame(this.store.sessionId,sf.FIRST_AUDIO_DECODE,af.FIRST_AUDIO_DECODE,{peer:i._uintid,subscribeElapse:aI.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;const i=Array.from(ig(t=this.remoteUserMap).call(t)).find(t=>t._audioSSRC===e);i&&Tg.firstRemoteFrame(this.store.sessionId,sf.FIRST_AUDIO_RECEIVED,af.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:aI.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;const i=Array.from(ig(t=this.remoteUserMap).call(t)).find(t=>t._videoSSRC===e);i&&Tg.firstRemoteFrame(this.store.sessionId,sf.FIRST_VIDEO_RECEIVED,af.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:aI.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onSelectedLocalCandidateChanged=(e,t)=>{const i="relay"===e.candidateType,n="relay"===t.candidateType;"unknown"!==t.candidateType&&i===n||this.emit(vS.ConnectionTypeChange,i),CE.info("[p2pId: ".concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(vI(t))," -> ").concat(JSON.stringify(vI(e)),")"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{CE.info("[p2pId: ".concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(vI(t))," -> ").concat(JSON.stringify(vI(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){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const i=this.localTrackMap.get(RS.LocalAudioTrack);if(e instanceof tI&&(null==i?void 0:i.track)instanceof rI)return i.track.isActive||t.push([RS.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i});if(n&&(t.push(n),n[0]===RS.LocalVideoTrack)){const e=this.localTrackMap.get(RS.LocalVideoLowTrack);e&&t.push([RS.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){const t=[],i=this.localTrackMap.get(RS.LocalAudioTrack);if(e instanceof tI&&(null==i?void 0:i.track)instanceof rI)return i.track.isActive&&t.push([RS.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i});if(n)if(n[0]===RS.LocalVideoTrack){t.push(n);const e=this.localTrackMap.get(RS.LocalVideoLowTrack);e&&t.push([RS.LocalVideoLowTrack,e])}else t.push(n);return t}createMuteMessage(e){return e.map(e=>{let t,[i,{track:n,ssrcs:r,id:o}]=e;switch(i){case RS.LocalAudioTrack:t=iS.Audio;break;case RS.LocalVideoTrack:t=n._hints.includes(aS.SCREEN_TRACK)?iS.Screen:iS.High;break;case RS.LocalVideoLowTrack:t=iS.Low}return{stream_type:t,ssrcs:r,mid:o}})}createUnmuteMessage(e){return e.map(e=>{let t,[i,{track:n,ssrcs:r,id:o}]=e;switch(i){case RS.LocalAudioTrack:t=iS.Audio;break;case RS.LocalVideoTrack:t=n._hints.includes(aS.SCREEN_TRACK)?iS.Screen:iS.High;break;case RS.LocalVideoLowTrack:t=iS.Low}return{stream_type:t,ssrcs:r,mid:o}})}filterTobeUnSubscribedTracks(e,t){const i=[],n=this.remoteUserMap.get(e);if(!n)return i;if(t){const r=n.get(t);if(!r)return i;i.push([e,{kind:t,id:r}])}else Array.from(n.entries()).forEach(t=>{let[n,r]=t;i.push([e,{kind:n,id:r}])});return i}createUnsubscribeMessage(e){const t=[];return e.forEach(e=>{let[i,{kind:n,id:r}]=e;switch(n){case gS.VIDEO:return void(i._videoSSRC&&t.push({stream_type:gS.VIDEO,ssrcId:i._videoSSRC}));case gS.AUDIO:return void(i._audioSSRC&&t.push({stream_type:gS.AUDIO,ssrcId:i._audioSSRC}))}}),t}createUnsubscribeAllMessage(e){const t=new Map;return e.forEach(e=>{let[i,{kind:n}]=e;if(t.has(i)){let e=t.get(i);n===gS.VIDEO?e|=rS.Video:e|=rS.Audio,t.set(i,e)}else n===gS.VIDEO?t.set(i,rS.Video):t.set(i,rS.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;const n=this.remoteUserMap.get(t);n&&(n.delete(i),0===Array.from(n.entries()).length&&this.remoteUserMap.delete(t))})}async updateBitrateLimit(e){const t=this.localTrackMap.get(RS.LocalVideoTrack),i=this.localTrackMap.get(RS.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(){if(this.connection){return"connected"!==this.connection.peerConnectionState}return!0}mapPubResToRemoteConfig(e,t){return e.map((e,i)=>{var n;let{stream_type:r}=e;return null===(n=t.find(e=>{let{stream_type:t}=e;return r===t}))||void 0===n?void 0:n.attributes})}async tryToUnmuteAudio(e){for(let i=0;i<e.length;i++)if(e[i]instanceof tI){var t;const n=this.filterTobeUnmutedTracks(e[i]);if(0===n.length)continue;await(null===(t=this.connection)||void 0===t?void 0:t.unmuteLocal(n.map(e=>{let[,{id:t}]=e;return t})));const r=this.createUnmuteMessage(n);return void await MI(this,vS.RequestUnmuteLocal,r)}}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)||void 0===t||!t.getRemoteVideoIsReady(e))},this.statsUploader.requestUpload=(e,t)=>this.emit(vS.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 OI(fE(this.dtlsFailedCount,mE)),this.emit(vS.RequestReconnect)}async reconnectP2P(){const e=Array.from(this.localTrackMap.entries()),t=this.createGatewayUnpublishMessage(e);Array.from(this.remoteUserMap.entries()),t.length>0&&await kI(this,vS.RequestUnpublishForReconnectPC,t),this.disconnectForReconnect(),this.emit(vS.RequestReconnectPC)}canPublishLowStream(){return this.localTrackMap.has(RS.LocalVideoTrack)||this.pendingLocalTracks.some(e=>e instanceof QC)}throwIfTrackTypeNotMatch(e){if(e.filter(e=>e instanceof QC).length>1)throw new EE(_E.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter(e=>e instanceof tI).length>1&&(e.some(e=>e instanceof tI&&e._bypassWebAudio)||!MS().webAudioMediaStreamDest))throw new EE(_E.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(const t of e){if(t instanceof QC&&this.pendingLocalTracks.some(e=>e instanceof QC))throw new EE(_E.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof tI&&this.pendingLocalTracks.some(e=>e instanceof tI)&&(!MS().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some(e=>e instanceof tI&&e._bypassWebAudio)))throw new EE(_E.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(e,t){const i=MS().supportDualStreamEncoding,n=Yb(Yb({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=i?e._mediaStreamTrack.clone():cb(e,n);const o=wI(8,"track-low-"),s=new QC(r,Yb(Yb({},i&&{scaleResolutionDownBy:II(n,e)}),{},{frameRate:n.framerate,bitrateMax:n.bitrate,bitrateMin:n.bitrate}),void 0,void 0,o);return s._hints.push(aS.LOW_STREAM),e.addListener(sS.NEED_CLOSE,()=>{s.close()}),s}async globalLock(){return this.mutex.lock("From P2PChannel.globalLock")}reportVideoFirstFrameDecoded(e,t,i,n){var r;const o=Array.from(ig(r=this.remoteUserMap).call(r)).find(t=>t._videoSSRC===e);if(o){n||this.store.subscribe(o.uid,"video",void 0,void 0,void 0,void 0,Date.now());const r=this.store.keyMetrics,s=r.subscribe.find(e=>e.userId===o.uid&&"video"===e.type);Tg.firstRemoteVideoDecode(this.store.sessionId,sf.FIRST_VIDEO_DECODE,af.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:i,subscribeElapse:aI.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:r.requestAPEnd||0,apStart:r.requestAPStart||0,joinGwEnd:r.joinGatewayEnd||0,joinGwStart:r.joinGatewayStart||0,pcEnd:r.peerConnectionEnd||0,pcStart:r.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:n?1:0})}}async remoteMediaSsrcChanged(e,t,i){if(!this.connection)return!1;const n=this.remoteUserMap.get(e);if(!n)return!1;const r=n.get(t);if(!r)return!1;const o=await this.connection.getRemoteSSRC(r);return void 0!==o&&o!==i}resetConnection(e){CE.debug("[P2PChannel] reset connection to ".concat(e)),this.state===IS.Connected?(CE.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===oS.datachannel?new Gb({},this.store):this.isPlanB?new ZO({},this.store):new sb({},this.store),this.bindConnectionEvents(this.connection)))}}).prototype,"startP2PConnection",[zb],Object.getOwnPropertyDescriptor(Hb.prototype,"startP2PConnection"),Hb.prototype),JT(Hb.prototype,"connect",[zb],Object.getOwnPropertyDescriptor(Hb.prototype,"connect"),Hb.prototype),JT(Hb.prototype,"preConnect",[zb],Object.getOwnPropertyDescriptor(Hb.prototype,"preConnect"),Hb.prototype),JT(Hb.prototype,"unpublish",[zb],Object.getOwnPropertyDescriptor(Hb.prototype,"unpublish"),Hb.prototype),JT(Hb.prototype,"unpublishLowStream",[zb],Object.getOwnPropertyDescriptor(Hb.prototype,"unpublishLowStream"),Hb.prototype),JT(Hb.prototype,"subscribe",[zb],Object.getOwnPropertyDescriptor(Hb.prototype,"subscribe"),Hb.prototype),JT(Hb.prototype,"massSubscribe",[zb],Object.getOwnPropertyDescriptor(Hb.prototype,"massSubscribe"),Hb.prototype),JT(Hb.prototype,"unsubscribe",[zb],Object.getOwnPropertyDescriptor(Hb.prototype,"unsubscribe"),Hb.prototype),JT(Hb.prototype,"massUnsubscribe",[zb],Object.getOwnPropertyDescriptor(Hb.prototype,"massUnsubscribe"),Hb.prototype),JT(Hb.prototype,"muteRemote",[zb],Object.getOwnPropertyDescriptor(Hb.prototype,"muteRemote"),Hb.prototype),JT(Hb.prototype,"unmuteRemote",[zb],Object.getOwnPropertyDescriptor(Hb.prototype,"unmuteRemote"),Hb.prototype),JT(Hb.prototype,"hasRemoteMediaWithLock",[zb],Object.getOwnPropertyDescriptor(Hb.prototype,"hasRemoteMediaWithLock"),Hb.prototype),JT(Hb.prototype,"disconnectForReconnect",[zb],Object.getOwnPropertyDescriptor(Hb.prototype,"disconnectForReconnect"),Hb.prototype),JT(Hb.prototype,"updateBitrateLimit",[zb],Object.getOwnPropertyDescriptor(Hb.prototype,"updateBitrateLimit"),Hb.prototype),JT(Hb.prototype,"remoteMediaSsrcChanged",[zb],Object.getOwnPropertyDescriptor(Hb.prototype,"remoteMediaSsrcChanged"),Hb.prototype),Hb);function zb(e,t,i){const n=e[t];if("function"!=typeof n)throw new Error("Cannot use mutex on object property.");return i.value=async function(){const e=this.mutex,i=await e.lock("From P2PChannel.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return await n.apply(this,o)}finally{i()}},i}function Qb(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function Zb(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Qb(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Qb(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}var $b;!function(e){e.SET_SESSION_ID="SET_SESSION_ID",e.SET_P2P_ID="SET_P2P_id",e.SET_DC_ID="SET_DC_id",e.SET_UID="SET_UID",e.SET_PUB_ID="SET_PUB_ID",e.SET_CLOUD_PROXY_SERVER_MODE="SET_CLOUD_PROXY_SERVER_MODE",e.KEY_METRIC_CLIENT_CREATED="KEY_METRIC_CLIENT_CREATED",e.KEY_METRIC_JOIN_START="KEY_METRIC_JOIN_START",e.AVOID_JOIN_START="AVOID_JOIN_START",e.KEY_METRIC_JOIN_END="KEY_METRIC_JOIN_END",e.KEY_METRIC_REQUEST_AP_START="KEY_METRIC_REQUEST_AP_START",e.KEY_METRIC_REQUEST_AP_END="KEY_METRIC_REQUEST_AP_END",e.KEY_METRIC_JOIN_GATEWAY_START="KEY_METRIC_JOIN_GATEWAY_START",e.KEY_METRIC_JOIN_GATEWAY_END="KEY_METRIC_JOIN_GATEWAY_END",e.KEY_METRIC_PEER_CONNECTION_START="KEY_METRIC_PEER_CONNECTION_START",e.KEY_METRIC_PEER_CONNECTION_END="KEY_METRIC_PEER_CONNECTION_END",e.KEY_METRIC_ICE_CONNECTION_END="KEY_METRIC_ICE_CONNECTION_END",e.KEY_METRIC_SIGNAL_CHANNEL_OPEN="KEY_METRIC_SIGNAL_CHANNEL_OPEN",e.KEY_METRIC_PUBLISH="KEY_METRIC_PUBLISH",e.KEY_METRIC_SUBSCRIBE="KEY_METRIC_SUBSCRIBE",e.RECORD_JOIN_CHANNEL_SERVICE="RECORD_JOIN_CHANNEL_SERVICE",e.RESET_JOIN_CHANNEL_SERVICE_RECORDS="RESET_JOIN_CHANNEL_SERVICE_RECORDS",e.RESET_KEY_METRICS="RESET_KEY_METRICS",e.SET_USE_DATACHANNEL="SET_USE_DATACHANNEL"}($b||($b={}));class ew{constructor(e,t,i,n){lp(this,"state",void 0),this.state={codec:e,audioCodec:t,mode:i,clientId:n,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 $b.SET_SESSION_ID:return Zb(Zb({},e),{},{sessionId:t.sessionId});case $b.SET_P2P_ID:return Zb(Zb({},e),{},{p2pId:t.p2pId});case $b.SET_UID:return Zb(Zb({},e),{},{uid:t.uid});case $b.SET_PUB_ID:return Zb(Zb({},e),{},{pubId:t.pubId});case $b.KEY_METRIC_CLIENT_CREATED:return Zb(Zb({},e),{},{keyMetrics:Zb(Zb({},e.keyMetrics),{},{clientCreated:t.metric})});case $b.KEY_METRIC_JOIN_START:return Zb(Zb({},e),{},{keyMetrics:Zb(Zb({},e.keyMetrics),{},{joinStart:t.metric})});case $b.AVOID_JOIN_START:return Zb(Zb({},e),{},{avoidJoinStart:t.avoidJoinStart});case $b.KEY_METRIC_JOIN_END:return Zb(Zb({},e),{},{keyMetrics:Zb(Zb({},e.keyMetrics),{},{joinEnd:t.metric})});case $b.KEY_METRIC_REQUEST_AP_START:return Zb(Zb({},e),{},{keyMetrics:Zb(Zb({},e.keyMetrics),{},{requestAPStart:t.metric})});case $b.KEY_METRIC_REQUEST_AP_END:return Zb(Zb({},e),{},{keyMetrics:Zb(Zb({},e.keyMetrics),{},{requestAPEnd:t.metric})});case $b.KEY_METRIC_JOIN_GATEWAY_START:return Zb(Zb({},e),{},{keyMetrics:Zb(Zb({},e.keyMetrics),{},{joinGatewayStart:t.metric})});case $b.KEY_METRIC_JOIN_GATEWAY_END:return Zb(Zb({},e),{},{keyMetrics:Zb(Zb({},e.keyMetrics),{},{joinGatewayEnd:t.metric})});case $b.KEY_METRIC_PEER_CONNECTION_START:return Zb(Zb({},e),{},{keyMetrics:Zb(Zb({},e.keyMetrics),{},{peerConnectionStart:t.metric})});case $b.KEY_METRIC_PEER_CONNECTION_END:return Zb(Zb({},e),{},{keyMetrics:Zb(Zb({},e.keyMetrics),{},{peerConnectionEnd:t.metric})});case $b.KEY_METRIC_SIGNAL_CHANNEL_OPEN:return Zb(Zb({},e),{},{keyMetrics:Zb(Zb({},e.keyMetrics),{},{signalChannelOpen:t.metric})});case $b.KEY_METRIC_ICE_CONNECTION_END:return Zb(Zb({},e),{},{keyMetrics:Zb(Zb({},e.keyMetrics),{},{iceConnectionEnd:t.metric})});case $b.KEY_METRIC_PUBLISH:{const i=e.keyMetrics.publish,n=i.findIndex(e=>e.trackId===t.metric.trackId);return-1!==n?(i[n]=Zb(Zb({},i[n]),t.metric),Zb(Zb({},e),{},{keyMetrics:Zb(Zb({},e.keyMetrics),{},{publish:[...i]})})):Zb(Zb({},e),{},{keyMetrics:Zb(Zb({},e.keyMetrics),{},{publish:[...e.keyMetrics.publish,t.metric]})})}case $b.KEY_METRIC_SUBSCRIBE:{const i=e.keyMetrics.subscribe,n=i.findIndex(e=>e.userId===t.metric.userId&&e.type===t.metric.type);return-1!==n?(i[n]=Zb(Zb({},i[n]),t.metric),Zb(Zb({},e),{},{keyMetrics:Zb(Zb({},e.keyMetrics),{},{subscribe:[...i]})})):Zb(Zb({},e),{},{keyMetrics:Zb(Zb({},e.keyMetrics),{},{subscribe:[...e.keyMetrics.subscribe,t.metric]})})}case $b.SET_CLOUD_PROXY_SERVER_MODE:return e.cloudProxyServerMode=t.mode,e;case $b.RECORD_JOIN_CHANNEL_SERVICE:return"number"!=typeof t.index?e.joinChannelServiceRecords=[...e.joinChannelServiceRecords,t.record]:(e.joinChannelServiceRecords[t.index]=Zb(Zb({},e.joinChannelServiceRecords[t.index]),t.record),e.joinChannelServiceRecords=[...e.joinChannelServiceRecords]),e;case $b.RESET_JOIN_CHANNEL_SERVICE_RECORDS:return e.joinChannelServiceRecords=[],e;case $b.RESET_KEY_METRICS:return e.keyMetrics={publish:[],subscribe:[]},e;case $b.SET_USE_DATACHANNEL:return Zb(Zb({},e),{},{useDataChannel:t.val});default:return e}}(this.state,e)}set sessionId(e){this.dispatch({type:$b.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:$b.SET_P2P_ID,p2pId:e})}get p2pId(){return this.state.p2pId}set dcId(e){this.dispatch({type:$b.SET_DC_ID,dcId:e})}get dcId(){return this.state.dcId}set uid(e){this.dispatch({type:$b.SET_UID,uid:e})}get uid(){return this.state.uid}set pubId(e){this.dispatch({type:$b.SET_PUB_ID,pubId:e})}get pubId(){return this.state.pubId}set cloudProxyServerMode(e){this.dispatch({type:$b.SET_CLOUD_PROXY_SERVER_MODE,mode:e})}get cloudProxyServerMode(){return this.state.cloudProxyServerMode}set useDataChannel(e){this.dispatch({type:$b.SET_USE_DATACHANNEL,val:e})}get useDataChannel(){return this.state.useDataChannel}clientCreated(){this.dispatch({type:$b.KEY_METRIC_CLIENT_CREATED,metric:Date.now()})}joinStart(){this.dispatch({type:$b.KEY_METRIC_JOIN_START,metric:Date.now()})}joinEnd(){this.dispatch({type:$b.KEY_METRIC_JOIN_END,metric:Date.now()})}requestAPStart(){this.dispatch({type:$b.KEY_METRIC_REQUEST_AP_START,metric:Date.now()})}requestAPEnd(){this.dispatch({type:$b.KEY_METRIC_REQUEST_AP_END,metric:Date.now()})}joinGatewayStart(){this.dispatch({type:$b.KEY_METRIC_JOIN_GATEWAY_START,metric:Date.now()})}joinGatewayEnd(){this.dispatch({type:$b.KEY_METRIC_JOIN_GATEWAY_END,metric:Date.now()})}peerConnectionStart(){this.dispatch({type:$b.KEY_METRIC_PEER_CONNECTION_START,metric:Date.now()})}peerConnectionEnd(){this.dispatch({type:$b.KEY_METRIC_PEER_CONNECTION_END,metric:Date.now()})}signalChannelOpen(){this.dispatch({type:$b.KEY_METRIC_SIGNAL_CHANNEL_OPEN,metric:Date.now()})}iceConnectionEnd(){this.dispatch({type:$b.KEY_METRIC_ICE_CONNECTION_END,metric:Date.now()})}publish(e,t,i,n){this.dispatch({type:$b.KEY_METRIC_PUBLISH,metric:Zb(Zb({trackId:e,type:t},i&&{publishStart:i}),n&&{publishEnd:n})})}subscribe(e,t,i,n,r,o,s){this.dispatch({type:$b.KEY_METRIC_SUBSCRIBE,metric:Zb(Zb(Zb(Zb(Zb({userId:e,type:t},i&&{subscribeStart:i}),n&&{subscribeEnd:n}),r&&{firstFrame:r}),o&&{streamAdded:o}),s&&{firstDecoded:s})})}massSubscribe(e,t,i,n){e.forEach(e=>{this.dispatch({type:$b.KEY_METRIC_SUBSCRIBE,metric:Zb(Zb(Zb({userId:e.userId,type:e.type},t&&{subscribeStart:t}),i&&{subscribeEnd:i}),n&&{firstFrame:n})})})}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:$b.RECORD_JOIN_CHANNEL_SERVICE,record:Zb(Zb({},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:$b.RECORD_JOIN_CHANNEL_SERVICE,record:e,index:t}),t)}catch(e){return 0}}resetJoinChannelServiceRecords(){this.dispatch({type:$b.RESET_JOIN_CHANNEL_SERVICE_RECORDS})}resetKeyMetrics(){this.dispatch({type:$b.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:$b.AVOID_JOIN_START,avoidJoinStart:e})}}let tw;const iw=()=>"HTTPS"===(tw||tw||(tw=(window.location.protocol.split(":")[0]||"").toUpperCase(),tw)),nw=()=>void 0!==window.isSecureContext;function rw(e){let t=Ew();return function(e,t){let i=e.appId;void 0!==i&&(ww(t,10),Iw(t,i));let n=e.cid;void 0!==n&&(ww(t,16),ww(t,n));let r=e.cname;void 0!==r&&(ww(t,26),Iw(t,r));let o=e.deviceId;void 0!==o&&(ww(t,34),Iw(t,o));let s=e.elapse;void 0!==s&&(ww(t,40),Nw(t,s));let a=e.fileSize;void 0!==a&&(ww(t,48),Nw(t,pw(a)));let c=e.height;void 0!==c&&(ww(t,56),Nw(t,pw(c)));let d=e.jpg;void 0!==d&&(ww(t,66),ww(t,d.length),function(e,t){let i=Tw(e,t.length);e.bytes.set(t,i)}(t,d));let u=e.networkType;void 0!==u&&(ww(t,72),Nw(t,pw(u)));let l=e.osType;void 0!==l&&(ww(t,80),Nw(t,pw(l)));let h=e.requestId;void 0!==h&&(ww(t,90),Iw(t,h));let p=e.sdkVersion;void 0!==p&&(ww(t,98),Iw(t,p));let _=e.sequence;void 0!==_&&(ww(t,104),Nw(t,pw(_)));let E=e.sid;void 0!==E&&(ww(t,114),Iw(t,E));let m=e.timestamp;void 0!==m&&(ww(t,120),Nw(t,m));let f=e.uid;void 0!==f&&(ww(t,128),ww(t,f));let S=e.vid;void 0!==S&&(ww(t,136),ww(t,S));let T=e.width;void 0!==T&&(ww(t,144),Nw(t,pw(T)));let g=e.service;void 0!==g&&(ww(t,152),ww(t,g));let R=e.callbackData;void 0!==R&&(ww(t,162),Iw(t,R));let I=e.jpgEncryption;void 0!==I&&(ww(t,168),ww(t,I));let v=e.requestType;void 0!==v&&(ww(t,176),ww(t,v));let C=e.scorePorn;void 0!==C&&(ww(t,185),Ow(t,C));let y=e.scoreSexy;void 0!==y&&(ww(t,193),Ow(t,y));let A=e.scoreNeutral;void 0!==A&&(ww(t,201),Ow(t,A));let O=e.scene;void 0!==O&&(ww(t,208),ww(t,O));let b=e.ossFilePrefix;void 0!==b&&(ww(t,218),Iw(t,b));let w=e.serviceVendor;if(void 0!==w)for(let e of w){ww(t,226);let i=Ew();aw(e,i),ww(t,i.limit),vw(t,i),mw(i)}}(e,t),function(e){let t=e.bytes,i=e.limit;return t.length===i?t:t.subarray(0,i)}(t)}function ow(e){return function(e){let t={};e:for(;!Sw(e);){let i=bw(e);switch(i>>>3){case 0:break e;case 1:t.code=bw(e);break;case 2:t.msg=Rw(e,bw(e));break;case 3:{let i=cw(e);t.data=sw(e),e.limit=i;break}default:dw(e,7&i)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function sw(e){let t={};e:for(;!Sw(e);){let i=bw(e);switch(i>>>3){case 0:break e;case 1:t.requestId=Rw(e,bw(e));break;case 2:t.requestType=bw(e)>>>0;break;case 3:t.scorePorn=Aw(e);break;case 4:t.scoreSexy=Aw(e);break;case 5:t.scoreNeutral=Aw(e);break;case 6:t.requestScene=bw(e)>>>0;break;case 7:t.scene=bw(e)>>>0;break;default:dw(e,7&i)}}return t}function aw(e,t){let i=e.service;void 0!==i&&(ww(t,8),ww(t,i));let n=e.vendor;void 0!==n&&(ww(t,16),ww(t,n));let r=e.token;void 0!==r&&(ww(t,26),Iw(t,r));let o=e.callbackUrl;void 0!==o&&(ww(t,34),Iw(t,o))}function cw(e){let t=bw(e),i=e.limit;return e.limit=e.offset+t,i}function dw(e,t){switch(t){case 0:for(;128&Cw(e););break;case 2:fw(e,bw(e));break;case 5:fw(e,4);break;case 1:fw(e,8);break;default:throw new Error("Unimplemented type: "+t)}}let uw=new Float32Array(1);new Uint8Array(uw.buffer);let lw=new Float64Array(1),hw=new Uint8Array(lw.buffer);function pw(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let _w=[];function Ew(){const e=_w.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function mw(e){_w.push(e)}function fw(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function Sw(e){return e.offset>=e.limit}function Tw(e,t){let i=e.bytes,n=e.offset,r=e.limit,o=n+t;if(o>i.length){let t=new Uint8Array(2*o);t.set(i),e.bytes=t}return e.offset=o,o>r&&(e.limit=o),n}function gw(e,t){let i=e.offset;if(i+t>e.limit)throw new Error("Read past limit");return e.offset+=t,i}function Rw(e,t){let i=gw(e,t),n=String.fromCharCode,r=e.bytes,o="<22>",s="";for(let e=0;e<t;e++){let a,c,d,u,l=r[e+i];0==(128&l)?s+=n(l):192==(224&l)?e+1>=t?s+=o:(a=r[e+i+1],128!=(192&a)?s+=o:(u=(31&l)<<6|63&a,u<128?s+=o:(s+=n(u),e++))):224==(240&l)?e+2>=t?s+=o:(a=r[e+i+1],c=r[e+i+2],32896!=(49344&(a|c<<8))?s+=o:(u=(15&l)<<12|(63&a)<<6|63&c,u<2048||u>=55296&&u<=57343?s+=o:(s+=n(u),e+=2))):240==(248&l)?e+3>=t?s+=o:(a=r[e+i+1],c=r[e+i+2],d=r[e+i+3],8421504!=(12632256&(a|c<<8|d<<16))?s+=o:(u=(7&l)<<18|(63&a)<<12|(63&c)<<6|63&d,u<65536||u>1114111?s+=o:(u-=65536,s+=n(55296+(u>>10),56320+(1023&u)),e+=3))):s+=o}return s}function Iw(e,t){let i=t.length,n=0;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)-56613888),n+=r<128?1:r<2048?2:r<65536?3:4}ww(e,n);let r=Tw(e,n),o=e.bytes;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)-56613888),n<128?o[r++]=n:(n<2048?o[r++]=n>>6&31|192:(n<65536?o[r++]=n>>12&15|224:(o[r++]=n>>18&7|240,o[r++]=n>>12&63|128),o[r++]=n>>6&63|128),o[r++]=63&n|128)}}function vw(e,t){let i=Tw(e,t.limit),n=e.bytes,r=t.bytes;for(let e=0,o=t.limit;e<o;e++)n[e+i]=r[e]}function Cw(e){return e.bytes[gw(e,1)]}function yw(e,t){let i=Tw(e,1);e.bytes[i]=t}function Aw(e){let t=gw(e,8),i=e.bytes;return hw[0]=i[t++],hw[1]=i[t++],hw[2]=i[t++],hw[3]=i[t++],hw[4]=i[t++],hw[5]=i[t++],hw[6]=i[t++],hw[7]=i[t++],lw[0]}function Ow(e,t){let i=Tw(e,8),n=e.bytes;lw[0]=t,n[i++]=hw[0],n[i++]=hw[1],n[i++]=hw[2],n[i++]=hw[3],n[i++]=hw[4],n[i++]=hw[5],n[i++]=hw[6],n[i++]=hw[7]}function bw(e){let t,i=0,n=0;do{t=Cw(e),i<32&&(n|=(127&t)<<i),i+=7}while(128&t);return n}function ww(e,t){for(t>>>=0;t>=128;)yw(e,127&t|128),t>>>=7;yw(e,t)}function Nw(e,t){let i=t.low>>>0,n=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,o=0===r?0===n?i<16384?i<128?1:2:i<1<<21?3:4:n<16384?n<128?5:6:n<1<<21?7:8:r<128?9:10,s=Tw(e,o),a=e.bytes;switch(o){case 10:a[s+9]=r>>>7&1;case 9:a[s+8]=9!==o?128|r:127&r;case 8:a[s+7]=8!==o?n>>>21|128:n>>>21&127;case 7:a[s+6]=7!==o?n>>>14|128:n>>>14&127;case 6:a[s+5]=6!==o?n>>>7|128:n>>>7&127;case 5:a[s+4]=5!==o?128|n:127&n;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}}const Dw=async(e,t,i)=>{const n=function(e){const 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){const t="0123456789abcdef";function i(e){let i,n="";for(i=0;i<=3;i++)n+=t.charAt(e>>8*i+4&15)+t.charAt(e>>8*i&15);return n}function n(e,t){const i=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(i>>16)<<16|65535&i}function r(e,t,i,r,o,s){return n(function(e,t){return e<<t|e>>>32-t}(n(n(t,e),n(r,s)),o),i)}function o(e,t,i,n,o,s,a){return r(t&i|~t&n,e,t,o,s,a)}function s(e,t,i,n,o,s,a){return r(t&n|i&~n,e,t,o,s,a)}function a(e,t,i,n,o,s,a){return r(t^i^n,e,t,o,s,a)}function c(e,t,i,n,o,s,a){return r(i^(t|~n),e,t,o,s,a)}const d=function(e){let t;const i=1+(e.length+8>>6),n=new Array(16*i);for(t=0;t<16*i;t++)n[t]=0;for(t=0;t<e.length;t++)n[t>>2]|=e.charCodeAt(t)<<t%4*8;return n[t>>2]|=128<<t%4*8,n[16*i-2]=8*e.length,n}(e);let u,l,h,p,_,E=1732584193,m=-271733879,f=-1732584194,S=271733878;for(u=0;u<d.length;u+=16)l=E,h=m,p=f,_=S,E=o(E,m,f,S,d[u+0],7,-680876936),S=o(S,E,m,f,d[u+1],12,-389564586),f=o(f,S,E,m,d[u+2],17,606105819),m=o(m,f,S,E,d[u+3],22,-1044525330),E=o(E,m,f,S,d[u+4],7,-176418897),S=o(S,E,m,f,d[u+5],12,1200080426),f=o(f,S,E,m,d[u+6],17,-1473231341),m=o(m,f,S,E,d[u+7],22,-45705983),E=o(E,m,f,S,d[u+8],7,1770035416),S=o(S,E,m,f,d[u+9],12,-1958414417),f=o(f,S,E,m,d[u+10],17,-42063),m=o(m,f,S,E,d[u+11],22,-1990404162),E=o(E,m,f,S,d[u+12],7,1804603682),S=o(S,E,m,f,d[u+13],12,-40341101),f=o(f,S,E,m,d[u+14],17,-1502002290),m=o(m,f,S,E,d[u+15],22,1236535329),E=s(E,m,f,S,d[u+1],5,-165796510),S=s(S,E,m,f,d[u+6],9,-1069501632),f=s(f,S,E,m,d[u+11],14,643717713),m=s(m,f,S,E,d[u+0],20,-373897302),E=s(E,m,f,S,d[u+5],5,-701558691),S=s(S,E,m,f,d[u+10],9,38016083),f=s(f,S,E,m,d[u+15],14,-660478335),m=s(m,f,S,E,d[u+4],20,-405537848),E=s(E,m,f,S,d[u+9],5,568446438),S=s(S,E,m,f,d[u+14],9,-1019803690),f=s(f,S,E,m,d[u+3],14,-187363961),m=s(m,f,S,E,d[u+8],20,1163531501),E=s(E,m,f,S,d[u+13],5,-1444681467),S=s(S,E,m,f,d[u+2],9,-51403784),f=s(f,S,E,m,d[u+7],14,1735328473),m=s(m,f,S,E,d[u+12],20,-1926607734),E=a(E,m,f,S,d[u+5],4,-378558),S=a(S,E,m,f,d[u+8],11,-2022574463),f=a(f,S,E,m,d[u+11],16,1839030562),m=a(m,f,S,E,d[u+14],23,-35309556),E=a(E,m,f,S,d[u+1],4,-1530992060),S=a(S,E,m,f,d[u+4],11,1272893353),f=a(f,S,E,m,d[u+7],16,-155497632),m=a(m,f,S,E,d[u+10],23,-1094730640),E=a(E,m,f,S,d[u+13],4,681279174),S=a(S,E,m,f,d[u+0],11,-358537222),f=a(f,S,E,m,d[u+3],16,-722521979),m=a(m,f,S,E,d[u+6],23,76029189),E=a(E,m,f,S,d[u+9],4,-640364487),S=a(S,E,m,f,d[u+12],11,-421815835),f=a(f,S,E,m,d[u+15],16,530742520),m=a(m,f,S,E,d[u+2],23,-995338651),E=c(E,m,f,S,d[u+0],6,-198630844),S=c(S,E,m,f,d[u+7],10,1126891415),f=c(f,S,E,m,d[u+14],15,-1416354905),m=c(m,f,S,E,d[u+5],21,-57434055),E=c(E,m,f,S,d[u+12],6,1700485571),S=c(S,E,m,f,d[u+3],10,-1894986606),f=c(f,S,E,m,d[u+10],15,-1051523),m=c(m,f,S,E,d[u+1],21,-2054922799),E=c(E,m,f,S,d[u+8],6,1873313359),S=c(S,E,m,f,d[u+15],10,-30611744),f=c(f,S,E,m,d[u+6],15,-1560198380),m=c(m,f,S,E,d[u+13],21,1309151649),E=c(E,m,f,S,d[u+4],6,-145523070),S=c(S,E,m,f,d[u+11],10,-1120210379),f=c(f,S,E,m,d[u+2],15,718787259),m=c(m,f,S,E,d[u+9],21,-343485551),E=n(E,l),m=n(m,h),f=n(f,p),S=n(S,_);return i(E)+i(m)+i(f)+i(S)}(""+t+i)).slice(0,16),r=n.slice(0,12),o=await window.crypto.subtle.importKey("raw",n,"AES-GCM",!0,["encrypt"]);return new Uint8Array(await window.crypto.subtle.encrypt({name:"AES-GCM",iv:r},o,e))};function Pw(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}const Lw=new Map([["moderation",1],["supervise",2]]);class kw extends hE{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(NS.CONNECTION_STATE_CHANGE,t,e)}get inspectType(){return this._inspectType}set inspectType(e){var t;this._inspectMode=zi(t=e.map(e=>Lw.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(),lp(this,"name","AgoraRTCVideoContentInspect"),lp(this,"_connectionState",bS.CONNECTING),lp(this,"_innerConnectionState",void 0),lp(this,"sequence",0),lp(this,"inspectStartTime",void 0),lp(this,"workerManagerConnection",void 0),lp(this,"workerConnection",void 0),lp(this,"workerMessageLengthLimit",void 0),lp(this,"inspectIntervalMinimum",void 0),lp(this,"qualityRatio",void 0),lp(this,"_connectInfo",void 0),lp(this,"_cancelTokenSource",uE.CancelToken.source()),lp(this,"_retryConfig",void 0),lp(this,"wmSequence",0),lp(this,"inspectInterval",void 0),lp(this,"inspectTimer",null),lp(this,"ossFilePrefix",void 0),lp(this,"extraInfo",void 0),lp(this,"_inspectType",void 0),lp(this,"_inspectMode",void 0),lp(this,"_quality",1),lp(this,"qualityTimer",null),lp(this,"_inspectId",void 0),lp(this,"_needWorkUrlOnly",!1),lp(this,"inspectImage",()=>{if(this.connectionState!==bS.CONNECTED)throw new EE(_E.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===bS.CONNECTED?this.requestToInspectImage():CE.debug("[".concat(this._inspectId,"] Inspect State is not connected , "),this.connectionState)},this.inspectInterval<this.inspectIntervalMinimum?this.inspectIntervalMinimum:this.inspectInterval),this.requestToInspectImage()}),this._inspectId=wI(5,"inspect-"),this.workerMessageLengthLimit=FE("VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT"),this.inspectIntervalMinimum=FE("VIDEO_INSPECT_INTERVAL_MINIMUM"),this.qualityRatio=FE("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 tv("worker-manager-"+this._inspectId,mE),this.on(NS.STATE_CHANGE,(e,t)=>{this._innerConnectionState=e,CE.debug("[".concat(this._inspectId,"] Inspect operation :").concat(wS[e]," ").concat(t||""))}),this.handleWorkerManagerEvents(),this.workerConnection=new tv("worker-"+this._inspectId,mE),this.handleWorkerEvents()}async init(e,t){this.emit(NS.STATE_CHANGE,wS.CONNECT_AP),this._connectInfo=e;const i=this._cancelTokenSource.token;return this._retryConfig=t,new Sl((n,r)=>{this.on(NS.CONNECTION_STATE_CHANGE,(e,t)=>{t===bS.CONNECTED&&n()}),this.requestAP(e,i,t).then(e=>{this.connectWorkerManager(e)}).catch(e=>{r(e)})})}async requestAP(e,t,i){const n=FE("WEBCS_DOMAIN").map(e=>"https://".concat(e,"/api/v1")),r=await function(e,t,i,n){let{appId:r,areaCode:o,cname:s,sid:a,token:c,uid:d}=t;xv++;const u="image_moderation_api",l={service_name:u,json_body:JSON.stringify({appId:r,areaCode:o,cname:s,command:"allocateEdge",requestId:xv,seq:xv,sid:a,token:c,ts:Date.now(),uid:d+""})};let h,p,_=e[0];return SE(async()=>{h=Date.now();const e=await ag(_,{data:l,cancelToken:i,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(p=Date.now()-h,0!==e.code){const t=new EE(_E.UNEXPECTED_RESPONSE,"image inspect ap error, code"+e.code,{retry:!0,responseTime:p});throw CE.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new EE(_E.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw CE.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new EE(_E.UNEXPECTED_RESPONSE,"image inspect ap empty server",{code:t.code,responseTime:p});throw CE.error(e.toString()),e}const n=FE("VIDEO_INSPECT_WORKER_MANAGER_HOST"),r=FE("VIDEO_INSPECT_WORKER_MANAGER_PORT");return{addressList:t.servers.map(e=>{let{address:t,wss:i}=e;if(t&&i)return"wss://".concat(t.replace(/\./g,"-"),".").concat(n,":").concat(r||i)}).filter(e=>!!e),workerToken:t.workerToken,vid:t.vid,responseTime:p}},(t,i)=>(Tg.apworkerEvent(a,{success:!0,sc:200,serviceName:u,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===i,responseTime:p,serverIp:e[i%e.length]}),!1),(t,i)=>(Tg.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:u,responseTime:p,serverIp:e[i%e.length]}),!!(t.code!==_E.OPERATION_ABORTED&&t.code!==_E.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(i+1)%e.length],!0)),n)}(n,e,t,i);this.emit(NS.STATE_CHANGE,wS.AP_CONNECTED);const{addressList:o}=r;return this.wmSequence++,o}async connectWorkerManager(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._needWorkUrlOnly=t,this.emit(NS.STATE_CHANGE,wS.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(e,1e4)}async connectWorker(e){await this.workerConnection.init([e])}handleWorkerManagerEvents(){this.workerManagerConnection.on(jf.CONNECTED,async()=>{this.emit(NS.STATE_CHANGE,wS.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.17.0",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(jf.CLOSED,()=>{this._innerConnectionState<wS.GET_WORKER_MANAGER_RESPONSE&&CE.debug("[".concat(this._inspectId,"] Inspect worker manager is closed before connecting worker"))}),this.workerManagerConnection.on(jf.FAILED,()=>{this._innerConnectionState<wS.GET_WORKER_MANAGER_RESPONSE&&CE.debug("[".concat(this._inspectId,"] Connecting inspect worker manager is failed before connecting worker"))}),this.workerManagerConnection.on(jf.RECONNECTING,()=>{this._innerConnectionState<wS.GET_WORKER_MANAGER_RESPONSE&&CE.debug("[".concat(this._inspectId,"] Inspect worker manager is reconnecting before connecting worker"))}),this.workerManagerConnection.on(jf.ON_MESSAGE,async e=>{this.emit(NS.STATE_CHANGE,wS.GET_WORKER_MANAGER_RESPONSE);const t=this.workerManagerConnection.url;this.workerManagerConnection.close();const i=JSON.parse(e.data);if(200!==i.code)throw CE.error("[".concat(this._inspectId,"] Unexpected code ").concat(i.code," from worker manager")),new EE(_E.UNEXPECTED_RESPONSE,"response code of worker is unexpected",i);if(!(i.serverResponse&&i.serverResponse.portWss&&t))throw CE.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(i))),new EE(_E.UNEXPECTED_RESPONSE,"response content of worker is unexpected",i);{const e=FE("VIDEO_INSPECT_WORKER_PORT")||i.serverResponse.portWss,n=t.replace(/:\d+\/?$/,":".concat(e));this.emit(NS.STATE_CHANGE,wS.CONNECT_WORKER,n),this._needWorkUrlOnly?this.emit(NS.REQUEST_NEW_WORKER_URL,n):await this.connectWorker(n)}}),this.workerManagerConnection.on(jf.WILL_RECONNECT,(e,t)=>{t(e)}),this.workerManagerConnection.on(jf.REQUEST_NEW_URLS,(e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)})}handleWorkerEvents(){this.workerConnection.on(jf.CONNECTED,async()=>{this.emit(NS.STATE_CHANGE,wS.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=bS.CONNECTED}),this.workerConnection.on(jf.ON_MESSAGE,async e=>{if(e.data instanceof ArrayBuffer){const i=ow(new Uint8Array(e.data));if(FE("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")&&CE.debug("[".concat(this._inspectId,"] Response message for worker of inspect content "),JSON.stringify(i)),200===i.code){if(Array.isArray(this.inspectType)&&1===this.inspectType.length&&"supervise"===this.inspectType[0])return void this.emit(NS.INSPECT_RESULT,void 0,void 0);if(i.data&&i.data.scorePorn&&i.data.scoreSexy&&i.data.scoreNeutral){var t;const e={porn:i.data.scorePorn,sexy:i.data.scoreSexy,neutral:i.data.scoreNeutral},n=zi(t=Object.keys(e)).call(t,(t,i)=>e[t]>e[i]?t:i,"porn"),r=Object.keys(e).find(e=>e===n);this.emit(NS.INSPECT_RESULT,r)}else this.emit(NS.INSPECT_RESULT,void 0,new EE(_E.UNEXPECTED_RESPONSE,i.code+"","There is an unexpected data on message"))}else this.emit(NS.INSPECT_RESULT,void 0,new EE(_E.UNEXPECTED_RESPONSE,i.code+"",i.msg))}else CE.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit(NS.INSPECT_RESULT,void 0,new EE(_E.UNEXPECTED_RESPONSE,"invalid worker message type"))}),this.workerConnection.on(jf.CLOSED,()=>{this.connectionState=bS.CLOSED}),this.workerConnection.on(jf.FAILED,()=>{this.connectionState=bS.CLOSED}),this.workerConnection.on(jf.RECONNECTING,()=>{this.connectionState=this.connectionState===bS.CONNECTED?bS.RECONNECTING:bS.CONNECTING}),this.workerConnection.on(jf.WILL_RECONNECT,(e,t)=>{"recover"===e&&t(e),t("tryNext")}),this.workerConnection.on(jf.REQUEST_NEW_URLS,(e,t)=>{this.workerManagerConnection.close(),this.once(NS.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++;const e=UI(this,NS.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(NS.INSPECT_RESULT,void 0,new EE(_E.INVALID_OPERATION,"Only the track being played can be inspected"));const i=await this.generateRequestData(e,t);this.workerConnection.sendMessage(i,!0,!0)}else this.emit(NS.INSPECT_RESULT,void 0,new EE(_E.INVALID_OPERATION,"Only the track being published can be inspected"))}async generateRequestData(e,t){let{appId:i,cname:n,cid:r,vid:o,sid:s,uid:a}=t;const c=Date.now(),d=await e.getCurrentFrameImage("image/jpeg",this.quality),u=await(async(e,t,i)=>await Dw(e.buffer,t,i))(d,i,n),l=this.sequence+"-"+r+"-"+a+"-"+c+"-"+wI(12,""),h={appId:i,cid:r,cname:n,deviceId:"",elapse:kw.intToLong(Number(c-this.inspectStartTime)),fileSize:u.byteLength,jpgEncryption:2,height:d.height,width:d.width,jpg:u,networkType:6,osType:7,requestId:l,sdkVersion:"4.17.0",sequence:this.sequence,sid:s,timestamp:kw.intToLong(c),uid:a,vid:o,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};void 0===this.extraInfo&&delete h.callbackData,void 0===this.ossFilePrefix&&delete h.ossFilePrefix;const p=rw(h);if(p.byteLength<this.workerMessageLengthLimit){if(FE("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")){const e=function(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){lp(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}({},h);delete e.jpg,CE.debug("[".concat(this._inspectId,"] Request message for worker of inspect content "),JSON.stringify(e))}return p}{const t=this.quality*this.qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:i,cname:n,cid:r,vid:o,sid:s,uid:a})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=uE.CancelToken.source(),this.workerManagerConnection&&this.workerManagerConnection.close(),this.workerConnection&&this.workerConnection.close(),this.inspectTimer&&window.clearInterval(this.inspectTimer),this.inspectTimer=null,this.connectionState=bS.CLOSED,this.emit(NS.STATE_CHANGE,wS.CLOSED)}}var Mw,Uw,xw,Vw,Fw,jw,Bw,Gw,Ww,Hw,Kw,Yw,qw,Jw,Xw,zw,Qw,Zw,$w,eN,tN,iN,nN,rN,oN,sN,aN,cN,dN,uN,lN,hN,pN,_N,EN,mN,fN,SN,TN;function gN(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function RN(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?gN(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):gN(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let IN=(Mw=Sg(),Uw=Sg({argsMap:(e,t)=>(Array.isArray(t)||(t=[t]),t.map(e=>e?Object(e).toString():"null"))}),xw=Sg({argsMap:(e,t)=>(t||(t=[]),Array.isArray(t)||(t=[t]),t.map(e=>e.getTrackId()))}),Vw=Sg({argsMap:(e,t,i)=>[t.uid,i]}),Fw=Sg({argsMap:(e,t)=>t.map(e=>{let{user:t,mediaType:i}=e;return[null==t?void 0:t.uid,i]})}),jw=Sg({argsMap:(e,t,i)=>[t.uid,i]}),Bw=Sg({argsMap:(e,t)=>t.map(e=>{let{user:t,mediaType:i}=e;return{uid:null==t?void 0:t.uid,mediaType:i}})}),Gw=Sg(),Ww=Sg(),Hw=Sg(),Kw=Sg(),Yw=Sg(),qw=Sg(),Jw=Sg(),Xw=Sg(),zw=Sg(),Qw=Sg(),Zw=Sg(),$w=Sg(),eN=Sg(),tN=Sg(),iN=Sg({argsMap:(e,t)=>[t]}),nN=Sg(),rN=Sg(),oN=Sg(),sN=Sg(),aN=Sg(),cN=Sg(),dN=Sg(),uN=Sg(),lN=Sg(),hN=Sg(),pN=Sg({argsMap:(e,t)=>(Array.isArray(t)||(t=[t]),[JSON.stringify(t)])}),_N=Sg(),EN=Sg(),mN=Sg(),fN=Sg({reportResult:!0}),SN=Sg(),JT((TN=class extends hE{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(),lp(this,"store",void 0),lp(this,"_uid",void 0),lp(this,"_channelName",void 0),lp(this,"_uintUid",void 0),lp(this,"_users",[]),lp(this,"_codec",void 0),lp(this,"_mode",void 0),lp(this,"_config",void 0),lp(this,"_clientId",void 0),lp(this,"_appId",void 0),lp(this,"_sessionId",null),lp(this,"_key",void 0),lp(this,"_joinInfo",void 0),lp(this,"_gateway",void 0),lp(this,"_statsCollector",void 0),lp(this,"_configDistribute",void 0),lp(this,"_leaveMutex",new vg("client-leave")),lp(this,"_publishMutex",new vg("client-publish")),lp(this,"_renewTokenMutex",new vg("client-renewtoken")),lp(this,"_subscribeMutex",new vg("client-subscribe")),lp(this,"_encryptionMode","none"),lp(this,"_encryptionSecret",null),lp(this,"_encryptionSalt",null),lp(this,"_proxyServer",void 0),lp(this,"_turnServer",{servers:[],mode:"auto"}),lp(this,"_cloudProxyServerMode","disabled"),lp(this,"_isDualStreamEnabled",!1),lp(this,"_defaultStreamFallbackType",void 0),lp(this,"_lowStreamParameter",void 0),lp(this,"_streamFallbackTypeCacheMap",new Map),lp(this,"_remoteStreamTypeCacheMap",new Map),lp(this,"_axiosCancelSource",uE.CancelToken.source()),lp(this,"_audioVolumeIndicationInterval",void 0),lp(this,"_networkQualityInterval",void 0),lp(this,"_userOfflineTimeout",void 0),lp(this,"_streamRemovedTimeout",void 0),lp(this,"_injectStreamingClient",void 0),lp(this,"_liveTranscodeStreamingClient",void 0),lp(this,"_liveRawStreamingClient",void 0),lp(this,"_channelMediaRelayClient",void 0),lp(this,"_networkQualitySensitivity","normal"),lp(this,"_p2pChannel",void 0),lp(this,"_useLocalAccessPoint",!1),lp(this,"_setLocalAPVersion",void 0),lp(this,"_joinAndNotLeaveYet",!1),lp(this,"_numberOfJoinCount",0),lp(this,"_remoteDefaultVideoStreamType",void 0),lp(this,"_inspect",void 0),lp(this,"_license",void 0),lp(this,"_handleLocalTrackEnable",(e,t,i)=>{this.publish(e,!1).then(t).catch(i)}),lp(this,"_handleLocalTrackDisable",(e,t,i)=>{this.unpublish(e).then(t).catch(i)}),lp(this,"_handleUserOnline",e=>{this.isStringUID&&"string"!=typeof e.uid&&CE.error("[".concat(this._clientId,"] StringUID is Mixed with UintUID"));const t=this._users.find(t=>t.uid===e.uid);if(t)t._trust_in_room_=!0;else{const t=new $C(e.uid,e.uint_id||e.uid);this._users.push(t),CE.debug("[".concat(this._clientId,"] user online"),e.uid),this.emit(Rf.USER_JOINED,t)}}),lp(this,"_handleUserOffline",e=>{const t=this._users.find(t=>t.uid===e.uid);t&&(this._handleRemoveStream(e),VI(this._users,t),this._remoteStreamTypeCacheMap.delete(t.uid),this._streamFallbackTypeCacheMap.delete(t.uid),CE.debug("[".concat(this._clientId,"] user offline"),e.uid,"reason:",e.reason),this.emit(Rf.USER_LEAVED,t,e.reason))}),lp(this,"_handleAddAudioOrVideoStream",(e,t,i,n,r,o,s)=>{const a=this._users.find(e=>e.uid===t);if(!a)return void CE.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));CE.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());const c="audio"===e?a.hasAudio:a.hasVideo;a._uintid||(a._uintid=r||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!==n&&(a._cname=n),o&&(a._audioOrtc=o)):(a._video_added_=!0,void 0!==i&&(a._videoSSRC=i),void 0!==n&&(a._cname=n),void 0!==s&&(a._rtxSsrcId=s),o&&(a._videoOrtc=o)),("audio"===e?a.hasAudio:a.hasVideo)&&!c&&(CE.info("[".concat(this._clientId,"] remote user ").concat(a.uid," published ").concat(e)),this.emit(Rf.USER_PUBLISHED,a,e)),"video"===e?Tg.onGatewayStream(this._sessionId,sf.ON_ADD_VIDEO_STREAM,af.ON_ADD_VIDEO_STREAM,{peer:r||t}):Tg.onGatewayStream(this._sessionId,sf.ON_ADD_AUDIO_STREAM,af.ON_ADD_AUDIO_STREAM,{peer:r||t}),this._p2pChannel.remoteMediaSsrcChanged(a,e,i).then(t=>{if(t)return CE.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=>{CE.error("[".concat(this._clientId,"] resubscribe error"),e.toString())}))}),this._p2pChannel.hasPendingRemoteMedia(a,e)&&(CE.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(a.uid," after reconnect.")),this._subscribe(a,e,!0).catch(e=>{CE.error("[".concat(this._clientId,"] resubscribe error"),e.toString())}))}),lp(this,"_handleRemoveStream",e=>{const t=this._users.find(t=>t.uid===e.uid);if(!t)return void CE.warning("[".concat(this._clientId,"] can not find target user!(on_remove_stream)"));CE.debug("[".concat(this._clientId,"] stream removed with uid ").concat(e.uid));let i=()=>{};t.hasAudio&&t.hasVideo?i=()=>{CE.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.emit(Rf.USER_UNPUBLISHED,t,"audio"),CE.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.emit(Rf.USER_UNPUBLISHED,t,"video")}:t.hasVideo?i=()=>{CE.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.emit(Rf.USER_UNPUBLISHED,t,"video")}:t.hasAudio&&(i=()=>{CE.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.emit(Rf.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,Tg.onGatewayStream(this._sessionId,sf.ON_REMOVE_STREAM,af.ON_REMOVE_STREAM,{peer:e.uint_id||e.uid}),i()}),lp(this,"_handleSetStreamLocalEnable",(e,t,i)=>{const n=this._users.find(e=>e.uid===t);if(!n)return void CE.error("[".concat(this._clientId,"] can not find target user!(disable_local)"));CE.debug("[".concat(this._clientId,"] local ").concat(e," ").concat(i?"enabled":"disabled"," with uid ").concat(t));const r="audio"===e?n.hasAudio:n.hasVideo;if("audio"===e){n._trust_audio_enabled_state_=!0;const e=n._audio_enabled_;if(n._audio_enabled_=i,n._audio_enabled_===e)return;{const e=n._audio_enabled_?"enable-local-audio":"disable-local-audio";CE.debug("[".concat(this._clientId,"] user-info-updated, uid: ").concat(t,", msg: ").concat(e)),this.emit(Rf.USER_INFO_UPDATED,t,e)}}else{n._trust_video_enabled_state_=!0;const e=n._video_enabled_;if(n._video_enabled_=i,n._video_enabled_===e)return;{const e=n._video_enabled_?"enable-local-video":"disable-local-video";CE.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(t,", msg: ").concat(e)),this.emit(Rf.USER_INFO_UPDATED,t,e)}}const o="audio"===e?n.hasAudio:n.hasVideo;return r!==o?!r&&o?(CE.info("[".concat(this._clientId,"] remote user ").concat(t," published ").concat(e)),void this.emit(Rf.USER_PUBLISHED,n,e)):("video"===e&&n._videoTrack&&n._videoTrack._destroy(),"audio"===e&&n._audioTrack,this._p2pChannel.muteRemote(n,e),CE.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished ").concat(e)),void this.emit(Rf.USER_UNPUBLISHED,n,e)):void 0}),lp(this,"_handleMuteStream",(e,t,i)=>{CE.debug("[".concat(this._clientId,"] receive mute message"),e,t,i);const n=this._users.find(t=>t.uid===e);if(!n)return void CE.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(e));const r="audio"===t?n.hasAudio:n.hasVideo;if("audio"===t){n._trust_audio_mute_state_=!0;const t=n._audio_muted_;if(n._audio_muted_=i,n._audio_muted_===t)return;{const t=n._audio_muted_?"mute-audio":"unmute-audio";CE.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.emit(Rf.USER_INFO_UPDATED,e,t)}}else{n._trust_video_mute_state_=!0;const t=n._video_muted_;if(n._video_muted_=i,n._video_muted_===t)return;{const t=n._video_muted_?"mute-video":"unmute-video";CE.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.emit(Rf.USER_INFO_UPDATED,e,t)}}const o="audio"===t?n.hasAudio:n.hasVideo;if(r!==o){if(!r&&o){return("audio"===t?n._audioSSRC:n._videoSSRC)?(CE.info("[".concat(this._clientId,"] remote user ").concat(e," published ").concat(t)),void this.emit(Rf.USER_PUBLISHED,n,t)):void CE.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&&n._videoTrack&&n._videoTrack._destroy(),"audio"===t&&n._audioTrack,this._p2pChannel.muteRemote(n,t),CE.info("[".concat(this._clientId,"] remote user ").concat(e," unpublished ").concat(t)),this.emit(Rf.USER_UNPUBLISHED,n,t)}}),lp(this,"_handleP2PLost",async e=>{CE.debug("[".concat(this._clientId,"] receive p2p lost"),e),parseInt(e.p2pid,10)===this.store.p2pId?await this._p2pChannel.requestReconnect():CE.warning("P2PLost stream not found",e)}),lp(this,"_handleTokenWillExpire",()=>{CE.debug("[".concat(this._clientId,"] received message onTokenPrivilegeWillExpire")),this.emit(Rf.ON_TOKEN_PRIVILEGE_WILL_EXPIRE)}),lp(this,"_handleBeforeUnload",e=>{"beforeunload"===e.type&&void 0!==e.returnValue&&""!==e.returnValue||(this.leave(),CE.info("[".concat(this._clientId,"] auto leave onbeforeunload or pagehide")))}),lp(this,"_handleUpdateNetworkQuality",()=>{if("normal"===this._networkQualitySensitivity)return;if(navigator&&void 0!==navigator.onLine&&!navigator.onLine)return void this.emit(Rf.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6});const e={downlinkNetworkQuality:0,uplinkNetworkQuality:0};e.uplinkNetworkQuality=this._p2pChannel.getUplinkNetworkQuality(),e.downlinkNetworkQuality=this._p2pChannel.getDownlinkNetworkQuality(),this.emit(Rf.NETWORK_QUALITY,e)}),this._codec=e.codec,this._mode=e.mode,this._clientId=wI(5,"client-"),this.store=new ew(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),CE.info("[".concat(this._clientId,"] Initializing AgoraRTC client v").concat(AE," build: ").concat(yE,", mode: ").concat(this._mode,", codec: ").concat(this._codec)),e.clientRoleOptions)try{kf(e.clientRoleOptions),t=Object.assign({},e.clientRoleOptions)}catch(e){CE.warning("[".concat(this._clientId,"] ").concat(e.toString()))}this._statsCollector=new uI(this.store),this._statsCollector.onStatsException=(e,t,i)=>{CE.debug("[".concat(this._clientId,"] receive exception msg, code: ").concat(e,", msg: ").concat(t,", uid: ").concat(i)),this.emit(Rf.EXCEPTION,{code:e,msg:t,uid:i})},this._statsCollector.onUploadPublishDuration=(e,t,i,n)=>{const r=this._users.find(t=>t.uid===e);r&&Tg.peerPublishStatus(this._sessionId,{subscribeElapse:n,audioPublishDuration:t,videoPublishDuration:i,peer:r._uintid})},this.store.useDataChannel=MS().supportDataChannel&&FE("SIGNAL_CHANNEL"),this._gateway=new Ev(this.store,{clientId:this._clientId,mode:this._mode,codec:this._codec,websocketRetryConfig:e.websocketRetryConfig||mE,httpRetryConfig:e.httpRetryConfig||mE,forceWaitGatewayResponse:void 0===e.forceWaitGatewayResponse||e.forceWaitGatewayResponse,statsCollector:this._statsCollector,role:e.role,clientRoleOptions:t}),this._config=e,this._configDistribute=new Jv,this._p2pChannel=new Xb(this.store,this._statsCollector),this._handleP2PChannelEvents(),this._handleGatewayEvents(),this._handleGatewaySignalEvents()}async join(e,t,i,n,r){const o=++this._numberOfJoinCount;this.store.joinStart(),n&&(this.store.uid=n);const s=iw(),a=nw()?window.isSecureContext:"Browser Not Support";if(!nw()&&!s||!window.isSecureContext){const e="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";CE.warning(e)}const c=NI();"DISCONNECTED"===this.connectionState&&(this.store.avoidJoinStart=Math.round(Date.now()),CE.debug("[".concat(this._clientId,"] set avoidJoinStart to ").concat(this.store.avoidJoinStart)));const d=Tg.reportApiInvoke(c,{name:uf.JOIN,options:[e,t,i,n],states:{isHttps:s,isSecureContext:a},tag:lf.TRACER});Tg.setAppId(e);try{if(!i&&null!==i)throw new EE(_E.INVALID_PARAMS,"Invalid token: ".concat(i,". If you don not use token, set it to null"));i&&Km(i,"token",1,2047),Km(e,"appid",1,2047),qm(t),n&&Jm(n),r&&Km(r,"optionalInfo",1,2047)}catch(e){throw d.onError(e),e}if(CE.info("[".concat(this._clientId,"] start join channel ").concat(t,", join number: ").concat(o)),this._leaveMutex.isLocked){CE.debug("[".concat(this._clientId,"] join: waiting leave operation"));(await this._leaveMutex.lock())(),CE.debug("[".concat(this._clientId,"] join: continue"))}if(this._joinAndNotLeaveYet=!0,"DISCONNECTED"!==this.connectionState){const e=new EE(_E.INVALID_OPERATION,"[".concat(this._clientId,"] Client already in connecting/connected state"));throw d.onError(e),e}this._sessionId||(this._sessionId=c,this.store.sessionId=this._sessionId),this._gateway.state="CONNECTING";const u=RN({clientId:this._clientId,appId:e,sid:this._sessionId,cname:t,uid:"string"!=typeof n?n:null,turnServer:this._turnServer,proxyServer:this._proxyServer,token:i||e,cloudProxyServer:this._cloudProxyServerMode,optionalInfo:r,license:this._license,useLocalAccessPoint:this._useLocalAccessPoint},void 0!==this._remoteDefaultVideoStreamType&&{defaultVideoStream:this._remoteDefaultVideoStreamType});if(this._useLocalAccessPoint&&(u.setLocalAPVersion=this._setLocalAPVersion),"string"==typeof n&&(u.stringUid=n,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=>{const t=HI("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCMnXAHkKIGAM+x4N22gCI+Wyu\nSTM9ztkT3uYslTT2PuKmZfPzhH6kVdO7PTjGCOZnAsyb3oTtWat0KcxQ4jxvqQV+\nHvYl3iI1Yd4vl2c3qRMJPLtRDfNxa2Mcxgq7e9aEUibzdd0st+OJAy3tOj/Y0aVy\nxQiYDz3vqa6bP29adwIDAQAB"),i=await window.crypto.subtle.importKey("spki",t,{name:"RSA-OAEP",hash:"SHA-256"},!0,["encrypt"]),n=pg(e),r=await window.crypto.subtle.encrypt({name:"RSA-OAEP"},i,n);return KI(new Uint8Array(r))})(this._encryptionSecret),!this._joinAndNotLeaveYet)throw new EE(_E.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this._encryptionSalt&&(u.aessalt=this._encryptionSalt)}this._startSession(this._sessionId,{channel:t,appId:e});const l=this._sessionId;setTimeout(()=>{"CONNECTING"===this.connectionState&&l===this._sessionId&&Tg.joinChannelTimeout(this._sessionId,5)},5e3);try{let n;const r=u.cloudProxyServer;if(["proxy3","proxy4","proxy5"].includes(r)){const e=FE("PROXY_SERVER_TYPE3");Array.isArray(e)?u.proxyServer=e[0]:u.proxyServer=e}if(Tg.setProxyServer(u.proxyServer),CE.setProxyServer(u.proxyServer),this.store.requestAPStart(),u.stringUid&&!u.uid){const e=await jv(u.stringUid,u,this._axiosCancelSource.token,this._config.httpRetryConfig||mE,this.store);CE.debug("getUserAccount Success ".concat(u.stringUid," => ").concat(e)),u.uid=e,n=await Fv(u,this._axiosCancelSource.token,this._config.httpRetryConfig||mE,!0,this.store)}else n=await Fv(u,this._axiosCancelSource.token,this._config.httpRetryConfig||mE,!0,this.store);if(!this._joinAndNotLeaveYet)throw new EE(_E.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this.store.requestAPEnd(),setTimeout(()=>{this._configDistribute.startGetConfigDistribute(u,this._axiosCancelSource.token),this._configDistribute.on(SS.UPDATE_BITRATE_LIMIT,e=>{this._p2pChannel.updateBitrateLimit(e)})},0),this._key=i||e;const o=n.gatewayInfo;this._joinInfo=RN(RN({},u),{},{cid:o.cid,uid:u.uid?u.uid:o.uid,vid:o.vid,apResponse:o.res,uni_lbs_ip:o.uni_lbs_ip,gatewayAddrs:o.gatewayAddrs});const s=await this._joinGateway();if(!this._joinAndNotLeaveYet)throw new EE(_E.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));d.onSuccess(s),this._appId=e,this._channelName=u.cname,this._uid=s,this.store.uid=s,setTimeout(()=>{this._networkQualityInterval&&window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=window.setInterval(this._handleUpdateNetworkQuality,2e3),window.addEventListener(Wh()?"beforeunload":"pagehide",this._handleBeforeUnload)},0);const a=u.stringUid?"string uid: ".concat(u.stringUid,",uid: ").concat(u.uid):"uid: ".concat(this._uid);return CE.info("[".concat(this._clientId,"] Joining channel success: channel: ").concat(t,",").concat(a)),setTimeout(()=>{CE.startUpload()},5e3),this.store.joinEnd(),h=this,qE.includes(h)||qE.push(h),s}catch(e){const t=Array.isArray(e)?e[0]:e;throw CE.error("[".concat(this._clientId,"] join number: ").concat(o,", Joining channel failed, rollback"),t),t.code!==_E.OPERATION_ABORTED&&this._numberOfJoinCount===o&&(this._gateway.state="DISCONNECTED",this._reset()),d.onError(t),t}var h}_joinGateway(){if(!this._joinInfo||!this._key)throw new EE(_E.INVALID_OPERATION);return this._gateway.join(this._joinInfo,this._key,!("disabled"!==this._joinInfo.cloudProxyServer||this._joinInfo.proxyServer||!FE("JOIN_WITH_FALLBACK_SIGNAL_PROXY"))).then(e=>e).catch(e=>{if(e.code===_E.INIT_WEBSOCKET_TIMEOUT)return this._gateway.leave(!0,gf.FALLBACK),e;if(e.code===_E.INIT_DATACHANNEL_TIMEOUT)return this._gateway.leave(!0,gf.FALLBACK),e;throw e}).then(e=>{if(e instanceof EE){if(e.code===_E.INIT_WEBSOCKET_TIMEOUT){if(CE.info("[".concat(this._clientId,"] join timeout, fallback to proxy")),!this._joinInfo||!this._key)throw new EE(_E.INVALID_OPERATION);this._joinInfo.cloudProxyServer="fallback",this._cloudProxyServerMode="fallback",this.store.cloudProxyServerMode="fallback";const e=FE("PROXY_SERVER_TYPE3");if(Array.isArray(e))if(this._joinInfo.apUrl){const 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;const t=FE("LOG_UPLOAD_SERVER").match(/.+:(\d{1,5})$/);t&&t[1]&&"443"!==t[1]&&CE.setProxyServer(this._joinInfo.proxyServer),"443"!==FE("STATS_COLLECTOR_PORT").toString()&&Tg.setProxyServer(this._joinInfo.proxyServer);return Tg.reportApiInvoke(this._sessionId,{name:uf.JOIN_FALLBACK_TO_PROXY,options:[this._joinInfo.proxyServer],tag:lf.TRACER}).onSuccess(),this.emit(Rf.JOIN_FALLBACK_TO_PROXY,this._joinInfo.proxyServer),this._gateway.join(this._joinInfo,this._key)}if(CE.info("[".concat(this._clientId,"] join by datachannel timeout, fallback to websocket")),!this._joinInfo||!this._key)throw new EE(_E.INVALID_OPERATION);return Tg.reportApiInvoke(this._sessionId,{name:uf.DATACHANNEL_FAILBACK,options:[this.store.clientId],tag:lf.TRACER}).onSuccess(),this._joinGateway()}return e}).then(e=>e)}async leave(){CE.info("[".concat(this._clientId,"] Leaving channel")),window.removeEventListener(Wh()?"beforeunload":"pagehide",this._handleBeforeUnload),this._reset(),function(e){const t=qE.indexOf(e);-1!==t&&qE.splice(t,1)}(this);const e=await this._leaveMutex.lock();if("DISCONNECTED"===this.connectionState)return CE.info("[".concat(this._clientId,"] Leaving channel repeated, success")),void e();await this._gateway.leave("CONNECTED"!==this.connectionState),CE.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 EE(_E.INVALID_PARAMS,"track list is empty");if("audience"===this._gateway.role)throw new EE(_E.INVALID_OPERATION,"audience can not publish stream");for(const i of e){if(!(i instanceof yg))throw new EE(_E.INVALID_PARAMS,"parameter is not local track");if(!i._enabled&&t)throw new EE(_E.TRACK_IS_DISABLED,"can not publish a disabled track: ".concat(i.getTrackId()))}CE.info("[".concat(this._clientId,"] Publishing tracks, id ").concat(e.map(e=>"".concat(e.getTrackId()," ")))),await this._configDistribute.awaitConfigDistributeComplete(),t&&e.forEach(e=>{const t=this._configDistribute.getBitrateLimit();e instanceof QC&&t&&e.setBitrateLimit(t.uplink)});const i=await this._publishMutex.lock();try{await this._publishHighStream(e),CE.info("[".concat(this._clientId,"] Publish success, id ").concat(e.map(e=>"".concat(e.getTrackId()," "))))}catch(e){throw CE.error("[".concat(this._clientId,"] publish error"),e.toString()),e}finally{i()}}async unpublish(e){if(!this._joinInfo||void 0===this._uid)throw new EE(_E.INVALID_OPERATION,"Can't unpublish stream, haven't joined yet!");e?Array.isArray(e)||(e=[e]):e=this._p2pChannel.getAllTracks(!0),CE.info("[".concat(this._clientId,"] Unpublish tracks, tracks ").concat(e.map(e=>"".concat(e.getTrackId()," "))," "));const t=await this._publishMutex.lock();try{const i=await this._p2pChannel.unpublish(e);i&&await this._gateway.unpublish(i,this._uid),CE.info("[".concat(this._clientId,"] Unpublish success,tracks ").concat(e.map(e=>"".concat(e.getTrackId()))))}catch(e){throw CE.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(Gm(t,"mediaType",["audio","video"]),!this._joinInfo)throw new EE(_E.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new EE(_E.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));if(!this._users.find(t=>t===e)){const t=new EE(_E.INVALID_REMOTE_USER,"user is not in the channel");throw CE.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),t}if(!e.hasAudio&&!e.hasVideo){const t=new EE(_E.INVALID_REMOTE_USER,"user is not published");throw CE.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))){const i=new EE(_E.REMOTE_USER_IS_NOT_PUBLISHED);throw CE.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),i}const n="audio"===t?e._audioSSRC:e._videoSSRC,r="audio"===t?e._audioOrtc:e._videoOrtc,o="video"===t?e._rtxSsrcId:void 0,s={stream_type:"audio"===t?gS.AUDIO:gS.VIDEO,ssrcId:n},a=await this._subscribeMutex.lock();CE.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{aI.markSubscribeStart(this.store.clientId,n),this.store.subscribe(e.uid,t,Date.now()),await this._p2pChannel.subscribe(e,t,n,o,r);try{await this._gateway.subscribe(e.uid,s,!0)}catch(i){if((null==i?void 0:i.code)!==_E.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}CE.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch(e=>{CE.warning("[".concat(this._clientId,"] auto set fallback failed"),e)});const i="audio"===t?e._audioTrack:e._videoTrack;if(!i)throw new EE(_E.UNEXPECTED_ERROR,"can not find remote track in user object");return i}catch(t){throw CE.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{a()}}async massSubscribe(e){if(Ym(e,"subscribeList"),!this._joinInfo)throw new EE(_E.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new EE(_E.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const t=Date.now(),i=new Map,n=await this._subscribeMutex.lock();CE.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("; ")));const r=(e=[...e]).map(e=>{let{user:t,mediaType:i}=e;return{user:t,mediaType:i}}),o=await this._p2pChannel.globalLock();try{var s;for(let t=e.length-1;t>=0;t--){const n=e[t],{user:o,mediaType:s}=n;if(Gm(s,"mediaType",["audio","video"]),!o){const e=new EE(_E.INVALID_PARAMS,"user property does not exist in subscribeList item");throw CE.error("[".concat(this._clientId,"] user property does not exist in subscribeList item")),e}if(!this._users.find(e=>e===o)){const i=new EE(_E.INVALID_REMOTE_USER,"user is not in the channel");CE.error("[".concat(this._clientId,"] can not massSubscribe ").concat(o.uid,", this user is not in the channel")),r[t].error=i,e.splice(t,1);continue}if("audio"===s&&(!o.hasAudio||void 0===o._audioSSRC)||"video"===s&&(!o.hasVideo||void 0===o._videoSSRC)){const i=new EE(_E.REMOTE_USER_IS_NOT_PUBLISHED);CE.error("[".concat(this._clientId,"] can not subscribe ").concat(o.uid," with mediaType ").concat(s,", remote user is not published")),r[t].error=i,e.splice(t,1);continue}const a=rS.Video|rS.LwoVideo,c=i.get(o);if(c){if("video"===s?c&a:c&rS.Audio){e.splice(t,1),CE.warning("repeat massSubscribe user:".concat(o.uid,", mediaType:").concat(s," twice"));continue}i.set(o,c|("video"===s?a:rS.Audio))}else i.set(o,"video"===s?a:rS.Audio)}for(let t=e.length-1;t>=0;t--){const n=e[t],{user:r,mediaType:o}=n,s=rS.Video|rS.LwoVideo;if(this._p2pChannel.hasRemoteMedia(r,o)){await this._p2pChannel.unmuteRemoteNoLock(r,o);const n=i.get(r);i.set(r,"video"===o?n^s:n^rS.Audio),e.splice(t,1)}}this.store.massSubscribe(e.map(e=>({userId:e.user.uid,type:e.mediaType})),t);const a=zi(s=Array.from(i.entries())).call(s,(e,t)=>{let[i,n]=t;if(0===n)return e;const r={stream_id:i.uid,stream_type:n};return n&rS.Audio&&(r.audio_ssrc=i._audioSSRC),n&rS.Video&&(r.video_ssrc=i._videoSSRC),e.push(r),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===gS.VIDEO?t._videoSSRC:t._audioSSRC,rtxSsrcId:t._rtxSsrcId}}));const i=new Map;if(a.length>0){const e=await this._gateway.subscribeAll(a,!0);((null==e?void 0:e.users)||[]).forEach(e=>{let{stream_id:t,video_error_code:n,audio_error_code:r,error_code:o}=e;(n||r||o)&&i.set(t,{video_error_code:n,audio_error_code:r,error_code:o})})}if(Array.from(i.entries()).length>0){const e=Array.from(i.entries()).map(e=>{let t,[i,n]=e;n.error_code||n.video_error_code&&n.audio_error_code?t=void 0:n.video_error_code?t=gS.VIDEO:n.audio_error_code&&(t=gS.AUDIO);return{user:this.remoteUsers.find(e=>e.uid===i),mediaType:t}});await this._p2pChannel.massUnsubscribeNoLock(e)}for(const e of r){const t=i.get(e.user.uid);if(t){const i=t.error_code||"audio"===e.mediaType&&t.audio_error_code||"video"===e.mediaType&&t.video_error_code;if(i){const t=$I(i);CE.error("user:".concat(e.user.uid," mediaType:").concat(e.mediaType," has massSubscribe error ").concat(t.desc)),e.error=new EE(_E.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(r.filter(e=>!e.error).map(e=>({userId:e.user.uid,type:e.mediaType})),void 0,Date.now()),r.forEach(e=>{var i;Tg.subscribe(this.store.sessionId,{succ:!!e.error,ec:(null===(i=e.error)||void 0===i?void 0:i.code)||null,video:e.mediaType===gS.VIDEO,audio:e.mediaType===gS.AUDIO,peerid:e.user.uid,subscribeRequestid:e.mediaType===gS.VIDEO?e.user._videoSSRC:e.user._audioSSRC,p2pid:this.store.p2pId,eventElapse:Math.floor(performance.now()-t)},!0)}),CE.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("; "))),r}catch(t){throw await this._p2pChannel.massUnsubscribeNoLock(e),t}}finally{o(),n()}}async unsubscribe(e,t){if(t&&Gm(t,"mediaType",["audio","video"]),!this._joinInfo)throw new EE(_E.INVALID_OPERATION,"Can't unsubscribe stream, haven't joined yet!");if(!this._users.find(t=>t===e)){const t=new EE(_E.INVALID_REMOTE_USER,"user is not in the channel");throw CE.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}CE.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: ").concat(t));try{const i=await this._p2pChannel.unsubscribe(e,t);i&&await this._gateway.unsubscribe(i,e.uid),CE.info("[".concat(this._clientId,"] unsubscribe success uid: ").concat(e.uid,", mediaType: ").concat(t))}catch(t){if(t.code===_E.DISCONNECT_P2P)return void CE.warning("disconnecting p2p, abort unsubscribe request.");throw CE.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}}async massUnsubscribe(e){if(Ym(e,"unsubscribeList"),!this._joinInfo)throw new EE(_E.INVALID_OPERATION,"Can't unsubscribeAll stream, haven't joined yet!");CE.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];const t=new Map;for(let i=e.length-1;i>=0;i--){const{user:n,mediaType:r}=e[i];if(!n){const e=new EE(_E.INVALID_PARAMS,"user property does not exist in unsubscribeList item");throw CE.error("[".concat(this._clientId,"] user property does not exist in unsubscribeList item")),e}Gm(r,"mediaType",["video","audio",void 0]);if(!this._users.find(e=>e===n)){CE.warning("[".concat(this._clientId,"] can not unsubscribe ").concat(n.uid,", user is not in the channel")),e.splice(i,1);continue}const o=rS.Video|rS.LwoVideo;if(t.has(n)){const s=t.get(n);let a;switch(r){case"video":a=s&o;break;case"audio":a=s&rS.Audio;break;default:a=s&(rS.Audio|o)}if(a){CE.warning("repeat massUnsubscribe user:".concat(n.uid,",mediaType:").concat(r," twice.")),e.splice(i,1);continue}r?"audio"===r?t.set(n,s|rS.Audio):"video"===r&&t.set(n,s|o):t.set(n,s|rS.Audio|o)}else r?"audio"===r?t.set(n,rS.Audio):"video"===r&&t.set(n,o):t.set(n,rS.Audio|o)}try{const t=await this._p2pChannel.massUnsubscribe(e);t&&await this._gateway.massUnsubscribe(t),CE.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===_E.DISCONNECT_P2P)return void CE.warning("disconnecting p2p, abort unsubscribe request.");throw CE.error("[".concat(this._clientId,"] massUnsubscribe error"),e.toString()),e}}setLowStreamParameter(e){!function(e){if(!e)throw new EE(_E.INVALID_PARAMS);Xm(e.width)||Hm(e.width,"streamParameter.width"),Xm(e.height)||Hm(e.height,"streamParameter.height"),Xm(e.framerate)||Hm(e.framerate,"streamParameter.framerate"),Xm(e.bitrate)||Wm(e.bitrate,"streamParameter.bitrate")}(e),(!e.width&&e.height||e.width&&!e.height)&&CE.warning("[".concat(this._clientId,"] The width and height parameters take effect only when both are set")),CE.info("[".concat(this._clientId,"] set low stream parameter to"),JSON.stringify(e));const t=this._configDistribute.getLowStreamConfigDistribute();t&&t.bitrate&&e.bitrate&&t.bitrate<e.bitrate&&(e.bitrate=t.bitrate),this._lowStreamParameter=e}async enableDualStream(){if(!MS().supportDualStream)throw Tg.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),new EE(_E.NOT_SUPPORTED,"Your browser is not support dual stream");if(this._isDualStreamEnabled)throw new EE(_E.INVALID_OPERATION,"Dual stream is already enabled");if(this._p2pChannel.canPublishLowStream())try{await this._publishLowStream()}catch(e){throw Tg.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),e}this._isDualStreamEnabled=!0,Tg.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!0}),CE.info("[".concat(this._clientId,"] enable dual stream"))}async disableDualStream(){if(this._isDualStreamEnabled){if(!this._joinInfo)throw new EE(_E.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if(this._p2pChannel.getLocalMedia(RS.LocalVideoLowTrack))try{const e=await this._p2pChannel.unpublishLowStream();e&&await this._gateway.unpublish(e,this._joinInfo.stringUid||this._joinInfo.uid)}catch(e){throw Tg.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!1}),e}this._isDualStreamEnabled=!1,Tg.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!0}),CE.info("[".concat(this._clientId,"] disable dual stream"))}}async setClientRole(e,t){if(function(e){Gm(e,"role",["audience","host"])}(e),t&&kf(t),"rtc"===this._mode)throw CE.warning("[".concat(this._clientId,"]rtc mode can not use setClientRole")),new EE(_E.INVALID_OPERATION,"rtc mode can not use setClientRole");if(t&&t.level&&"host"===e)throw new EE(_E.INVALID_OPERATION,"host mode can not set audience latency level");if("audience"===e&&this._p2pChannel.hasLocalMedia())throw new EE(_E.INVALID_OPERATION,"can not set client role to audience when publishing stream");await this._gateway.setClientRole(e,t),CE.info("[".concat(this._clientId,"] set client role to ").concat(e,", level: ").concat(t&&t.level))}setProxyServer(e,t){if(Km(e,"proxyServer"),!t){if("DISCONNECTED"!==this.connectionState)throw new EE(_E.INVALID_OPERATION,"Set proxy server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new EE(_E.INVALID_OPERATION,"You have already set the proxy")}this._proxyServer=e,Tg.setProxyServer(this._proxyServer),CE.setProxyServer(this._proxyServer),CE.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 EE(_E.INVALID_OPERATION,"Set turn server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new EE(_E.INVALID_OPERATION,"You have already set the proxy")}if(Pf(e))return this._turnServer={servers:e,mode:"original-manual"},void CE.info("[".concat(this._clientId,"] Set original turnserver ").concat(t?"by initialize call":""," success: ").concat(e.map(e=>e.urls).join(","),"."));e.forEach(e=>Lf(e)),this._turnServer={servers:e,mode:"manual"},CE.info("[".concat(this._clientId,"] Set turnserver ").concat(t?"by initialize call":""," success."))}setLicense(e){if("DISCONNECTED"!==this.connectionState){throw new EE(_E.INVALID_OPERATION,"you should set license before join channel")}if(Km(e,"license",32,32),!/^[A-Za-z\d]+$/.test(e))throw new EE(_E.INVALID_PARAMS,"license should only contains characters from A-Z a-z 0-9");this._license=e,CE.info("[".concat(this._clientId,"] set license success"),e)}startProxyServer(e){if("DISCONNECTED"!==this.connectionState)throw new EE(_E.INVALID_OPERATION,"Start proxy server before join channel");if(this._proxyServer||"manual"===this._turnServer.mode||this._useLocalAccessPoint)throw new EE(_E.INVALID_OPERATION,"You have already set the proxy");const t=[3,4,5];let i;switch(void 0===e&&(e=3),e){case 1:case 2:throw new EE(_E.NOT_SUPPORTED,"proxy mode 1/2 has been deprecated and not supported.");case 3:i="proxy3";break;case 4:i="proxy4";break;case 5:i="proxy5";break;default:throw new EE(_E.INVALID_PARAMS,"proxy server mode must be ".concat(t.join("|")))}this._cloudProxyServerMode=i,this.store.cloudProxyServerMode=i,CE.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode)}stopProxyServer(){if("DISCONNECTED"!==this.connectionState)throw new EE(_E.INVALID_OPERATION,"Stop proxy server after leave channel");Tg.setProxyServer(),CE.setProxyServer(),this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled",CE.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 EE(_E.INVALID_PARAMS,"accessPoints is required.");Ym(e.accessPoints.serverList,"accessPoints.serverList"),Km(e.accessPoints.domain,"accessPoints.domain");const t=(e,t)=>{Wm(e,t,0,65535,!0)};let i=443;if(e.accessPoints.port&&(t(e.accessPoints.port,"accessPoints.port"),i=e.accessPoints.port),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new EE(_E.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");FE("CLOSE_AFB_FOR_LOCAL_AP")&&(VE("JOIN_WITH_FALLBACK_SIGNAL_PROXY",!1),VE("JOIN_WITH_FALLBACK_MEDIA_PROXY",!1));const n=/^((\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])$/,r=e.accessPoints.domain,o=e.accessPoints.serverList.map(e=>n.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(r):e),s=o.map(e=>"".concat(e,":").concat(i));this._useLocalAccessPoint=!0,this._setLocalAPVersion=2,VE("WEBCS_DOMAIN",s),VE("WEBCS_DOMAIN_BACKUP_LIST",s),VE("GATEWAY_DOMAINS",[r]),e.report&&e.report.hostname&&Array.isArray(e.report.hostname)&&e.report.hostname.length?(Ym(e.report.hostname,"report.hostname"),VE("EVENT_REPORT_DOMAIN",e.report.hostname[0]),VE("EVENT_REPORT_BACKUP_DOMAIN",e.report.hostname[1]||e.report.hostname[0])):(VE("EVENT_REPORT_DOMAIN",o[0]),VE("EVENT_REPORT_BACKUP_DOMAIN",o[1]||o[0]));let a=6443;e.report&&e.report.port&&(t(e.report.port,"report.port"),a=e.report.port),VE("STATS_COLLECTOR_PORT",a),e.report?VE("ENABLE_EVENT_REPORT",!0):VE("ENABLE_EVENT_REPORT",!1);let c="";e.log&&e.log.hostname&&Array.isArray(e.log.hostname)&&e.log.hostname.length?(Ym(e.log.hostname,"log.hostname"),c=e.log.hostname[0]):c=o[0];let d=6444;e.log&&e.log.port&&(t(e.log.port,"log.port"),d=e.log.port),VE("LOG_UPLOAD_SERVER","".concat(c,":").concat(d));let u=[];e.cds&&e.cds.hostname&&Array.isArray(e.cds.hostname)&&e.cds.hostname.length?(Ym(e.cds.hostname,"cds.hostname"),u=e.cds.hostname):u=o;let l=443;e.cds&&e.cds.port&&(t(e.cds.port,"cds.port"),l=e.cds.port),VE("CDS_AP",u.map(e=>"".concat(e,":").concat(l))),e.cds?VE("ENABLE_CONFIG_DISTRIBUTE",!0):VE("ENABLE_CONFIG_DISTRIBUTE",!1),CE.info("set local access point v2 success")}setLocalAccessPoints(e,t){if(Ym(e,"serverList"),Km(t,"domain"),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new EE(_E.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");const 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,VE("WEBCS_DOMAIN",e),VE("WEBCS_DOMAIN_BACKUP_LIST",e),VE("GATEWAY_DOMAINS",[t]),VE("EVENT_REPORT_DOMAIN",e[0]),VE("EVENT_REPORT_BACKUP_DOMAIN",e[1]||e[0]),VE("LOG_UPLOAD_SERVER","".concat(e[0],":6444")),CE.info("set local access point success")}async setRemoteDefaultVideoStreamType(e){if(Gm(e,"streamType",[0,1]),this._remoteDefaultVideoStreamType=e,this._joinInfo)try{await this._gateway.setDefaultRemoteVideoStreamType(e),this._joinInfo.defaultVideoStream=this._remoteDefaultVideoStreamType}catch(e){throw CE.error("[".concat(this._clientId,"] set default remote video stream type error"),e.toString()),e}else CE.debug("haven't joined yet, cache remoteDefaultVideoStreamType ".concat(e))}async setRemoteVideoStreamType(e,t){Gm(t,"streamType",[0,1]);try{await this._gateway.setRemoteVideoStreamType(e,t),setTimeout(()=>{const t=this._users.find(t=>t.uid===e);t&&t.videoTrack&&t.videoTrack.updateMediaStreamTrackResolution()},2e3)}catch(e){throw CE.error("[".concat(this._clientId,"] set remote video stream type error"),e.toString()),e}CE.info("[".concat(this._clientId,"] set remote ").concat(e," video stream type to ").concat(t)),this._remoteStreamTypeCacheMap.set(e,t)}async setStreamFallbackOption(e,t){Gm(t,"fallbackType",[0,1,2]);try{await this._gateway.setStreamFallbackOption(e,t)}catch(e){throw CE.error("[".concat(this._clientId,"] set stream fallback option"),e.toString()),e}CE.info("[".concat(this._clientId,"] set remote ").concat(e," stream fallback type to ").concat(t)),this._streamFallbackTypeCacheMap.set(e,t)}setEncryptionConfig(e,t,i){!function(e){Gm(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"])}(e),Km(t,"secret");if(["aes-128-gcm2","aes-256-gcm2"].includes(e)){if(!i||!(i instanceof Uint8Array&&32===i.length))throw new EE(_E.INVALID_PARAMS,"salt must be an Uint8Array and exactly equal to 32 bytes")}else if(i)throw new EE(_E.INVALID_PARAMS,"current encrypt mode does not need salt");new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*,.<>?/:;'\"|{}\\[\\]])(?=.{8,})").test(t)||CE.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=KI(i))}async renewToken(e){if(Km(e,"token",1,2047),!this._key||!this._joinInfo)throw new EE(_E.INVALID_OPERATION,"renewToken should not be called before user join");const t=this._key;this._key=e,this._joinInfo&&(this._joinInfo.token=e);const i=await this._renewTokenMutex.lock();try{if(FE("USE_NEW_TOKEN")){CE.debug("start renew token with ticket from unilbs");const t=await Kv(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||mE);CE.debug("[".concat(this._clientId,"] get ticket from unilbs success")),await this._gateway.renewToken({token:e,ticket:t})}else CE.debug("start renew token without ticket"),await this._gateway.renewToken({token:e});CE.debug("[".concat(this._clientId,"] renewToken success"))}catch(e){throw this._key=t,this._joinInfo.token=t,CE.error("[".concat(this._clientId,"] renewToken failed"),e.toString()),e}finally{i()}}enableAudioVolumeIndicator(){this._audioVolumeIndicationInterval?CE.warning("you have already enabled audio volume indicator!"):this._audioVolumeIndicationInterval=window.setInterval(()=>{const e=this._p2pChannel.getAudioLevels();this.emit(Rf.VOLUME_INDICATOR,e)},FE("AUDIO_VOLUME_INDICATION_INTERVAL")||2e3)}getRTCStats(){const e=this._statsCollector.getRTCStats(),t=this._gateway.getInChannelInfo();return e.Duration=Math.round(t.duration/1e3),e}async startLiveStreaming(e,t){if(!t){if("h264"!==this._codec)throw new EE(_E.LIVE_STREAMING_INVALID_RAW_STREAM,"raw streaming is only support h264");if(!this._p2pChannel.hasLocalMedia())throw new EE(_E.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 EE(_E.LIVE_STREAMING_TASK_CONFLICT);const i=t?Bf.TRANSCODE:Bf.RAW;return this._createLiveStreamingClient(i).startLiveStreamingTask(e,i)}setLiveTranscoding(e){return this._createLiveStreamingClient(Bf.TRANSCODE).setTranscodingConfig(e)}async stopLiveStreaming(e){const t=[this._liveRawStreamingClient,this._liveTranscodeStreamingClient].filter(t=>t&&t.hasUrl(e));if(!t.length)throw new EE(_E.INVALID_PARAMS,"can not find live streaming url to stop");await Sl.all(t.map(t=>t&&t.stopLiveStreamingTask(e)))}async addInjectStreamUrl(e,t){if(!this._joinInfo)throw new EE(_E.INVALID_OPERATION,"can not addInjectStreamUrl, no joininfo");const i=this._createLiveStreamingClient(Bf.INJECT);i.setInjectStreamConfig(t,0),await i.startLiveStreamingTask(e,Bf.INJECT)}async removeInjectStreamUrl(){var e;const t=this._createLiveStreamingClient(Bf.INJECT),i=Array.from(HR(e=t.streamingTasks).call(e)).find(e=>e.mode===Bf.INJECT);if(!this._joinInfo||!i)throw new EE(_E.INVALID_OPERATION,"can remove addInjectStreamUrl, no joininfo or inject task");await t.stopLiveStreamingTask(i.url)}async startChannelMediaRelay(e){iC(e);const t=this._createChannelMediaRelayClient();await t.startChannelMediaRelay(e)}async updateChannelMediaRelay(e){iC(e);const t=this._createChannelMediaRelayClient();await t.updateChannelMediaRelay(e)}async stopChannelMediaRelay(){const e=this._createChannelMediaRelayClient();await e.stopChannelMediaRelay()}sendStreamMessage(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!this._joinInfo)throw new EE(_E.INVALID_OPERATION,"can not send data stream, not joined");if("string"==typeof e){e=(new TextEncoder).encode(e)}if(new Blob([e]).size>1024)throw new EE(_E.INVALID_PARAMS,"stream message out of range.");return this._gateway.signal.request(yf.DATA_STREAM,{payload:KI(e)},!t)}sendMetadata(e){if(!this._joinInfo)throw new EE(_E.INVALID_OPERATION,"can not send metadata, not joined");if(new Blob([e]).size>1024)throw new EE(_E.METADATA_OUT_OF_RANGE);return this._gateway.signal.request(yf.SEND_METADATA,{session_id:this._joinInfo.sid,metadata:KI(e)})}async sendCustomReportMessage(e){if(Array.isArray(e)||(e=[e]),e.forEach(rf),!this._joinInfo)throw new EE(_E.INVALID_OPERATION,"can not send custom report, not joined");await Tg.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){Gm(t.spatialLayer,"spatialLayer",[0,1,2,3]),Gm(t.temporalLayer,"temporalLayer",[0,1,2,3]);try{await this._gateway.pickSVCLayer(e,t)}catch(e){throw CE.error("[".concat(this._clientId,"] pick SVC layer failed"),e.toString()),e}}_reset(){if(CE.debug("[".concat(this._clientId,"] reset client")),this._axiosCancelSource.cancel(),this._axiosCancelSource=uE.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.forEach(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 vg("client-publish"),this._subscribeMutex=new vg("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){const i=e||NI();e?CE.debug("[".concat(this._clientId,"] new Session ").concat(i)):CE.debug("[".concat(this._clientId,"] renewSession ").concat(this._sessionId," => ").concat(i)),this._sessionId=i,this.store.sessionId=i,t?Tg.sessionInit(this._sessionId,{lts:(new Date).getTime(),cname:t.channel,appid:t.appId,mode:this._mode}):this._joinInfo?Tg.sessionInit(this._sessionId,{lts:(new Date).getTime(),cname:this._joinInfo.cname,appid:this._joinInfo.appId,mode:this._mode}):this._gateway.joinInfo&&Tg.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 EE(_E.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new EE(_E.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&FE("FORCE_TURN")&&!FE("TURN_ENABLE_TCP")&&!FE("TURN_ENABLE_UDP"))throw new EE(_E.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");CE.debug("[".concat(this._clientId,"] publish high stream"));try{const i=await this._p2pChannel.publish(e,this._isDualStreamEnabled,this._lowStreamParameter),n=(await i.next()).value;if(n){var t;let e;try{e=await this._gateway.publish(this._uid,n,!0)}catch(e){if(e.code!==_E.DISCONNECT_P2P)throw i.throw(e),e}await i.next((null===(t=e)||void 0===t?void 0:t.ortc)||[])}this._p2pChannel.reportPublishEvent(!0,null);for(const t of e)t instanceof QC&&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)===_E.WS_ABORT)return;throw t}}async _publishLowStream(){if(!this._joinInfo||void 0===this._uid)throw new EE(_E.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new EE(_E.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));CE.debug("[".concat(this._clientId,"] publish low stream"));const 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{const e=await this._p2pChannel.publishLowStream(this._lowStreamParameter),i=(await e.next()).value;if(i){var t;let n;try{n=await this._gateway.publish(this._uid,i,!0)}catch(t){if(t.code!==_E.DISCONNECT_P2P)throw e.throw(t),t}e.next((null===(t=n)||void 0===t?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)===_E.WS_ABORT)return;throw e}}_createLiveStreamingClient(e){if(!this._joinInfo||!this._appId){return new EE(_E.INVALID_OPERATION,"can not create live streaming client, please join channel first").throw()}const t=()=>new eC(this._joinInfo,this._config.websocketRetryConfig||mE,this._config.httpRetryConfig||mE),i=e=>{e.onLiveStreamError=(e,t)=>{Tg.reportApiInvoke(this._sessionId,{name:uf.ON_LIVE_STREAM_ERROR,options:[e,t],tag:lf.TRACER}).onSuccess(),this.emit(Rf.LIVE_STREAMING_ERROR,e,t)},e.onLiveStreamWarning=(e,t)=>{Tg.reportApiInvoke(this._sessionId,{name:uf.ON_LIVE_STREAM_WARNING,options:[e,t],tag:lf.TRACER}).onSuccess(),this.emit(Rf.LIVE_STREAMING_WARNING,e,t)},e.on(Xf.REQUEST_WORKER_MANAGER_LIST,(e,t,i)=>{if(!this._joinInfo)return i(new EE(_E.INVALID_OPERATION,"can not find join info to get worker manager"));Wv(e,this._joinInfo,this._axiosCancelSource.token,mE).then(t).catch(i)})};switch(e){case Bf.RAW:return this._liveRawStreamingClient||(this._liveRawStreamingClient=t(),i(this._liveRawStreamingClient)),this._liveRawStreamingClient;case Bf.TRANSCODE:return this._liveTranscodeStreamingClient||(this._liveTranscodeStreamingClient=t(),i(this._liveTranscodeStreamingClient)),this._liveTranscodeStreamingClient;case Bf.INJECT:return this._injectStreamingClient||(this._injectStreamingClient=t(),this._injectStreamingClient.on(Xf.REQUEST_WORKER_MANAGER_LIST,(e,t,i)=>{if(!this._joinInfo)return i(new EE(_E.INVALID_OPERATION,"can not find join info to get worker manager"));Wv(e,this._joinInfo,this._axiosCancelSource.token,mE).then(t).catch(i)}),this._injectStreamingClient.onInjectStatusChange=(e,t,i)=>{this.emit(Rf.INJECT_STREAM_STATUS,e,t,i)}),this._injectStreamingClient}}_createChannelMediaRelayClient(){if(!this._joinInfo){return new EE(_E.INVALID_OPERATION,"can not create channel media relay client, please join channel first").throw()}return this._channelMediaRelayClient||(this._channelMediaRelayClient=new rC(this._joinInfo,this._clientId,this._config.websocketRetryConfig||mE,this._config.httpRetryConfig||mE),this._channelMediaRelayClient.on("state",e=>{e===eS.RELAY_STATE_FAILURE&&this._channelMediaRelayClient&&this._channelMediaRelayClient.dispose(),this.emit(Rf.CHANNEL_MEDIA_RELAY_STATE,e)}),this._channelMediaRelayClient.on("event",e=>{this.emit(Rf.CHANNEL_MEDIA_RELAY_EVENT,e)})),this._channelMediaRelayClient}_handleGatewayEvents(){this._gateway.on(nS.DISCONNECT_P2P,async()=>{await this._p2pChannel.disconnectForReconnect()}),this._gateway.on(nS.CONNECTION_STATE_CHANGE,(e,t,i)=>{var n;if(i===gf.FALLBACK)return;const r=()=>{this.emit(Rf.CONNECTION_STATE_CHANGE,e,t,i)};if(Tg.reportApiInvoke(this._sessionId||(null===(n=this._gateway.joinInfo)||void 0===n?void 0:n.sid)||null,{name:uf.CONNECTION_STATE_CHANGE,options:[e,t,i],tag:lf.TRACER}).onSuccess(JSON.stringify({cur:e,prev:t,reason:i})),CE.info("[".concat(this._clientId,"] connection state change: ").concat(t," -> ").concat(e)),"DISCONNECTED"===e)return this._reset(),void r();if("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;else if("CONNECTED"===e){var o;this._streamFallbackTypeCacheMap.forEach((e,t)=>{this._gateway.setStreamFallbackOption(t,e).catch(e=>{CE.warning("[".concat(this._clientId,"] auto set stream fallback option failed"),e)})}),this._remoteStreamTypeCacheMap.forEach((e,t)=>{this._gateway.setRemoteVideoStreamType(t,e).catch(e=>{CE.warning("[".concat(this._clientId,"] auto set remote stream type failed"),e)})}),void 0!==this._remoteDefaultVideoStreamType&&void 0===(null===(o=this._joinInfo)||void 0===o?void 0:o.defaultVideoStream)&&this.setRemoteDefaultVideoStreamType(this._remoteDefaultVideoStreamType).then(()=>{CE.debug("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway connected"))}).catch(e=>{CE.error("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway failed, ").concat(e))}),this._p2pChannel.republish(),this._userOfflineTimeout=window.setTimeout(()=>{if("CONNECTED"!==this.connectionState)return;this._userOfflineTimeout=void 0;this._users.filter(e=>!e._trust_in_room_).forEach(e=>{CE.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_||(CE.debug("[".concat(this._clientId,"] auto dispatch audio unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,"audio",!1)),e._trust_video_mute_state_||(CE.debug("[".concat(this._clientId,"] auto dispatch video unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,"video",!1)),e._trust_audio_enabled_state_||(CE.debug("[".concat(this._clientId,"] auto dispatch enable local audio ").concat(e.uid)),this._handleSetStreamLocalEnable("audio",e.uid,!0)),e._trust_video_enabled_state_||(CE.debug("[".concat(this._clientId,"] auto dispatch enable local video ").concat(e.uid)),this._handleSetStreamLocalEnable("video",e.uid,!0)),e._trust_video_stream_added_state_||(CE.debug("[".concat(this._clientId,"] auto dispatch reset video stream added ").concat(e.uid)),this._handleResetAddStream(e,"video")),e._trust_audio_stream_added_state_||(CE.debug("[".concat(this._clientId,"] auto dispatch reset audio stream added ").concat(e.uid)),this._handleResetAddStream(e,"audio")),e._video_added_||e._audio_added_||(CE.debug("[".concat(this._clientId,"] auto dispatch stream remove ").concat(e.uid)),this._handleRemoveStream({uid:e.uid,uint_id:e._uintid}))}))},1e3)}r()}),this._gateway.on(nS.REQUEST_NEW_GATEWAY_LIST,(e,t)=>{if(!this._joinInfo)return t(new EE(_E.UNEXPECTED_ERROR,"can not recover, no join info"));Vv(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||mE,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){const 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(nS.NETWORK_QUALITY,e=>{"normal"===this._networkQualitySensitivity&&this.emit(Rf.NETWORK_QUALITY,e)}),this._gateway.on(nS.STREAM_TYPE_CHANGE,(e,t)=>{this.emit(Rf.STREAM_TYPE_CHANGED,e,t);Tg.reportApiInvoke(this._sessionId,{name:uf.STREAM_TYPE_CHANGE,options:[e,t],tag:lf.TRACER}).onSuccess(JSON.stringify({uid:e,streamType:t}))}),this._gateway.on(nS.IS_P2P_DISCONNECTED,e=>{this._p2pChannel.isP2PDisconnected()?e(!0):this._p2pChannel.hasLocalMedia()||this._p2pChannel.hasRemoteMedia()?e(!1):e(!0)}),this._gateway.on(nS.NEED_RENEW_SESSION,()=>{this._startSession()}),this._gateway.on(nS.REQUEST_P2P_CONNECTION_PARAMS,async(e,t,i)=>{try{t(await this._p2pChannel.startP2PConnection(e))}catch(e){i(e)}}),this._gateway.on(nS.JOIN_RESPONSE,(e,t)=>{const{dtlsParameters:i,iceParameters:n,candidates:r,rtpCapabilities:o,setup:s,cname:a}=mO(e.ortc,t);this._p2pChannel.connect(n,i,r,o,s,a)}),this._gateway.on(nS.REQUEST_DC_CONNECTION_PARAMS,e=>{e(this._p2pChannel.getEstablishParams())}),this._gateway.on(nS.RESET_SIGNAL,e=>{this._p2pChannel.resetConnection(e),this._handleGatewaySignalEvents()}),this._gateway.on(nS.DATACHANNEL_FAILBACK,()=>{this._joinGateway()}),this._gateway.on(nS.DATACHANNEL_PRECONNECT,async(e,t,i,n)=>{var r,o,s,a,c,d;await this._p2pChannel.startP2PConnection({turnServer:null===(r=this._joinInfo)||void 0===r?void 0:r.turnServer},!0);const u=function(e,t){let i;return 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:{}}],CE.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:{}}),CE.debug("Using IPV6 remote candidate from AP ".concat(t.ip6,":").concat(t.port)))):i=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:e.ip,port:e.port.toString(),type:"host",extension:{}}],i}(e,t);return this._p2pChannel.preConnect({iceUfrag:"".concat(null===(o=this._joinInfo)||void 0===o?void 0:o.apResponse.cid,"_").concat(null===(s=this._joinInfo)||void 0===s?void 0:s.apResponse.cert),icePwd:"".concat(null===(a=this._joinInfo)||void 0===a?void 0:a.apResponse.cid,"_").concat(null===(c=this._joinInfo)||void 0===c?void 0:c.apResponse.cert)},{fingerprints:[{hashFunction:"sha-256",fingerprint:null!==(d=FE("FINGERPRINT"))&&void 0!==d?d:e.fingerprint}]},u,{send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},"active","o/i14u9pJrxRKAsu").then(i).catch(n)})}_handleGatewaySignalEvents(){this._gateway.signal.on(Of.ON_USER_ONLINE,this._handleUserOnline),this._gateway.signal.on(Of.ON_USER_OFFLINE,this._handleUserOffline),this._gateway.signal.on(Of.ON_ADD_AUDIO_STREAM,e=>this._handleAddAudioOrVideoStream("audio",e.uid,e.ssrcId,e.cname,e.uint_id,e.ortc)),this._gateway.signal.on(Of.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(Of.ON_REMOVE_STREAM,this._handleRemoveStream),this._gateway.signal.on(Of.ON_P2P_LOST,this._handleP2PLost),this._gateway.signal.on(Of.MUTE_AUDIO,e=>this._handleMuteStream(e.uid,"audio",!0)),this._gateway.signal.on(Of.UNMUTE_AUDIO,e=>this._handleMuteStream(e.uid,"audio",!1)),this._gateway.signal.on(Of.MUTE_VIDEO,e=>this._handleMuteStream(e.uid,"video",!0)),this._gateway.signal.on(Of.UNMUTE_VIDEO,e=>this._handleMuteStream(e.uid,"video",!1)),this._gateway.signal.on(Of.RECEIVE_METADATA,e=>{const t=HI(e.metadata);this.emit(Rf.RECEIVE_METADATA,e.uid,t)}),this._gateway.signal.on(Of.ON_DATA_STREAM,e=>{e.seq&&delete e.seq,e.payload=HI(e.payload),this.emit(Rf.STREAM_MESSAGE,e.uid,e.payload),this.onStreamMessage&&this.onStreamMessage(e)}),this._gateway.signal.on(Of.ON_CRYPT_ERROR,()=>{WI(()=>{CE.warning("[".concat(this._clientId,"] on crypt error")),this.emit(Rf.CRYPT_ERROR)},this._sessionId)}),this._gateway.signal.on(Of.ON_TOKEN_PRIVILEGE_WILL_EXPIRE,this._handleTokenWillExpire),this._gateway.signal.on(Of.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{CE.warning("[".concat(this._clientId,"] received message onTokenPrivilegeDidExpire, please get new token and join again")),this._gateway.leave(!0),this.emit(Rf.ON_TOKEN_PRIVILEGE_DID_EXPIRE),this._reset()}),this._gateway.signal.on(Of.ON_STREAM_FALLBACK_UPDATE,e=>{CE.debug("[".concat(this._clientId,"] stream fallback peerId: ").concat(e.stream_id,", attr: ").concat(e.stream_type)),this.emit(Rf.STREAM_FALLBACK,e.stream_id,1===e.stream_type?"fallback":"recover")}),this._gateway.signal.on(Of.ON_PUBLISH_STREAM,e=>{this.uid===this._uid&&(this._p2pChannel.reportPublishEvent(!0,null,void 0,!1,JSON.stringify({proxy:e.proxy})),CE.info("[".concat(this._clientId,"] on publish stream, ").concat(JSON.stringify(e))))}),this._gateway.signal.on(Of.ENABLE_LOCAL_VIDEO,e=>{this._handleSetStreamLocalEnable("video",e.uid,!0)}),this._gateway.signal.on(Of.DISABLE_LOCAL_VIDEO,e=>{this._handleSetStreamLocalEnable("video",e.uid,!1)}),this._gateway.signal.on(Cf.REQUEST_TIMEOUT,(e,t)=>{if(this._joinInfo)switch(e){case yf.PUBLISH:{if(!t)return;const e=(t=t).ortc;if(e){var i,n,r,o;const s=e.some(e=>{let{stream_type:t}=e;return t===iS.Audio}),a=e.some(e=>{let{stream_type:t}=e;return t!==iS.Audio}),c=e.some(e=>{let{stream_type:t}=e;return t===iS.Screen||t===iS.ScreenLow});"offer"===t.state&&Tg.publish(this._joinInfo.sid,{eventElapse:aI.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:!1,ec:_E.TIMEOUT,audio:s,video:a,p2pid:t.p2p_id,publishRequestid:this.store.pubId,screenshare:c,audioName:s?null===(i=e.find(e=>{let{stream_type:t}=e;return t===iS.Audio}))||void 0===i||null===(n=i.ssrcs[0])||void 0===n?void 0:n.ssrcId.toString():void 0,videoName:a?null===(r=e.find(e=>{let{stream_type:t}=e;return t!==iS.Audio}))||void 0===r||null===(o=r.ssrcs[0])||void 0===o?void 0:o.ssrcId.toString():void 0})}break}case yf.SUBSCRIBE:(t=t)&&Tg.subscribe(this._joinInfo.sid,{succ:!1,ec:_E.TIMEOUT,audio:t.stream_type===gS.AUDIO,video:t.stream_type===gS.VIDEO,peerid:t.stream_id,subscribeRequestid:t.ssrcId,p2pid:this.store.p2pId,eventElapse:aI.measureFromSubscribeStart(this.store.clientId,t.ssrcId)})}}),this._gateway.signal.on(Of.ON_P2P_OK,e=>{this.uid,this._uid}),this._gateway.signal.on(Of.ON_PUBLISHED_USER_LIST,e=>{if(null==e||!e.users)return;const t=[],i=[];for(const n of e.users){let e=this._users.find(e=>e.uid===n.stream_id);e?e._trust_in_room_=!0:(e=new $C(n.stream_id,n.stream_id),this._users.push(e),0===this.getListeners(Rf.PUBLISHED_USER_LIST).length&&(CE.debug("[".concat(this._clientId,"] user online"),n.stream_id),this.emit(Rf.USER_JOINED,e)));const r=rS.Audio&n.stream_type,o=(rS.Video|rS.LwoVideo)&n.stream_type,s=r&&e.hasAudio,a=o&&e.hasVideo;o&&(e._trust_video_stream_added_state_=!0,e._video_added_=!0,e._videoSSRC=n.video_ssrc),r&&(e._trust_audio_stream_added_state_=!0,e._audio_added_=!0,e._audioSSRC=n.audio_ssrc),r&&!s&&0===this.getListeners(Rf.PUBLISHED_USER_LIST).length&&(CE.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published audio")),this.emit(Rf.USER_PUBLISHED,e,"audio")),o&&!a&&0===this.getListeners(Rf.PUBLISHED_USER_LIST).length&&(CE.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published video")),this.emit(Rf.USER_PUBLISHED,e,"video")),(r&&!s||o&&!a)&&t.push(e),o&&this._p2pChannel.hasPendingRemoteMedia(e,"video")&&i.push({user:e,mediaType:"video"}),r&&this._p2pChannel.hasPendingRemoteMedia(e,"audio")&&i.push({user:e,mediaType:"audio"})}i.length>0&&(CE.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=>{CE.error("[".concat(this._clientId,"] mass resubscribe error"),e.toString())})),this.getListeners(Rf.PUBLISHED_USER_LIST).length>0?(CE.info("[".concat(this._clientId,"] client emit user-list event, users: ").concat(t.map(e=>e.uid).join(", "))),this.emit(Rf.PUBLISHED_USER_LIST,t)):CE.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(vS.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===_E.DISCONNECT_P2P?t():i(e)}else t()}),this._p2pChannel.on(vS.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===_E.DISCONNECT_P2P?t():i(e)}else t()}),this._p2pChannel.on(vS.RequestRePublish,(e,t,i)=>{this.publish(e,!1).then(t).catch(i)}),this._p2pChannel.on(vS.RequestReSubscribe,async(e,t,i)=>{try{for(const{user:t,kind:i}of e)i===gS.VIDEO?await this.subscribe(t,"video"):await this.subscribe(t,"audio");t()}catch(e){i(e)}}),this._p2pChannel.on(vS.RequestUploadStats,(e,t)=>{this._gateway.uploadStats(e,t)}),this._p2pChannel.on(vS.MediaReconnectStart,e=>{this.emit(Rf.MEDIA_RECONNECT_START,e)}),this._p2pChannel.on(vS.MediaReconnectEnd,e=>{this.emit(Rf.MEDIA_RECONNECT_END,e)}),this._p2pChannel.on(vS.NeedSignalRTT,e=>{e(this._gateway.getSignalRTT())}),this._p2pChannel.on(vS.RequestRestartICE,async()=>{const e=await this._p2pChannel.restartICE(),t=await e.next();if(t.done)return;const i=t.value;let n;try{n=await this._gateway.restartICE({iceParameters:i})}catch(t){return void e.throw(t)}const{iceParameters:r}=function(e){const t=e.iceParameters;return{iceParameters:{iceUfrag:t.iceUfrag,icePwd:t.icePwd}}}(n);await e.next({remoteIceParameters:r})}),this._p2pChannel.on(vS.RequestReconnect,async()=>{this._gateway.reconnect()}),this._p2pChannel.on(vS.RequestReconnectPC,async()=>{var e;const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=await this._p2pChannel.startP2PConnection({turnServer:null===(e=this._joinInfo)||void 0===e?void 0:e.turnServer}),{gatewayEstablishParams:r,gatewayAddress:o}=await this._gateway.reconnectPC({iceParameters:t,dtlsParameters:i,rtpCapabilities:n}),{dtlsParameters:s,iceParameters:a,candidates:c,rtpCapabilities:d,setup:u,cname:l}=mO(r,o);await this._p2pChannel.connect(a,s,c,d,u,l),await this._p2pChannel.republish(),await this._p2pChannel.reSubscribe()}),this._p2pChannel.on(vS.RequestUnpublishForReconnectPC,async(e,t,i)=>{this._joinInfo&&void 0!==this._uid?(await this._gateway.unpublish(e,this._uid),t()):i()}),this._p2pChannel.on(vS.P2PLost,()=>{this.emit(Rf.P2P_LOST,this.store.uid)}),this._p2pChannel.on(vS.UpdateVideoEncoder,e=>{e._encoderConfig&&this._gateway.setVideoProfile(e._encoderConfig)}),this._p2pChannel.on(vS.ConnectionTypeChange,e=>{this.emit(Rf.IS_USING_CLOUD_PROXY,e)}),this._p2pChannel.on(vS.RequestLowStreamParameter,e=>{e(this._lowStreamParameter||{width:160,height:120,framerate:15,bitrate:50})}),this._p2pChannel.on(vS.QueryClientConnectionState,e=>{e(this.connectionState)})}getKeyMetrics(){return this.store.keyMetrics}async enableContentInspect(e){if("CONNECTED"!==this.connectionState||!this._joinInfo)throw new EE(_E.INVALID_OPERATION,"[".concat(this._clientId,"] Client did not join channel"));if(this._inspect)throw new EE(_E.INVALID_OPERATION,"[".concat(this._clientId,"] Inspect content service already in connecting/connected state"));if(!e)throw new EE(_E.INVALID_PARAMS,"[".concat(this._clientId,"] inspectConfig is necessary"));if(!e.inspectType||!Array.isArray(e.inspectType))throw new EE(_E.INVALID_PARAMS,"[".concat(this._clientId,"] inspectConfig.inspectType is necessary and is an instance of Array."));{const t=[...new Set(e.inspectType)];t.forEach(e=>{if(!["supervise","moderation"].includes(e))throw new EE(_E.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 EE(_E.INVALID_PARAMS,"[".concat(this._clientId,"] inspectConfig.extraInfo length cannot exceed 1024 bytes"));try{const t=new kw(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},mE)}catch(e){throw Array.isArray(e)?e[0]:e}}async disableContentInspect(){if(!this._inspect)throw new EE(_E.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(NS.CONNECTION_STATE_CHANGE,(t,i)=>{switch(this.emit(Rf.CONTENT_INSPECT_CONNECTION_STATE_CHANGE,t,i),i){case bS.CONNECTED:if("CONNECTED"!==this.connectionState)return void this.emit(Rf.CONTENT_INSPECT_ERROR,new EE(_E.OPERATION_ABORTED,"Content inspect was cancelled because it left the channel"));e.inspectImage()}}),e.on(NS.INSPECT_RESULT,(e,t)=>{var i;if((null==t?void 0:t.code)===_E.INVALID_OPERATION&&"DISCONNECTED"===this.connectionState)return CE.debug("Stop inspect content because that has left channel"),null==this||null===(i=this._inspect)||void 0===i||i.close(),void(this._inspect=void 0);this.emit(Rf.CONTENT_INSPECT_RESULT,e,t)}),e.on(NS.CLIENT_LOCAL_VIDEO_TRACK,e=>{e(this.localTracks.filter(e=>"video"===e.trackMediaType)[0])})}getJoinChannelServiceRecords(){return CE.debug("getJoinChannelServiceRecords"),this.store.joinChannelServiceRecords}async setPublishAudioFilterEnabled(e){Bm(e,"enabled"),VE("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",[Mw],Object.getOwnPropertyDescriptor(TN.prototype,"leave"),TN.prototype),JT(TN.prototype,"publish",[Uw],Object.getOwnPropertyDescriptor(TN.prototype,"publish"),TN.prototype),JT(TN.prototype,"unpublish",[xw],Object.getOwnPropertyDescriptor(TN.prototype,"unpublish"),TN.prototype),JT(TN.prototype,"subscribe",[Vw],Object.getOwnPropertyDescriptor(TN.prototype,"subscribe"),TN.prototype),JT(TN.prototype,"massSubscribe",[Fw],Object.getOwnPropertyDescriptor(TN.prototype,"massSubscribe"),TN.prototype),JT(TN.prototype,"unsubscribe",[jw],Object.getOwnPropertyDescriptor(TN.prototype,"unsubscribe"),TN.prototype),JT(TN.prototype,"massUnsubscribe",[Bw],Object.getOwnPropertyDescriptor(TN.prototype,"massUnsubscribe"),TN.prototype),JT(TN.prototype,"setLowStreamParameter",[Gw],Object.getOwnPropertyDescriptor(TN.prototype,"setLowStreamParameter"),TN.prototype),JT(TN.prototype,"enableDualStream",[Ww],Object.getOwnPropertyDescriptor(TN.prototype,"enableDualStream"),TN.prototype),JT(TN.prototype,"disableDualStream",[Hw],Object.getOwnPropertyDescriptor(TN.prototype,"disableDualStream"),TN.prototype),JT(TN.prototype,"setClientRole",[Kw],Object.getOwnPropertyDescriptor(TN.prototype,"setClientRole"),TN.prototype),JT(TN.prototype,"setProxyServer",[Yw],Object.getOwnPropertyDescriptor(TN.prototype,"setProxyServer"),TN.prototype),JT(TN.prototype,"setTurnServer",[qw],Object.getOwnPropertyDescriptor(TN.prototype,"setTurnServer"),TN.prototype),JT(TN.prototype,"setLicense",[Jw],Object.getOwnPropertyDescriptor(TN.prototype,"setLicense"),TN.prototype),JT(TN.prototype,"startProxyServer",[Xw],Object.getOwnPropertyDescriptor(TN.prototype,"startProxyServer"),TN.prototype),JT(TN.prototype,"stopProxyServer",[zw],Object.getOwnPropertyDescriptor(TN.prototype,"stopProxyServer"),TN.prototype),JT(TN.prototype,"setLocalAccessPointsV2",[Qw],Object.getOwnPropertyDescriptor(TN.prototype,"setLocalAccessPointsV2"),TN.prototype),JT(TN.prototype,"setLocalAccessPoints",[Zw],Object.getOwnPropertyDescriptor(TN.prototype,"setLocalAccessPoints"),TN.prototype),JT(TN.prototype,"setRemoteDefaultVideoStreamType",[$w],Object.getOwnPropertyDescriptor(TN.prototype,"setRemoteDefaultVideoStreamType"),TN.prototype),JT(TN.prototype,"setRemoteVideoStreamType",[eN],Object.getOwnPropertyDescriptor(TN.prototype,"setRemoteVideoStreamType"),TN.prototype),JT(TN.prototype,"setStreamFallbackOption",[tN],Object.getOwnPropertyDescriptor(TN.prototype,"setStreamFallbackOption"),TN.prototype),JT(TN.prototype,"setEncryptionConfig",[iN],Object.getOwnPropertyDescriptor(TN.prototype,"setEncryptionConfig"),TN.prototype),JT(TN.prototype,"renewToken",[nN],Object.getOwnPropertyDescriptor(TN.prototype,"renewToken"),TN.prototype),JT(TN.prototype,"enableAudioVolumeIndicator",[rN],Object.getOwnPropertyDescriptor(TN.prototype,"enableAudioVolumeIndicator"),TN.prototype),JT(TN.prototype,"startLiveStreaming",[oN],Object.getOwnPropertyDescriptor(TN.prototype,"startLiveStreaming"),TN.prototype),JT(TN.prototype,"setLiveTranscoding",[sN],Object.getOwnPropertyDescriptor(TN.prototype,"setLiveTranscoding"),TN.prototype),JT(TN.prototype,"stopLiveStreaming",[aN],Object.getOwnPropertyDescriptor(TN.prototype,"stopLiveStreaming"),TN.prototype),JT(TN.prototype,"addInjectStreamUrl",[cN],Object.getOwnPropertyDescriptor(TN.prototype,"addInjectStreamUrl"),TN.prototype),JT(TN.prototype,"removeInjectStreamUrl",[dN],Object.getOwnPropertyDescriptor(TN.prototype,"removeInjectStreamUrl"),TN.prototype),JT(TN.prototype,"startChannelMediaRelay",[uN],Object.getOwnPropertyDescriptor(TN.prototype,"startChannelMediaRelay"),TN.prototype),JT(TN.prototype,"updateChannelMediaRelay",[lN],Object.getOwnPropertyDescriptor(TN.prototype,"updateChannelMediaRelay"),TN.prototype),JT(TN.prototype,"stopChannelMediaRelay",[hN],Object.getOwnPropertyDescriptor(TN.prototype,"stopChannelMediaRelay"),TN.prototype),JT(TN.prototype,"sendCustomReportMessage",[pN],Object.getOwnPropertyDescriptor(TN.prototype,"sendCustomReportMessage"),TN.prototype),JT(TN.prototype,"pickSVCLayer",[_N],Object.getOwnPropertyDescriptor(TN.prototype,"pickSVCLayer"),TN.prototype),JT(TN.prototype,"enableContentInspect",[EN],Object.getOwnPropertyDescriptor(TN.prototype,"enableContentInspect"),TN.prototype),JT(TN.prototype,"disableContentInspect",[mN],Object.getOwnPropertyDescriptor(TN.prototype,"disableContentInspect"),TN.prototype),JT(TN.prototype,"getJoinChannelServiceRecords",[fN],Object.getOwnPropertyDescriptor(TN.prototype,"getJoinChannelServiceRecords"),TN.prototype),JT(TN.prototype,"setPublishAudioFilterEnabled",[SN],Object.getOwnPropertyDescriptor(TN.prototype,"setPublishAudioFilterEnabled"),TN.prototype),TN);class vN extends Ug{set currentState(e){e!==this._currentState&&(this._currentState=e,this.emit(wf.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(),lp(this,"audioBuffer",void 0),lp(this,"sourceNode",void 0),lp(this,"startPlayTime",0),lp(this,"startPlayOffset",0),lp(this,"pausePlayTime",0),lp(this,"options",void 0),lp(this,"currentLoopCount",0),lp(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):CE.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(){const 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}}const CN=new Map;async function yN(e,t){let i=null;if("string"==typeof e){const t=CN.get(e);if(t)return CE.debug("use cached audio resource: ",e),t;try{i=(await SE(()=>uE.get(e,{responseType:"arraybuffer"}),void 0,void 0,{maxRetryCount:3})).data}catch(e){throw new EE(_E.FETCH_AUDIO_FILE_FAILED,e.toString())}}else{const t=new Sl((t,i)=>{const n=new FileReader;n.onload=e=>{e.target?t(e.target.result):i(new EE(_E.READ_LOCAL_AUDIO_FILE_ERROR))},n.onerror=()=>{i(new EE(_E.READ_LOCAL_AUDIO_FILE_ERROR))},n.readAsArrayBuffer(e)});i=await t}const n=await function(e){const t=Dg();return new Sl((i,n)=>{t.decodeAudioData(e,e=>{i(e)},e=>{n(new EE(_E.DECODE_AUDIO_FILE_FAILED,e.toString()))})})}(i);return"string"==typeof e&&t&&CN.set(e,n),n}function AN(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function ON(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?AN(Object(i),!0).forEach((function(t){lp(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):AN(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function bN(e,t,i,n){i.optimizationMode&&(n&&n.width&&n.height?(i.encoderConfig=ON(ON({},n),{},{bitrateMin:n.bitrateMin,bitrateMax:n.bitrateMax}),"motion"!==i.optimizationMode&&"detail"!==i.optimizationMode||(t.contentHint=i.optimizationMode,t.contentHint===i.optimizationMode?CE.debug("[".concat(e,"] set content hint to"),i.optimizationMode):CE.debug("[".concat(e,"] set content hint failed")))):CE.warning("[".concat(e,"] can not apply optimization mode bitrate config, no encoderConfig")))}const wN=Mh().name;function NN(e,t,i,n){let r,o=0,s=null;return new Sl((a,c)=>{setTimeout(()=>{r&&(r(),a(o))},t),r=kg(()=>{!function(){o>n&&r&&(r(),a(o));const t=i.getContext("2d");if(!t){const e=new EE(_E.UNEXPECTED_ERROR,"can not get canvas 2d context.");return CE.error(e.toString()),void c(e)}t.drawImage(e,0,0,160,120);const d=t.getImageData(0,0,i.width,i.height),u=Math.floor(d.data.length/3);if(s){for(let e=0;e<u;e+=3)if(d.data[e]!==s[e])return o+=1,void(s=d.data);s=d.data}else s=d.data}()},30)})}class DN{constructor(e,t){lp(this,"id",0),lp(this,"element",void 0),lp(this,"peerPair",void 0),lp(this,"context",void 0),lp(this,"audioPlayerElement",void 0),lp(this,"audioTrack",void 0),DN.count+=1,this.id=DN.count,this.element=e,this.context=t}initPeers(){this.peerPair=[new RTCPeerConnection,new RTCPeerConnection],this.peerPair[1].ontrack=e=>{const t=document.createElement("audio");t.srcObject=new MediaStream([e.track]),t.play(),this.audioPlayerElement=t}}async switchSdp(){if(!this.peerPair)return;const e=async(e,t)=>{const i="offer"===t?await e.createOffer():await e.createAnswer();return await e.setLocalDescription(i),"complete"===e.iceGatheringState?e.localDescription:new Sl(t=>{e.onicegatheringstatechange=()=>{"complete"===e.iceGatheringState&&t(e.localDescription)}})},t=async(e,t)=>await e.setRemoteDescription(t);try{const i=await e(this.peerPair[0],"offer");await t(this.peerPair[1],i);const n=await e(this.peerPair[1],"answer");await t(this.peerPair[0],n)}catch(e){throw new EE(_E.LOCAL_AEC_ERROR,e.toString()).print()}}async getTracksFromMediaElement(e){if(this.audioTrack)return this.audioTrack;let t;try{e instanceof HTMLVideoElement&&(e.captureStream?e.captureStream():e.mozCaptureStream()),t=this.context.createMediaStreamDestination();this.context.createMediaElementSource(e).connect(t)}catch(e){throw new EE(_E.LOCAL_AEC_ERROR,e.toString()).print()}if(!t){throw new EE(_E.LOCAL_AEC_ERROR,"no dest node when local aec").print()}const 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();const e=this.element,t=await this.getTracksFromMediaElement(e);this.peerPair&&this.peerPair[0].addTrack(t),await this.switchSdp()}close(){CE.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}}var PN,LN;lp(DN,"count",0);const kN=window.AudioContext||window.webkitAudioContext;const MN=new(PN=Sg({report:Tg}),JT((LN=class{constructor(){lp(this,"units",[]),lp(this,"context",void 0)}processExternalMediaAEC(e){if(!this._doesEnvironmentNeedAEC())return CE.debug("the system does not need to process local aec"),-1;this.context||(this.context=new kN);let t=this.units.find(t=>t&&t.getElement()===e);return t||(t=new DN(e,this.context),this.units.push(t)),t.startEchoCancellation(),CE.debug("start processing local audio echo cancellation, id is",t.id),t.id}_doesEnvironmentNeedAEC(){return Mh().name!==Nh.SAFARI}}).prototype,"processExternalMediaAEC",[PN],Object.getOwnPropertyDescriptor(LN.prototype,"processExternalMediaAEC"),LN.prototype),LN);VE("PROCESS_ID","process-".concat(wI(8,""),"-").concat(wI(4,""),"-").concat(wI(4,""),"-").concat(wI(4,""),"-").concat(wI(12,""))),function(){const e=Mh();kS.getDisplayMedia=function(e){if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)return!0;return!1}(),kS.getStreamFromExtension=e.name===Nh.CHROME&&Number(e.version)>34,kS.supportUnifiedPlan=function(){if(!window.RTCRtpTransceiver)return!1;if(!("currentDirection"in RTCRtpTransceiver.prototype))return!1;const e=new RTCPeerConnection;let t=!1;try{e.addTransceiver("audio"),t=!0}catch(e){}return e.close(),t}(),kS.supportMinBitrate=e.name===Nh.CHROME||e.name===Nh.EDGE,kS.supportSetRtpSenderParameters=function(){const e=Mh();if(!window.RTCRtpSender||!window.RTCRtpSender.prototype.setParameters||!window.RTCRtpSender.prototype.getParameters)return!1;return!!tp()||(!(!Wh()&&!Fh())||e.name===Nh.FIREFOX&&Number(e.version)>=64)}(),e.name===Nh.SAFARI&&(Number(e.version)>=14?kS.supportDualStream=!0:kS.supportDualStream=!1),kS.webAudioMediaStreamDest=function(){const e=Mh();if(e.name===Nh.SAFARI&&Number(e.version)<12)return!1;return!0}(),kS.supportReplaceTrack=function(){if(!window.RTCRtpSender)return!1;if("function"==typeof RTCRtpSender.prototype.replaceTrack)return!0;return!1}(),kS.supportWebGL="undefined"!=typeof WebGLRenderingContext,kS.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,tp()||(kS.webAudioWithAEC=!0),kS.supportShareAudio=function(){const e=Mh();if((e.os===wh.WIN_10||e.os===wh.WIN_81||e.os===wh.WIN_7||e.os===wh.LINUX||e.os===wh.MAC_OS)&&e.name===Nh.CHROME&&Number(e.version)>=74)return!0;return!1}(),kS.supportDualStreamEncoding=function(){const e=Mh();if(FE("DISABLE_WEBAUDIO"))return!0;return"Safari"===e.name&&Number(e.version)>=14||!!("Chrome"===e.name&&/Windows/i.test(e.os||"")&&Number(e.version)>=100&&FE("CHROME_DUAL_STREAM_USE_ENCODING"))}(),kS.supportDataChannel=function(){if(function(e){const t=Mh();return!(t.name!==Nh.CHROME||!t.osVersion)&&Number(t.version)>=e}(76)||function(e){const t=Mh();return!(t.name!==Nh.FIREFOX||!t.osVersion)&&Number(t.version)>=e}(68)||function(e){const t=Mh();return!(t.name!==Nh.SAFARI||!t.osVersion)&&Number(t.version)>=e}(14))return!0;return!1}(),CE.info("browser compatibility",JSON.stringify(kS),JSON.stringify(e)),kS.supportPCSetConfiguration=!Hh()&&!!RTCPeerConnection.prototype.setConfiguration}(),function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void CE.error("Error loading sdk config",e.message)}if(e)try{const t=JSON.parse(window.atob(e)),i=Date.now();CE.debug("Loading global parameters from cache",t),Object.keys(t).forEach(e=>{if(Object.prototype.hasOwnProperty.call(jE,e)){const{value:n,expires:r}=t[e];if(r&&r<=i)return;BE[e]=n,jE[e]=n}})}catch(t){CE.error("Error loading mutableParamsCache: ".concat(e),t.message)}}(),Array.isArray(BE.AREAS)&&BE.AREAS.length>0&&Cv(BE.AREAS,!0);const UN={__CLIENT_LIST__:qE,__TRACK_LIST__:JE,VERSION:AE,BUILD:yE,setParameter:(e,t,i)=>{CE.debug("setParameter key:".concat(e,", value:").concat(JSON.stringify(t))),VE(e,t,i)},getParameter:FE,getSupportedCodec:async function(){let e={audio:[],video:[]};try{let t=new RTCPeerConnection;t.addTransceiver("video",{direction:"recvonly"}),t.addTransceiver("audio",{direction:"recvonly"});const i=(await t.createOffer()).sdp;if(!i)return e;t.close(),t=null,e=function(e){const 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 EE(_E.CREATE_OFFER_FAILED,e.toString&&e.toString()).print()}return e},checkSystemRequirements:function(){const e=Tg.reportApiInvoke(null,{name:uf.CHECK_SYSTEM_REQUIREMENTS,options:[],tag:lf.TRACER});let t=!1;try{const e=window.RTCPeerConnection,i=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,n=window.WebSocket;t=!!(e&&i&&n)}catch(e){return CE.error("check system requirement failed: ",e),!1}let i=!1;const n=Mh();n.name===Nh.CHROME&&Number(n.version)>=58&&(!Bh()||jh())&&(i=!0),n.name===Nh.FIREFOX&&Number(n.version)>=56&&(i=!0),n.name===Nh.OPERA&&Number(n.version)>=45&&(i=!0),n.name===Nh.SAFARI&&Number(n.version)>=11&&(i=!0),($h()||Mh().name===Nh.QQ)&&(i=!0),CE.debug("checkSystemRequirements, api:",t,"browser",i);const r=t&&i;return e.onSuccess(r),r},getDevices:function(e){return zg.enumerateDevices(!0,!0,e)},getMicrophones:function(e){return zg.getRecordingDevices(e)},getCameras:function(e){return zg.getCamerasDevices(e)},getElectronScreenSources:jg,getPlaybackDevices:function(e){return zg.getSpeakers(e)},createClient:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{codec:"vp8",audioCodec:"opus",mode:"rtc"};const t=Tg.reportApiInvoke(null,{name:uf.CREATE_CLIENT,options:[e],tag:lf.TRACER});try{Df(e)}catch(e){throw t.onError(e),e}return void 0===e.audioCodec&&(e.audioCodec="opus"),t.onSuccess(),new IN(RN(RN({forceWaitGatewayResponse:!0},e),{},{role:"rtc"===e.mode?"host":e.role}))},createCameraVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=Tg.reportApiInvoke(null,{tag:lf.TRACER,name:uf.CREATE_CAM_VIDEO_TRACK,options:[ON({},e)]}),i=lC(e),n=wI(8,"track-cam-");let r=null;CE.info("start create camera video track with config",JSON.stringify(e),"trackId",n);try{r=(await Yg({video:i},n)).getVideoTracks()[0]||null}catch(e){throw t.onError(e),e}if(!r){const e=new EE(_E.UNEXPECTED_ERROR,"can not find track in media stream");return t.onError(e),e.throw()}e.optimizationMode&&bN(n,r,e,LE(e.encoderConfig));const o=new ZC(r,e,i,e.scalabiltyMode?ME(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,n);return t.onSuccess(o.getTrackId()),CE.info("create camera video success, trackId:",n),o},createCustomVideoTrack:function(e){const t=Tg.reportApiInvoke(null,{tag:lf.TRACER,name:uf.CREATE_CUSTOM_VIDEO_TRACK,options:[e]}),i=new QC(e.mediaStreamTrack,{bitrateMax:e.bitrateMax,bitrateMin:e.bitrateMin},e.scalabiltyMode?ME(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode);return t.onSuccess(i.getTrackId()),CE.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";const i=Tg.reportApiInvoke(null,{tag:lf.TRACER,name:uf.CREATE_SCREEN_VIDEO_TRACK,options:[ON({},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";const n=hC(e),r=wI(8,"track-scr");let o=null,s=null;const a=MS();if(!a.supportShareAudio&&"enable"===t){const e=new EE(_E.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return i.onError(e),e.throw()}CE.info("start create screen video track with config",e,"withAudio",t,"trackId",r);try{const e=await Yg({screen:n,screenAudio:"auto"===t?a.supportShareAudio:"enable"===t},r);o=e.getVideoTracks()[0]||null,s=e.getAudioTracks()[0]||null}catch(e){throw i.onError(e),e}if(!o){const e=new EE(_E.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(e),e.throw()}if(!s&&"enable"===t){o&&o.stop();const e=new EE(_E.SHARE_AUDIO_NOT_ALLOWED);return i.onError(e),e.throw()}e.optimizationMode||(e.optimizationMode="detail"),e.optimizationMode&&(bN(r,o,e,e.encoderConfig&&kE(e.encoderConfig)),e.encoderConfig&&"string"!=typeof e.encoderConfig&&(e.encoderConfig.bitrateMin=e.encoderConfig.bitrateMax));const c=new QC(o,e.encoderConfig?kE(e.encoderConfig):{},e.scalabiltyMode?ME(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,r,[aS.SCREEN_TRACK]);if(!s)return i.onSuccess(c.getTrackId()),CE.info("create screen video track success","video:",c.getTrackId()),c;const d=new tI(s);return i.onSuccess([c.getTrackId(),d.getTrackId()]),CE.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]:{};const i=Tg.reportApiInvoke(null,{tag:lf.TRACER,name:uf.CREATE_MIC_AND_CAM_TRACKS,options:[e,t]}),n=lC(t),r=pC(e),o=wI(8,"track-mic-"),s=wI(8,"track-cam-");let a=null,c=null;CE.info("start create camera video track(".concat(s,") and microphone audio track(").concat(o,") with config, audio: ").concat(JSON.stringify(e),", video: ").concat(JSON.stringify(t)));try{const e=await Yg({audio:r,video:n},"".concat(o,"-").concat(s));a=e.getAudioTracks()[0],c=e.getVideoTracks()[0]}catch(e){throw i.onError(e),e}if(!a||!c){const e=new EE(_E.UNEXPECTED_ERROR,"can not find tracks in media stream");return i.onError(e),e.throw()}t.optimizationMode&&bN(s,c,t,LE(t.encoderConfig));const d=new iI(a,e,r,o),u=new ZC(c,t,n,t.scalabiltyMode?ME(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,s);return i.onSuccess([d.getTrackId(),u.getTrackId()]),CE.info("create camera video track(".concat(s,") and microphone audio track(").concat(o,") success")),[d,u]},createMicrophoneAudioTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=Tg.reportApiInvoke(null,{tag:lf.TRACER,name:uf.CREATE_MIC_AUDIO_TRACK,options:[e]}),i=pC(e),n=wI(8,"track-mic-");let r=null;CE.info("start create microphone audio track with config",JSON.stringify(e),"trackId",n);try{r=(await Yg({audio:i},n)).getAudioTracks()[0]||null}catch(e){throw t.onError(e),e}if(!r){const e=new EE(_E.UNEXPECTED_ERROR,"can not find track in media stream");return t.onError(e),e.throw()}const o=new iI(r,e,i,n);return t.onSuccess(o.getTrackId()),CE.info("create microphone audio track success, trackId:",n),o},createCustomAudioTrack:function(e){const t=Tg.reportApiInvoke(null,{tag:lf.TRACER,name:uf.CREATE_CUSTOM_AUDIO_TRACK,options:[e]}),i=new tI(e.mediaStreamTrack,e.encoderConfig?xE(e.encoderConfig):{});return CE.info("create custom audio track success with config",e,"trackId",i.getTrackId()),t.onSuccess(i.getTrackId()),i},createBufferSourceAudioTrack:async function(e){const t=Tg.reportApiInvoke(null,{tag:lf.TRACER,name:uf.CREATE_BUFFER_AUDIO_TRACK,options:[e]});if(FE("DISABLE_WEBAUDIO"))throw new EE(_E.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");const i=wI(8,"track-buf-");CE.info("start create buffer source audio track with config",JSON.stringify(e),"trackId",i);const n=e.source;if(!(e.source instanceof AudioBuffer))try{e.source=await yN(e.source,e.cacheOnlineFile)}catch(e){return t.onError(e),e.throw()}const r=new vN(e.source),o=new nI(n,r,e.encoderConfig?xE(e.encoderConfig):{},i);return CE.info("create buffer source audio track success, trackId:",i),t.onSuccess(o.getTrackId()),o},setAppType:function(e){if(CE.debug("setAppType: ".concat(e)),!(Number.isInteger(e)&&e>=0))throw CE.debug("Invalid appType"),new EE(_E.INVALID_PARAMS,"invalid app type",e);VE("APP_TYPE",Math.floor(e))},setLogLevel:function(e){CE.setLogLevel(e)},enableLogUpload:function(){FE("USE_NEW_LOG")?VE("UPLOAD_LOG",!0):CE.enableLogUpload()},disableLogUpload:function(){FE("USE_NEW_LOG")?VE("UPLOAD_LOG",!1):CE.disableLogUpload()},createChannelMediaRelayConfiguration:function(){return new tC},checkAudioTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=Tg.reportApiInvoke(null,{tag:lf.TRACER,name:uf.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof tI||e instanceof yb)){const e=new EE(_E.INVALID_TRACK,"the parameter is not a audio track");return i.onError(e),e.throw()}t&&t<1e3&&(t=1e3);const n=e instanceof tI?e.getTrackLabel():"remote_track",r=e.getVolumeLevel();let o=r,s=r;const a=Date.now();return new Sl(r=>{const c=setInterval(()=>{const d=e.getVolumeLevel();o=d>o?d:o,s=d<s?d:s;const u=o-s>1e-4,l=Date.now()-a;if(u||l>t){clearInterval(c);const t=u,s={duration:l,deviceLabel:n,maxVolumeLevel:o,result:t};CE.info("[track-".concat(e.getTrackId(),"] check audio track active completed. ").concat(JSON.stringify(s))),i.onSuccess(s),r(t)}},200)})},checkVideoTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=Tg.reportApiInvoke(null,{tag:lf.TRACER,name:uf.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof QC||e instanceof Cb)){const e=new EE(_E.INVALID_TRACK,"the parameter is not a video track");return i.onError(e),e.throw()}const n=4;t&&t<1e3&&(t=1e3);const r=e instanceof QC?e.getTrackLabel():"remote_track",o=e.getMediaStreamTrack(!0),s=document.createElement("video");s.style.width="1px",s.style.height="1px",s.setAttribute("muted",""),s.muted=!0,s.setAttribute("playsinline",""),s.controls=!1,(Wh()||Fh())&&(s.style.opacity="0.01",s.style.position="fixed",s.style.left="0",s.style.top="0",document.body.appendChild(s)),s.srcObject=new MediaStream([o]),s.play();const a=document.createElement("canvas");a.width=160,a.height=120;let c=0,d=0;try{const e=Date.now();c=await NN(s,t,a,n),d=Date.now()-e}catch(e){throw i.onError(e),e}wN===Nh.SAFARI&&(s.pause(),s.remove()),s.srcObject=null;const u=c>n,l={duration:d,changedPicNum:c,deviceLabel:r,result:u};return CE.info("[track-".concat(e.getTrackId(),"] check video track active completed. ").concat(JSON.stringify(l))),i.onSuccess(l),u},setArea:Cv,audioElementPlayCenter:Zg,processExternalMediaAEC:function(e){MN.processExternalMediaAEC(e)},registerExtensions:function(e){e.forEach(e=>{const t=e;t.__registered__=!0,t.logger.hookLog=CE.extLog,t.reporter.hookApiInvoke=Tg.extApiInvoke,t.parameters&&Object.keys(t.parameters).forEach(e=>{t.parameters[e]=FE(e)})})},ChannelMediaRelayError:tS,ChannelMediaRelayEvent:$f,ChannelMediaRelayState:eS,RemoteStreamFallbackType:dS,RemoteStreamType:cS,ConnectionDisconnectedReason:gf,AudienceLatencyLevelType:Tf,AREAS:hS},xN=window||document;return Object.defineProperties(UN,{onAudioAutoplayFailed:{get:()=>lg.onAudioAutoplayFailed,set:e=>{lg.onAudioAutoplayFailed=e}},onAutoplayFailed:{get:()=>lg.onAutoplayFailed,set:e=>{lg.onAutoplayFailed=e}},_onSecurityPolicyViolation:{value:void 0,writable:!0},_cspEventHandlerPointer:{value:void 0,writable:!0},onSecurityPolicyViolation:{get:()=>UN._onSecurityPolicyViolation,set(e){if(UN._onSecurityPolicyViolation=e,!xN)return;const t=e=>{if(!(e&&e.blockedURI&&UN.onSecurityPolicyViolation))return;const t=e.blockedURI;FE("CSP_DETECTED_HOSTNAME_LIST").some(e=>t.includes(e))&&UN.onSecurityPolicyViolation&&"function"==typeof UN.onSecurityPolicyViolation&&UN.onSecurityPolicyViolation(e)},i=UN._cspEventHandlerPointer;i&&xN.removeEventListener("securitypolicyviolation",i),e&&"function"==typeof e&&xN.addEventListener("securitypolicyviolation",t),UN._cspEventHandlerPointer=t}}}),zg.on(pf.CAMERA_DEVICE_CHANGED,e=>{CE.info("camera device changed",JSON.stringify(e)),UN.onCameraChanged&&UN.onCameraChanged(e)}),zg.on(pf.RECORDING_DEVICE_CHANGED,e=>{CE.info("microphone device changed",JSON.stringify(e)),UN.onMicrophoneChanged&&UN.onMicrophoneChanged(e)}),zg.on(pf.PLAYOUT_DEVICE_CHANGED,e=>{CE.debug("playout device changed",JSON.stringify(e)),UN.onPlaybackDeviceChanged&&UN.onPlaybackDeviceChanged(e)}),Zg.onAutoplayFailed=()=>{CE.info("detect audio element autoplay failed"),lg.onAudioAutoplayFailed&&lg.onAudioAutoplayFailed()},wg.on("autoplay-failed",()=>{CE.info("detect webaudio autoplay failed"),lg.onAudioAutoplayFailed&&lg.onAudioAutoplayFailed()}),window&&(window.__ARTC__=UN),UN}));
|