vendor: 11,391 bytes, lines 1-5
1/** 2 * AgoraWebSDK_N-v4.17.2-0-gb960eec4-dirty Copyright AgoraInc. 3 */ 4 5!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).forEac
vendor: 4,187 bytes, line 5
5h(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.INT
vendor: 8,565 bytes, line 5
5ERRUPTED),_=_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[
vendor: 4,508 bytes, line 5
5n],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}});
vendor: 3,496 bytes, line 5
5var 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});
vendor: 4,187 bytes, line 5
5const 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().forEac
vendor: 4,102 bytes, line 5
5h(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||{}
vendor: 4,443 bytes, line 5
5,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");
vendor: 8,700 bytes, line 5
5if(!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("getL
5ocalStreams"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.pu
vendor: 9,488 bytes, line 5
5sh(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.
vendor: 4,109 bytes, line 5
5sdpMLineIndex,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.s
vendor: 4,455 bytes, line 5
5dp.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;
vendor: 4,548 bytes, line 5
5a++)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?|;
vendor: 5,512 bytes, line 5
5|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]],[/\
vendor: 1,497 bytes, line 5
5(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\
5:([\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;
5if(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(e){const t=Mh();return!(t.name!==Nh.CHROME||!t.osVersion)&&Number(t.version)>=e}function qh(e){const t=Mh();return!(t.name!==Nh.EDGE||!t.osVersion)&&Number(t.version)>=e}function Jh(e){const t=Mh();return!(t.name!==Nh.OPERA||!t.osVersion)&&Number(t.version)>=e}function Xh(){const e=Mh();return!(e.name!==Nh.CHROME||!e.osVersion)&&Number(e.version)<=90}function zh(){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 Qh(){const e=Mh();if(e.os!==wh.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])}function Zh(){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 $h(){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 ep(){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 tp(){return Wh()&&navigator.maxTouchPoints>0}function ip(){return Mh().name===Nh.WECHAT}function np(){return window.navigator.appVersion&&null!==window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)&&window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)[1]<=35}function rp(){const e=Mh();if(e.name===Nh.EDGE||e.name===Nh.SAFARI)return!1;return!!navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]./i)}function op(){return Mh().os===wh.ANDROID}function sp(){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 ap={exports:{}},cp=Ii,dp=g,up=Ht.f;cp({target:"Object",stat:!0,forced:Object.defineProperty!==up,sham:!dp},{defineProperty:up});var lp=J.Object,hp=ap.exports=function(e,t,i){return lp.defineProperty(e,t,i)};lp.defineProperty.sham&&(hp.sham=!0);var pp=ap.exports;function _p(e,t,i){return t in e?pp(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}var Ep,mp={exports:{}},fp=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)}},Sp=fp,Tp=Object.prototype.toString,gp=(Ep=Object.create(null),function(e){var t=Tp.call(e);return Ep[t]||(Ep[t]=t.slice(8,-1).toLowerCase())});function Rp(e){return e=e.toLowerCase(),function(t){return gp(t)===e}}function Ip(e){return Array.isArray(e)}function vp(e){return void 0===e}var Cp=Rp("ArrayBuffer");function yp(e){return null!==e&&"object"==typeof e}function Ap(e){if("object"!==gp(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}var Op=Rp("Date"),bp=Rp("File"),wp=Rp("Blob"),Np=Rp("FileList");function Dp(e){return"[object Function]"===Tp.call(e)}var Pp=Rp("URLSearchParams");function Lp(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),Ip(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 kp,Mp=(kp="undefined"!=typeof Uint8Array&&Object.getPrototypeOf(Uint8Array),function(e){return kp&&e instanceof kp}),Up={isArray:Ip,isArrayBuffer:Cp,isBuffer:function(e){return null!==e&&!vp(e)&&null!==e.constructor&&!vp(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||Tp.call(e)===t||Dp(e.toString)&&e.toString()===t)},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Cp(e.buffer)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:yp,isPlainObject:Ap,isUndefined:vp,isDate:Op,isFile:bp,isBlob:wp,isFunction:Dp,isStream:function(e){return yp(e)&&Dp(e.pipe)},isURLSearchParams:Pp,isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)}
vendor: 15,930 bytes, line 5
5,forEach:Lp,merge:function e(){var t={};function i(i,n){Ap(t[n])&&Ap(i)?t[n]=e(t[n],i):Ap(i)?t[n]=e({},i):Ip(i)?t[n]=i.slice():t[n]=i}for(var n=0,r=arguments.length;n<r;n++)Lp(arguments[n],i);return t},extend:function(e,t,i){return Lp(t,(function(t,n){e[n]=i&&"function"==typeof t?Sp(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:gp,kindOfTest:Rp,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(vp(t))return null;for(var i=new Array(t);t-- >0;)i[t]=e[t];return i},isTypedArray:Mp,isFileList:Np},xp=Up;function Vp(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var Fp=function(e,t,i){if(!t)return e;var n;if(i)n=i(t);else if(xp.isURLSearchParams(t))n=t.toString();else{var r=[];xp.forEach(t,(function(e,t){null!=e&&(xp.isArray(e)?t+="[]":e=[e],xp.forEach(e,(function(e){xp.isDate(e)?e=e.toISOString():xp.isObject(e)&&(e=JSON.stringify(e)),r.push(Vp(t)+"="+Vp(e))})))})),n=r.join("&")}if(n){var o=e.indexOf("#");-1!==o&&(e=e.slice(0,o)),e+=(-1===e.indexOf("?")?"?":"&")+n}return e},jp=Up;function Bp(){this.handlers=[]}Bp.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},Bp.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},Bp.prototype.forEach=function(e){jp.forEach(this.handlers,(function(t){null!==t&&e(t)}))};var Gp=Bp,Wp=Up,Hp=Up;function Kp(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)}Hp.inherits(Kp,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 Yp=Kp.prototype,qp={};["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){qp[e]={value:e}})),Object.defineProperties(Kp,qp),Object.defineProperty(Yp,"isAxiosError",{value:!0}),Kp.from=function(e,t,i,n,r,o){var s=Object.create(Yp);return Hp.toFlatObject(e,s,(function(e){return e!==Error.prototype})),Kp.call(s,e.message,t,i,n,r),s.name=e.name,o&&Object.assign(s,o),s};var Jp=Kp,Xp={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},zp=Up;var Qp=function(e,t){t=t||new FormData;var i=[];function n(e){return null===e?"":zp.isDate(e)?e.toISOString():zp.isArrayBuffer(e)||zp.isTypedArray(e)?"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}return function e(r,o){if(zp.isPlainObject(r)||zp.isArray(r)){if(-1!==i.indexOf(r))throw Error("Circular reference detected in "+o);i.push(r),zp.forEach(r,(function(i,r){if(!zp.isUndefined(i)){var s,a=o?o+"."+r:r;if(i&&!o&&"object"==typeof i)if(zp.endsWith(r,"{}"))i=JSON.stringify(i);else if(zp.endsWith(r,"[]")&&(s=zp.toArray(i)))return void s.forEach((function(e){!zp.isUndefined(e)&&t.append(a,n(e))}));e(i,a)}})),i.pop()}else t.append(o,n(r))}(e),t},Zp=Jp,$p=Up,e_=$p.isStandardBrowserEnv()?{write:function(e,t,i,n,r,o){var s=[];s.push(e+"="+encodeURIComponent(t)),$p.isNumber(i)&&s.push("expires="+new Date(i).toGMTString()),$p.isString(n)&&s.push("path="+n),$p.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(){}},t_=function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)},i_=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e},n_=function(e,t){return e&&!t_(t)?i_(e,t):t},r_=Up,o_=["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"],s_=Up,a_=s_.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=s_.isString(t)?n(t):t;return i.protocol===e.protocol&&i.host===e.host}}():function(){return!0},c_=Jp;function d_(e){c_.call(this,null==e?"canceled":e,c_.ERR_CANCELED),this.name="CanceledError"}Up.inherits(d_,c_,{__CANCEL__:!0});var u_=d_,l_=Up,h_=function(e,t,i){var n=i.config.validateStatus;i.status&&n&&!n(i.status)?t(new Zp("Request failed with status code "+i.status,[Zp.ERR_BAD_REQUEST,Zp.ERR_BAD_RESPONSE][Math.floor(i.status/100)-4],i.config,i.request,i)):e(i)},p_=e_,__=Fp,E_=n_,m_=function(e){var t,i,n,r={};return e?(r_.forEach(e.split("\n"),(function(e){if(n=e.indexOf(":"),t=r_.trim(e.substr(0,n)).toLowerCase(),i=r_.trim(e.substr(n+1)),t){if(r[t]&&o_.indexOf(t)>=0)return;r[t]="set-cookie"===t?(r[t]?r[t]:[]).concat([i]):r[t]?r[t]+", "+i:i}})),r):r},f_=a_,S_=Xp,T_=Jp,g_=u_,R_=function(e){var t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""},I_=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)}l_.isFormData(r)&&l_.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=E_(e.baseURL,e.url);function h(){if(c){var n="getAllResponseHeaders"in c?m_(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};h_((function(e){t(e),a()}),(function(e){i(e),a()}),r),c=null}}if(c.open(e.method.toUpperCase(),__(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 T_("Request aborted",T_.ECONNABORTED,e,c)),c=null)},c.onerror=function(){i(new T_("Network Error",T_.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||S_;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),i(new T_(t,n.clarifyTimeoutError?T_.ETIMEDOUT:T_.ECONNABORTED,e,c)),c=null},l_.isStandardBrowserEnv()){var p=(e.withCredentials||f_(l))&&e.xsrfCookieName?p_.read(e.xsrfCookieName):void 0;p&&(o[e.xsrfHeaderName]=p)}"setRequestHeader"in c&&l_.forEach(o,(function(e,t){void 0===r&&"content-type"===t.toLowerCase()?delete o[t]:c.setRequestHeader(t,e)})),l_.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 g_: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 _=R_(l);_&&-1===["http","https","file"].indexOf(_)?i(new T_("Unsupported protocol "+_+":",T_.ERR_BAD_REQUEST,e)):c.send(r)}))},v_=Up,C_=function(e,t){Wp.forEach(e,(function(i,n){n!==t&&n.toUpperCase()===t.toUpperCase()&&(e[t]=i,delete e[n])}))},y_=Jp,A_=Qp,O_={"Content-Type":"application/x-www-form-urlencoded"};function b_(e,t){!v_.isUndefined(e)&&v_.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var w_,N_={transitional:Xp,adapter:(("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(w_=I_),w_),transformRequest:[function(e,t){if(C_(t,"Accept"),C_(t,"Content-Type"),v_.isFormData(e)||v_.isArrayBuffer(e)||v_.isBuffer(e)||v_.isStream(e)||v_.isFile(e)||v_.isBlob(e))return e;if(v_.isArrayBufferView(e))return e.buffer;if(v_.isURLSearchParams(e))return b_(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString();var i,n=v_.isObject(e),r=t&&t["Content-Type"];if((i=v_.isFileList(e))||n&&"multipart/form-data"===r){var o=this.env&&this.env.FormData;return A_(i?{"files[]":e}:e,o&&new o)}return n||"application/json"===r?(b_(t,"application/json"),function(e,t,i){if(v_.isString(e))try{return(t||JSON.parse)(e),v_.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(i||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){var t=this.transitional||N_.transitional,i=t&&t.silentJSONParsing,n=t&&t.forcedJSONParsing,r=!i&&"json"===this.responseType;if(r||n&&v_.isString(e)&&e.length)try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw y_.from(e,y_.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, */*"}}};v_.forEach(["delete","get","head"],(function(e){N_.headers[e]={}})),v_.forEach(["post","put","patch"],(function(e){N_.headers[e]=v_.merge(O_)}));var D_=N_,P_=Up,L_=D_,k_=function(e){return!(!e||!e.__CANCEL__)},M_=Up,U_=function(e,t,i){var n=this||L_;return P_.forEach(i,(function(i){e=i.call(n,e,t)})),e},x_=k_,V_=D_,F_=u_;function j_(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new F_}var B_=Up,G_=function(e,t){t=t||{};var i={};function n(e,t){return B_.isPlainObject(e)&&B_.isPlainObject(t)?B_.merge(e,t):B_.isPlainObject(t)?B_.merge({},t):B_.isArray(t)?t.slice():t}function r(i){return B_.isUndefined(t[i])?B_.isUndefined(e[i])?void 0:n(void 0,e[i]):n(e[i],t[i])}function o(e){if(!B_.isUndefined(t[e]))return n(void 0,t[e])}function s(i){return B_.isUndefined(t[i])?B_.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 B_.forEach(Object.keys(e).concat(Object.keys(t)),(function(e){var t=c[e]||r,n=t(e);B_.isUndefined(n)&&t!==a||(i[e]=n)})),i},W_="0.27.2",H_=W_,K_=Jp,Y_={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){Y_[e]=function(i){return typeof i===e||"a"+(t<1?"n ":" ")+e}}));var q_={};Y_.transitional=function(e,t,i){function n(e,t){return"[Axios v"+H_+"] Transitional option '"+e+"'"+t+(i?". "+i:"")}return function(i,r,o){if(!1===e)throw new K_(n(r," has been removed"+(t?" in "+t:"")),K_.ERR_DEPRECATED);return t&&!q_[r]&&(q_[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 J_=Up,X_=Fp,z_=Gp,Q_=function(e){return j_(e),e.headers=e.headers||{},e.data=U_.call(e,e.data,e.headers,e.transformRequest),e.headers=M_.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),M_.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||V_.adapter)(e).then((function(t){return j_(e),t.data=U_.call(e,t.data,t.headers,e.transformResponse),t}),(function(t){return x_(t)||(j_(e),t&&t.response&&(t.response.data=U_.call(e,t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))},Z_=G_,$_=n_,eE={assertOptions:function(e,t,i){if("object"!=typeof e)throw new K_("options must be an object",K_.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 K_("option "+o+" must be "+c,K_.ERR_BAD_OPTION_VALUE)}else if(!0!==i)throw new K_("Unknown option "+o,K_.ERR_BAD_OPTION)}},validators:Y_},tE=eE.validators;function iE(e){this.defaults=e,this.interceptors={request:new z_,response:new z_}}iE.prototype.request=function(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},(t=Z_(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&&eE.assertOptions(i,{silentJSONParsing:tE.transitional(tE.boolean),forcedJSONParsing:tE.transitional(tE.boolean),clarifyTimeoutError:tE.transitional(tE.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=[Q_,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=Q_(c)}catch(e){return Promise.reject(e)}for(;s.length;)o=o.then(s.shift(),s.shift());return o},iE.prototype.getUri=function(e){e=Z_(this.defaults,e);var t=$_(e.baseURL,e.url);return X_(t,e.params,e.paramsSerializer)},J_.forEach(["delete","get","head","options"],(function(e){iE.prototype[e]=function(t,i){return this.request(Z_(i||{},{method:e,url:t,data:(i||{}).data}))}})),J_.forEach(["post","put","patch"],(function(e){function t(t){return function(i,n,r){return this.request(Z_(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:i,data:n}))}}iE.prototype[e]=t(),iE.prototype[e+"Form"]=t(!0)}));var nE=iE,rE=u_;function oE(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 rE(e),t(i.reason))}))}oE.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},oE.prototype.subscribe=function(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]},oE.prototype.unsubscribe=function(e){if(this._listeners){var t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}},oE.source=function(){var e;return{token:new oE((function(t){e=t})),cancel:e}};var sE=oE,aE=Up,cE=Up,dE=fp,uE=nE,lE=G_;var hE=function e(t){var i=new uE(t),n=dE(uE.prototype.request,i);
5return cE.extend(n,uE.prototype,i),cE.extend(n,i),n.create=function(i){return e(lE(t,i))},n}(D_);hE.Axios=uE,hE.CanceledError=u_,hE.CancelToken=sE,hE.isCancel=k_,hE.VERSION=W_,hE.toFormData=Qp,hE.AxiosError=Jp,hE.Cancel=hE.CanceledError,hE.all=function(e){return Promise.all(e)},hE.spread=function(e){return function(t){return e.apply(null,t)}},hE.isAxiosError=function(e){return aE.isObject(e)&&!0===e.isAxiosError},mp.exports=hE,mp.exports.default=hE;var pE=mp.exports;class _E{constructor(e){_p(this,"logger",void 0),_p(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 EE{constructor(){_p(this,"_events",{}),_p(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 mE=new class extends EE{reportLogUploadError(e){this.emit("REPORT_LOG_UPLOAD",e)}};let fE;!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_INVA
5LID="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"}(fE||(fE={}));
5class SE 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),_p(this,"code",void 0),_p(this,"message",void 0),_p(this,"data",void 0),_p(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&&OE.error(this.toString()),"warning"===e&&OE.warning(this.toString()),this}throw(){throw this.print(),this}}const TE={timeout:500,timeoutFactor:1.5,maxRetryCount:1/0,maxRetryTimeout:1e4};function gE(e,t){const i=Math.floor(t.timeout*Math.pow(t.timeoutFactor,e));return Math.min(t.maxRetryTimeout,i)}function RE(e,t,i,n){const r=Object.assign({},TE,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 SE(fE.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 IE(){const e=new Date;return e.toTimeString().split(" ")[0]+":"+e.getMilliseconds()}function vE(){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 CE={DEBUG:0,INFO:1,WARNING:2,ERROR:3,NONE:4},yE=Date.now(),AE=e=>{for(const t in CE)if(Object.prototype.hasOwnProperty.call(CE,t)&&CE[t]===e)return t;return"DEFAULT"};const OE=new class{constructor(){_p(this,"proxyServerURL",void 0),_p(this,"logLevel",CE.DEBUG),_p(this,"uploadState","collecting"),_p(this,"uploadLogWaitingList",[]),_p(this,"uploadLogUploadingList",[]),_p(this,"uploadErrorCount",0),_p(this,"currentLogID",0),_p(this,"url",void 0),_p(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=[CE.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=[CE.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=[CE.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=[CE.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=[CE.DEBUG].concat(t);this.uploadLog.apply(this,n)}setLogLevel(e){e=Math.min(Math.max(0,e),4),this.logLevel=e}enableLogUpload(){BE("UPLOAD_LOG",!0)}disableLogUpload(){BE("UPLOAD_LOG",!1),this.uploadLogUploadingList=[],this.uploadLogWaitingList=[]}setProxyServer(e){this.proxyServerURL=e}prefix(e){return new _E(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()-yE<100)return void setTimeout(()=>{this.log(...t)},Date.now()-yE);const n=Math.max(0,Math.min(4,t[0]));if(t[0]=IE()+" Agora-SDK [".concat(AE(n),"]:"),this.appendLogToWaitingList(n,...t),n<this.logLevel)return;const r=IE()+" %cAgora-SDK [".concat(AE(n),"]:");let o=[];if(!GE("USE_NEW_LOG"))switch(n){case CE.DEBUG:o=[r,"color: #64B5F6;"].concat(t.slice(1)),console.log.apply(console,o);break;case CE.INFO:o=[r,"color: #1E88E5; font-weight: bold;"].concat(t.slice(1)),console.log.apply(console,o);break;case CE.WARNING:o=[r,"color: #FB8C00; font-weight: bold;"].concat(t.slice(1)),console.warn.apply(console,o);break;case CE.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()-yE<100)return void setTimeout(()=>{this.uploadLog(...t)},Date.now()-yE);const n=Math.max(0,Math.min(4,t[0]));t[0]=IE()+" Agora-SDK [".concat(AE(n),"]:"),this.appendLogToWaitingList(n,...t)}appendLogToWaitingList(e){if(!GE("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]=vE()+" Agora-SDK [".concat(AE(e),"]:"):i[0]=vE()+" Agora-SDK [".concat(AE(e),"]:");let r="";
5i.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:wE,process_id:GE("PROCESS_ID"),payload:JSON.stringify(e)};return RE(async()=>{const e=await pE.post(this.url||(this.proxyServerURL?"https://".concat(this.proxyServerURL,"/ls/?h=").concat(GE("LOG_UPLOAD_SERVER"),"&p=443&d=upload/v1"):"https://".concat(GE("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?mE.reportLogUploadError({status:e.response.status,data:e.response.data,headers:e.response.headers,message:e.message}):e.request?mE.reportLogUploadError({status:e.request.status,message:e.message}):mE.reportLogUploadError({status:-1,message:e.message}),!0),{timeout:GE("UPLOAD_LOG_REQUEST_RETRY_INTERVAL"),maxRetryTimeout:GE("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,GE("UPLOAD_LOG_LENGTH_EACH_TIME"))),this.uploadLogs().then(()=>{this.uploadErrorCount=0,this.uploadLogWaitingList.length>0&&window.setTimeout(()=>this.uploadLogInterval(),GE("UPLOAD_LOG_INTERVAL"))}).catch(e=>{this.uploadErrorCount+=1,this.uploadErrorCount<2?window.setTimeout(()=>this.uploadLogInterval(),GE("UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1")):window.setTimeout(()=>this.uploadLogInterval(),GE("UPLOAD_LOG_RETRY_INTERVAL_V1"))}))}},bE="v4.17.2-0-gb960eec4-dirty(4/20/2023, 10:39:51 AM)",wE=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.2"),NE=function(){try{return!0===JSON.parse("true")}catch(e){return!0}}(),DE=["CHINA","GLOBAL"],PE=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=PE;const LE={"90p":YE(160,90),"90p_1":YE(160,90),"120p":YE(160,120,15,30,65),"120p_1":YE(160,120,15,30,65),"120p_3":YE(120,120,15,30,50),"120p_4":YE(212,120),"180p":YE(320,180,15,30,140),"180p_1":YE(320,180,15,30,140),"180p_3":YE(180,180,15,30,100),"180p_4":YE(240,180,15,30,120),"240p":YE(320,240,15,40,200),"240p_1":YE(320,240,15,40,200),"240p_3":YE(240,240,15,40,140),"240p_4":YE(424,240,15,40,220),"360p":YE(640,360,15,80,400),"360p_1":YE(640,360,15,80,400),"360p_3":YE(360,360,15,80,260),"360p_4":YE(640,360,30,80,600),"360p_6":YE(360,360,30,80,400),"360p_7":YE(480,360,15,80,320),"360p_8":YE(480,360,30,80,490),"360p_9":YE(640,360,15,80,800),"360p_10":YE(640,360,24,80,800),"360p_11":YE(640,360,24,80,1e3),"480p":YE(640,480,15,100,500),"480p_1":YE(640,480,15,100,500),"480p_2":YE(640,480,30,100,1e3),"480p_3":YE(480,480,15,100,400),"480p_4":YE(640,480,30,100,750),"480p_6":YE(480,480,30,100,600),"480p_8":YE(848,480,15,100,610),"480p_9":YE(848,480,30,100,930),"480p_10":YE(640,480,10,100,400),"720p":YE(1280,720,15,120,1130),"720p_1":YE(1280,720,15,120,1130),"720p_2":YE(1280,720,30,120,2e3),"720p_3":YE(1280,720,30,120,1710),"720p_5":YE(960,720,15,120,910),"720p_6":YE(960,720,30,120,1380),"1080p":YE(1920,1080,15,120,2080),"1080p_1":YE(1920,1080,15,120,2080),"1080p_2":YE(1920,1080,30,120,3e3),"1080p_3":YE(1920,1080,30,120,3150),"1080p_5":YE(1920,1080,60,120,4780),"1440p":YE(2560,1440,30,120,4850),"1440p_1":YE(2560,1440,30,120,4850),"1440p_2":YE(2560,1440,60,120,7350),"4k":YE(3840,2160,30,120,8910),"4k_1":YE(3840,2160,30,120,8910),"4k_3":YE(3840,2160,60,120,13500)},kE={"480p":qE(640,480,5),"480p_1":qE(640,480,5),"480p_2":qE(640,480,30),"480p_3":qE(640,480,15),"720p":qE(1280,720,5),"720p_1":qE(1280,720,5),"720p_2":qE(1280,720,30),"720p_3":qE(1280,720,15),"1080p":qE(1920,1080,5),"1080p_1":qE(1920,1080,5),"1080p_2":qE(1920,1080,30),"1080p_3":qE(1920,1080,15)},ME={"1SL1TL":JE(1,1),"3SL3TL":JE(3,3),"2SL3TL":JE(2,3)};function UE(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},LE[e]):e}function xE(e){return"string"==typeof e?Object.assign({},kE[e]):e}function VE(e){return"string"==typeof e?Object.assign({},ME[e]):e}const FE={speech_low_quality:KE(16e3,!1),speech_standard:KE(32e3,!1,18),music_standard:KE(48e3,!1),standard_stereo:KE(48e3,!0,56),high_quality:KE(48e3,!1,128),high_quality_stereo:KE(48e3,!0,192)};function jE(e){return"string"==typeof e?Object.assign({},FE[e]):e}function BE(e,t,i){Object.keys(WE).includes(e)&&(!i&&Object.keys(HE).includes(e)||(WE[e]=t))}function GE(e){return WE[e]}const WE={PROCESS_ID:"",ENCRYPT_AES:!0,AREAS:DE,WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io","webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io","webrtc2-4.ap.sd-rtn.com"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-web-2.ap.sd-rtn.com","cds-ap-web-3.agora.io","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-web-2.ap.sd-rtn.com","sua-ap-web-3.agora.io","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-ap-web-1.agora.io","uap-web-2.ap.sd-rtn.com","uap-ap-web-3.agora.io","uap-web-4.ap.sd-rtn.com"],LOG_UPLOAD_SERVER:"logservice.agora.io",EVENT_REPORT_DOMAIN:"statscollector-1.agora.io",EVENT_REPORT_BACKUP_DOMAIN:"web-2.statscollector.sd-rtn.com",ENABLE_EVENT_REPORT:!0,GATEWAY_ADDRESS:[],GATEWAY_WSS_ADDRESS:"",LIVE_STREAMING_ADDRESS:"",HTTP_CONNECT_TIMEOUT:5e3,SIGNAL_REQUEST_TIMEOUT:1e4,REPORT_STATS:!0,UPLOAD_LOG:!1,NOT_REPORT_EVENT:[],SUBSCRIBE_TWCC:!1,PUBLISH_TWCC:!1,PING_PONG_TIME_OUT:10,WEBSOCKET_TIMEOUT_MIN:1e4,EVENT_REPORT_SEND_INTERVAL:3e3,CONFIG_DISTRIBUTE_INTERVAL:3e5,ENABLE_CONFIG_DISTRIBUTE:!0,CANDIDATE_TIMEOUT:5e3,SHOW_REPORT_INVOKER_LOG:!1,JOIN_EXTEND:"",PUB_EXTEND:"",SUB_EXTEND:"",FORCE_TURN:!1,TURN_ENABLE_TCP:!0,TURN_ENABLE_UDP:!0,MAX_UPLOAD_CACHE:50,UPLOAD_CACHE_INTERVAL:2e3,AJAX_REQUEST_CONCURRENT:3,REPORT_APP_SCENARIO:void 0,GATEWAY_DOMAINS:["edge.agora.io","edge.sd-rtn.com"],WORKER_DOMAIN:"edge.agora.io",TURN_DOMAIN:"edge.agora.io",EVENT_REPORT_RETRY:!0,CHROME_FORCE_PLAN_B:!1,AUDIO_SOURCE_VOLUME_UPDATE_INTERVAL:400,AU
5DIO_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_
5SUBSCRIPTION:50,X_GOOGLE_START_BITRATE:void 0,NEW_REPORT_SERVER:!1,NEW_REPORT_SERVER_DOMAINS:["data-reporting.agora.io","data-reporting.agora.io"],VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT:3e5,VIDEO_INSPECT_INTERVAL_MINIMUM:1e3,VIDEO_INSPECT_QUALITY_RATIO:.9,VIDEO_INSPECT_WORKER_MANAGER_HOST:"edge.agora.io",VIDEO_INSPECT_WORKER_MANAGER_PORT:"",VIDEO_INSPECT_WORKER_PORT:"",SHOW_VIDEO_INSPECT_WORKER_MESSAGE:!1,STATS_COLLECTOR_PORT:443,FORCE_TURN_TCP:!1,SUBSCRIBE_AUDIO_FILTER_TOPN:void 0,ENABLE_PUBLISH_AUDIO_FILTER:void 0,WEBAUDIO_INIT_OPTIONS:void 0,FILTER_VIDEO_FEC:!0,FILTER_AUDIO_FEC:!1,CHROME_DUAL_STREAM_USE_ENCODING:!0,EXTENSION_USAGE_UPLOAD_INTERVAL:1e4,ICE_RESTART:!0,ENABLE_USER_LICENSE_CHECK:!0,SIGNAL_CHANNEL:0,TRANSMITTER_INITIAL_RTT:30,TRANSMITTER_INITIAL_RTO:30,TRANSMITTER_MAX_BATCH_ACK_COUNT:2,TRANSMITTER_MAX_RTO:500,DATACHANNEL_COMPRESS:!1,FINGERPRINT:null,DC_JOIN_WITH_FAILBACK:5e3,ENABLE_VIDEO_FRAME_CALLBACK:!0,VIDEO_FREEZE_DURATION:500,SPATIALIZER_PARAMETERS:{},UPLOAD_LOG_INTERVAL:3e3,UPLOAD_LOG_REQUEST_RETRY_INTERVAL:2e3,UPLOAD_LOG_REQUEST_MAX_RETRY_INTERVAL:2e4,UPLOAD_LOG_TRY_INTERVAL_WHILE_OFF:5e3,UPLOAD_LOG_RETRY_INTERVAL_V1:1e4,UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1:200,UPLOAD_LOG_LENGTH_EACH_TIME:10,APP_TYPE:0,DISABLE_WEBAUDIO:!1,CHANNEL_MEDIA_RELAY_SERVERS:void 0,KEEP_LAST_FRAME:!0,FORWARD_P2P_CREATION:!0,SYNC_GROUP:!0,BLOCK_LOCAL_CLIENT:!1,ACCOUNT_REGISTER_RETRY_TIMEOUT:1,ACCOUNT_REGISTER_RETRY_RATIO:2,ACCOUNT_REGISTER_RETRY_TIMEOUT_MAX:6e4,ACCOUNT_REGISTER_RETRY_COUNT_MAX:1e5,AUDIO_CONTEXT:null,WEBCS_BACKUP_CONNECT_TIMEOUT:6e3,PLAYER_STATE_DEFER:2e3,SIGNAL_REQUEST_WATCH_INTERVAL:1e3,FILEPATH_LENMAX:255,DUALSTREAM_OPERATION_CHECK:!0,MEDIA_ELEMENT_EXISTS_DEPTH:3,SHIM_CANDIDATE:!1,LEAVE_MSG_TIMEOUT:2e3,STATS_FILTER:{transportId:!0,googTrackId:!0}},HE={};function KE(e,t,i){return{sampleRate:e,stereo:t,bitrate:i}}function YE(e,t,i,n,r){return{width:e,height:t,frameRate:i,bitrateMin:n,bitrateMax:r}}function qE(e,t,i,n,r){return{width:{max:e},height:{max:t},frameRate:i,bitrateMin:n,bitrateMax:r}}function JE(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}NE||(WE.WEBCS_DOMAIN=["ap-web-1-oversea.agora.io","ap-web-1-north-america.agora.io"],WE.WEBCS_DOMAIN_BACKUP_LIST=["ap-web-2-oversea.agora.io","ap-web-2-north-america.agora.io"],WE.PROXY_CS=["proxy-ap-web-oversea.agora.io","proxy-ap-web-america.agora.io"],WE.CDS_AP=["cds-ap-web-oversea.agora.io","cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],WE.ACCOUNT_REGISTER=["sua-ap-web-oversea.agora.io","sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],WE.UAP_AP=["uap-ap-web-oversea.agora.io","uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],WE.LOG_UPLOAD_SERVER="logservice-oversea.agora.io",WE.EVENT_REPORT_DOMAIN="statscollector-1-oversea.agora.io",WE.EVENT_REPORT_BACKUP_DOMAIN="statscollector-2-oversea.agora.io",WE.PROXY_SERVER_TYPE3="webrtc-cloud-proxy.agora.io",WE.AREAS=["NORTH_AMERICA","OVERSEA"]);const XE=[[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]],zE=[],QE=[];function ZE(e,t){return!!t&&zE.some(i=>i.uid===e&&i.channelName===t)}var $E=Et,em=Ht,tm=N,im=function(e,t,i){var n=$E(t);n in e?em.f(e,n,tm(0,i)):e[n]=i},nm=Un,rm=wi,om=im,sm=h.Array,am=Math.max,cm=function(e,t,i){for(var n=rm(e),r=nm(t,n),o=nm(void 0===i?n:i,n),s=sm(am(o-r,0)),a=0;r<o;r++,a++)om(s,a,e[r]);return s.length=a,s},dm=cm,um=Math.floor,lm=function(e,t){var i=e.length,n=um(i/2);return i<8?hm(e,t):pm(e,lm(dm(e,0,n),t),lm(dm(e,n),t),t)},hm=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},pm=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},_m=lm,Em=ee.match(/firefox\/(\d+)/i),mm=!!Em&&+Em[1],fm=/MSIE|Trident/.test(ee),Sm=ee.match(/AppleWebKit\/(\d+)\./),Tm=!!Sm&&
5+Sm[1],gm=Ii,Rm=d,Im=ve,vm=Fe,Cm=wi,ym=No,Am=i,Om=_m,bm=Vi,wm=mm,Nm=fm,Dm=ae,Pm=Tm,Lm=[],km=Rm(Lm.sort),Mm=Rm(Lm.push),Um=Am((function(){Lm.sort(void 0)})),xm=Am((function(){Lm.sort(null)})),Vm=bm("sort"),Fm=!Am((function(){if(Dm)return Dm<70;if(!(wm&&wm>3)){if(Nm)return!0;if(Pm)return Pm<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++)Lm.push({k:t+n,v:i})}for(Lm.sort((function(e,t){return t.v-e.v})),n=0;n<Lm.length;n++)t=Lm[n].k.charAt(0),r.charAt(r.length-1)!==t&&(r+=t);return"DGBEFHACIJK"!==r}}));gm({target:"Array",proto:!0,forced:Um||!xm||!Vm||!Fm},{sort:function(e){void 0!==e&&Im(e);var t=vm(this);if(Fm)return void 0===e?km(t):km(t,e);var i,n,r=[],o=Cm(t);for(n=0;n<o;n++)n in t&&Mm(r,t[n]);for(Om(r,function(e){return function(t,i){return void 0===i?-1:void 0===t?1:void 0!==e?+e(t,i)||0:ym(t)>ym(i)?1:-1}}(e)),i=r.length,n=0;n<i;)t[n]=r[n++];for(;n<o;)delete t[n++];return t}});var jm=Hi("Array").sort,Bm=u,Gm=jm,Wm=Array.prototype,Hm=function(e){var t=e.sort;return e===Wm||Bm(Wm,e)&&t===Wm.sort?Gm:t};function Km(e,t){if("boolean"!=typeof e)throw new SE(fE.INVALID_PARAMS,"Invalid ".concat(t,": The value is of the boolean type."))}function Ym(e,t,i){if(i.includes(e))return;throw new SE(fE.INVALID_PARAMS,"".concat(t," can only be set as ").concat(JSON.stringify(i)))}function qm(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&&!tf(e)){throw new SE(fE.INVALID_PARAMS,"invalid ".concat(t,": the value range is [").concat(i,", ").concat(n,"]. integer only"))}}function Jm(e,t){if("number"!=typeof e){if(!(e.min||e.max||e.ideal||e.exact)){throw new SE(fE.INVALID_PARAMS,"".concat(t," is not a valid ConstrainLong"))}void 0!==e.min&&qm(e.min,"".concat(t,".min"),0,1/0),void 0!==e.max&&qm(e.max,"".concat(t,".max"),1,1/0),void 0!==e.exact&&qm(e.exact,"".concat(t,".exact"),1,1/0),void 0!==e.ideal&&qm(e.ideal,"".concat(t,".ideal"),1,1/0)}else qm(e,t,1,1/0)}function Xm(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 SE(fE.INVALID_PARAMS,"".concat(t||"param"," cannot be empty"));if(!ef(e,i,n,r))throw new SE(fE.INVALID_PARAMS,"Invalid ".concat(t||"string param",": Length of the string: [").concat(i,",").concat(n,"].").concat(r?" ASCII characters only.":""))}function zm(e,t){if(!Array.isArray(e))throw new SE(fE.INVALID_PARAMS,"".concat(t," should be an array"))}function Qm(e){if("string"!=typeof e||!/^[a-zA-Z0-9 \!\#\$\%\&\(\)\+\-\:\;\<\=\.\>\?\@\[\]\^\_\{\}\|\~\,]{1,64}$/.test(e))throw OE.error("Invalid Channel Name ".concat(e)),new SE(fE.INVALID_PARAMS,"The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _, {, }, |, ~, ,")}function Zm(e){if(!(t=e,"number"==typeof t&&Math.floor(t)===t&&0<=t&&t<=4294967295||ef(e,1,255)))throw OE.error("Invalid UID ".concat(e," ").concat(typeof e)),new SE(fE.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&&OE.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 $m(e){return null==e}function ef(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||nf(e))}function tf(e){return"number"==typeof e&&e%1==0}function nf(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 rf,of,sf;!function(e){e.FREE="free",e.UPLOADING="uploading"}(rf||(rf={})),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]="P
5UBLIC_API"}(of||(of={})),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"}(sf||(sf={}));const af={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 cf(e){return Xm(e.reportId,"params.reportId",0,100,!1),Xm(e.category,"params.category",0,100,!1),Xm(e.event,"params.event",0,100,!1),Xm(e.label,"params.label",0,100,!1),qm(e.value,"params.value",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,!1),!0}const df={sid:"",lts:0,success:null,cname:null,uid:null,peer:null,cid:null,elapse:null,extend:null,vid:0};let uf,lf,hf,pf,_f,Ef,mf,ff,Sf,Tf,gf,Rf,If,vf,Cf,yf,Af,Of,bf,wf,Nf,Df,Pf,Lf;function kf(e){return qm(e.timeout,"config.timeout",0,1e5),qm(e.timeoutFactor,"config.timeoutFactor",0,100,!1),qm(e.maxRetryCount,"config.maxRetryConfig",0,1/0),qm(e.maxRetryTimeout,"config.maxRetryTimeout",0,1/0),!0}function Mf(e){return Ym(e.codec,"config.codec",["vp8","vp9","av1","h264"]),Ym(e.mode,"config.mode",["rtc","live"]),void 0!==e.audioCodec&&Ym(e.audioCodec,"config.audioCodec",["opus","pcmu","pcma","g722"]),void 0!==e.proxyServer&&Xm(e.proxyServer,"config.proxyServer",1,1e4),void 0!==e.turnServer&&xf(e.turnServer),void 0!==e.httpRetryConfig&&kf(e.httpRetryConfig),void 0!==e.websocketRetryConfig&&kf(e.websocketRetryConfig),!0}function Uf(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 xf(e){return Xm(e.turnServerURL,"turnServerURL"),Xm(e.username,"username"),Xm(e.password,"password"),e.udpport&&qm(e.udpport,"udpport",1,99999,!0),e.forceturn&&Km(e.forceturn,"forceturn"),e.security&&Km(e.security,"security"),e.tcpport&&qm(e.tcpport,"tcpport",1,99999,!0),!0}function Vf(e){return void 0!==e.level&&Ym(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"}(uf||(uf={})),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"}(lf||(lf={})),function(e){e[e.WORKER_EVENT=156]="WORKER_EVENT",e[e.AP_WORKER_EVENT=160]="AP_WORKER_EVENT"}(hf||(hf={})),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"}(pf||(pf={})),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_
5VOLUME="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"}(_f||(_f={})),function(e){e.TRACER="tracer"}(Ef||(Ef={})),function(e){e.IDLE="IDLE",e.INITING="INITING",e.INITEND="INITEND"}(mf||(mf={})),function(e){e.STATE_CHANGE="state_change",e.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",e.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",e.CAMERA_DEVICE_CHANGED="cameraDeviceChanged"}(ff||(ff={})),function(e){e[e.ACCESS_POINT=101]="ACCESS_POINT",e[e.UNILBS=201]="UNILBS",e[e.STRING_UID_ALLOCATOR=901]="STRING_UID_ALLOCATOR"}(Sf||(Sf={})),function(e){e[e.IIIEGAL_APPID=1]="IIIEGAL_APPID",e[e.IIIEGAL_UID=2]="IIIEGAL_UID",e[e.INTERNAL_ERROR=3]="INTERNAL_ERROR"}(Tf||(Tf={})),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"}(gf||(gf={})),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"}(Rf||(Rf={})),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
vendor: 2,568 bytes, line 5
5",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_
5LICENSE_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"}(If||(If={})),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"}(vf||(vf={})),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"}(Cf||(Cf={})),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"}(yf||(yf={})),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"}(Af||(Af={})),function(e){e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.CLOSED="closed"}(Of||(Of={})),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"}(bf||(bf={})),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"}(wf||(wf={})),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"}(Nf||(Nf={})),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"}(Df||(Df={})),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"}(Pf||(Pf={})),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"}(Lf||(Lf={}));const Ff={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,currentPacketLossRate:0},jf={sendBytes:0,sendBitrate:0,sendPackets:0,sendPacketsLost:0,send
5ResolutionHeight:0,sendResolutionWidth:0,captureResolutionHeight:0,captureResolutionWidth:0,targetSendBitrate:0,totalDuration:0,totalFreezeTime:0,currentPacketLossRate:0},Bf={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},Gf={uplinkNetworkQuality:0,downlinkNetworkQuality:0},Wf={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 Hf,Kf,Yf;!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"}(Hf||(Hf={})),function(e){e.TRANSCODE="mix_streaming",e.RAW="raw_streaming",e.INJECT="inject_streaming"}(Kf||(Kf={})),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"}(Yf||(Yf={}));const qf={alpha:1,height:640,width:360,x:0,y:0,zOrder:0,audioChannel:0},Jf={x:0,y:0,width:160,height:160,zOrder:255,alpha:1};function Xf(e,t){Xm(e.url,"".concat(t,".url"),1,1e3,!1),$m(e.x)||qm(e.x,"".concat(t,".x"),0,1e4),$m(e.y)||qm(e.y,"".concat(t,".y"),0,1e4),$m(e.width)||qm(e.width,"".concat(t,".width"),0,1e4),$m(e.height)||qm(e.height,"".concat(t,".height"),0,1e4),$m(e.zOrder)||qm(e.zOrder,"".concat(t,".zOrder"),0,255),$m(e.alpha)||qm(e.alpha,"".concat(t,".alpha"),0,1,!1)}
5const zf={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 Zf,$f,eS,tS,iS,nS,rS,oS,sS,aS,cS,dS,uS,lS,hS,pS,_S,ES,mS;function fS(e){if(!e.channelName)throw new SE(fE.INVALID_PARAMS,"invalid channelName in info");if("number"!=typeof e.uid)throw new SE(fE.INVALID_PARAMS,"invalid uid in info, uid must be a number");return e.token&&Xm(e.token,"info.token",1,2047),Zm(e.uid),Qm(e.channelName),!0}function SS(e){return Ym(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"}(Zf||(Zf={})),function(e){e.REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager"}($f||($f={})),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"}(eS||(eS={})),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"}(tS||(tS={})),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"}(iS||(iS={})),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"}(nS||(nS={})),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"}(rS||(rS={})),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"}(oS||(oS={})),function(e){e.High="high",e.Low="low",e.Audio="audio",e.Screen="screen",e.ScreenLow="screen_low"}(sS||(sS={})),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"}(aS||(aS={})),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"}(cS||(cS={})),function(e){e[e.websocket=0]="websocket",e[e.datachannel=1]="datachannel"}(dS||(dS={})),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"}(uS||(uS={})),function(e){e.SCREEN_TRACK="screen_track",e.CUSTOM_TRACK="custome_track",e.LOW_STREAM="low_stream"}(lS||(lS={})),function(e){e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM"}(hS||(hS={})),function(e){e[e.DISABLE=0]="DISABLE",e[e.LOW_STREAM=1]="LOW_STREAM",e[e.AUDIO_ONLY=2]="AUDIO_ONLY"}(pS||(pS={})),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"}(_S||(_S={})),function(e){e.FIRST_FRAME_DECODED="first-frame-decoded",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status"}(ES||(ES={})),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"}(mS||(mS={}));const TS=[mS.AFRICA,mS.ASIA,mS.CHINA,mS.EUROPE,mS.GLOBAL,mS.INDIA,mS.JAPAN,mS.NORTH_AMERICA,mS.OCEANIA,mS.OVERSEA,mS.SOUTH_AMERICA];let gS;!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"}(gS||(gS={}));const RS={CHINA:{},ASIA:{CODE:gS.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:gS.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:gS.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:gS.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:gS.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:gS.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:gS.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:gS.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:gS.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:gS.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:gS.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:gS.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:gS.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 IS,vS,CS,yS,AS,OS,bS,wS,NS,DS,PS,LS,kS,MS,US;
5NE&&(RS.CHINA={CODE:gS.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"}(IS||(IS={}));class xS extends EE{constructor(e,t){super(),_p(this,"onICEConnectionStateChange",void 0),_p(this,"onConnectionStateChange",void 0),_p(this,"onDTLSTransportStateChange",void 0),_p(this,"onDTLSTransportError",void 0),_p(this,"onICETransportStateChange",void 0),_p(this,"onFirstAudioReceived",void 0),_p(this,"onFirstVideoReceived",void 0),_p(this,"onFirstAudioDecoded",void 0),_p(this,"onFirstVideoDecoded",void 0),_p(this,"onFirstVideoDecodedTimeout",void 0),_p(this,"onSelectedLocalCandidateChanged",void 0),_p(this,"onSelectedRemoteCandidateChanged",void 0),_p(this,"establishPromise",void 0)}}!function(e){e.SEND="sendonly",e.RECV="recvonly",e.SENDRECV="sendrecv",e.INACTIVE="inactive"}(vS||(vS={})),function(e){e.VIDEO="video",e.AUDIO="audio"}(CS||(CS={})),function(e){e.LocalVideoTrack="videoTrack",e.LocalAudioTrack="audioTrack",e.LocalVideoLowTrack="videoLowTrack"}(yS||(yS={})),function(e){e.New="new",e.Connected="connected",e.Reconnecting="reconnecting",e.Disconnected="disconnected"}(AS||(AS={})),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"}(OS||(OS={})),function(e){e.ONLINE="ONLINE",e.OFFLINE="OFFLINE"}(bS||(bS={})),function(e){e.NETWORK_STATE_CHANGE="NETWORK_STATE_CHANGE",e.ONLINE="ONLINE",e.OFFLINE="OFFLINE"}(wS||(wS={})),function(e){e.ON_TRACK="on_track",e.ON_NODE="on_node"}(NS||(NS={})),function(e){e.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",e.REQUEST_CONSTRAINTS="request_constraints"}(DS||(DS={})),function(e){e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED"}(PS||(PS={})),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"}(LS||(LS={})),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"}(kS||(kS={})),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"}(MS||(MS={})),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"}(US||(US={}));const VS={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 FS(){return VS}let jS;!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]="
5CLOUD_PROXY_FALLBACK"}(jS||(jS={}));var BS=k,GS=Array.isArray||function(e){return"Array"==BS(e)},WS=h,HS=GS,KS=oc,YS=q,qS=rt("species"),JS=WS.Array,XS=function(e){var t;return HS(e)&&(t=e.constructor,(KS(t)&&(t===JS||HS(t.prototype))||YS(t)&&null===(t=t[qS]))&&(t=void 0)),void 0===t?JS:t},zS=function(e,t){return new(XS(e))(0===t?0:t)},QS=Wt,ZS=j,$S=Fe,eT=wi,tT=zS,iT=d([].push),nT=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,_=$S(c),E=ZS(_),m=QS(d,u),f=eT(E),S=0,T=l||tT,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:iT(g,h)}else switch(e){case 4:return!1;case 7:iT(g,h)}return o?-1:n||r?r:g}},rT={forEach:nT(0),map:nT(1),filter:nT(2),some:nT(3),every:nT(4),find:nT(5),findIndex:nT(6),filterReject:nT(7)},oT=rT.forEach,sT=Vi("forEach")?[].forEach:function(e){return oT(this,e,arguments.length>1?arguments[1]:void 0)};Ii({target:"Array",proto:!0,forced:[].forEach!=sT},{forEach:sT});var aT=Hi("Array").forEach,cT=Zr,dT=Ge,uT=u,lT=aT,hT=Array.prototype,pT={DOMTokenList:!0,NodeList:!0},_T=function(e){var t=e.forEach;return e===hT||uT(hT,e)&&t===hT.forEach||dT(pT,cT(e))?lT:t},ET=Fe,mT=hr;Ii({target:"Object",stat:!0,forced:i((function(){mT(1)}))},{keys:function(e){return mT(ET(e))}});var fT=J.Object.keys,ST=Xi,TT=Ii,gT=GS,RT=d([].reverse),IT=[1,2];TT({target:"Array",proto:!0,forced:String(IT)===String(IT.reverse())},{reverse:function(){return gT(this)&&(this.length=this.length),RT(this)}});var vT=Hi("Array").reverse,CT=u,yT=vT,AT=Array.prototype,OT=function(e){var t=e.reverse;return e===AT||CT(AT,e)&&t===AT.reverse?yT:t},bT=i,wT=ae,NT=rt("species"),DT=function(e){return wT>=51||!bT((function(){var t=[];return(t.constructor={})[NT]=function(){return{foo:1}},1!==t[e](Boolean).foo}))},PT=Ii,LT=h,kT=GS,MT=oc,UT=q,xT=Un,VT=wi,FT=K,jT=im,BT=rt,GT=pc,WT=DT("slice"),HT=BT("species"),KT=LT.Array,YT=Math.max;PT({target:"Array",proto:!0,forced:!WT},{slice:function(e,t){var i,n,r,o=FT(this),s=VT(o),a=xT(e,s),c=xT(void 0===t?s:t,s);if(kT(o)&&(i=o.constructor,(MT(i)&&(i===KT||kT(i.prototype))||UT(i)&&null===(i=i[HT]))&&(i=void 0),i===KT||void 0===i))return GT(o,a,c);for(n=new(void 0===i?KT:i)(YT(c-a,0)),r=0;a<c;a++,r++)a in o&&jT(n,r,o[a]);return n.length=r,n}});var qT=Hi("Array").slice,JT=u,XT=qT,zT=Array.prototype,QT=function(e){var t=e.slice;return e===zT||JT(zT,e)&&t===zT.slice?XT:t};function ZT(e,t,i,n,r){var o,s,a,c={};return _T(o=fT(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=ST(s=OT(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&&(pp(e,t,c),c=null),c}var $T=Hi("Array").keys,eg=Zr,tg=Ge,ig=u,ng=$T,rg=Array.prototype,og={DOMTokenList:!0,NodeList:!0},sg=function(e){var t=e.keys;return e===rg||ig(rg,e)&&t===rg.keys||tg(og,eg(e))?ng:t};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 cg(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){_p(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}let dg=0,ug=0;function lg(e,t,i,n){return new Sl((r,o)=>{t.timeout=t.timeout||GE("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!i?(t.data=JSON.stringify(t.data),dg+=FI(t.data)):i&&(t.data.size?dg+=t.data.size:t.data instanceof FormData?dg+=function(e){let t=0;/DingTalk/i.test(navigator.userAgent)&&e.realFormData&&(e=e.realFormData);return e.forEach(e=>{t+="string"==typeof e?FI(e):e.size}),t+138}(t.data):dg+=FI(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,pE.request(t).then(e=>{"string"==typeof e.data?ug+=FI(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?ug+=e.data.byteLength:ug+=FI(JSON.stringify(e.data)),n&&r({data:e.data,headers:e.headers}),r(e.data)}).catch(e=>{pE.isCancel(e)?o(new SE(fE.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?o(new SE(fE.NETWORK_TIMEOUT,e.message)):e.response?o(new SE(fE.NETWORK_RESPONSE_E
5RROR,e.response.status)):o(new SE(fE.NETWORK_ERROR,e.message))})})}async function hg(e,t){const i=new Blob([t.data],{type:"buffer"});return await lg(e,cg(cg({},t),{},{data:i,headers:{"Content-Type":"application/octet-stream"}}),!0)}const pg=new class extends EE{set networkState(e){OE.info("[".concat(this._moduleName,"]")+"network state changed, "+this._networkState+" -> "+e),this.emit(wS.NETWORK_STATE_CHANGE,e,this._networkState),e===bS.ONLINE?this.emit(wS.ONLINE):e===bS.OFFLINE&&(this.onlineWaiter=new Sl(e=>{this.once(wS.ONLINE,()=>{this.onlineWaiter=void 0,e(bS.ONLINE)})}),this.emit(wS.OFFLINE)),this._networkState=e}get networkState(){return this._networkState}constructor(){super(),_p(this,"_moduleName","network-indicator"),_p(this,"_networkState",bS.ONLINE),_p(this,"onlineWaiter",void 0),window.addEventListener("online",()=>{this.networkState=bS.ONLINE}),window.addEventListener("offline",()=>{this.networkState=bS.OFFLINE})}};let _g=!1;const Eg=new class extends EE{constructor(){super(...arguments),_p(this,"onAutoplayFailed",void 0),_p(this,"onAudioAutoplayFailed",void 0)}};function mg(){if(Mh(),!_g){const e=t=>{t.preventDefault(),_g=!1,sp()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};_g=!0,sp()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),OE.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),Eg.onAutoplayFailed?Eg.onAutoplayFailed():Eg.onAudioAutoplayFailed?OE.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 ."):OE.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 ."),Eg.emit("autoplay-failed")}}function fg(e){return(new TextEncoder).encode(e)}const Sg=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 Tg=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",fg(e)),16);function gg(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?gg(Object(i),!0).forEach((function(t){_p(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):gg(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function Ig(){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){OE.warning(e),a=[]}try{JSON.stringify(a)}catch(e){OE.warning("arguments for method ".concat(o,".").concat(i," not serializable for apiInvoke.")),a=[]}const c=(e.report||vg).reportApiInvoke(this._sessionId||null,{name:"".concat(o,".").concat(i),options:a,tag:Ef.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 vg=new class{constructor(){_p(this,"baseInfoMap",new Map),_p(this,"proxyServer",void 0),_p(this,"clientList",zE),_p(this,"eventUploadTimer",void 0),_p(this,"setSessionIdTimer",void 0),_p(this,"url",void 0),_p(this,"backupUrl",void 0),_p(this,"_appId",void 0),_p(this,"keyEventUploadPendingItems",[]),_p(this,"normalEventUploadPendingItems",[]),_p(this,"apiInvokeUploadPendingItems",[]),_p(this,"apiInvokeCount",0),_p(this,"ltsList",[]),_p(this,"lastSendNormalEventTime",Date.now()),_p(this,"customReportCounterTimer",void 0),_p(this,"customReportCount",0),_p(this,"extApiInvoke",async e=>{for(const t of e){const e=Rg(Rg({},t),{},{sid:null,invokeId:++this.apiInvokeCount,tag:Ef.TRACER});this.sendApiInvoke(e)}}),this.eventUploadTimer=window.setInterval(this.doSend.bind(this),GE("EVENT_REPORT_SEND_INTERVAL")),this.setSessionIdTimer=window.setInterval(this.appendSessionId.bind(this),GE("EVENT_REPORT_SEND_INTERVAL"))}adjustSessionStartTime(e){if(!this.baseInfoMap.has(e)&&!this.baseInfoMap.get(e))return void OE.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,OE.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=!!GE("SHOW_REPORT_INVOKER_LOG");s&&OE.info("".concat(t.name," start"),t.options);let a=!1;jI(t.timeout).then(()=>{a||(this.sendApiInvoke(Rg(Rg({},o()),{},{error:fE.API_INVOKE_TIMEOUT,success:!1})),OE.debug("".concat(t.name," timeout")))});const c=new SE(fE.UNEXPECTED_ERROR,"".concat(t.name,": this api invoke is end"));return{onSuccess:e=>{const n=()=>
5{if(a)throw c;return a=!0,this.sendApiInvoke(Rg(Rg({},o()),{},{success:!0},t.reportResult&&{result:e})),s&&OE.info("".concat(t.name," onSuccess")),e};return i?sv(n,t.name+"Success",i,()=>a=!0):n()},onError:e=>{const n=()=>{if(a)throw e;a=!0,this.sendApiInvoke(Rg(Rg({},o()),{},{success:!1,error:e})),s&&OE.info("".concat(t.name," onFailure"),e.toString())};return i?sv(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:GE("UPLOAD_LOG"),maxTouchPoints:navigator.maxTouchPoints,areaVersion:NE?"global":"oversea",areas:GE("AREAS")&&GE("AREAS").join(",")},t.extend),o=Date.now(),s=Rg(Rg({},n),{},{eventType:uf.SESSION_INIT,appid:t.appid,browser:navigator.userAgent,build:bE,lts:o,elapse:o-i,extend:JSON.stringify(r),mode:t.mode,process:GE("PROCESS_ID"),appType:GE("APP_TYPE"),success:!0,version:wE});this.send({type:lf.SESSION,data:s},!0)}joinChooseServer(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=i.info,r=Date.now(),o=Rg(Rg({},n),{},{eventType:uf.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:lf.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=Rg(Rg({},n),{},{eventType:uf.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:lf.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=Rg(Rg({},n),{},{eventType:uf.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:lf.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:uf.REJOIN_GATEWAY});this.send({type:lf.RE_JOIN_GATEWAY,data:t},!0)}}joinChannelTimeout(e,t){const i=this.baseInfoMap.get(e);if(!i)return;const n=Date.now(),r=Rg(Rg({},i.info),{},{lts:n,timeout:t,elapse:n-i.startTime});this.send({type:lf.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=Rg(Rg({},n),{},{eventType:uf.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:lf.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=Rg(Rg({},r),{},{eventType:uf.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:lf.SUBSCRIBE,data:s},!0)}wsCompressorInit(e){var t;const i=[...sg(t=this.baseInfoMap).call(t)],n=i.length?i[0]:"UnableToGetSid",r=this.baseInfoMap.get(n);if(!r)return;
vendor: 3,398 bytes, line 5
5const o=r.info,s=Date.now(),a=Rg(Rg({},o),{},{eventType:uf.WS_COMPRESSOR_INIT,lts:s,eventElapse:e.eventElapse,elapse:s-r.startTime,status:e.status?1:2});this.send({type:lf.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=Rg(Rg(Rg({},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=Rg(Rg(Rg({},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=Rg(Rg(Rg({},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=Rg(Rg({},n),{},{eventType:uf.STREAM_SWITCH,lts:r,isDual:t.isdual,elapse:r-i.startTime,success:t.succ});this.send({type:lf.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=Rg(Rg({},n),{},{eventType:uf.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:lf.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=Rg(Rg({},n),{},{eventType:uf.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:lf.REQUEST_PROXY_WORKER_MANAGER,data:o},!0)}setProxyServer(e){this.proxyServer=e,e?OE.debug("reportProxyServerurl: ".concat(e)):OE.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=Rg(Rg({},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:lf.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=FI(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]=VI(VI({},e),{},{[t]:n.substring(o,c)}),o=c,a=n.charCodeAt(c)<=127?1:3);o!==n.length-1&&(s[s.length]=VI(VI({},e),{},{[t]:n.substring(o)}));return s})(Rg(Rg(Rg({},n),t),{},{elapse:r-i.startTime,lts:r,productType:"WebRTC"}
5),"payload",1300).forEach(e=>this.send({type:lf.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=Rg(Rg(Rg({},n),t),{},{elapse:r-i.startTime,lts:r});this.send({type:lf.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=Rg(Rg(Rg({},n),t),{},{elapse:r-i.startTime,lts:r,extend:t.extend||void 0});this.send({type:lf.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=Rg(Rg(Rg({},n),t),{},{elapse:r-i.startTime,lts:r});this.send({type:lf.WEBSOCKET_QUIT,data:o},!0)}async sendCustomReportMessage(e,t){if(this.customReportCount+=t.length,this.customReportCount>GE("CUSTOM_REPORT_LIMIT"))throw new SE(fE.CUSTOM_REPORT_FREQUENCY_TOO_HIGH);this.customReportCounterTimer||(this.customReportCounterTimer=window.setInterval(()=>{this.customReportCount=0},5e3));const i=Date.now(),n=t.map(t=>({type:lf.USER_ANALYTICS,data:Rg(Rg({sid:e},t),{},{lts:i})}));try{GE("NEW_REPORT_SERVER")?await this.postDataToStatsCollector2(n):await this.postDataToStatsCollector(n)}catch(e){throw OE.error("send custom report message failed",e.toString()),new SE(fE.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=Rg(Rg({},o),{},{vid:void 0===o.vid?0:Number(o.vid),lts:s,elapse:s-r.startTime,cbRegistered:Eg.onAutoplayFailed||Eg.onAudioAutoplayFailed?1:-1,errorMsg:i,mediaType:t,trackId:n,extend:void 0});this.send({type:lf.AUTOPLAY_FAILED,data:a},!0)}sendApiInvoke(e){const t=GE("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 SE){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:lf.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>GE("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),Hm(r=this.ltsList).call(r,(e,t)=>e-t)}
5t||(this.lastSendNormalEventTime=Date.now());return GE("ENABLE_EVENT_REPORT")?(i.length&&(GE("NEW_REPORT_SERVER")?this.postDataToStatsCollector2(i):this.postDataToStatsCollector(i)).catch((e=>i=>{GE("EVENT_REPORT_RETRY")&&(t?this.keyEventUploadPendingItems=this.keyEventUploadPendingItems.concat(e):(this.normalEventUploadPendingItems=this.normalEventUploadPendingItems.concat(e),this.normalEventUploadPendingItems.length>GE("NORMAL_EVENT_QUEUE_CAPACITY")&&(this.normalEventUploadPendingItems.splice(0,this.normalEventUploadPendingItems.length-GE("NORMAL_EVENT_QUEUE_CAPACITY")),OE.warning("report: drop normal events"))))})(i)),e):e}async postDataToStatsCollector2(e){pg.networkState===bS.OFFLINE&&await Sl.race([pg.onlineWaiter,jI(2*TE.maxRetryTimeout)]);const t=e=>{let t=new Uint8Array;return e.forEach(e=>{const i=fg(JSON.stringify(e.data)),n=new ArrayBuffer(5),r=(e=>{let t=0;return Object.entries(lf).forEach(i=>{let[n,r]=i;r===e.type&&(t=pf[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=Sg(t,new Uint8Array(n)),t=Sg(t,i)}),t},i="event";let n=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(GE("NEW_REPORT_SERVER_DOMAINS")[0],"&p=443&d=").concat(i):"https://".concat(GE("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(GE("NEW_REPORT_SERVER_DOMAINS")[1],"&p=443&d=").concat(i):"https://".concat(GE("NEW_REPORT_SERVER_DOMAINS")[1],"/").concat(i));try{await lg(n,{timeout:1e4,data:t(e),headers:Rg(Rg({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])};pg.networkState===bS.OFFLINE&&await Sl.race([pg.onlineWaiter,jI(2*TE.maxRetryTimeout)]);const n=t?"/events/proto-raws":"/events/messages";let r=this.url||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(GE("EVENT_REPORT_DOMAIN"),"&p=").concat(GE("STATS_COLLECTOR_PORT"),"&d=").concat(n):"https://".concat(GE("EVENT_REPORT_DOMAIN"),":").concat(GE("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(GE("EVENT_REPORT_BACKUP_DOMAIN"),"&p=").concat(GE("STATS_COLLECTOR_PORT"),"&d=").concat(n):"https://".concat(GE("EVENT_REPORT_BACKUP_DOMAIN"),":").concat(GE("STATS_COLLECTOR_PORT")).concat(n)));try{t?await hg(r,{timeout:1e4,data:i}):await lg(r,{timeout:1e4,data:i})}catch(t){if(1===e)throw t;continue}return}}createBaseInfo(e,t){const i=Object.assign({},df);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:Ef.TRACER}).onSuccess()}};mE.on("REPORT_LOG_UPLOAD",e=>{e.networkState=pg.networkState,vg.reportApiInvoke(null,{name:"logUploadError",options:e,tag:Ef.TRACER})});class Cg extends EE{constructor(e,t){super(),_p(this,"trackMediaType",void 0),_p(this,"_ID",void 0),_p(this,"_hints",[]),_p(this,"_isClosed",!1),_p(this,"_originMediaStreamTrack",void 0),_p(this,"_mediaStreamTrack",void 0),_p(this,"_external",{}),this._ID=t||GI(8,"track-"),this._originMediaStreamTrack=e,this._mediaStreamTrack=e,function(e){QE.includes(e)||QE.push(e)}(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){if(!e){const e=vg.reportApiInvoke(null,{name:_f.GET_MEDIA_STREAM_TRACK,options:[],tag:Ef.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=QE.indexOf(e);-1!==t&&QE.splice(t,1)}
5(this),this.emit(_S.CLOSED)}}let yg,Ag=1;class Og{constructor(e){_p(this,"lockingPromise",Sl.resolve()),_p(this,"locks",0),_p(this,"name",""),_p(this,"lockId",void 0),this.lockId=Ag++,e&&(this.name=e),OE.debug("[lock-".concat(this.name,"-").concat(this.lockId,"] is created."))}get isLocked(){return this.locks>0}lock(e){let t;this.locks+=1,OE.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,OE.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 bg(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 wg extends Cg{get isExternalTrack(){return this._isExternalTrack}get muted(){return this._muted}get enabled(){return this._enabled}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}constructor(e,t){super(e,t),_p(this,"_enabled",!0),_p(this,"_muted",!1),_p(this,"_isExternalTrack",!1),_p(this,"_isClosed",!1),_p(this,"_enabledMutex",void 0),_p(this,"processor",void 0),_p(this,"_processorContext",void 0),_p(this,"_handleTrackEnded",()=>{this.onTrackEnded()}),this._enabledMutex=new Og("".concat(this.getTrackId())),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,OE.debug("[".concat(this.getTrackId(),"] close")),this.emit(uS.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 JI(this,uS.NEED_REPLACE_TRACK,this),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){OE.debug("[".concat(this.getTrackId(),"] track ended")),this.emit(_S.TRACK_ENDED)}stateCheck(e,t){if(OE.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(t,"]")),Km(t,e),this._enabled&&this._muted&&"enabled"===e&&!1===t)throw new SE(fE.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print();if(!this._enabled&&!this._muted&&"muted"===e&&!0===t)throw new SE(fE.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}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(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"}(yg||(yg={}));const Dg=window.AudioContext||window.webkitAudioContext;let Pg=null;
5const Lg=new class extends EE{constructor(){super(...arguments),_p(this,"prevState",void 0),_p(this,"curState",void 0),_p(this,"currentTime",void 0),_p(this,"currentTimeStuckAt",void 0),_p(this,"interruptDetectorTrack",void 0),_p(this,"onLocalAudioTrackMute",()=>{OE.info("ios15-interruption-start"),this.emit(yg.IOS_15_INTERRUPTION_START)}),_p(this,"onLocalAudioTrackUnmute",async()=>{OE.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?OE.info("ios15-interruption-end-canceled"):(Pg&&await Pg.suspend(),this.emit(yg.IOS_15_INTERRUPTION_END))})}get duringInterruption(){return"running"===this.prevState&&"interrupted"===this.curState}bindInterruptDetectorTrack(e){OE.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){OE.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 kg(){if(!Dg)return void OE.error("your browser is not support web audio");OE.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?Ng(Object(i),!0).forEach((function(t){_p(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}({},GE("WEBAUDIO_INIT_OPTIONS"));OE.debug("audio context init option:",JSON.stringify(e)),Pg=new Dg(e),Lg.curState=Pg.state,Pg.onstatechange=()=>{Lg.prevState=Lg.curState,Lg.curState=Pg?Pg.state:void 0,(Kh()||tp())&&"running"===Lg.prevState&&"interrupted"===Lg.curState&&(OE.info("ios-interruption-start"),Lg.emit(yg.IOS_INTERRUPTION_START)),(Kh()||tp())&&"interrupted"===Lg.prevState&&"running"===Lg.curState&&(OE.info("ios-interruption-end"),Lg.emit(yg.IOS_INTERRUPTION_END)),Lg.prevState!==Lg.curState&&(OE.debug("AudioContext State Change","".concat(Lg.prevState,"=>").concat(Lg.curState)),Lg.emit(yg.STATE_CHANGE))},setInterval(()=>{var e;const t=null===(e=Pg)||void 0===e?void 0:e.currentTime;if(Lg.currentTime!==t)Lg.currentTimeStuckAt&&(OE.debug("AudioContext current time resume at ".concat(t)),Lg.currentTimeStuckAt=void 0),Lg.currentTime=t;else{if(t!==Lg.currentTimeStuckAt){vg.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:t},tag:Ef.TRACER}).onSuccess(),OE.warning("AudioContext current time stuck at ".concat(t))}Lg.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()||tp()?"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)}Lg.on(yg.STATE_CHANGE,c),s(!1)}(Pg)}function Mg(){if(!Pg){if(kg(),!Pg)throw new SE(fE.NOT_SUPPORTED,"can not create audio context");return Pg}return Pg}function Ug(){return!!Pg}function xg(e){if(function(){if(null!==Vg)return Vg;const e=Mg(),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(),Vg=r,r}())return;const t=e.connect,i=e.disconnect;e.connect=(i,n,r)=>
vendor: 9,346 bytes, line 5
5(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?QI(e._inputNodes,n):e._inputNodes=[];for(const i of e._inputNodes)t.call(e,i)}}let Vg=null;function Fg(e,t){let i=!1;const n=1/t;if(GE("DISABLE_WEBAUDIO")){const t=window.setInterval(()=>{i?window.clearInterval(t):e(performance.now()/1e3)},1e3*n)}else{const t=Mg();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 jg{constructor(){_p(this,"context",void 0),_p(this,"analyserNode",void 0),_p(this,"sourceNode",void 0),this.context=Mg(),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()||tp()||"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){OE.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}}class Bg extends EE{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(),_p(this,"outputNode",void 0),_p(this,"outputTrack",void 0),_p(this,"isPlayed",!1),_p(this,"sourceNode",void 0),_p(this,"context",void 0),_p(this,"audioBufferNode",void 0),_p(this,"destNode",void 0),_p(this,"audioOutputLevel",0),_p(this,"volumeLevelAnalyser",void 0),_p(this,"_processedNode",void 0),_p(this,"playNode",void 0),_p(this,"isDestroyed",!1),_p(this,"onNoAudioInput",void 0),_p(this,"isNoAudioInput",!1),_p(this,"_noAudioInputCount",0),this.context=Mg(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),xg(this.outputNode),this.volumeLevelAnalyser=new jg}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(Lf.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(!FS().webAudioMediaStreamDest)throw new SE(fE.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&&$I(()=>{Lg.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()||tp()?"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 jI(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 Gg extends Bg{get isFreeze(){return!1}constructor(e,t,i){var n;if(super(),_p(this,"sourceNode",void 0),_p(this,"track",void 0),_p(this,"clonedTrack",void 0),_p(this,"audioElement",void 0),_p(this,"isCurrentTrackCloned",!1),_p(this,"isRemoteTrack",!1),_p(this,"originVolumeLevelAnalyser",void 0),_p(this,"rebuildWebAudio",async()=>{if(OE.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 OE.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then(()=>OE.info("resume success")),OE.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),xg(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const i=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(i,this.context.currentTime),xg(this.outputNode),this.emit(Lf.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()}),"audio"!==e.kind)throw new SE(fE.UNEXPECTED_ERROR);this.track=e;const r=new MediaStream([this.track]);if(this.isRemoteTrack=!!t,this.sourceNode=this.context.createMediaStreamSource(r),xg(this.sourceNode),i){const e=i.clone();e.enabled=!0,this.clonedTrack=e,OE.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]));xg(t),this.originVolumeLevelAnalyser=new jg,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&&(Lg.on(yg.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),xg(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(Lf.UPDATE_SOURCE),this.audioElement.srcObject=t}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),Lg.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),OE.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]));xg(i),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(i)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}}async function Wg(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.
5width,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 Hg(e){const t=await Kg(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 Wg(i,e)}
5async function Kg(e){let t=["window","screen"];"application"!==e&&"window"!==e||(t=["window"]),"screen"===e&&(t=["screen"]);const i=qg();if(!i)throw new SE(fE.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 SE(fE.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}let Yg=null;function qg(){if(Yg)return Yg;try{return Yg=window.require("electron"),Yg}catch(e){return null}}function Jg(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 Xg=new Og("safari");let zg=!1,Qg=!1;async function Zg(e,t){let i=0,n=null;for(;i<2;)try{n=await $g(e,t,i>0);break}catch(e){if(e instanceof SE)throw OE.error("[".concat(t,"] ").concat(e.toString())),e;const n=eR(e.name||e.code||e,e.message);
5if(n.code===fE.MEDIA_OPTION_INVALID){OE.debug("[".concat(t,"] detect media option invalid, retry")),i+=1,await jI(500);continue}throw OE.error("[".concat(t,"] ").concat(n.toString())),n}if(!n)throw new SE(fE.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return n}async function $g(e,t,i){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new SE(fE.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=FS(),r=new MediaStream;if(e.audioSource&&r.addTrack(e.audioSource),e.videoSource&&r.addTrack(e.videoSource),!e.audio&&!e.video&&!e.screen)return OE.debug("Using Video Source/ Audio Source"),r;if(e.screen)if(qg())if(e.screen.sourceId){tR(r,await Wg(e.screen.sourceId,e.screen))}else{tR(r,await Hg(e.screen))}else if(Gh()&&e.screen.extensionId&&e.screen.mandatory){if(!n.getStreamFromExtension)throw new SE(fE.NOT_SUPPORTED,"This browser does not support screen sharing");OE.debug("[".concat(t,'] Screen access on chrome stable, looking for extension"'));const i=await(s=e.screen.extensionId,a=t,new Sl((e,t)=>{try{chrome.runtime.sendMessage(s,{getStream:!0},i=>{if(!i||!i.streamId)return OE.error("[".concat(a,"] No response from Chrome Plugin. Plugin not installed properly"),i),void t(new SE(fE.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));e(i.streamId)})}catch(e){OE.error("[".concat(a,"] AgoraRTC screensharing plugin is not accessible(").concat(s,")"),e.toString()),t(new SE(fE.CHROME_PLUGIN_NOT_INSTALL))}}));e.screen.mandatory.chromeMediaSourceId=i;tR(r,await navigator.mediaDevices.getUserMedia({video:{mandatory:e.screen.mandatory}}))}else if(n.getDisplayMedia){var o;e.screen.mediaSource&&SS(e.screen.mediaSource);const i={width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate,displaySurface:null!==(o=e.screen.displaySurface)&&void 0!==o?o:"screen"===e.screen.mediaSource?"monitor":e.screen.mediaSource},{selfBrowserSurface:n,surfaceSwitching:s,systemAudio:a}=e.screen,c={selfBrowserSurface:n,surfaceSwitching:s,systemAudio:a};!n&&delete c.selfBrowserSurface,!s&&delete c.surfaceSwitching,!a&&delete c.systemAudio,OE.debug("[".concat(t,"] getDisplayMedia:"),JSON.stringify({video:i,audio:!!e.screenAudio,controls:c}));tR(r,await navigator.mediaDevices.getDisplayMedia(function(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Jg(Object(i),!0).forEach((function(t){_p(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Jg(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({video:i,audio:!!e.screenAudio},c)))}else{if(!Hh())throw OE.error("[".concat(t,"] This browser does not support screenSharing")),new SE(fE.NOT_SUPPORTED,"This browser does not support screen sharing");{e.screen.mediaSource&&SS(e.screen.mediaSource);const i={video:{mediaSource:e.screen.mediaSource,width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate}};OE.debug("[".concat(t,"] getUserMedia: ").concat(JSON.stringify(i)));tR(r,await navigator.mediaDevices.getUserMedia(i))}}var s,a;if(!e.video&&!e.audio)return r;let c={video:e.video,audio:e.audio},d=GE("MEDIA_DEVICE_CONSTRAINTS");if(d)try{"string"==typeof d&&(d=JSON.parse(d)),c=function e(t,i){if(!cv(t)||!cv(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=VI({},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}}(c,d)}catch(e){}OE.debug("[".concat(t,"] GetUserMedia"),JSON.stringify(c)),Mh();let u,l=null;(Wh()||Kh()||Fh())&&(l=await Xg.lock());try{u=await navigator.mediaDevices.getUserMedia(c)}catch(e){throw l&&l(),e}return c.audio&&(zg=!0),c.video&&(Qg=!0),tR(r,u),l&&l(),r}function eR(e,t){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new SE(fE.MEDIA_OPTION_INVA
5LID,"".concat(e,": ").concat(t));case"NotFoundError":case"DevicesNotFoundError":return new SE(fE.DEVICE_NOT_FOUND,"".concat(e,": ").concat(t));case"NotSupportedError":return new SE(fE.NOT_SUPPORTED,"".concat(e,": ").concat(t));case"NotReadableError":return new SE(fE.NOT_READABLE,"".concat(e,": ").concat(t));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new SE(fE.PERMISSION_DENIED,"".concat(e,": ").concat(t));case"ConstraintNotSatisfiedError":return new SE(fE.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(t));default:return OE.error("getUserMedia unexpected error",e),new SE(fE.UNEXPECTED_ERROR,"".concat(e,": ").concat(t))}}function tR(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 iR=new class extends EE{get state(){return this._state}set state(e){e!==this._state&&(this.emit(ff.STATE_CHANGE,e),this._state=e)}constructor(){super(),_p(this,"_state",mf.IDLE),_p(this,"isAccessMicrophonePermission",!1),_p(this,"isAccessCameraPermission",!1),_p(this,"lastAccessMicrophonePermission",!1),_p(this,"lastAccessCameraPermission",!1),_p(this,"checkdeviceMatched",!1),_p(this,"deviceInfoMap",new Map),this.init().then(()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval(()=>{(GE("ENUMERATE_DEVICES_INTERVAL")||op()&&rp())&&this.updateDevicesInfo()},GE("ENUMERATE_DEVICES_INTERVAL_TIME"))}).catch(e=>OE.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 SE(fE.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(Xg.isLocked){OE.debug("[device manager] wait GUM lock");(await Xg.lock())(),OE.debug("[device manager] GUM unlock")}if(zg&&(o=!1,this.isAccessMicrophonePermission=!0),Qg&&(s=!1,this.isAccessCameraPermission=!0),OE.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=eR(e.name||e.code||e,e.message);if(t.code===fE.PERMISSION_DENIED)throw t;OE.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=eR(e.name||e.code||e,e.message);if(t.code===fE.PERMISSION_DENIED)throw t;OE.warning("getUserMedia failed in getDevices",t)}this.isAccessMicrophonePermission=!0}else if(s){try{c=await navigator.mediaDevices.getUserMedia({video:t})}catch(e){const t=eR(e.name||e.code||e,e.message);if(t.code===fE.PERMISSION_DENIED)throw t;OE.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0}OE.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 SE(fE.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)}
5searchDeviceIdByName(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 SE(fE.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return t}async init(){this.state=mf.INITING;try{await this.updateDevicesInfo(),this.state=mf.INITEND}catch(e){if(OE.warning("Device Detection functionality cannot start properly.",e.toString()),this.state=mf.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 SE(fE.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?OE.debug("[device-check] default input ".concat(t.label," and output ").concat(i.label," is the same group")):OE.warning("[device-check] default input ".concat(t.label," and output ").concat(i.label," is not the same group")):OE.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!==mf.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(ff.RECORDING_DEVICE_CHANGED,e);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(ff.CAMERA_DEVICE_CHANGED,e);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(ff.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 nR=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],rR=new class{constructor(){_p(this,"onAutoplayFailed",void 0),_p(this,"elementMap",new Map),_p(this,"elementStateMap",new Map),_p(this,"elementsNeedToResume",[]),_p(this,"sinkIdMap",new Map),_p(this,"autoResumeAfterInterruption",()=>{Array.from(this.elementMap.entries()).forEach(e=>{let[t,i]=e;const n=this.elementStateMap.get(t),r=i.srcObject.getAudioTracks()[0];Qh()?r&&"live"===r.readyState&&"running"===Lg.curState&&(OE.debug("auto resume after interruption for iOS 15"),i.pause(),i.play()):n&&"paused"===n&&r&&"live"===r.readyState&&"running"===Lg.curState&&(OE.debug("auto resume after interruption for iOS"),i.play())})}),_p(this,"autoResumeAfterInterruptionOnIOS15",()=>{Array.from(this.elementMap.entries()).forEach(e=>{let[t,i]=e;const n=i.srcObject.getAudioTracks()[0];n&&"live"===n.readyState&&(OE.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),i.pause(),i.play())})}),this.autoResumeAudioElement(),Lg.on(yg.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),Lg.on(yg.IOS_15_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15),Lg.on(yg.STATE_CHANGE,()=>{Kh()&&"suspended"===Lg.prevState&&"running"===Lg.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 SE(fE.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");
5r.autoplay=!0,r.srcObject=new MediaStream([e]),this.bindAudioElementEvents(t,r),this.elementMap.set(t,r),this.elementStateMap.set(t,sf.INIT),this.setVolume(t,i);const o=this.sinkIdMap.get(t);if(o)try{r.setSinkId(o).catch(e=>{OE.warning("[".concat(t,"] set sink id failed"),e.toString())})}catch(e){OE.warning("[".concat(t,"] set sink id failed"),e.toString())}const s=r.play();s&&s.then&&s.catch(e=>{n&&vg.autoplayFailed(n,"audio",e.message,t),OE.warning("audio element play warning",e.toString()),this.elementMap.has(t)&&"NotAllowedError"===e.name&&(OE.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(r),$I(()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),mg()}))})}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){nR.forEach(i=>{t.addEventListener(i,i=>{const n=this.elementStateMap.get(e),r="pause"===i.type?"paused":i.type;if(OE.debug("[".concat(e,"] audio-element-status change ").concat(n," => ").concat(r)),"error"===i.type){const i=null==t?void 0:t.error;i&&OE.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=>{OE.debug("Auto resume audio element success")}).catch(e=>{OE.warning("Auto resume audio element failed!",e)})}),this.elementsNeedToResume=[]};new Sl(e=>{document.body?e():window.addEventListener("load",()=>e())}).then(()=>{sp()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0))})}};function oR(){return function(e,t,i){const n=i.value;return"function"==typeof n&&(i.value=function(){this._isClosed&&new SE(fE.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 sR=Hi("Array").values,aR=Zr,cR=Ge,dR=u,uR=sR,lR=Array.prototype,hR={DOMTokenList:!0,NodeList:!0},pR=function(e){var t=e.values;return e===lR||dR(lR,e)&&t===lR.values||cR(hR,aR(e))?uR:t};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 ER(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){_p(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}
5class mR extends EE{constructor(e){super(),_p(this,"name","VideoProcessorDestination"),_p(this,"ID","0"),_p(this,"_source",void 0),_p(this,"videoContext",void 0),_p(this,"inputTrack",void 0),this.videoContext=e}get kind(){return"video"}get enabled(){return!0}pipe(){throw new SE(fE.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor")}unpipe(){throw new SE(fE.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(NS.ON_TRACK,e.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(NS.ON_TRACK,void 0)}}class fR extends EE{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t){super(),_p(this,"constraintsMap",new Map),_p(this,"statsRegistry",[]),_p(this,"usageRegistry",[]),_p(this,"trackId",void 0),_p(this,"direction",void 0),_p(this,"_chained",!1),this.trackId=e,this.direction=t}async getConstraints(){return await qI(this,DS.REQUEST_CONSTRAINTS)}async requestApplyConstraints(e,t){var i;return OE.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),JI(this,DS.REQUEST_UPDATE_CONSTRAINTS,Array.from(pR(i=this.constraintsMap).call(i)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return OE.info("processor ".concat(e.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(e),JI(this,DS.REQUEST_UPDATE_CONSTRAINTS,Array.from(pR(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){OE.error(new SE(fE.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(ER(ER({},i),{},{direction:this.direction}))}catch(e){OE.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class SR extends EE{constructor(e){super(),_p(this,"name","AudioProcessorDestination"),_p(this,"ID","0"),_p(this,"inputTrack",void 0),_p(this,"inputNode",void 0),_p(this,"audioProcessorContext",void 0),_p(this,"_source",void 0),this.audioProcessorContext=e}get kind(){return"audio"}get enabled(){return!0}pipe(){throw new SE(fE.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new SE(fE.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(NS.ON_TRACK,void 0),this.emit(NS.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
5(NS.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(NS.ON_NODE,this.inputNode))}}class TR extends EE{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t,i){super(),_p(this,"constraintsMap",new Map),_p(this,"statsRegistry",[]),_p(this,"audioContext",void 0),_p(this,"trackId",void 0),_p(this,"direction",void 0),_p(this,"usageRegistry",[]),_p(this,"_chained",!1),this.audioContext=e,this.trackId=t,this.direction=i}async getConstraints(){return qI(this,DS.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(e,t){var i;return OE.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),JI(this,DS.REQUEST_UPDATE_CONSTRAINTS,Array.from(pR(i=this.constraintsMap).call(i)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),JI(this,DS.REQUEST_UPDATE_CONSTRAINTS,Array.from(pR(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){OE.error(new SE(fE.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(ER(ER({},i),{},{direction:this.direction}))}catch(e){OE.error("gather extension usage error",e)}return e}getDirection(){return this.direction}}class gR extends EE{get isPlayed(){return!0}get isFreeze(){return!1}constructor(){super(),_p(this,"context",void 0),_p(this,"processSourceNode",void 0),_p(this,"outputTrack",void 0),_p(this,"processedNode",void 0),_p(this,"clonedTrack",void 0),_p(this,"outputNode",void 0),this.outputNode=new RR}setVolume(){}createOutputTrack(){throw new SE(fE.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 RR{disconnect(){}connect(){}}let IR,vR=null;class CR{constructor(){_p(this,"state","open"),_p(this,"trigger",void 0),_p(this,"tasks",[]),OE.debug("[macro-task-queue] is created."),this.trigger=setTimeout(()=>{this.state="closed",OE.debug("[macro-task-queue] will be closed, all remaining tasks will execute. [".concat(this.tasks.map(e=>e.key),"]")),this.trigger=void 0,this.tasks.forEach(e=>{let{func:t}=e;return t()}),this.tasks.length=0,OE.debug("[macro-task-queue] is closed.")})}enqueue(e,t){"closed"!==this.state&&(this.tasks.push({key:e,func:t}),OE.debug("[macro-task-queue] is queued, current queue ".concat(this.tasks.length,". ").concat("string"==typeof e?e:"")))}runTask(e){if("closed"===this.state)return;const t=this.tasks.findIndex(t=>t.key===e);if(-1!==t){const i=this.tasks.splice(t,1);OE.debug("[macro-task-queue] is unqueued, current queue ".concat(this.tasks.length,". ").concat("string"==typeof e?e:"")),i[0].func()}}release(){this.trigger&&(this.state="closed",clearTimeout(this.trigger),this.trigger=void 0,this.tasks.length=0,OE.debug("[macro-task-queue] is closed."))}}function yR(e){return function(t,i,n){var r;const o=null!==(r=n.value)&&void 0!==r?r:n.get,s=function(){vR&&"open"===vR.state&&vR.runTask(e);for(var t=arguments.length,i=new Array(t),n=0;n<t;n++)i[n]=arguments[n];return null==o?void 0:o.apply(this,...i)};return n.value?n.value=s:n.get=s,n}}var AR,OR,bR,wR,NR,DR,PR,LR,kR,MR,UR,xR,VR,FR,jR,BR,GR,WR,HR,KR,YR,qR,JR,XR,zR,QR,ZR,$R,eI,tI,iI,nI,rI,oI,sI,aI,cI,dI,uI,lI;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]:{};
5t%2?hI(Object(i),!0).forEach((function(t){_p(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(e){e.UPDATE_TRACK_SOURCE="update-track-source"}(IR||(IR={}));let _I=(AR=yR("INIT_WEBAUDIO"),OR=yR("INIT_WEBAUDIO"),bR=yR("INIT_WEBAUDIO"),wR=Ig({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),NR=Ig({argsMap:(e,t)=>[e.getTrackId(),t]}),DR=oR(),PR=bg("LocalAudioTrack","_enabledMutex"),LR=Ig({argsMap:(e,t)=>[e.getTrackId(),t]}),kR=oR(),MR=bg("LocalAudioTrack","_enabledMutex"),UR=Ig({argsMap:(e,t)=>[e.getTrackId(),t]}),xR=oR(),VR=oR(),FR=oR(),jR=Ig({argsMap:e=>[e.getTrackId()]}),BR=oR(),GR=Ig({argsMap:e=>[e.getTrackId()]}),WR=oR(),HR=Ig({argsMap:e=>[e.getTrackId()]}),KR=Ig({argsMap:(e,t)=>[e.getTrackId(),t.name]}),YR=Ig({argsMap:e=>[e.getTrackId()]}),ZT((qR=class extends wg{get _source(){return this._trackSource}set _source(e){this._trackSource=e}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}get processorDestination(){return this._processorDestination}set processorDestination(e){this._processorDestination=e}get isPlaying(){return this._useAudioElement?rR.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"LocalAudioTrack"}constructor(e,t,i,n,r){super(e,i),_p(this,"trackMediaType","audio"),_p(this,"_encoderConfig",void 0),_p(this,"_trackSource",void 0),_p(this,"_enabled",!0),_p(this,"_volume",100),_p(this,"_useAudioElement",!1),_p(this,"_bypassWebAudio",!1),_p(this,"processor",void 0),_p(this,"_processorContext",void 0),_p(this,"_processorDestination",void 0),_p(this,"_getOriginVolumeLevel",void 0),this._encoderConfig=t,this._getOriginVolumeLevel=!!n;const o=()=>{this.processorContext=new TR(this._source.context,this.getTrackId(),"local"),this.processorDestination=new SR(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(Lf.UPDATE_SOURCE,()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})})},s=r&&Wh()&&!Ug();if(GE("DISABLE_WEBAUDIO")?(this._source=new gR,this._useAudioElement=!0,this._bypassWebAudio=!0):s?this._source=new gR:(this._source=new Gg(e,!1,this._getOriginVolumeLevel?e:void 0),GE("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")||(this._useAudioElement=!0)),o(),!GE("DISABLE_WEBAUDIO")&&s){(vR||(vR=new CR),vR).enqueue("INIT_WEBAUDIO",()=>{this._source=new Gg(e,!1,this._getOriginVolumeLevel?e:void 0),GE("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")||(this._useAudioElement=!0),o(),this.emit(IR.UPDATE_TRACK_SOURCE)})}}setVolume(e){qm(e,"volume",0,1e3),this._volume=e,this._source.setVolume(e/100),this._useAudioElement&&rR.setVolume(this.getTrackId(),e);try{if(this._bypassWebAudio)return void OE.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));const e=this._source.createOutputTrack();this._mediaStreamTrack!==e&&(this._mediaStreamTrack=e,JI(this,uS.NEED_REPLACE_TRACK,this).then(()=>{OE.debug("[".concat(this.getTrackId(),"] replace web audio track success"))}).catch(e=>{OE.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 SE(fE.NOT_SUPPORTED,"your browser does not support setting the audio output device");await rR.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(OE.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){this._originMediaStreamTrack.enabled=!0;try{i||(this._enabled=!0),await JI(this,uS.NEED_ENABLE_TRACK,this),OE.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(e," success"))}catch(e){throw i||(this._enabled=!1),OE.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}}else{this._originMediaStreamTrack.enabled=!1,i||(this._enabled=!1);try{await JI(this,uS.NEED_DISABLE_TRACK,this)}catch(e){throw i||(this._enabled=!0),OE.error("[".concat(this.getTrackId(),"] setEnabled to fal
5se error"),e.toString()),e}}}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,OE.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await JI(this,uS.NEED_MUTE_TRACK,this):await JI(this,uS.NEED_UNMUTE_TRACK,this))}getStats(){iv(()=>{OE.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")},"localAudioTrackGetStatsWarning");const e=XI(this,uS.GET_STATS);return e||pI({},Ff)}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(Lf.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(Lf.ON_AUDIO_BUFFER),this._source.on(Lf.ON_AUDIO_BUFFER,t=>e(t))}play(){OE.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(OE.debug("[".concat(this.getTrackId(),"] start audio playback in element")),rR.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){OE.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?rR.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];OE.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&rR.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 JI(this,uS.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 SE(fE.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===e)return e;if(e._source)throw new SE(fE.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(NS.ON_TRACK,async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e),await JI(this,uS.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await JI(this,uS.NEED_REPLACE_TRACK,this))}),this.processorDestination.on(NS.ON_NODE,e=>{this._source.processedNode=e})}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(NS.ON_TRACK),this.processorDestination.removeAllListeners(NS.ON_NODE)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(DS.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(DS.REQUEST_CONSTRAINTS)}}).prototype,"_source",[AR],Object.getOwnPropertyDescriptor(qR.prototype,"_source"),qR.prototype),ZT(qR.prototype,"processorContext",[OR],Object.getOwnPropertyDescriptor(qR.prototype,"processorContext"),qR.prototype),ZT(qR.prototype,"processorDestination",[bR],Object.getOwnPropertyDescriptor(qR.prototype,"processorDestination"),qR.prototype),ZT(qR.prototype,"setVolume",[wR],Object.getOwnPropertyDescriptor(qR.prototype,"setVolume"),qR.prototype),ZT(qR.prototype,"setPlaybackDevice",[NR,DR],Object.getOwnPropertyDescriptor(qR.prototype,"setPlaybackDevice"),qR.prototype),ZT(qR.prototype,"setEnabled",[PR,LR,kR],Object.getOwnPropertyDescriptor(qR.prototype,"setEnabled"),qR.prototype),ZT(qR.prototype,"setMuted",[MR,UR,xR],Object.getOwnPropertyDescriptor(qR.prototype,"setMuted"),qR.prototype),ZT(qR.prototype,"getStats",[VR],Object.getOwnPropertyDescriptor(qR.prototype,"getStats"),qR.prototype),ZT(qR.prototype,"setAudioFrameCallback",[FR],Object.getOwnPropertyDescriptor(qR.prototype,"setAudioFrameCallback"),qR.prototype),ZT(qR.prototype,"play",[jR,BR],Object.getOwnPropertyDescriptor(qR.prototype,"play"),qR.prototype),ZT(qR.prototype,"stop",[GR,WR],Object.getOwnPropertyDescriptor(qR.prototype,"stop"),qR.prototype),ZT(qR.prototype,"close",[HR],Object.getOwnPropertyDescriptor(qR.prototype,"close"),qR.prototype),ZT(qR.prototype,"pipe",[KR],Object.getOwnPropertyDescriptor(qR.prototype,"pipe"),qR.prototype),ZT(qR.prototype,"unpipe",[YR],Object.getOwnPropertyDescriptor(qR.prototype,"unpipe"),qR.prototype),qR),EI=(JR=Ig({argsMap:(e,t)=>[e.getTrackId(),t]}),XR=oR(),zR=bg("MicrophoneAudioTrack","_enabledMutex"),QR=Ig({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),ZR=oR(),$R=Ig({argsMap:e=>[e.getTrackId()]}),ZT((eI=class extends _I{get __className__(){return"MicrophoneAudioTrack"}constructor(e,t,i,n){super(e,t.encoderConfig?jE(t.encoderConfig):{},n,GE("GET_VOLUME_OF_MUTED_AUDIO_TRACK"),!0),_p(this,"_config",void 0),_p(this,"_deviceName","default"),_p(this,"_constraints",void 0),_p(this,"_originalConstraints",void 0),_p(this,"_enabled",!0),this._config=t,this._constraints=i,this._originalConstraints=i,this._deviceName=e.label,"boolean"==typeof t.bypassWebAudio&&(this._bypassWebAudio=t.bypassWebAudio),Qh()&&Lg.bindInterruptDetectorTrack(this),this.on(IR.UPDATE_TRACK_SOURCE,()=>{this.bindProcessorContextEvents()}),Ug()&&this.bindProcessorContextEvents()}async setDevice(e){if(OE.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{const t=await iR.getDeviceById(e),i={};i.audio=pI({},this._constraints),i.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let n=null;try{n=await Zg(i,this.getTrackId())}catch(e){throw OE.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),n=await Zg({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 OE.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await iR.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw OE.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}OE.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"))}async setEnabled(e,t,i){if(t)return OE.debug("[".concat(this.getTrackId(),"] setEnabled false (
5do not close microphone)")),await super._setEnabled(e);if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(OE.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 JI(this,uS.NEED_DISABLE_TRACK,this)}catch(e){throw OE.error("[".concat(this.getTrackId(),"] setEnabled false failed"),e.toString()),e}return}const r=pI({},this._constraints),o=iR.searchDeviceIdByName(this._deviceName);o&&!r.deviceId&&(r.deviceId=o);try{i||(this._enabled=!0);const e=await Zg({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1),await JI(this,uS.NEED_ENABLE_TRACK,this)}catch(e){throw i||(this._enabled=!1),OE.error("[".concat(this.getTrackId(),"] setEnabled true failed"),e.toString()),e}OE.info("[".concat(this.getTrackId(),"] setEnabled success"))}close(){super.close(),Qh()&&Lg.unbindInterruptDetectorTrack(this)}onTrackEnded(){if((Kh()||tp())&&this._enabled&&!this._isClosed&&Lg.duringInterruption){const e=async()=>{Lg.off(yg.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(OE.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};Lg.on(yg.IOS_INTERRUPTION_END,e)}else OE.debug("[".concat(this.getTrackId(),"] track ended")),this.emit(_S.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=iR.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId=i),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();const e=await Zg({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0)}}bindProcessorContextEvents(){this.processorContext.on(DS.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(DS.REQUEST_CONSTRAINTS,async e=>{e(this._originMediaStreamTrack.getSettings())})}}).prototype,"setDevice",[JR,XR],Object.getOwnPropertyDescriptor(eI.prototype,"setDevice"),eI.prototype),ZT(eI.prototype,"setEnabled",[zR,QR,ZR],Object.getOwnPropertyDescriptor(eI.prototype,"setEnabled"),eI.prototype),ZT(eI.prototype,"close",[$R],Object.getOwnPropertyDescriptor(eI.prototype,"close"),eI.prototype),eI),mI=(tI=Ig({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),iI=oR(),nI=Ig({argsMap:e=>[e.getTrackId()]}),rI=oR(),oI=Ig({argsMap:e=>[e.getTrackId()]}),sI=oR(),aI=Ig({argsMap:e=>[e.getTrackId()]}),cI=oR(),dI=Ig({argsMap:e=>[e.getTrackId()]}),uI=oR(),ZT((lI=class extends _I{get __className__(){return"BufferSourceAudioTrack"}constructor(e,t,i,n){super(t.createOutputTrack(),i,n),_p(this,"source",void 0),_p(this,"_bufferSource",void 0),this.source=e,this._bufferSource=t,this._bufferSource.on(Lf.AUDIO_SOURCE_STATE_CHANGE,e=>{this.emit(_S.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",[tI,iI],Object.getOwnPropertyDescriptor(lI.prototype,"startProcessAudioBuffer"),lI.prototype),ZT(lI.prototype,"pauseProcessAudioBuffer",[nI,rI],Object.getOwnPropertyDescriptor(lI.prototype,"pauseProcessAudioBuffer"),lI.prototype),ZT(lI.prototype,"seekAudioBuffer",[oI,sI],Object.getOwnPropertyDescriptor(lI.prototype,"seekAudioBuffer"),lI.prototype),ZT(lI.prototype,"resumeProcessAudioBuffer",[aI,cI],Object.getOwnPropertyDescriptor(lI.prototype,"resumeProcessAudioBuffer"),lI.prototype),ZT(lI.prototype,"stopProcessAudioBuffer",[dI,uI],Object.getOwnPropertyDescriptor(lI.prototype,"stopProcessAudioBuffer"),lI.prototype),lI);class fI extends _I{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=Mg().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,GI(8,"track-mix-")),_p(this,"trackList",void 0),_p(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)?(OE.debug("add ".concat(e.getTrackId()," to mixing track")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):OE.debug("track ".concat(e.getTrackId()," is already added"))}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){OE.debug("remove ".concat(e.getTrackId()," from mixing track"));try{e._source.outputNode.disconnect(this.destNode)}catch(e){}QI(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}}
vendor: 4,576 bytes, line 5
5class SI extends EE{constructor(){super(...arguments),_p(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",TI[e],e,t),!n.isPrevNormal&&i&&this.emit("exception",TI[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 fI&&!t.isActive||(!!t.muted||0!==e.sendVolumeLevel)}checkFramerateInput(e,t){let i=null;t._encoderConfig&&t._encoderConfig.frameRate&&(i=wI(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 fI&&!t.isActive||(!!t.muted||0!==e.sendBitrate)}checkVideoDecode(e){return 0===e.receiveBitrate||0!==e.decodeFrameRate}}const TI={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 gI=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 RI(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 II(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?RI(Object(i),!0).forEach((function(t){_p(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):RI(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class vI{constructor(e){_p(this,"store",void 0),_p(this,"onStatsException",void 0),_p(this,"onUploadPublishDuration",void 0),_p(this,"localStats",new Map),_p(this,"remoteStats",new Map),_p(this,"updateStatsInterval",void 0),_p(this,"trafficStats",void 0),_p(this,"trafficStatsPeerList",[]),_p(this,"uplinkStats",void 0),_p(this,"exceptionMonitor",void 0),_p(this,"p2pChannel",void 0),_p(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 SI,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(yS.LocalAudioTrack)||II({},Ff)}getLocalVideoTrackStats(){return this.localStats.get(yS.LocalVideoTrack)||II({},jf)}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))}
5else 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(yS.LocalAudioTrack);r&&(e+=r.sendBytes,t+=r.sendBitrate);const o=this.localStats.get(yS.LocalVideoTrack);o&&(e+=o.sendBytes,t+=o.sendBitrate);const s=this.localStats.get(yS.LocalVideoLowTrack);
5s&&(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?gI.measureFromSubscribeStart(this.store.clientId,i.videoSSRC):0,r=null!=i&&i.audioSSRC?gI.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&&OE.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 yS.LocalVideoTrack:case yS.LocalVideoLowTrack:{const t=n,r=II({},jf),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(yS.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 yS.LocalAudioTrack:{const t=n,r=II({},Ff),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(yS.LocalAudioTrack,r),r&&s&&this.exceptionMonitor.setLocalAudioStats(this.store.uid,s.track,r);break}}})}updateRemoteStats(e){Array.from(this.remoteStats.entries()).forEac
5h(t=>{let[i,{videoStats:n,audioStats:r,videoPcStats:o}]=t;const s=r,a=n,c=o,d=II({},Bf),u=II({},Wf),l=II({},Gf),{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&&vI.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&&vI.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 CI=new class extends EE{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}constructor(){super(),_p(this,"_lastHiddenTime",0),_p(this,"_lastVisibleTime",0),document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),OE.debug("document visibility went ".concat(document.visibilityState)),this.emit("VISIBILITY_CHANGE",document.visibilityState)})}};function yI(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 AI(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?yI(Object(i),!0).forEach((function(t){_p(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):yI(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function OI(e){return e.match(/^[\.\:\d]+$/)?"".concat(e.replace(/[^\d]/g,"-"),".").concat(GE("TURN_DOMAIN")):(OE.info("Cannot recognized as IP address ".concat(e,". Used As Host instead")),e)}function bI(e,t){var i,n;const r=GE("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)}:(OE.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 wI(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function NI(e){const t=e._encoderConfig;if(!t)return{};const i={resolution:t.width&&t.height?"".concat(wI(t.width),"x").concat(wI(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 DI(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:GI(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 PI(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 LI(e,t){let i,n,r=void 0;switch(t){case jS.CHOOSE_SERVER:i=4096,n="choose server";break;case jS.CLOUD_PROXY:i=1048576,n="proxy";break;case jS.CLOUD_PROXY_5:i=4194304,n="proxy5";break;case jS.CLOUD_PROXY_FALLBACK:i=4194310,n="proxy fallback";break;default:throw new SE(fE.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=>AI(AI({},e),{},{ticket:t.buffer.cert})),server_ts:e.enter_ts,uid:t.buffer.uid,cid:t.buffer.cid,cname:t.buffer.cname,detail
5:AI(AI({},t.buffer.detail),e.detail),flag:t.buffer.flag,opid:e.opid,cert:t.buffer.cert})}),!r)throw new SE(fE.MULTI_UNILBS_RESPONSE_ERROR,"cannot parse response ".concat(n," from multi unilbs response"),{csIp:e.detail&&e.detail[502]});return r}async function kI(e,t){return await Sl.all(e.addresses.map(async e=>({address:OI(e.ip),tcpport:e.port,udpport:e.port,username:t&&GE("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?t.toString():PE.username,password:t&&GE("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?await Tg(t.toString()):PE.password})))}function MI(e,t){const i=t._videoWidth||t.getMediaStreamTrack(!0).getSettings().width;return i||OE.warning("cannot get original video track's width, default scale down 4 times for low stream"),i?i/wI(e.width):4}function UI(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 xI(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 VI(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?xI(Object(i),!0).forEach((function(t){_p(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):xI(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function FI(e){return window.TextEncoder?(new TextEncoder).encode(e).length:e.length}function jI(e){return new Sl(t=>{window.setTimeout(t,e)})}function BI(e){const t=new SE(fE.TIMEOUT,"timeout");return new Sl((i,n)=>{window.setTimeout(()=>n(t),e)})}function GI(){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)+GI(e-i.length,"")}function WI(){return GI(32,"").toUpperCase()}const HI=()=>{};function KI(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(HI),setTimeout(()=>{n||(r.srcObject=null,r.remove(),t([r.videoWidth,r.videoHeight]))},4e3)})}function YI(e){return Sl.all(e.map(e=>e.then(e=>{throw e},e=>e))).then(e=>{throw e},e=>e)}function qI(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 SE(fE.UNEXPECTED_ERROR,"can not emit promise")):new Sl((i,r)=>{e.emit(t,...n,i,r)})}function JI(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 qI(e,t,...n)}function XI(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 zI(e,t,...n)}function zI(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 SE(fE.UNEXPECTED_ERROR,"handler is not sync");return i}function QI(e,t){const i=e.indexOf(t);-1!==i&&e.splice(i,1)}function ZI(e){const t=[];return e.forEach(e=>{-1===t.indexOf(e)&&t.push(e)}),t}function $I(e){Sl.resolve().then(e)}function ev(e){return JSON.parse(JSON.stringify(e))}const tv={};function iv(e,t){tv[t]||(tv[t]=!0,e())}function nv(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 rv(e){let t="";for(let i=0;i<e.length;i+=1)t+=String.fromCharCode(e[i]);return window.btoa(t)}const ov=new class{constructor(){_p(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})}
vendor: 8,716 bytes, line 5
5else r.skipFn&&r.skipFn(...r.args),this.fnMap.set(t,VI(VI({},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})}}},sv=ov.throttleByKey.bind(ov),av=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 YI(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 cv(e){return"object"==typeof e&&null!==e&&!(e instanceof RegExp)}const dv={[Sf.ACCESS_POINT]:{[Rf.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[Rf.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[Rf.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[Rf.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[Rf.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[Rf.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[Rf.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[Rf.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voice service available",retry:!0},[Rf.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[Rf.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[Rf.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[Rf.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[Rf.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[Rf.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[Rf.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[Rf.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[Rf.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[Rf.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[Sf.UNILBS]:{[gf.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[gf.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[gf.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[gf.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[gf.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[gf.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[gf.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[gf.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[gf.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[gf.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[gf.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[gf.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1}},[Sf.STRING_UID_ALLOCATOR]:{[Tf.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[Tf.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[Tf.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function uv(e){const t=dv[Math.floor(e/1e4)];if(!t)return{desc:"unkonw error",retry:!1};const i=t[e%1e4];if(!i){if(Math.floor(e/1e4)===Sf.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 lv={[If.K_TIMESTAMP_EXPIRED]:{desc:"K_TIMESTAMP_EXPIRED",action:"failed"},[If.K_CHANNEL_PERMISSION_INVALID]:{desc:"K_CHANNEL_PERMISSION_INVALID",action:"failed"},[If.K_CERTIFICATE_INVALID]:{desc:"K_CERTIFICATE_INVALID",action:"failed"},[If.K_CHANNEL_NAME_EMPTY]:{desc:"K_CHANNEL_NAME_EMPTY",action:"failed"},[If.K_CHANNEL_NOT_FOUND]:{desc:"K_CHANNEL_NOT_FOUND",action:"failed"},[If.K_TICKET_INVALID]:{desc:"K_TICKET_INVALID",action:"failed"},[If.K_CHANNEL_CONFLICTED]:{desc:"K_CHANNEL_CONFLICTED",action:"failed"},[If.K_SERVICE_NOT_READY]:{desc:"K_SERVICE_NOT_READY",action:"tryNext"},[If.K_SERVICE_TOO_HEAVY]:{desc:"K_SERVICE_TOO_HEAVY",action:"tryNext"},[If.K_UID_BANNED]:{desc:"K_UID_BANNED",action:"failed"},[If.K_IP_BANNED]:{desc:"K_IP_BANNED",action:"failed"},[If.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[If.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[If.WARN_NO_AVAILABLE_CHANNEL]:{desc:"WARN_NO_AVAILABLE_CHANNEL",action:"failed"},[If.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:"WARN_LOOKUP_CHANNEL_TIMEOUT",action:"tryNext"},[If.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:"WARN_LOOKUP_CHANNEL_REJECTED",action:"failed"},[If.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:"WARN_OPEN_CHANNEL_TIMEOUT",action:"tryNext"},[If.WARN_OPEN_CHANNEL_REJECTED]:{desc:"WARN_OPEN_CHANNEL_REJECTED",action:"failed"},[If.WARN_REQUEST_DEFERRED]:{desc:"WARN_REQUEST_DEFERRED",action:"failed"},[If.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:"ERR_DYNAMIC_KEY_TIMEOUT",action:"failed"},[If.ERR_NO_AUTHORIZED]:{desc:"ERR_NO_AUTHORIZED",action:"failed"},[If.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:"ERR_VOM_SERVICE_UNAVAILABLE",action:"tryNext"},[If.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:"ERR_NO_CHANNEL_AVAILABLE_CODE",action:"failed"},[If.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:"ERR_MASTER_VOCS_UNAVAILABLE",action:"tryNext"},[If.ERR_INTERNAL_ERROR]:{desc:"ERR_INTERNAL_ERROR",action:"tryNext"},[If.ERR_NO_ACTIVE_STATUS]:{desc:"ERR_NO_ACTIVE_STATUS",action:"failed"},[If.ERR_INVALID_UID]:{desc:"ERR_INVALID_UID",action:"failed"},[If.ERR_DYNAMIC_KEY_EXPIRED]:{desc:"ERR_DYNAMIC_KEY_EXPIRED",action:"failed"},[If.ERR_STATIC_USE_DYANMIC_KE]:{desc:"ERR_STATIC_USE_DYANMIC_KE",action:"failed"},[If.ERR_DYNAMIC_USE_STATIC_KE]:{desc:"ERR_DYNAMIC_USE_STATIC_KE",action:"failed"},[If.ERR_NO_VOCS_AVAILABLE]:{desc:"ERR_NO_VOCS_AVAILABLE",action:"tryNext"},[If.ERR_NO_VOS_AVAILABLE]:{desc:"ERR_NO_VOS_AVAILABLE",action:"tryNext"},[If.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:"ERR_JOIN_CHANNEL_TIMEOUT",action:"tryNext"},[If.ERR_JOIN_BY_MULTI_IP]:{desc:"ERR_JOIN_BY_MULTI_IP",action:"recover"},[If.ERR_NOT_JOINED]:{desc:"ERR_NOT_JOINED",action:"failed"},[If.ERR_REPEAT_JOIN_REQUEST]:{desc:"ERR_REPEAT_JOIN_REQUEST",action:"quit"},[If.ERR_REPEAT_JOIN_CHANNEL]:{desc:"ERR_REPEAT_JOIN_CHANNEL",action:"quit"},[If.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[If.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[If.ERR_INVALID_STRINGUID]:{desc:"ERR_INVALID_STRINGUID",action:"failed"},[If.ERR_TOO_MANY_USERS]:{desc:"ERR_TOO_MANY_USERS",action:"tryNext"},[If.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[If.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[If.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",action:"success"},[If.ERR_PUBLISH_REQUEST_INVALID]:{desc:"ERR_PUBLISH_REQUEST_INVALID",action:"failed"},[If.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:"ERR_SUBSCRIBE_REQUEST_INVALID",action:"failed"},[If.ERR_NOT_SUPPORTED_MESSAGE]:{desc:"ERR_NOT_SUPPORTED_MESSAGE",action:"failed"},[If.ERR_ILLEAGAL_PLUGIN]:{desc:"ERR_ILLEAGAL_PLUGIN",action:"failed"},[If.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:"ILLEGAL_CLIENT_ROLE_LEVEL",action:"failed"},[If.ERR_REJOIN_TOKEN_INVALID]:{desc:"ERR_REJOIN_TOKEN_INVALID",action:"failed"},[If.ERR_REJOIN_USER_NOT_JOINED]:{desc:"ERR_REJOIN_NOT_JOINED",action:"failed"},[If.ERR_INVALID_OPTIONAL_INFO]:{desc:"ERR_INVALID_OPTIONAL_INFO",action:"quit"},[If.ERR_TEST_RECOVER]:{desc:"ERR_TEST_RECOVER",action:"recover"},[If.ERR_TEST_TRYNEXT]:{desc:"ERR_TEST_TRYNEXT",action:"recover"},[If.ERR_TEST_RETRY]:{desc:"ERR_TEST_RETRY",action:"recover"},[If.ILLEGAL_AES_PASSWORD]:{desc:"ERR_TEST_RETRY",action:"failed"},[If.ERR_TOO_MANY_BROADCASTERS]:{desc:"ERR_TOO_MANY_BROADCASTERS",action:"failed"},[If.ERR_TOO_MANY_SUBSCRIBERS]:{desc:"ERR_TOO_MANY_SUBSCRIBERS",action:"failed"},[If.ERR_LICENSE_ILLEGAL]:{desc:"ERR_LICENSE_ILLEGAL",action:"quit"},[If.ERR_LICENSE_MISSING]:{desc:"ERR_LICENSE_MISSING",action:"quit"},[If.ERR_LICENSE_EXPIRED]:{desc:"ERR_LICENSE_EXPIRED",action:"quit"},[If.ERR_LICENSE_MINUTES_EXCEEDED]:{desc:"ERR_LICENSE_MINUTES_EXCEEDED",action:"quit"},[If.ERR_LICENSE_PERIOD_INVALID]:{desc:"ERR_LICENSE_PERIOD_INVALID",action:"quit"},[If.ERR_LICENSE_MULTIPLE_SDK_SERVICE]:{desc:"ERR_LICENSE_MULTIPLE_SDK_SERVICE",action:"quit"}};function hv(e){const t=lv[e];return t||{desc:"UNKNOW_ERROR_".concat(e),action:"failed"}}function pv(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}
5class _v extends EE{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(Hf.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(Hf.CONNECTED):"closed"===this._state?this.emit(Hf.CLOSED):"failed"===this._state&&this.emit(Hf.FAILED))}resetReconnectCount(e){OE.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(),_p(this,"connectionID",0),_p(this,"currentURLIndex",0),_p(this,"urls",void 0),_p(this,"_reconnectMode","tryNext"),_p(this,"reconnectReason",void 0),_p(this,"_initMutex",new Og("websocket")),_p(this,"name",void 0),_p(this,"_state","closed"),_p(this,"reconnectInterrupter",void 0),_p(this,"websocket",void 0),_p(this,"retryConfig",void 0),_p(this,"reconnectCount",0),_p(this,"forceCloseTimeout",5e3),_p(this,"onlineReconnectListener",void 0),_p(this,"useCompress",void 0),_p(this,"tryDoubleDomain",!1),_p(this,"wsInflateLength",0),_p(this,"wsDeflateLength",0),_p(this,"closeEstablishingWs",()=>{}),_p(this,"store",void 0),_p(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?pv(Object(i),!0).forEach((function(t){_p(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):pv(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);bS.ONLINE&&(this.retryConfig.timeout=a,this.retryConfig.timeoutFactor=c),pg.on(wS.NETWORK_STATE_CHANGE,(e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===bS.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(Hf.CLOSED,()=>i(new SE(fE.WS_DISCONNECT))),this.once(Hf.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 OE.warning("[".concat(this.name,"] can not reconnect, no websocket"));var i;(void 0!==e&&(this.reconnectMode=e),OE.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 SE(fE.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new SE(fE.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(),OE.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),i()},s=async e=>{if(OE.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=XI(this,Hf.WILL_RECONNECT,this.reconnectMode)||this.reconnectMode,r=await this.reconnectWithAction(t);
5if("closed"===this.state)return void OE.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!r)return n(new SE(fE.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),void this.close(!0);i()}else n(new SE(fE.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close()},a=e=>{this.emit(Hf.ON_MESSAGE,e)};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),GE("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=GE("GATEWAY_WSS_ADDRESS")),OE.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 SE&&e.code===fE.WS_ABORT?"aborted":"error",errors:[e]},c),"closed"!==this.state){if(e instanceof SE&&e.code===fE.WS_ERR){const t=new SE(fE.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return OE.error("[".concat(this.name,"]").concat(t)),void n(t)}s&&s(e)}else n(new SE(fE.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||pg.networkState!==bS.OFFLINE||(this.onlineReconnectListener=pg.onlineWaiter&&pg.onlineWaiter.then(()=>{this.onlineReconnectListener=void 0}));let i=!0;if(this.reconnectInterrupter=()=>{i=!1},t){const t=gE(this.reconnectCount,this.retryConfig);OE.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await Sl.race([jI(t),this.onlineReconnectListener||new Sl(()=>{})])}if("closed"===this.state||!i)return!1;this.reconnectCount+=1;const n=async(e,t)=>{this.emit(Hf.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e){const t=this.urls[this.currentURLIndex];this.emit(Hf.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);OE.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex));const t=this.urls[this.currentURLIndex];this.emit(Hf.RECONNECT_WAITTING_FINISH,e),await n(t,e)}else if("recover"===e){OE.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.emit(Hf.RECONNECT_WAITTING_FINISH,e),this.urls=await qI(this,Hf.REQUEST_NEW_URLS),this.currentURLIndex=0;const t=this.urls[this.currentURLIndex];await n(t,e)}return!0}catch(i){var r;return OE.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(Hf.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=()=>{OE.debug("[choose-best-ws] close establishing websockets"),s.forEach(e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()}),r(new SE(fE.WS_ABORT,"choose best websocket aborted"))};const a=GE("GATEWAY_DOMAINS");let c;const d=e.indexOf("?h="),u=a.find(t=>-1!==d?e.includes(t,d):e.includes(t));OE.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),OE.debug("[choose-best-ws] ws is connecting:",n.url)})}catch(e){for(OE.debug("[choose-best-ws] ws create failed, fallback to single url"),s.forEac
5h(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;OE.debug("[choose-best-ws] ws open cost ".concat(i,"ms")),s.filter(t=>t!==e).forEach(e=>{OE.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))||(OE.debug("[choose-best-ws] all websocket is closed"),o=!0,r(c))},e.onmessage=t=>{OE.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}}),jI(this.forceCloseTimeout).then(()=>{s.forEach(e=>{e.readyState!==WebSocket.OPEN&&e.close()})})}if(l){var p;let t;OE.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 SE(fE.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return OE.error("[".concat(this.name,"]").concat(t)),void r(t)}t.onopen=()=>{n(t)},t.onclose=e=>{r(e)},t.onmessage=e=>{OE.debug("[choose-best-ws]".concat(t.url," onmessage: ").concat(e.data))},jI(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 Ev{constructor(e){_p(this,"input",[]),_p(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 mv extends EE{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===Of.CONNECTED?this.emit(bf.WS_CONNECTED):e===Of.RECONNECTING?this.emit(bf.WS_RECONNECTING,this._websocketReconnectReason):e===Of.CLOSED&&this.emit(bf.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(),_p(this,"_disconnectedReason",void 0),_p(this,"_websocketReconnectReason",void 0),_p(this,"_connectionState",Of.CLOSED),_p(this,"reconnectToken",void 0),_p(this,"websocket",void 0),_p(this,"openConnectionTime",void 0),_p(this,"clientId",void 0),_p(this,"lastMsgTime",Date.now()),_p(this,"uploadCache",[]),_p(this,"uploadCacheInterval",void 0),_p(this,"rttRolling",new Ev(5)),_p(this,"pingpongTimer",void 0),_p(this,"wsInflateDataTimer",void 0),_p(this,"pingpongTimeoutCount",0),_p(this,"joinResponse",void 0),_p(this,"multiIpOption",void 0),_p(this,"initError",void 0),_p(this,"spec",void 0),_p(this,"store",void 0),_p(this,"onWebsocketMessage",e=>{if(e.data instanceof ArrayBuffer)return void this.emit(bf.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===Df.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===Df.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close(Cf.UID_BANNED);break;case 15:this.close(Cf.IP_BANNED);break;case 16:this.close(Cf.CHANNEL_BANNED)}if(t._type===Df.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case If.ERR_LICENSE_MISSING:this.close(Cf.LICENSE_MISSING);break;case If.ERR_LICENSE_EXPIRED:this.close(Cf.LICENSE_EXPIRED);break;case If.ERR_LICENSE_MINUTES_EXCEEDED:this.close(Cf.LICENSE_MINUTES_EXCEEDED);break;case If.ERR_LICENSE_PERIOD_INVALID:this.close(Cf.LICENSE_PERIOD_INVALID);break;case If.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(Cf.LICENSE_MULTIPLE_SDK_SERVICE);break;case If.ERR_LICENSE_ILLEGAL:this.close(Cf.LICENSE_ILLEGAL);break;default:this.close()}}}),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new _v("gateway-".concat(this.clientId),this.spec.retryConfig,!0,!0,t),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===Of.CONNECTED&&this.reconnect("retry",Af.OFFLINE)})}async request(e,t,i,n){const r=GI(6,""),o={_id:r,_type:e,_message:t},s=this.websocket.connectionID,a=()=>new Sl((t,i)=>{if(this.connectionState===Of.CONNECTED)return t();const n=()=>{this.off(bf.WS_CLOSED,r),t()},r=()=>{this.off(bf.WS_CONNECTED,n),i(new SE(fE.WS_ABORT))};this.once(bf.WS_CONNECTED,n),this.once(bf.WS_CLOSED,r),e!==wf.PUBLISH&&e!==wf.SUBSCRIBE&&e!==wf.UNSUBSCRIBE&&e!==wf.UNPUBLISH&&e!==wf.CONTROL&&e!==wf.RESTART_ICE||this.once(bf.DISCONNECT_P2P,()=>{i(new SE(fE.DISCONNECT_P2P))}),e!==wf.PUBLISH&&e!==wf.RESTART_ICE||this.once(bf.ABORT_P2P_EXECUTION,()=>{i(new SE(fE.DISCONNECT_P2P))})});if(this.connectionState!==Of.CONNECTING&&this.connectionState!==Of.RECONNECTING||e===wf.JOIN||e===wf.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(bf.WS_CLOSED,c),this.off(bf.WS_RECONNECTING,c),this.emit
vendor: 4,619 bytes, line 5
5(bf.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{n(new SE(fE.WS_ABORT,"type: ".concat(e))),this.off(bf.WS_CLOSED,c),this.off(bf.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(bf.WS_CLOSED,c),this.once(bf.WS_RECONNECTING,c),jI(GE("SIGNAL_REQUEST_TIMEOUT")).then(()=>{this.websocket.connectionID!==s||o||(OE.warning("ws request timeout, type: ".concat(e)),this.emit(bf.REQUEST_TIMEOUT,e,t))})});let d=null;try{d=await c}catch(n){if(this.connectionState===Of.CLOSED||e===wf.LEAVE)throw new SE(fE.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===wf.JOIN||e===wf.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=hv(u),h=new SE(fE.UNEXPECTED_RESPONSE,"".concat(l.desc,": ").concat(d.message.error_str),{code:u,data:d.message});return"success"===l.action?d.message:(OE.warning("[".concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(u,", message: ").concat(l.desc,", action: ").concat(l.action)),u===If.ERR_TOO_MANY_BROADCASTERS?e===wf.JOIN||e===wf.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===If.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,OE.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",Af.MULTI_IP)):this.reconnect(l.action,Af.SERVER_ERROR),e===wf.JOIN||e===wf.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=GE("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!==Of.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)},GE("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(bf.WS_CONNECTED,()=>i(this.joinResponse)),this.once(bf.WS_CLOSED,()=>n(this.initError||new SE(fE.WS_ABORT))),this.connectionState=Of.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&&(OE.debug("[".concat(this.clientId,"] init websocket timeout while join with fallback to proxy")),n(new SE(fE.INIT_WEBSOCKET_TIMEOUT)))},GE("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||Cf.LEAVE,this.connectionState=Of.CLOSED,OE.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close(),e===Cf.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new _v("gateway-".concat(this.clientId),this.spec.retryConfig,!0,!0,this.store),this.handleWebsocketEvents())}async join(){if(!this.joinResponse){this.emit(bf.ABORT_P2P_EXECUTION);const e=await qI(this,bf.REQUEST_JOIN_INFO),t=await this.request(wf.JOIN,e);if(!t)return this.emit(bf.REPORT_JOIN_GATEWAY,fE.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(bf.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=Of.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new SE(fE.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=zI(this,bf.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(wf.REJOIN,e);return!!t&&(this.connectionState=Of.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEac
5h(e=>{this.emit(Df.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(Df.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(Df.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(Df.MUTE_AUDIO,{uid:e.uid}):this.emit(Df.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(Df.MUTE_VIDEO,{uid:e.uid}):this.emit(Df.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(Df.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(Df.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(Df.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(Df.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(Df.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){OE.debug("[".concat(this.clientId,"] receive notification: "),e);const t=hv(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(Cf.UID_BANNED),void this.close()):void this.reconnect(t.action,Af.SERVER_ERROR);OE.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=GE("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(OE.warning("PINGPONG Timeout. Last Socket Message: ".concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>GE("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",Af.TIMEOUT):this.request(wf.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),GE("REPORT_STATS")&&this.send(wf.PING_BACK,{pingpongElapse:e})}).catch(e=>{})}handleWsInflateData(){const{wsInflateLength:e,wsDeflateLength:t}=this.websocket.getWsInflateData();0!==e&&0!==t&&this.upload(Nf.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(Hf.RECONNECT_WAITTING_FINISH,e=>{this.emit(bf.WS_RECONNECT_WAITTING_FINISH,e)}),this.websocket.on(Hf.RECONNECT_CREATE_CONNECTION,e=>{this.emit(bf.WS_RECONNECT_CREATE_CONNECTION,e)}),this.websocket.on(Hf.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(Hf.CLOSED,()=>{this.connectionState=Of.CLOSED}),this.websocket.on(Hf.FAILED,()=>{this._disconnectedReason=Cf.NETWORK_ERROR,this.connectionState=Of.CLOSED}),this.websocket.on(Hf.RECONNECTING,e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===Of.CONNECTED?this.connectionState=Of.RECONNECTING:this.connectionState=Of.CONNECTING}),this.websocket.on(Hf.WILL_RECONNECT,(e,t)=>{if(zI(this,bf.IS_P2P_DISCONNECTED)&&"retry"===e)return OE.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit(bf.NEED_RENEW_SESSION),this.emit(bf.DISCONNECT_P2P),t("tryNext");"retry"!==e&&(OE.debug("".concat(this.clientId," websockt will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0,this.emit(bf.NEED_RENEW_SESSION),this.emit(bf.DISCONNECT_P2P)),t(e)}),this.websocket.on(Hf.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch(e=>{OE.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",Af.SERVER_ERROR)}):this.join().catch(e=>{if(this.emit(bf.REPORT_JOIN_GATEWAY,e.message||e.code,this.url||""),e instanceof SE&&e.code===fE.UNEXPECTED_RESPONSE&&e.data.code===If.ERR_NO_AUTHORIZED)return OE.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",Af.SERVER_ERROR);OE.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",Af.SERVER_ERROR):(this.initError=e,this.close())})}),this.websocket.on(Hf.REQUEST_NEW_URLS,(e,t)=>{qI(this,bf.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)}),this.websocket.on(Hf.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>
vendor: 6,564 bytes, line 5
5{this.emit(Df.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})}}function fv(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 Sv extends EE{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(US.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(US.CONNECTED):"closed"===this._state?this.emit(US.CLOSED):"failed"===this._state&&this.emit(US.FAILED))}constructor(e,t,i,n){super(),_p(this,"connectionID",0),_p(this,"currentURLIndex",0),_p(this,"reconnectReason",void 0),_p(this,"_reconnectMode","tryNext"),_p(this,"_initMutex",void 0),_p(this,"_name",void 0),_p(this,"_state","closed"),_p(this,"_reconnectInterrupter",void 0),_p(this,"_url",void 0),_p(this,"_retryConfig",void 0),_p(this,"_reconnectCount",0),_p(this,"_forceCloseTimeout",5e3),_p(this,"_onlineReconnectListener",void 0),_p(this,"_closeEstablishingTransmitter",()=>{}),_p(this,"_store",void 0),_p(this,"_joinChannelServiceRecordIndex",void 0),_p(this,"_transmitter",void 0),_p(this,"_useCompress",void 0),_p(this,"_inflateLength",0),_p(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?fv(Object(i),!0).forEach((function(t){_p(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):fv(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({},t),this._useCompress=i}resetReconnectCount(e){OE.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 OE.warning("[".concat(this._name,"] can not reconnect, no websocket"));var i;(void 0!==e&&(this.reconnectMode=e),OE.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 Tv(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 gv(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 Rv;!function(e){e[e.Default=0]="Default",e[e.Ack=1]="Ack"}(Rv||(Rv={}));class Iv{constructor(e,t,i){_p(this,"version",1),_p(this,"initialRTO",void 0),_p(this,"maxBatchAckCount",void 0),_p(this,"maxRTO",void 0),_p(this,"initialRTT",void 0),_p(this,"ID",void 0),_p(this,"rtt",void 0),_p(this,"packetNumber",1),_p(this,"rtoRatioMap",new Map),_p(this,"timeoutMap",new Map),_p(this,"unorderedPacketQueue",[]),_p(this,"batchAckPacketQueue",[]),_p(this,"lastOrderedPacketNumber",0),_p(this,"batchAckTimer",void 0),_p(this,"sendImpl",void 0),_p(this,"receiveImpl",void 0),this.sendImpl=e,this.receiveImpl=t,this.ID=GI(7,"transmitter-"),this.initialRTO=void 0!==(null==i?void 0:i.initialRTO)?i.initialRTO:GE("TRANSMITTER_INITIAL_RTO"),this.initialRTT=void 0!==(null==i?void 0:i.initialRTT)?i.initialRTT:GE("TRANSMITTER_INITIAL_RTT"),this.rtt=void 0!==(null==i?void 0:i.initialRTT)?i.initialRTT:GE("TRANSMITTER_INITIAL_RTT"),this.maxBatchAckCount=void 0!==(null==i?void 0:i.maxBatchAckCount)?i.maxBatchAckCount:GE("TRANSMITTER_MAX_BATCH_ACK_COUNT"),this.maxRTO=void 0!==(null==i?void 0:i.maxRTO)?i.maxRTO:GE("TRANSMITTER_MAX_RTO")}packetize(e,t){return{type:Rv.Default,version:this.version,packetNumber:t,payload:e}}serialize(e){switch(e.type){case Rv.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),gv(n,7,BigInt(e.sendTs));return new Uint8Array(n.buffer).set(t,15),i}case Rv.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),gv(i,8,BigInt(e.ackSendTs)),t}}}deserialize(e){const t=new DataView(e),i=t.getUint16(0),n=t.getUint8(2);switch(n){case Rv.Default:{const r=t.getUint32(3),o=Tv(t,7),s=e.slice(15),a=(new TextDecoder).decode(s);return{version:i,type:n,packetNumber:r,sendTs:Number(o),payload:a}}case Rv.Ack:{const e=t.getUint32(3),r=t.getUint8(7),o=Tv(t,8);return{version:i,type:n,maxAckPacketNumber:e,shift:r,ackSendTs:Number(o)}}default:throw OE.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===Rv.Default?this.ack(t):t.type===Rv.Ack&&(this.updateRTT(t,Math.round(performance.now())),this.clearRTO(t))}close(){this.rtt=this.initialRTT,this.packetNumber=1,Array.from(this.timeoutMap.entries()).forEac
5h(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:Rv.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:Rv.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:Rv.Ack,version:this.version};this.sendPacket(e),this.batchAckPacketQueue=[]}sendPacket(e){e.type===Rv.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 vv extends Sv{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3?arguments[3]:void 0),_p(this,"_initMutex",void 0),_p(this,"_reconnectInterrupter",void 0),_p(this,"_url",void 0),_p(this,"_transmitter",void 0),_p(this,"_addresses",void 0),_p(this,"_reliableTransmission",void 0),this._initMutex=new Og("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);bS.ONLINE&&(this._retryConfig.timeout=r,this._retryConfig.timeoutFactor=o),pg.on(wS.NETWORK_STATE_CHANGE,(e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===bS.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||GE("FINGERPRINT"));const n=this._addresses[this.currentURLIndex];this.state="connecting",this.createTransmitterConnection(n).then(t).catch(i),this.once(US.CLOSED,()=>i(new SE(fE.WS_DISCONNECT))),this.once(US.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 SE(fE.WS_ABORT,"datachannel is not ready");try{t||(e=JSON.stringify(e)),this._reliableTransmission.sendMessage(e)}catch(e){throw new SE(fE.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=()=>{OE.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),OE.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=XI(this,US.WILL_RECONNECT,this.reconnectMode)||this.reconnectMode,r=await this.reconnectWithAction(n);if("closed"===this.state)return void OE.debug("[".concat(this.connectionID,"] dc is closed, no need to reconnect"));if(!r)return i(new SE(fE.WS_DISCONNECT,"datachannel reconnect failed: ".concat(e.code))),void this.close(!0);t()}else i(new SE(fE.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),OE.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();qI(this,US.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;OE.debug("[choose dc] dc open cost ".concat(u,"ms"));this._reliableTransmission=new Iv(e=>{var t;this._transmitter&&"open"===this._transmitter.readyState&&(null===(t=this._transmitter)||void 0===t||t.send(e))},e=>
vendor: 4,147 bytes, line 5
5{"string"==typeof e&&this.emit(US.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 SE&&e.code===fE.WS_ABORT?"aborted":"error",errors:[e]},a),"closed"!==this.state){if(e instanceof SE&&e.code===fE.WS_ERR){const t=new SE(fE.WS_ERR,"init datachannel failed! Error: ".concat(e.toString()));return OE.error("[".concat(this._name,"]").concat(t)),void i(t)}o&&o(e)}else i(new SE(fE.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||pg.networkState!==bS.OFFLINE||(this._onlineReconnectListener=pg.onlineWaiter&&pg.onlineWaiter.then(()=>{this._onlineReconnectListener=void 0}));let i=!0;if(this._reconnectInterrupter=()=>{i=!1},t){const t=gE(this._reconnectCount,this._retryConfig);OE.debug("[".concat(this._name,"] wait ").concat(t,"ms to reconnect datachannel, mode: ").concat(e)),await Sl.race([jI(t),this._onlineReconnectListener||new Sl(()=>{})])}if("closed"===this.state||!i)return!1;this._reconnectCount+=1;const n=async(e,t)=>{this.emit(US.RECONNECT_CREATE_CONNECTION,t),await this.createTransmitterConnection(e)};try{if("retry"===e){const t=this._addresses[this.currentURLIndex];this.emit(US.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||GE("FINGERPRINT")){this.currentURLIndex=e;break}this.currentURLIndex+=1}if(this.currentURLIndex>=this._addresses.length)return OE.debug("[".concat(this._name,"] the available addresses are exhausted, change to recover")),await this.reconnectWithAction("recover",!1);OE.debug("[".concat(this._name,"] datachannel url length: ").concat(this._addresses.length," current index: ").concat(this.currentURLIndex));const t=this._addresses[this.currentURLIndex];this.emit(US.RECONNECT_WAITTING_FINISH,e),await n(t,e)}else"recover"===e&&(OE.debug("[".concat(this._name,"] start to failback to websocket")),this.resetReconnectCount("recover mode"),this.emit(US.RECONNECT_WAITTING_FINISH,e),this.emit(US.FAILBACK));return!0}catch(i){var r;return OE.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(US.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):await this.reconnectWithAction(e,t)}}}class Cv extends EE{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===Of.CONNECTED?this.emit(bf.WS_CONNECTED):e===Of.RECONNECTING?this.emit(bf.WS_RECONNECTING,this._websocketReconnectReason):e===Of.CLOSED&&this.emit(bf.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(),_p(this,"_disconnectedReason",void 0),_p(this,"_websocketReconnectReason",void 0),_p(this,"_connectionState",Of.CLOSED),_p(this,"reconnectToken",void 0),_p(this,"websocket",void 0),_p(this,"openConnectionTime",void 0),_p(this,"clientId",void 0),_p(this,"lastMsgTime",Date.now()),_p(this,"uploadCache",[]),_p(this,"uploadCacheInterval",void 0),_p(this,"rttRolling",new Ev(5)),_p(this,"pingpongTimer",void 0),_p(this,"inflateDataTimer",void 0),_p(this,"pingpongTimeoutCount",0),_p(this,"joinResponse",void 0),_p(this,"multiIpOption",void 0),_p(this,"initError",void 0),_p(this,"spec",void 0),_p(this,"store",void 0),_p(this,"onWebsocketMessage",e=>
5{if(e instanceof ArrayBuffer)return void this.emit(bf.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===Df.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===Df.ON_USER_BANNED))switch(t._message.error_code){case 14:this.close(Cf.UID_BANNED);break;case 15:this.close(Cf.IP_BANNED);break;case 16:this.close(Cf.CHANNEL_BANNED)}}),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new vv("gateway-".concat(this.clientId),this.spec.retryConfig,!0,t),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===Of.CONNECTED&&this.reconnect("retry",MS.OFFLINE)})}async request(e,t,i,n){const r=GI(6,""),o={_id:r,_type:e,_message:t},s=this.websocket.connectionID,a=()=>new Sl((t,i)=>{if(this.connectionState===Of.CONNECTED)return t();const n=()=>{this.off(bf.WS_CLOSED,r),t()},r=()=>{this.off(bf.WS_CONNECTED,n),i(new SE(fE.WS_ABORT))};this.once(bf.WS_CONNECTED,n),this.once(bf.WS_CLOSED,r),e!==wf.PUBLISH&&e!==wf.SUBSCRIBE&&e!==wf.UNSUBSCRIBE&&e!==wf.UNPUBLISH&&e!==wf.CONTROL&&e!==wf.RESTART_ICE||this.once(bf.DISCONNECT_P2P,()=>{i(new SE(fE.DISCONNECT_P2P))}),e!==wf.PUBLISH&&e!==wf.RESTART_ICE||this.once(bf.ABORT_P2P_EXECUTION,()=>{i(new SE(fE.DISCONNECT_P2P))})});if(this.connectionState!==Of.CONNECTING&&this.connectionState!==Of.RECONNECTING||e===wf.JOIN||e===wf.REJOIN||await a(),e===wf.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(bf.WS_CLOSED,c),this.off(bf.WS_RECONNECTING,c),this.emit(bf.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{n(new SE(fE.WS_ABORT,"type: ".concat(e))),this.off(bf.WS_CLOSED,c),this.off(bf.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(bf.WS_CLOSED,c),this.once(bf.WS_RECONNECTING,c),jI(GE("SIGNAL_REQUEST_TIMEOUT")).then(()=>{this.websocket.connectionID!==s||o||(OE.warning("dc request timeout, type: ".concat(e)),this.emit(bf.REQUEST_TIMEOUT,e,t))})});let d=null;try{d=await c}catch(n){if(this.connectionState===Of.CLOSED||e===wf.LEAVE)throw new SE(fE.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?n.throw():e===wf.JOIN||e===wf.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=hv(u),h=new SE(fE.UNEXPECTED_RESPONSE,"".concat(l.desc,": ").concat(d.message.error_str),{code:u,data:d.message});return"success"===l.action?d.message:(OE.warning("[".concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(u,", message: ").concat(l.desc,", action: ").concat(l.action)),u===If.ERR_TOO_MANY_BROADCASTERS?e===wf.JOIN||e===wf.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===If.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,OE.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",MS.MULTI_IP)):this.reconnect(l.action,MS.SERVER_ERROR),e===wf.JOIN||e===wf.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=GE("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!==Of.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)},GE("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(bf.WS_CONNECTED,()=>i(this.joinResponse)),this.once(bf.WS_CLOSED,()=>n(this.initError||new SE(fE.WS_ABORT))),this.connectionState=Of.CONNECTING,this.websocket.init(e).catch(n),this.websocket.once(US.FAILBACK,()=>{void 0===this.openConnectionTime&&n(new SE(fE.INIT_DATACHANNEL_TIMEOUT))}),this.inflateDataTimer&&window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=window.setInterval(()=>{this.handleInflateData()},2e4),setTimeout(()=>{t&&void 0===this.openConnectionTime&&(OE.debug("[".concat(this.clientId,"] init datachannel timeout while join with failback to websocket")),n(new SE(fE.INIT_DATACHANNEL_TIMEOUT)))},GE("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||Cf.LEAVE,this.connectionState=Of.CLOSED,OE.debug("[".concat(this.clientId,"] ")+"will close datachannel in signal"),this.websocket.close(),e===Cf.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new vv("gateway-".concat(this.clientId),this.spec.retryConfig,!0,this.store),this.handleWebsocketEvents())}
5async join(){if(!this.joinResponse){this.emit(bf.ABORT_P2P_EXECUTION);const e=await qI(this,bf.DATACHANNEL_CONNECTING),t=await this.request(wf.JOIN,e);if(!t)return this.emit(bf.REPORT_JOIN_GATEWAY,fE.TIMEOUT,this.url||""),!1;this.joinResponse=t,this.emit(bf.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=Of.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new SE(fE.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=zI(this,bf.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(wf.REJOIN,e);return!!t&&(this.connectionState=Of.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach(e=>{this.emit(Df.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(Df.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(Df.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(Df.MUTE_AUDIO,{uid:e.uid}):this.emit(Df.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(Df.MUTE_VIDEO,{uid:e.uid}):this.emit(Df.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(Df.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(Df.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(Df.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(Df.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(Df.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){OE.debug("[".concat(this.clientId,"] receive notification: "),e);const t=hv(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close(Cf.UID_BANNED),void this.close()):void this.reconnect(t.action,MS.SERVER_ERROR);OE.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=GE("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(OE.warning("PINGPONG Timeout. Last Socket Message: ".concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>GE("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",MS.TIMEOUT):this.request(wf.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),GE("REPORT_STATS")&&this.send(wf.PING_BACK,{pingpongElapse:e})}).catch(e=>{})}handleInflateData(){const{inflateLength:e,deflateLength:t}=this.websocket.getInflateData();0!==e&&0!==t&&this.upload(Nf.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:t,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(US.RECONNECT_WAITTING_FINISH,e=>{this.emit(bf.WS_RECONNECT_WAITTING_FINISH,e)}),this.websocket.on(US.RECONNECT_CREATE_CONNECTION,e=>{this.emit(bf.WS_RECONNECT_CREATE_CONNECTION,e)}),this.websocket.on(US.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(US.CLOSED,()=>{this.connectionState=Of.CLOSED}),this.websocket.on(US.FAILED,()=>{this._disconnectedReason=Cf.NETWORK_ERROR,this.connectionState=Of.CLOSED}),this.websocket.on(US.RECONNECTING,e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===Of.CONNECTED?this.connectionState=Of.RECONNECTING:this.connectionState=Of.CONNECTING}),this.websocket.on(US.WILL_RECONNECT,(e,t)=>{if(zI(this,bf.IS_P2P_DISCONNECTED)&&"retry"===e)return OE.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit(bf.NEED_RENEW_SESSION),this.emit(bf.DISCONNECT_P2P),t("tryNext");"retry"!==e&&(OE.debug("".concat(this.clientId," websockt will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0,this.emit
5(bf.NEED_RENEW_SESSION),this.emit(bf.DISCONNECT_P2P)),t(e)}),this.websocket.on(US.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch(e=>{OE.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",MS.SERVER_ERROR)}):this.join().catch(e=>{if(this.emit(bf.REPORT_JOIN_GATEWAY,e.message||e.code,this.url||""),e instanceof SE&&e.code===fE.UNEXPECTED_RESPONSE&&e.data.code===If.ERR_NO_AUTHORIZED)return OE.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",MS.SERVER_ERROR);OE.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",MS.SERVER_ERROR):(this.initError=e,this.close())})}),this.websocket.on(US.REQUEST_NEW_URLS,(e,t)=>{qI(this,bf.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)}),this.websocket.on(US.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(Df.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}),this.websocket.on(US.TO_CONNECT_DATACHANNEL,async(e,t,i)=>qI(this,bf.DATACHANNEL_PRECONNECT,e).then(t).catch(i)),this.websocket.on(US.FAILBACK,()=>{void 0!==this.openConnectionTime&&this.emit(bf.DATACHANNEL_FAILBACK)})}}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){_p(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}const Ov=new Map;class bv extends EE{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(aS.CONNECTION_STATE_CHANGE,e,t,this._disconnectedReason):this.emit(aS.CONNECTION_STATE_CHANGE,e,t)}get joinGatewayStartTime(){return this._joinGatewayStartTime}set joinGatewayStartTime(e){OE.debug("[".concat(this.store.clientId,"] set joinGatewayStartTime at ").concat(e)),this._joinGatewayStartTime=e}constructor(e,t){super(),_p(this,"store",void 0),_p(this,"joinInfo",void 0),_p(this,"key",void 0),_p(this,"signal",void 0),_p(this,"role",void 0),_p(this,"inChannelInfo",{joinAt:null,duration:0}),_p(this,"spec",void 0),_p(this,"_state","DISCONNECTED"),_p(this,"_statsCollector",void 0),_p(this,"_disconnectedReason",void 0),_p(this,"isSignalRecover",!1),_p(this,"hasChangeBGPAddress",!1),_p(this,"trafficStatsInterval",void 0),_p(this,"networkQualityInterval",void 0),_p(this,"_joinGatewayStartTime",0),_p(this,"_signalTimeout",!1),_p(this,"_clientRoleOptions",void 0),_p(this,"_isProactiveJoin",!1),this.store=e,this.spec=t,this.signal=this.store.useDataChannel?new Cv(Av(Av({},t),{},{retryConfig:t.websocketRetryConfig}),e):new mv(Av(Av({},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 Cv){let t=!1;"disabled"!==e.cloudProxyServer?(OE.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?(OE.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)||GE("FINGERPRINT")||(OE.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=Ov.get(e.cname);if(r||(r=new Map,Ov.set(e.cname,r)),this._isProactiveJoin=!0,r.has(e.uid)){const t=new SE(fE.UID_CONFLICT);throw vg.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 Cv?"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(OE.debug("[".concat(this.store.clientId,"] use ").concat(this.signal instanceof Cv?"datachannel":"websocket"," join uid ").concat(o)),this.signal instanceof Cv)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,OE.debug("[".concat(this.store.clientId,"] ").concat(this.signal instanceof Cv?"datachannel":"websocket"," join uid ").concat(o," cost ").concat(Date.now()-this.joinGatewayStartTime))}catch(t){if(t&&t.code===fE.INIT_WEBSOCKET_TIMEOUT)throw OE.warning("[".concat(this.store.clientId,"] User join failed"),t.toString()),t;if(t&&t.code===fE.INIT_DATACHANNEL_TIMEOUT)throw OE.warning("[".concat(this.store.clientId,"] User join datachannel failed"),t.toString()),this.resetSignal(),t;throw OE.error("[".concat(this.store.clientId,"] User join failed"),t.toString()),vg.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 Cv?"1":"0"}),this._isProactiveJoin=!1,r.delete(e.uid),this.signal.close(),t}return this.state="CONNECTED",this.inChannelInfo.joinAt=Date.now(),OE.debug("[".concat(this.store.clientId,"] Connected to gateway server")),this.trafficStatsInterval=window.setInterval(()=>{this.updateTrafficStats().catch(e=>{OE.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
vendor: 5,327 bytes, line 5
5(aS.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6}):this._signalTimeout?this.emit(aS.NETWORK_QUALITY,{downlinkNetworkQuality:5,uplinkNetworkQuality:5}):"CONNECTED"===this.state&&this._statsCollector.trafficStats?this.emit(aS.NETWORK_QUALITY,{uplinkNetworkQuality:PI(this._statsCollector.trafficStats.B_unq),downlinkNetworkQuality:PI(this._statsCollector.trafficStats.B_dnq)}):this.emit(aS.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!==Cf.FALLBACK&&(this.state="DISCONNECTING");try{e||this.signal.connectionState!==Of.CONNECTED||await function(e,t){return t===1/0?e:Sl.race([e,BI(t)])}(this.signal.request(wf.LEAVE,void 0,!0),3e3)}catch(e){OE.warning("[".concat(this.store.clientId,"] leave request failed, ignore"),e)}this.signal.close(t),t!==Cf.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}}async publish(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new SE(fE.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:GE("PUB_EXTEND"),twcc:!!GE("PUBLISH_TWCC")};try{return(await this.signal.request(wf.PUBLISH,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===If.ERR_PUBLISH_REQUEST_INVALID)return OE.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 SE(fE.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await this.signal.request(wf.UNPUBLISH,{stream_id:t,ortc:e},!0)}catch(e){OE.warning("unpublish warning: ",e)}}async subscribe(e,t,i){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new SE(fE.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:!!GE("SUBSCRIBE_TWCC"),extend:GE("SUB_EXTEND"),ssrcId:t.ssrcId};try{return(await this.signal.request(wf.SUBSCRIBE,n,!0))._message}catch(n){if(i&&n.data&&n.data.code===If.ERR_SUBSCRIBE_REQUEST_INVALID)return OE.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 SE(fE.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(wf.SUBSCRIBE_STREAMS,i,!0)}catch(i){if(t&&i.data&&i.data.code===If.ERR_SUBSCRIBE_REQUEST_INVALID)return OE.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(wf.SET_VIDEO_PROFILE,t);OE.debug("[".concat(this.store.clientId,"] encoder config is not complete, do not report to gateway"))}async unsubscribe(e,t){try{await this.signal.request(wf.UNSUBSCRIBE,{p2p_id:this.store.p2pId,ortc:e,stream_id:t},!0)}catch(e){OE.warning("unsubscribe warning: ",e)}}async massUnsubscribe(e){try{await this.signal.request(wf.UNSUBSCRIBE_STREAMS,e,!0)}catch(e){OE.warning("unsubscribeAll warning: ",e)}}async reconnectPC(e){const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=e;return{gatewayEstablishParams:await this.signal.request(wf.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(wf.GATEWAY_INFO)}renewToken(e){return this.signal.request(wf.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(wf.SET_CLIENT_ROLE,{role:e,level:i,client_ts:Date.now()}),this.role=e}async setRemoteVideoStreamType(e,t){await this.signal.request(wf.SWITCH_VIDEO_STREAM,{stream_id:e,stream_type:t})}async setDefaultRemoteVideoStreamType(e){await this.signal.request(wf.DEFAULT_VIDEO_STREAM,{stream_type:e})}async setStreamFallbackOption(e,t){await this.signal.request(wf.SET_FALLBACK_OPTION,{stream_id:e,fallback_type:t})}async pickSVCLayer(e,t){await this.signal.request(wf.PICK_SVC_LAYER,{stream_id:e,spatial_layer:t.spatialL
5ayer,temporal_layer:t.temporalLayer})}getInChannelInfo(){return this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt),Av({},this.inChannelInfo)}async getGatewayVersion(){return(await this.signal.request(wf.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=Ov.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:PE.username,password:PE.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(Av(Av({},PE),{},{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(wf.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&&$I(()=>{this.emit(aS.STREAM_TYPE_CHANGE,e.peer_uid,e.B_st)})}),this._statsCollector.updateTrafficStats(e)}getJoinMessage(e){if(!this.joinInfo||!this.key)throw new SE(fE.UNEXPECTED_ERROR,"can not generate join message, no join info");const t=Object.assign({},this.joinInfo.apResponse);let i=GE("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=Av({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:wE,browser:navigator.userAgent,process_id:GE("PROCESS_ID"),mode:this.spec.mode,codec:this.spec.codec,role:this.role,has_changed_gateway:this.hasChangeBGPAddress,ap_response:t,extend:GE("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:GE("ENABLE_PUBLISHED_USER_LIST"),maxSubscription:GE("MAX_SUBSCRIPTION"),subscribeAudioFilterTopN:"number"==typeof GE("SUBSCRIBE_AUDIO_FILTER_TOPN")?GE("SUBSCRIBE_AUDIO_FILTER_TOPN"):void 0,enablePublishAudioFilter:"boolean"==typeof GE("ENABLE_PUBLISH_AUDIO_FILTER")?GE("ENABLE_PUBLISH_AUDIO_FILTER"):void 0,enableUserLicenseCheck:"boolean"==typeof GE("ENABLE_USER_LICENSE_CHECK")?GE("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,GE("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 SE(fE.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(bf.WS_RECONNECT_WAITTING_FINISH,e=>{["tryNext","recover"].includes(e)&&this.joinInfo&&vg.adjustSessionStartTime(this.joinInfo.sid)}),this.signal.on(bf.WS_RECONNECT_CREATE_CONNECTION,e=>{this.joinGatewayStartTime=Date.now()}),this.signal.on(bf.WS_RECONNECTING,e=>{this.joinInfo&&vg.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:e||Af.NETWORK_E
5RROR}),this.joinInfo&&(this.state="RECONNECTING",vg.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(bf.WS_CLOSED,e=>{let t;switch(e){case Cf.LEAVE:t=Af.LEAVE;break;case Cf.UID_BANNED:case Cf.IP_BANNED:case Cf.CHANNEL_BANNED:case Cf.SERVER_ERROR:t=Af.SERVER_ERROR;break;case Cf.FALLBACK:t=Af.FALLBACK;break;case Cf.LICENSE_MISSING:case Cf.LICENSE_EXPIRED:case Cf.LICENSE_MINUTES_EXCEEDED:case Cf.LICENSE_PERIOD_INVALID:case Cf.LICENSE_MULTIPLE_SDK_SERVICE:case Cf.LICENSE_ILLEGAL:t=e;break;default:t=Af.NETWORK_ERROR}OE.debug("[signal] websocket closed, reason: ".concat(t||"undefined -> "+Af.NETWORK_ERROR)),this.joinInfo&&vg.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:e===Cf.LEAVE?1:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:t}),this._disconnectedReason=e,e!==Cf.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}),this.signal.on(bf.WS_CONNECTED,()=>{if(this.updateTurnConfigFromSignal(),this.state="CONNECTED",this.joinInfo&&("audience"===this.role&&this._clientRoleOptions&&this._clientRoleOptions.level&&(OE.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)),vg.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 Cv?"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 OE.error("[".concat(this.store.clientId,"] set local access point after joined failed: ").concat(e));BE("EVENT_REPORT_DOMAIN",e[1]),BE("EVENT_REPORT_BACKUP_DOMAIN",e[1]),BE("LOG_UPLOAD_SERVER","".concat(e[1],":6444"))}}),this.signal.on(Df.ON_UPLINK_STATS,e=>{this._statsCollector.updateUplinkStats(e)}),this.signal.on(bf.REQUEST_RECOVER,(e,t,i)=>{if(!this.joinInfo)return i(new SE(fE.UNEXPECTED_ERROR,"gateway: can not recover, no join info"));e&&(this.joinInfo.multiIP=e,this.hasChangeBGPAddress=!0),this.isSignalRecover=!0,qI(this,aS.REQUEST_NEW_GATEWAY_LIST).then(t).catch(i)}),this.signal.on(bf.REQUEST_JOIN_INFO,async e=>{var t;this.updateTurnConfigFromSignal();const{iceParameters:i,dtlsParameters:n,rtpCapabilities:r}=await qI(this,aS.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(bf.REQUEST_REJOIN_INFO,e=>{e(this.getRejoinMessage())}),this.signal.on(bf.REPORT_JOIN_GATEWAY,(e,t)=>{this.joinInfo&&(vg.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 Cv?"1":"0"}),this._isProactiveJoin=!1)}),this.signal.on(bf.IS_P2P_DISCONNECTED,e=>{e(zI(this,aS.IS_P2P_DISCONNECTED))}),this.signal.on(bf.DISCONNECT_P2P,()=>{this.emit(aS.DISCONNECT_P2P)}),this.signal.on(bf.NEED_RENEW_SESSION,()=>{this.emit(aS.NEED_RENEW_SESSION)}),this.signal.on(bf.REQUEST_SUCCESS,()=>{this._signalTimeout=!1}),this.signal.on(bf.REQUEST_TIMEOUT,()=>{this._signalTimeout=!0}),this.signal.on(bf.JOIN_RESPONSE,e=>{const t=this.getCurrentGatewayAddress();this.emit(aS.JOIN_RESPONSE,e,t)}),this.signal.on(bf.DATACHANNEL_PRECONNECT,async(e,t,i)=>{this.updateTurnConfigFromSignal();const n=this.getCurrentGatewayAddress();
vendor: 14,018 bytes, lines 5-6
5return qI(this,aS.DATACHANNEL_PRECONNECT,e,n).then(t).catch(i)}),this.signal.on(bf.DATACHANNEL_CONNECTING,async e=>{const{iceParameters:t,dtlsParameters:i,rtpCapabilities:n}=await qI(this,aS.REQUEST_DC_CONNECTION_PARAMS);e(this.getJoinMessage({ortc:{iceParameters:t,dtlsParameters:i,rtpCapabilities:n,version:"2"}}))}),this.signal.on(bf.DATACHANNEL_FAILBACK,()=>{OE.warning("[".concat(this.store.clientId,"] User join datachannel failed")),this.reset(),this.resetSignal(),this.emit(aS.DATACHANNEL_FAILBACK)})}async tryUnsubBeforeResub(e,t){try{await this.signal.request(wf.UNSUBSCRIBE,{p2p_id:this.store.p2pId,stream_id:e,ortc:[t]},!0)}catch(e){throw OE.warning("unsubscribe warning",e),e}}async tryUnpubBeforeRepub(e,t){try{await this.signal.request(wf.UNPUBLISH,{stream_id:e,ortc:t},!0)}catch(e){throw OE.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(wf.UNSUBSCRIBE_STREAMS,t,!0)}catch(e){throw OE.warning("massUnsubscribe warning",e),e}}async muteLocal(e,t){const i={action:e.find(e=>e.stream_type===sS.Audio)?"mute_local_audio":"mute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(wf.CONTROL,i,!0,!0)}catch(e){throw OE.warning("gateway unmuteLocal warning: ",e),e}}async unmuteLocal(e,t){const i={action:e.find(e=>e.stream_type===sS.Audio)?"unmute_local_audio":"unmute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(wf.CONTROL,i,!0,!0)}catch(e){throw OE.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(wf.RESTART_ICE,t,!0)}catch(e){throw OE.warning("P2PChannel.restartICE warning: ",e),e}}reconnect(){"CONNECTED"===this.state&&this.signal.reconnect(void 0,Af.P2P_FAILED)}getCurrentGatewayAddress(){var e;if(!GE("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(wf.SET_PARAMETER,{enablePublishAudioFilter:e})}resetSignal(){this.signal&&(this.signal.removeAllListeners(),this.signal.close(Cf.FALLBACK)),this.store.useDataChannel=!1,this.signal=new mv(Av(Av({},this.spec),{},{retryConfig:this.spec.websocketRetryConfig}),this.store),this.handleSignalEvents(),this.emit(aS.RESET_SIGNAL,dS.websocket)}} 6/*! 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 wv=()=>{const e=GE("AREAS");0===e.length&&e.push(mS.GLOBAL);return zi(e).call(e,(e,t,i)=>{const n=Nv(t);return n?0===i?n:"".concat(e,",").concat(n):e},"")},Nv=e=>e===mS.OVERSEA?"".concat(gS.ASIA,",").concat(gS.EUROPE,",").concat(gS.AFRICA,",").concat(gS.NORTH_AMERICA,",").concat(gS.SOUTH_AMERICA,",").concat(gS.OCEANIA):gS[e],Dv=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=RS[e],n=Object.keys(i);n&&n.map(e=>{"CODE"!==e&&(t[e]=t[e].concat(i[e]))})}),t},Pv={GLOBAL:{ASIA:[mS.CHINA,mS.JAPAN,mS.INDIA,mS.KOREA,mS.HKMC],EUROPE:[],NORTH_AMERICA:[mS.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}},Lv=Object.keys(Pv[mS.GLOBAL]),kv=[mS.CHINA,mS.NORTH_AMERICA,mS.EUROPE,mS.ASIA,mS.JAPAN,mS.INDIA,mS.OCEANIA,mS.SOUTH_AMERICA,mS.AFRICA,mS.KOREA,mS.HKMC,mS.US],Mv=function(e,t){let i=[];if(e.includes(mS.GLOBAL)){const o=[mS.GLOBAL,mS.OVERSEA],s=Object.keys(RS);if(t===mS.GLOBAL)throw new SE(fE.INVALID_PARAMS,"GLOBAL is an invalid excludedArea value");if(t===mS.CHINA)i=[mS.OVERSEA];else if(r=t,Lv.includes(r)){const e=(n=t,Pv[mS.GLOBAL][n]||[]),r=[...o,t,...e];i=s.filter(e=>!r.includes(e))}else if(function(e){let t=!1;return Lv.forEach(i=>{Pv[mS.GLOBAL][i].includes(e)&&(t=!0)}),t}(t)){const e=function(e){let t;return Lv.forEach(i=>{Pv[mS.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 kv.forEach(i=>{e.includes(i)&&t.push(i)}),t.concat(e.filter(e=>!kv.includes(e)))}(i)}else i=e;var n,r;return i};function Uv(e){if(!e&&GE("AREAS").includes(mS.EXTENSIONS))return OE.debug("update area from ap : reset"),void xv(DE,!0);if(!GE("AREAS").includes(mS.GLOBAL)||!e)return;let t=RS.EXTENSIONS;t&&(t={CODE:Nv(mS.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")]},OE.debug("update area from ap success: ".concat(e,",config is "),t),BE("AREAS",[mS.EXTENSIONS],!0),Ob
6ject.keys(t).map(e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){BE(e,t[e][0])}else BE(e,t[e])}))}function xv(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=vg.reportApiInvoke(null,{name:_f.SET_AREA,options:e,tag:Ef.TRACER});try{let n=[];if("string"==typeof e&&(n=[e]),Array.isArray(e)&&(e.forEach(e=>{if(!TS.includes(e))throw new SE(fE.INVALID_PARAMS,"invalid area code")}),n=e),"[object Object]"===Object.prototype.toString.call(e)){const{areaCode:t,excludedArea:i}=e;if(!t)throw new SE(fE.INVALID_PARAMS,"area code is needed");let r=t;"string"==typeof t&&(r=[t]),n=i?Mv(r,i):r}if(!t){if(HE.AREAS){const e=new SE(fE.PROHIBITED_OPERATION,"setArea is prohibited because of config-distribute");return i.onError(e),void OE.warning("setArea is prohibited because of config-distribute")}if(n.includes(mS.GLOBAL)&&GE("AREAS")===mS.EXTENSIONS){const e=new SE(fE.PROHIBITED_OPERATION,"setArea is prohibited because of ap extensions");return i.onError(e),void OE.warning("setArea is prohibited because of ap extensions")}}BE("AREAS",n,t);const r=Dv(n);Object.keys(r).map(e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){BE(e,r[e][0])}else BE(e,r[e])}),OE.debug("set area success:",n.join(","))}catch(e){throw i.onError(e),e}i.onSuccess()}function Vv(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 Fv(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Vv(Object(i),!0).forEach((function(t){_p(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Vv(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let jv=1;function Bv(e,t,i,n,r){jv+=1;const o={sid:i.sid,command:"convergeAllocateEdge",uid:"666",appId:i.appId,ts:Math.floor(Date.now()/1e3),seq:jv,requestId:jv,version:wE,cname:i.cname},s={service_name:t,json_body:JSON.stringify(o)};let a,c,d=e[0];return RE(async()=>{a=Date.now();const e=await lg(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 SE(fE.UNEXPECTED_RESPONSE,"live streaming ap error, code"+e.code,{retry:!0,responseTime:c});throw OE.error(t.toString()),t}const i=JSON.parse(e.json_body);if(200!==i.code){const e=new SE(fE.UNEXPECTED_RESPONSE,"live streaming app center error, code: ".concat(i.code,", reason: ").concat(i.reason),{code:i.code,responseTime:c});throw OE.error(e.toString()),e}if(!i.servers||0===i.servers.length){const e=new SE(fE.UNEXPECTED_RESPONSE,"live streaming app center empty server",{code:i.code,responseTime:c});throw OE.error(e.toString()),e}const r=function(e,t){return{addressList:e.servers.map(e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(GE("WORKER_DOMAIN"),":").concat(e.wss,"?serviceName=").concat(encodeURIComponent(t))),workerToken:e.workerToken,vid:e.vid}}(i,t);return GE("LIVE_STREAMING_ADDRESS")&&(r.addressList=GE("LIVE_STREAMING_ADDRESS")instanceof Array?GE("LIVE_STREAMING_ADDRESS"):[GE("LIVE_STREAMING_ADDRESS")]),Fv(Fv({},r),{},{responseTime:c})},(n,r)=>(vg.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)=>(vg.apworkerEvent(i.sid,{success:!1,sc:n.data&&n.data.code||200,serviceName:t,responseTime:c,serverIp:e[r%e.length]}),!!(n.code!==fE.OPERATION_ABORTED&&n.code!==fE.UNEXPECTED_RESPONSE||n.data&&n.data.retry)&&(d=e[(r+1)%e.length],!0)),r)}let Gv=1;function Wv(e,t,i,n){let{url:r,areaCode:o}=e;const s=Date.now();let a;const[c,d]=Jv(t,o,[jS.CHOOSE_SERVER]);let u=pg.networkState;return RE(async()=>{u&&pg.networkState===bS.OFFLINE&&pg.onlineWaiter&&await Sl.race([pg.onlineWaiter,jI(n&&n.maxRetryTimeout||TE.maxRetryTimeout)]),u=pg.networkState;const{data:e,headers:o}=await lg(r,{data:c,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);a="1"===o.http3?1:-1,vg.reportResourceTiming(r,t.sid),Kv(e,r,t,s,[jS.CHOOSE_SERVER],a);const d=LI(e,jS.CHOOSE_SERVER);return Yv(d),bI(d,r)},e=>(e&&vg.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:[jS.CHOOSE_SERVER].toString(),isHttp3:a}),!1),e=>e.code!==fE.OPERATION_ABORTED&&(e.code===fE.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(vg.joinChooseServer(t.sid,{lts:s,succ:!1,csAddr:r,serverList:null,opid:d,ec:e.code,csIp:e.data&&e.data.csIp,unilbsServerIds:[jS.CHOOSE_SERVER].toString(),extend:JSON.stringify({networkState:u}),isHttp3:a}),OE.warning("[".concat(t.clientId,"] Choose server network error, retry"),e),!0)),n)}function Hv(e,t,i,n){let r,{url:o,areaCode:s,serviceIds:a}=e;const c=Date.now(),[d,u]=Jv(t,s,a);let l=void 0;return RE(async()=>{l&&pg.networkState===bS.OFFLINE&&pg.onlineWaiter&&await Sl.race([pg.onlineWaiter,jI(n&&n.maxRetryTimeout||TE.maxRetryTimeout)]),l=pg.networkState;const{data:e,headers:s}=await lg(o,{data:d,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);r="1"===s.http3?1:-1,vg.reportResourceTiming(o,t.sid),Kv(e,o,t,c,a,r);const u=LI(e,jS.CHOOSE_SERVER),h=LI(e,"proxy5"===t.cloudProxyServer?jS.CLOUD_PROXY_5:"proxy3"===t.cloudProxyServer||"proxy4"===t.cloudProxyServer?jS.CLOUD_PROXY:jS.CLOUD_PROXY_FALLBACK);return Yv(u),{gatewayInfo:bI(u,o),proxyInfo:h,url:o}},e=>(e.gatewayInfo&&vg.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&&vg.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!==fE.OPERATION_ABORTED&&(e.code===fE.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(vg.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})}),OE.warning("[".concat(t.clientId,"] multi unilbs network error, retry"),e),!0)),n)}const Kv=(e,t,i,n,r,o)=>{const s=[],a=s=>{4096===s.flag?vg.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}
6):1048576!==s.flag&&4194304!==s.flag&&4194310!==s.flag||vg.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)OE.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 SE(fE.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=uv(i),r={error:new SE(fE.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?OE.warning(r.error.toString()):s.push(r),a(r)}}),s.length)throw OE.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 SE(fE.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))]})},Yv=e=>{var t,i,n,r;if(e.addresses&&0===e.addresses.length&&0===e.code)throw new SE(fE.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])?Uv(e.detail[23].toLowerCase()):Uv(),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(GE("GATEWAY_ADDRESS")&&GE("GATEWAY_ADDRESS").length>0){OE.debug("assign gateway address to",GE("GATEWAY_ADDRESS"));const t=GE("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}},qv=(e,t)=>{if(e.response_body&&e.response_body.length){const t=e.response_body[0];if(0!==t.buffer.code){const e=uv(t.buffer.code);throw new SE(fE.UPDATE_TICKET_FAILED,"[".concat(t.buffer.code,"]: ").concat(e.desc),{retry:e.retry})}return t.buffer.ticket}throw OE.debug("update ticket request received ap response without response body:",t),new SE(fE.UPDATE_TICKET_FAILED,"cannot find response body from ap response",{retry:!1})},Jv=(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:GE("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]},Xv=(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 zv=0;async function Qv(e,t,i,n){const r=async function(e,t,i,n){let r=null;const o=[],s=async()=>{const r=GE("WEBCS_DOMAIN").slice(0,GE("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:wv()})),s=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map(e=>e.url)}),a=await av({fragementLength:GE("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(OE.debug("[".concat(e.clientId,"] Connect to choose_server:"),n.url),Wv(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()=>
6{if(await jI(1e3),null!==r)return r;const s=GE("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:wv()})),a=n.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:s.map(e=>e.url)}),c=await av({fragementLength:GE("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:n=>(OE.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),n.url),Wv(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 YI([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 Zv(e,t,i,n,r){const o=e.cloudProxyServer;if("disabled"===o){if(!n)return;if(e.useLocalAccessPoint)return await Qv(e,t,i,r);if(GE("JOIN_WITH_FALLBACK_MEDIA_PROXY")){const{gatewayInfo:n,proxyInfo:o}=await tC(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||PE.tcpport,udpport:e.udpport||PE.udpport,username:e.username||PE.username,password:e.password||PE.password,forceturn:!1,security:!0}))}),{gatewayInfo:n}}return await Qv(e,t,i,r)}const{proxyInfo:s,gatewayInfo:a}=await tC(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:PE.tcpport,udpport:"proxy4"===o?void 0:e.udpport?e.udpport:PE.udpport,username:e.username||PE.username,password:e.password||PE.password,forceturn:"proxy4"!==o,security:"proxy5"===o}))},OE.debug("[".concat(e.clientId,"] set proxy server: ").concat(e.proxyServer,", mode: ").concat(o)),c}async function $v(e,t,i,n,r){const o=GE("ACCOUNT_REGISTER").slice(0,GE("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 RE(()=>lg(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 OE.error("Invalid Uint Uid ".concat(t," => ").concat(i.uid),i),vg.reqUserAccount(s.sid,{lts:o,success:!1,serverAddr:a,stringUid:s.string_uid,uid:i.uid,errorCode:fE.INVALID_UINT_UID_FROM_STRING_UID,extend:s}),new SE(fE.INVALID_UINT_UID_FROM_STRING_UID);return vg.reqUserAccount(s.sid,{lts:o,success:!0,serverAddr:a,stringUid:s.string_uid,uid:i.uid,errorCode:null,extend:s}),!1}const r=uv(i.code);return r.retry&&(a=e[(n+1)%e.length]),vg.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!==fE.OPERATION_ABORTED&&(vg.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=uv(c.code);throw new SE(fE.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 eC(e,t,i){const n=GE("CDS_AP").slice(0,GE("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:wE,cname:t.cname,sid:t.sid,session_id:t.sid,detail:"",proxyServer:t.proxyServer}};return RE(()=>lg(e,{data:o,timeout:1e3,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":54}}),void 0,e=>e.code!==fE.OPERATION_ABORTED,n)}(n,e,t,i));let r=null,o=null,s={};try{r=await YI(n)}catch(e){if(e.code===fE.OPERATION_ABORTED)throw e;o=e}
6n.forEach(e=>e.cancel());if(vg.reportApiInvoke(e.sid,{name:_f.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 tC(e,t,i,n){const r=GE("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=GE("WEBCS_DOMAIN").slice(0,GE("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:wv(),serviceIds:[jS.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?jS.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?jS.CLOUD_PROXY:jS.CLOUD_PROXY_FALLBACK]}}),s=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map(e=>e.url)}),c=await av({fragementLength:GE("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(OE.debug("[".concat(e.clientId,"] Connect to choose_server:"),n.url),Hv(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 jI(1e3),null!==s)return s;const r=GE("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:wv(),serviceIds:[jS.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?jS.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?jS.CLOUD_PROXY:jS.CLOUD_PROXY_FALLBACK]}}),c=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map(e=>e.url)}),d=await av({fragementLength:GE("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:n=>(OE.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),n.url),Hv(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 YI([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 SE(fE.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,OE.setProxyServer(t),vg.setProxyServer(t))}return s={gatewayInfo:u,proxyInfo:await kI(l,u.uid)},s}async function iC(e,t,i,n){const r=GE("UAP_AP").slice(0,GE("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 nC(e,t,i){const n=GE("UAP_AP").slice(0,GE("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:wE,cname:t.cname,uid:t.uid.toString(),requestId:Gv,seq:Gv};Gv+=1;const o={service_name:"tele_channel",json_body:JSON.stringify(r)};return RE(async()=>{const t=await lg(e,{data:o,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":61}});if(0!==t.code){const e=new SE(fE.UNEXPECTED_RESPONSE,"cross channel ap error, code"+t.code,{retry:!0});throw OE.error(e.toString()),e}const n=JSON.parse(t.json_body);if(200!==n.code){const e=new SE(fE.UNEXPECTED_RESPONSE,"cross channel app center error, code: ".concat(n.code,", reason: ").concat(n.reason));throw OE.error(e.toString()),e}if(!n.servers||0===n.servers.length){const e=new SE(fE.UNEXPECTED_RESPONSE,"cross channel app center empty server");throw OE.error(e.toString()),e}return{vid:n.vid,workerToken:n.workerToken,addressList:(GE("CHANNEL_MEDIA_RELAY_SERVERS")||n.servers).map(e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(GE("WORKER_DOMAIN"),":").concat(e.wss))}},void 0,e=>!!(e.code!==fE.OPERATION_ABORTED&&e.code!==fE.UNEXPECTED_RESPONSE||e.data&&e.data.retry),n)}(n,e,t,i));try{const e=await YI(n);
6return n.forEach(e=>e.cancel()),e}catch(e){throw e[0]}}async function rC(e,t,i){let n=null;const r=[],o=async o=>{const s=GE(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 jI(1e3),null!==n)?n:await av({fragementLength:GE("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:n=>(OE.debug("[".concat(e.clientId,"] update ticket, Connect to ").concat(o?"backup":""," choose_server:"),n),function(e,t,i,n){const[r]=Xv(t,[jS.CHOOSE_SERVER]);let o=pg.networkState;return RE(async()=>{o&&pg.networkState===bS.OFFLINE&&pg.onlineWaiter&&await Sl.race([pg.onlineWaiter,jI(n&&n.maxRetryTimeout||TE.maxRetryTimeout)]),o=pg.networkState;const t=await lg(e,{data:r,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0);return qv(t,e)},()=>!1,e=>e.code!==fE.OPERATION_ABORTED&&(e.code===fE.UPDATE_TICKET_FAILED?e.data.retry:(OE.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 YI([o(!1),o(!0)]),r.length&&r.forEach(e=>e.cancel&&"function"==typeof e.cancel&&e.cancel()),n}catch(e){throw e[0]}}function oC(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 sC(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?oC(Object(i),!0).forEach((function(t){_p(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):oC(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}
vendor: 1,028 bytes, line 6
6class aC extends EE{constructor(){super(),_p(this,"configs",void 0),_p(this,"joinInfo",void 0),_p(this,"cancelToken",void 0),_p(this,"retryConfig",{timeout:3e3,timeoutFactor:1.5,maxRetryCount:1,maxRetryTimeout:1e4}),_p(this,"interval",void 0),_p(this,"mutex",new Og("config-distribute")),_p(this,"mutableParamsRead",!1)}startGetConfigDistribute(e,t){this.joinInfo=e,this.cancelToken=t,this.interval&&this.stopGetConfigDistribute(),GE("ENABLE_CONFIG_DISTRIBUTE")&&(this.updateConfigDistribute(),this.interval=window.setInterval(()=>{this.updateConfigDistribute()},GE("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;vg.reportApiInvoke(null,{options:void 0,name:_f.LOAD_CONFIG_FROM_LOCALSTORAGE,tag:Ef.TRACER}).onSuccess(JSON.str
6ingify(HE))}if(!this.joinInfo||!this.cancelToken||!this.retryConfig)return void OE.debug("[config-distribute] get config distribute interrupted have no joininfo");let e;const t=await this.mutex.lock();try{e=await eC(this.joinInfo,this.cancelToken,this.retryConfig),OE.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 SE(fE.NETWORK_RESPONSE_ERROR,e);OE.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(IS.UPDATE_BITRATE_LIMIT,e):this.emit(IS.UPDATE_BITRATE_LIMIT,e))}getLowStreamConfigDistribute(){return this.configs&&this.configs.limit_bitrate&&sC({},this.configs.limit_bitrate.low_stream_uplink)}cacheGlobalParameterConfig(e){var t;const i=Hm(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;
6Object.keys(i).forEach(e=>{"__priority"===e||"__expires"===e||Object.prototype.hasOwnProperty.call(n,e)||(n[e]=sC({value:i[e]},r&&{expires:r}))})});try{const e=JSON.stringify(n),t=window.btoa(e);window.localStorage.setItem("websdk_ng_global_parameter",t),OE.debug("Caching global parameters ".concat(e))}catch(e){OE.error("Error caching global parameters:",e.message)}}}function cC(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 dC(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?cC(Object(i),!0).forEach((function(t){_p(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):cC(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class uC extends EE{constructor(e,t,i,n){super(),_p(this,"spec",void 0),_p(this,"token",void 0),_p(this,"websocket",void 0),_p(this,"pingpongTimer",void 0),_p(this,"reconnectMode","retry"),_p(this,"serviceMode",void 0),_p(this,"reqId",0),_p(this,"commandReqId",0),_p(this,"handleWebSocketOpen",()=>{this.reconnectMode="retry",this.startPingPong()}),_p(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===Kf.INJECT?this.emit(Zf.INJECT_STREAM_STATUS,t):(vg.workerEvent(this.spec.sid,{actionType:"status",serverCode:t.code,workerType:this.serviceMode===Kf.TRANSCODE?1:2}),this.emit(Zf.PUBLISH_STREAM_STATUS,t))}),this.spec=t,this.token=e,this.serviceMode=n,this.websocket=new _v("live-streaming",i),this.websocket.on(Hf.CONNECTED,this.handleWebSocketOpen),this.websocket.on(Hf.ON_MESSAGE,this.handleWebSocketMessage),this.websocket.on(Hf.REQUEST_NEW_URLS,(e,t)=>{qI(this,Zf.REQUEST_NEW_ADDRESS).then(e).catch(t)}),this.websocket.on(Hf.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 SE(fE.UNEXPECTED_ERROR);const s=dC({command:e,sdkVersion:"4.17.2"===wE?"0.0.1":wE,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 SE(fE.WS_DISCONNECT);const a=()=>new Sl((e,t)=>{this.websocket.once(Hf.CLOSED,()=>t(new SE(fE.WS_ABORT))),this.websocket.once(Hf.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 SE(fE.WS_ABORT))};this.websocket.once(Hf.RECONNECTING,i),this.websocket.once(Hf.CLOSED,i),this.once("@".concat(o,"-").concat(this.spec.sid),t=>{e(t)})});n&&vg.workerEvent(this.spec.sid,dC(dC({},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&&vg.workerEvent(this.spec.sid,dC(dC({},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.2"===wE?"0.0.1":wE;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 eS.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void OE.warning("live stream response already exists stream");case eS.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case eS.LIVE_STREAM_RESPONSE_BAD_STREAM:case eS.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return new SE(fE.LIVE_STREAMING_INVALID_ARGUMENT,"",{code:e.code}).throw();case eS.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if("UnpublishStream"
vendor: 4,609 bytes, line 6
6===e.serverResponse.command||"UninjectStream"===e.serverResponse.command)return;throw new SE(fE.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case eS.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new SE(fE.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:e.code}).throw();case eS.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const t=new SE(fE.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(Zf.WARNING,t,e.serverResponse.url)}case eS.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:{const t=new SE(fE.LIVE_STREAMING_WARN_FREQUENT_REQUEST);return this.emit(Zf.WARNING,t,e.serverResponse.url)}case eS.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new SE(fE.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case eS.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new SE(fE.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:e.code}).throw();case eS.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{const t=new SE(fE.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT);return this.emit(Zf.WARNING,t,e.serverResponse.url)}case eS.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return new SE(fE.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code}).throw();case eS.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new SE(fE.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream resource limit",{retry:!0,changeAddress:!0});case eS.LIVE_STREAM_RESPONSE_WORKER_LOST:case eS.LIVE_STREAM_RESPONSE_WORKER_QUIT:if("UnpublishStream"===e.serverResponse.command||"UninjectStream"===e.serverResponse.command)return;throw new SE(fE.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case eS.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 SE(fE.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:e.code}).throw();throw new SE(fE.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case eS.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case eS.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case eS.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case eS.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return new SE(fE.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(HI)},6e3)}}function lC(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 hC(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?lC(Object(i),!0).forEach((function(t){_p(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):lC(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class pC extends EE{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:TE,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:TE;super(),_p(this,"onLiveStreamWarning",void 0),_p(this,"onLiveStreamError",void 0),_p(this,"onInjectStatusChange",void 0),_p(this,"spec",void 0),_p(this,"retryTimeout",1e4),_p(this,"connection",void 0),_p(this,"httpRetryConfig",void 0),_p(this,"wsRetryConfig",void 0),_p(this,"streamingTasks",new Map),_p(this,"isStartingStreamingTask",!1),_p(this,"taskMutex",new Og("live-streaming")),_p(this,"cancelToken",pE.CancelToken.source()),_p(this,"transcodingConfig",void 0),_p(this,"injectConfig",hC({},Qf)),_p(this,"injectLoopTimes",0),_p(this,"uapResponse",void 0),_p(this,"lastTaskId",1),_p(this,"statusError",new Map),this.spec=e,this.httpRetryConfig=i,this.wsRetryConfig=t}async setTranscodingConfig(e){const t=hC(hC({},zf),e);66!==t.videoCodecProfile&&77!==t.videoCodecProfile&&100!==t.videoCodecProfile&&(OE.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=>hC(hC(hC({},qf),e),{},{zOrder:e.zOrder?e.zOrder+1:1}))),function(e){$m(e.width)||qm(e.width,"config.width",0,1e4),$m(e.height)||qm(e.height,"config.height",0,1e4),$m(e.videoBitrate)||qm(e.videoBitrate,"config.videoBitrate",1,1e6),$m
6(e.videoFrameRate)||qm(e.videoFrameRate,"config.videoFrameRate"),$m(e.lowLatency)||Km(e.lowLatency,"config.lowLatency"),$m(e.audioSampleRate)||Ym(e.audioSampleRate,"config.audioSampleRate",[32e3,44100,48e3]),$m(e.audioBitrate)||qm(e.audioBitrate,"config.audioBitrate",1,128),$m(e.audioChannels)||Ym(e.audioChannels,"config.audioChannels",[1,2,3,4,5]),$m(e.videoGop)||qm(e.videoGop,"config.videoGop"),$m(e.videoCodecProfile)||Ym(e.videoCodecProfile,"config.videoCodecProfile",[66,77,100]),$m(e.userCount)||qm(e.userCount,"config.userCount",0,17),$m(e.backgroundColor)||qm(e.backgroundColor,"config.backgroundColor",0,16777215),$m(e.userConfigExtraInfo)||Xm(e.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1),e.transcodingUsers&&!$m(e.transcodingUsers)&&(zm(e.transcodingUsers,"config.transcodingUsers"),e.transcodingUsers.forEach((e,t)=>{Zm(e.uid),$m(e.x)||qm(e.x,"transcodingUser[".concat(t,"].x"),0,1e4),$m(e.y)||qm(e.y,"transcodingUser[".concat(t,"].y"),0,1e4),$m(e.width)||qm(e.width,"transcodingUser[".concat(t,"].width"),0,1e4),$m(e.height)||qm(e.height,"transcodingUser[".concat(t,"].height"),0,1e4),$m(e.zOrder)||qm(e.zOrder-1,"transcodingUser[".concat(t,"].zOrder"),0,100),$m(e.alpha)||qm(e.alpha,"transcodingUser[".concat(t,"].alpha"),0,1,!1)})),$m(e.watermark)||Xf(e.watermark,"watermark"),$m(e.backgroundImage)||Xf(e.backgroundImage,"backgroundImage"),e.images&&!$m(e.images)&&(zm(e.images,"config.images"),e.images.forEach((e,t)=>{Xf(e,"images[".concat(t,"]"))}))}(t);const i=[];t.images&&i.push(...t.images.map(e=>hC(hC(hC({},Jf),e),{},{zOrder:255}))),t.backgroundImage&&(i.push(hC(hC(hC({},Jf),t.backgroundImage),{},{zOrder:0})),delete t.backgroundImage),t.watermark&&(i.push(hC(hC(hC({},Jf),t.watermark),{},{zOrder:255})),delete t.watermark),t.images=i,t.transcodingUsers&&(t.userConfigs=t.transcodingUsers.map(e=>hC({},e)),t.userCount=t.transcodingUsers.length,delete t.transcodingUsers);const n=(t.userConfigs||[]).map(e=>"number"==typeof e.uid?Sl.resolve(e.uid):$v(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(pR(r=this.streamingTasks).call(r)).map(e=>e.taskId).join("#")});OE.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=>{OE.warning("[".concat(this.spec.clientId,"] live streaming receive error"),e.toString(),"try to republish",t.url),this.startLiveStreamingTask(t.url,t.mode,e).then(()=>{OE.debug("[".concat(this.spec.clientId,"] live streaming republish ").concat(t.url," success"))}).catch(e=>{OE.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(pR(n=this.streamingTasks).call(n)).find(e=>e.mode===Kf.INJECT)&&t===Kf.INJECT)return new SE(fE.LIVE_STREAMING_TASK_CONFLICT,"inject stream over limit").throw();if(!this.transcodingConfig&&t===Kf.TRANSCODE)throw new SE(fE.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};OE.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 SE(fE.LIVE_STREAMING_TASK_CONFLICT).throw();try{this.connection||(this.connection=await this.connect(t))}catch(e){throw o(),e}switch(t){case Kf.TRANSCODE:r.transcodingConfig=hC({},this.transcodingConfig);break;case Kf.RAW:break;case Kf.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
6),this.isStartingStreamingTask=!0;const s=this.lastTaskId++;try{const n=new Sl((t,n)=>{jI(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===Kf.TRANSCODE?1:2,requestByUser:!i,tid:s.toString()}),n]);this.isStartingStreamingTask=!1,OE.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 SE(fE.UNEXPECTED_ERROR,"can not find streaming task to stop").throw();const r=n.mode;n.abortTask=()=>{OE.debug("[".concat(this.spec.clientId,"] stop live streaming success(worker exception)")),this.streamingTasks.delete(e),t()},this.connection.request("request",{clientRequest:{command:r===Kf.INJECT?"UninjectStream":"UnpublishStream",url:n.url}},!1,{url:e,command:"UnPublishStream",workerType:r===Kf.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then(i=>{OE.debug("[".concat(this.spec.clientId,"] stop live streaming success, code: ").concat(i.code)),this.streamingTasks.delete(e),0===this.streamingTasks.size&&r!==Kf.INJECT&&(this.connection&&this.connection.close(),this.connection=void 0),t(),r===Kf.INJECT&&this.onInjectStatusChange&&this.onInjectStatusChange(Yf.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!==Kf.INJECT)throw new SE(fE.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(pR(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=pE.CancelToken.source(),this.uapResponse=void 0,this.connection&&this.connection.close(),this.connection=void 0}async connect(e){if(this.connection)throw new SE(fE.UNEXPECTED_ERROR,"live streaming connection has already connected");const t=await qI(this,$f.REQUEST_WORKER_MANAGER_LIST,e);return this.uapResponse=t,this.connection=new uC(t.workerToken,this.spec,this.wsRetryConfig,e),this.connection.on(Zf.WARNING,(e,t)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e)),this.connection.on(Zf.PUBLISH_STREAM_STATUS,e=>this.handlePublishStreamServer(e)),this.connection.on(Zf.INJECT_STREAM_STATUS,e=>this.handleInjectStreamServerStatus(e)),this.connection.on(Zf.REQUEST_NEW_ADDRESS,(t,i)=>{if(!this.connection)return i(new SE(fE.UNEXPECTED_ERROR,"can not get new live streaming address list"));qI(this,$f.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 eS.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case eS.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case eS.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case eS.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:{const n=new SE(fE.LIVE_STREAMING_CDN_ERROR,"",{code:e.code});if(i)return OE.error(n.toString()),this.onLiveStreamError&&this.onLiveStreamError(t,n);if(!this.isStartingStreamingTask)return;this.statusError.set(t,n)}case eS.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const e=new SE(fE.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,n);return this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e)}case eS.LIVE_STREAM_RESPONSE_WORKER_LOST:case eS.LIVE_STREAM_RESPONSE_WORKER_QUIT:{var r;if(!this.connection)return;this.connection.tryNextAddress();const t=Array.from(pR(r=this.streamingTasks).call(r));for(const i of t)i.abortTask?i.abortTask():(OE.warning("[".concat(this.spec.clientId,"] publish stream status code"),e.code,"try to republish",i.url),this.startLiveStreamingTask(i.url,i.mode,new SE(fE.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code})).then(()=>{OE.debug("[".concat(this.spec.clientId,"] republish live stream success"),i.url)}).catch(e=>{OE.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(Yf.INJECT_STREAM_STATUS_START_SUCCESS,t,i));case 451:return this.onInjectStatusChange&&this.onInjectStatusChange(Yf.INJECT_STREAM_STATUS_START_ALREADY_EXISTS,t,i),void this.streamingTasks.delete(i);case 453:return this.onInjectStatusChange&&this.onInjectStatusChange(Yf.INJECT_STREAM_STATUS_START_UNAUTHORIZED,t,i),void this.streamingTasks.delete(i);case 470:return this.onInjectStatusChange&&this.onInjectStatusChange(Yf.INJECT_STREAM_STATUS_BROKEN,t,i),void this.streamingTasks.delete(i);case 499:return this.onInjectStatusChange&&this.onInjectStatusChange(Yf.INJECT_STREAM_STATUS_START_TIMEOUT,t,i),void this.streamingTasks.delete(i);default:return void OE.debug("inject stream server status",e)}}hasUrl(e){return this.streamingTasks.has(e)}}class _C{constructor(){_p(this,"destChannelMediaInfos",new Map),_p(this,"srcChannelMediaInfo",void 0)}setSrcChannelInfo(e){fS(e),this.srcChannelMediaInfo=e}addDestChannelInfo(e){fS(e),this.destChannelMediaInfos.set(e.channelName,e)}removeDestChannelInfo(e){Qm(e),this.destChannelMediaInfos.delete(e)}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo}getDestChannelMediaInfo(){return this.destChannelMediaInfos}}function EC(e){if(!(e instanceof _C)){return new SE(fE.INVALID_PARAMS,"Config should be instance of [ChannelMediaRelayConfiguration]").throw()}const t=e.getSrcChannelMediaInfo(),i=e.getDestChannelMediaInfo();if(!t){return new SE(fE.INVALID_PARAMS,"srcChannelMediaInfo should not be empty").throw()}if(0===i.size){return new SE(fE.INVALID_PARAMS,"destChannelMediaInfo should not be empty").throw()}}
6class mC extends EE{constructor(e,t,i){super(),_p(this,"ws",void 0),_p(this,"requestId",1),_p(this,"heartBeatTimer",void 0),_p(this,"joinInfo",void 0),_p(this,"clientId",void 0),_p(this,"onOpen",()=>{this.emit("open"),this.startHeartBeatCheck()}),_p(this,"onClose",e=>{this.emit("close"),this.dispose()}),_p(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 _v("cross-channel-".concat(this.clientId),i),this.ws.on(Hf.RECONNECTING,()=>{this.ws.reconnectMode="retry",this.emit("reconnecting")}),this.ws.on(Hf.CONNECTED,this.onOpen),this.ws.on(Hf.ON_MESSAGE,this.onMessage),this.ws.on(Hf.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 SE(fE.TIMEOUT,"wait status timeout, status: ".concat(e)))},5e3);this.once(e,r=>{window.clearTimeout(n),r.state&&0!==r.state?i(new SE(fE.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(e))):t(void 0)}),this.once("dispose",()=>{window.clearTimeout(n),i(new SE(fE.WS_ABORT))})})}async request(e){if("closed"===this.ws.state)throw new SE(fE.WS_DISCONNECT);const t=()=>new Sl((e,t)=>{this.ws.once(Hf.CLOSED,()=>t(new SE(fE.WS_ABORT))),this.ws.once(Hf.CONNECTED,e)});"connected"!==this.ws.state&&await t();const i=this.sendMessage(e),n=new Sl((e,t)=>{const n=()=>{t(new SE(fE.WS_ABORT))};this.ws.once(Hf.RECONNECTING,n),this.ws.once(Hf.CLOSED,n),this.once("req_".concat(i),e),jI(3e3).then(()=>{this.removeAllListeners("req_".concat(i)),this.ws.off(Hf.RECONNECTING,n),this.ws.off(Hf.CLOSED,n),t(new SE(fE.TIMEOUT,"cross channel ws request timeout"))})}),r=await n;if(!r||200!==r.code)throw new SE(fE.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(JSON.stringify(r)));return r}async connect(e){this.ws.removeAllListeners(Hf.REQUEST_NEW_URLS),this.ws.on(Hf.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 fC extends EE{set state(e){e!==this._state&&(e!==rS.RELAY_STATE_FAILURE&&(this.errorCode=oS.RELAY_OK),this.emit("state",e,this.errorCode),this._state=e)}get state(){return this._state}constructor(e,t,i,n){super(),_p(this,"joinInfo",void 0),_p(this,"sid",void 0),_p(this,"clientId",void 0),_p(this,"cancelToken",pE.CancelToken.source()),_p(this,"workerToken",void 0),_p(this,"requestId",0),_p(this,"signal",void 0),_p(this,"prevChannelMediaConfig",void 0),_p(this,"httpRetryConfig",void 0),_p(this,"_state",rS.RELAY_STATE_IDLE),_p(this,"errorCode",oS.RELAY_OK),_p(this,"onStatus",e=>{OE.debug("[".concat(this.clientId,"] ChannelMediaStatus: ").concat(JSON.stringify(e))),e&&e.command&&("onAudioPacketReceived"===e.command&&this.emit("event",nS.PACKET_RECEIVED_AUDIO_FROM_SRC),"onVideoPacketReceived"===e.command&&this.emit("event",nS.PACKET_RECEIVED_VIDEO_FROM_SRC),"onSrcTokenPrivilegeDidExpire"===e.command&&(this.errorCode=oS.SRC_TOKEN_EXPIRED,this.state=rS.RELAY_STATE_FAILURE),"onDestTokenPrivilegeDidExpire"===e.command&&(this.errorCode=oS.DEST_TOKEN_EXPIRED,this.state=rS.RELAY_STATE_FAILURE))}),_p(this,"onReconnect",async()=>{OE.debug("[".concat(this.clientId,"] ChannelMediaSocket disconnect, reconnecting")),this.emit("event",nS.NETWORK_DISCONNECTED),this.state=rS.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch(e=>{this.state!==rS.RELAY_STATE_IDLE&&(OE.error("auto restart channel media relay failed",e.toString()),this.errorCode=oS.SERVER_CONNECTION_LOST,this.state=rS.RELAY_STATE_FAILURE)})}),this.joinInfo=e,this.clientId=t,this.sid=WI(),this.signal=new mC(this.joinInfo,this.clientId,i),this.httpRetryConfig=n}async startChannelMediaRelay(e){if(this.state!==rS.RELAY_STATE_IDLE)throw new SE(fE.INVALID_OPERATION);this.state=rS.RELAY_STATE_CONNECTING,await this.connect(),OE.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 SE(fE.CROSS_CHANNEL_FAILED_JOIN_SRC);if(e.data&&e.data.serverResponse&&"SetDestChannelStatus"===e.serverResponse.command)throw new SE(fE.CROSS_CHANNEL_FAILED_JOIN_DEST);if(e.data&&e.data.serverResponse&&"StartPacketTransfer"===e.serverResponse.command)throw new SE(fE.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST);throw e}this.prevChannelMediaConfig=e}async updateChannelMediaRelay(e){if(this.state!==rS.RELAY_STATE_RUNNING)throw new SE(fE.INVALID_OPERATION);await this.sendUpdateMessage(e),this.prevChannelMediaConfig=e}async stopChannelMediaRelay(){await this.sendStopRelayMessage(),OE.debug("[".concat(this.clientId,"] stopChannelMediaRelay: send stop message success")),this.state=rS.RELAY_STATE_IDLE,this.dispose()}dispose(){OE.debug("[".concat(this.clientId,"] disposeChannelMediaRelay")),this.cancelToken.cancel(),this.cancelToken=pE.CancelToken.source(),this.state=rS.RELAY_STATE_IDLE,this.emit
vendor: 4,502 bytes, line 6
6("dispose"),this.signal.dispose(),this.prevChannelMediaConfig=void 0}async connect(){const e=await nC(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=e.workerToken,await this.signal.connect(e.addressList),this.emit("event",nS.NETWORK_CONNECTED),this.signal.on("status",this.onStatus),this.signal.on("reconnecting",this.onReconnect)}async sendStartRelayMessage(e){const t=this.genMessage(iS.StopPacketTransfer);await this.signal.request(t),await this.signal.waitStatus("Normal Quit"),OE.debug("[".concat(this.clientId,"] startChannelMediaRelay: StopPacketTransfer success"));const i=this.genMessage(iS.SetSdkProfile,e);await this.signal.request(i),OE.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));const n=this.genMessage(iS.SetSourceChannel,e);await this.signal.request(n),await this.signal.waitStatus("SetSourceChannelStatus"),this.emit("event",nS.PACKET_JOINED_SRC_CHANNEL),OE.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));const r=this.genMessage(iS.SetSourceUserId,e);await this.signal.request(r),OE.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));const o=this.genMessage(iS.SetDestChannel,e);await this.signal.request(o),await this.signal.waitStatus("SetDestChannelStatus"),this.emit("event",nS.PACKET_JOINED_DEST_CHANNEL),OE.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetDestChannel success"));const s=this.genMessage(iS.StartPacketTransfer,e);await this.signal.request(s),this.emit("event",nS.PACKET_SENT_TO_DEST_CHANNEL),this.state=rS.RELAY_STATE_RUNNING,OE.debug("[".concat(this.clientId,"] startChannelMediaRelay: StartPacketTransfer success"))}async sendUpdateMessage(e){const t=this.genMessage(iS.UpdateDestChannel,e);await this.signal.request(t),this.emit("event",nS.PACKET_UPDATE_DEST_CHANNEL),OE.debug("[".concat(this.clientId,"] sendUpdateMessage: UpdateDestChannel success"))}async sendStopRelayMessage(){const e=this.genMessage(iS.StopPacketTransfer);await this.signal.request(e),OE.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:wE,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};"4.17.2"===o.sdkVersion&&(o.sdkVersion="0.0.1");let s=null,a=null;switch(e){case iS.SetSdkProfile:return o.clientRequest={command:"SetSdkProfile",type:"multi_channel"},o;case iS.SetSourceChannel:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new SE(fE.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 iS.SetSourceUserId:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new SE(fE.UNEXPECTED_ERROR,"can not find source config");return o.clientRequest={command:"SetSourceUserId",uid:a.uid+""},o;case iS.SetDestChannel:if(s=t&&t.getDestChannelMediaInfo(),!s)throw new SE(fE.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 iS.StartPacketTransfer:return o.clientRequest={command:"StartPacketTransfer"},o;case iS.Reconnect:return o.clientRequest={command:"Reconnect"},o;case iS.StopPacketTransfer:return o.clientRequest={command:"StopPacketTransfer"},o;case iS.UpdateDestChannel:if(s=t&&t.getDestChannelMediaInfo(),!s)throw new SE(fE.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 SC=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 TC(e);i({buffer:n,width:t.width,height:t.height})}else n(new SE(fE.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))},e,1)})},TC=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t)};function gC(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 RC(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
6t%2?gC(Object(i),!0).forEach((function(t){_p(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):gC(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class IC{get videoElementStatus(){return this._videoElementStatus}set videoElementStatus(e){e!==this._videoElementStatus&&(OE.debug("[".concat(this.trackId,"] video-element-status change ").concat(this._videoElementStatus," => ").concat(e)),this._videoElementStatus=e)}constructor(e){_p(this,"trackId",void 0),_p(this,"config",void 0),_p(this,"onFirstVideoFrameDecoded",void 0),_p(this,"freezeTimeCounterList",[]),_p(this,"renderFreezeAccTime",0),_p(this,"timeUpdatedCount",0),_p(this,"freezeTime",0),_p(this,"playbackTime",0),_p(this,"lastTimeUpdatedTime",0),_p(this,"autoplayFailed",!1),_p(this,"videoTrack",void 0),_p(this,"videoElement",void 0),_p(this,"cacheVideoElement",void 0),_p(this,"videoElementCheckInterval",void 0),_p(this,"_videoElementStatus",sf.NONE),_p(this,"isGettingVideoDimensions",!1),_p(this,"startGetVideoDimensions",()=>{const e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return OE.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(e,500)};!this.isGettingVideoDimensions&&e()}),_p(this,"autoResumeAfterInterruption",()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&"running"===Lg.curState&&(ep()?(OE.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()):$h()?(OE.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()):Zh()&&(OE.debug("[track-".concat(this.trackId,"] video element paused, auto resume for iOS 15.0")),this.videoElement.pause(),this.videoElement.play()))}),_p(this,"handleVideoEvents",e=>{switch(e.type){case"play":case"playing":this.startGetVideoDimensions(),this.videoElementStatus=sf.PLAYING;break;case"loadeddata":if(this.onFirstVideoFrameDecoded&&this.onFirstVideoFrameDecoded(),this.cacheVideoElement){try{this.cacheVideoElement.remove()}catch(e){}this.cacheVideoElement=void 0}break;case"canplay":this.videoElementStatus=sf.CANPLAY;break;case"stalled":this.videoElementStatus=sf.STALLED;break;case"suspend":this.videoElementStatus=sf.SUSPEND;break;case"pause":this.videoElementStatus=sf.PAUSED,Kh()||tp()||Wh()&&this.autoplayFailed||!this.videoTrack||"live"!==this.videoTrack.readyState||(OE.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=sf.WAITING;break;case"abort":this.videoElementStatus=sf.ABORT;break;case"ended":this.videoElementStatus=sf.ENDED;break;case"emptied":this.videoElementStatus=sf.EMPTIED;break;case"error":{this.videoElementStatus=sf.ERROR;const e=this.videoElement.error;e&&OE.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,CI.lastVisibleTime<CI.lastHiddenTime||i<CI.lastHiddenTime||i<CI.lastVisibleTime)return;for(t>GE("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}}}),_p(this,"autoResumeAfterInterruptionOnIOS15",()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&(ep()?(OE.debug("[track-".concat(this.trackId,"] video element paused, auto resume for iOS 15.2")),this.videoElement.srcObject=null,this.videoElement.srcObject=ne
6w MediaStream([this.videoTrack]),this.videoElement.play()):$h()?(OE.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()):Zh()&&(OE.debug("[track-".concat(this.trackId,"] video element paused, auto resume for iOS 15.0")),this.videoElement.pause(),this.videoElement.play()))}),this.trackId=e.trackId,this.config=e,e.element instanceof HTMLVideoElement?this.videoElement=e.element:this.videoElement=document.createElement("video"),Lg.on(yg.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),Lg.on(yg.IOS_15_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15)}getVideoElement(){return this.videoElement}getContainerElement(){var e;return null!==(e=this.videoElement.parentElement)&&void 0!==e?e:void 0}updateConfig(e){this.config=e,this.trackId=e.trackId,e.element!==this.videoElement&&(this.destroy(),this.videoElement=e.element),this.videoTrack&&this.initVideoElement()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.initVideoElement())}play(e){const t=this.videoElement.play();t&&t.catch&&t.catch(t=>{e&&vg.autoplayFailed(e,"video",t.message,this.trackId),"NotAllowedError"===t.name?(OE.warning("detected video element autoplay failed",t),this.autoplayFailed=!0,this.handleAutoPlayFailed()):OE.warning("[".concat(this.trackId,"] play warning: "),t)});const i=Mh();if(("Safari"===i.name&&15===Number(i.version)||Qh())&&t&&t.then&&t.catch){const e=()=>{this.config.mirror&&(this.videoElement.style.transform="rotateY(180deg)")};t.then(e).catch(e)}}getCurrentFrame(){const e=document.createElement("canvas");e.width=this.videoElement.videoWidth,e.height=this.videoElement.videoHeight;const t=e.getContext("2d");if(!t)return OE.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;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 TC(e);n({buffer:t,width:i.width,height:i.height})}else r(new SE(fE.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))},e,t<0?.1:t>1?1:t)})):await SC(e)}destroy(){Lg.off(yg.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),Lg.off(yg.IOS_15_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15),this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[]}initVideoElement(){if(this.videoElementStatus=sf.INIT,!this.videoElementCheckInterval&&(vC.forEach(e=>{this.videoElement.addEventListener(e,this.handleVideoEvents)}),this.videoElementCheckInterval=window.setInterval(()=>{(function(e){return e!==document.body&&document.body.contains(e)})(this.videoElement)||(this.videoElementStatus=sf.DESTROYED)},1e3),GE("ENABLE_VIDEO_FRAME_CALLBACK"))){var e,t;let i;const n=(e,t)=>{if(this.videoElementStatus===sf.PLAYING){if(i){const e=t.presentationTime-i.presentationTime;e>GE("VIDEO_FREEZE_DURATION")&&CI.lastVisibleTime>=CI.lastHiddenTime&&i.timestamp>CI.lastVisibleTime&&i.timestamp>CI.lastHiddenTime&&(this.renderFreezeAccTime+=e)}i=RC(RC({},t),{},{timestamp:e})}var r,o;GE("ENABLE_VIDEO_FRAME_CALLBACK")&&(null===(r=(o=this.videoElement).requestVideoFrameCallback)||void 0===r||r.call(o,n))};null===(e=(t=this.videoElement).requestVideoFrameCallback)||void 0===e||e.call(t,n)}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),op()&&(this.videoElement.poster="noposter");const i=Mh();if("Safari"===i.name&&15===Number(i.version)||Qh()||!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=>{OE.debug("[".concat(this.trackId,"] playback interrupted"),e.toString())})}
6resetVideoElement(){vC.forEach(e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents)}),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.videoElementStatus=sf.NONE}handleAutoPlayFailed(){const e=t=>{t.preventDefault(),this.videoElement.play().then(()=>{OE.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))}).catch(e=>{OE.error(e)}),this.autoplayFailed=!1,sp()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};sp()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),mg()}}const vC=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];class CC extends IC{constructor(e){super(e),_p(this,"container",void 0),_p(this,"slot",void 0),this.slot=e.element,this.updateConfig(e)}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){var t;null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)&&super.play(e)}getCurrentFrame(){var e;return null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)?super.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameToUint8Array(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)?await super.getCurrentFrameToUint8Array(e,i):await SC(e)}destroy(){if(super.destroy(),this.videoElement.remove(),this.videoElement=document.createElement("video"),this.container){try{this.container.remove(),this.slot.removeChild(this.container)}catch(e){}this.container=void 0}}createElements(){this.container||(this.container=document.createElement("div")),this.container.id="agora-video-player-".concat(this.trackId),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.overflow="hidden",this.videoTrack?(this.container.style.backgroundColor="black",GE("KEEP_LAST_FRAME")&&this.resetVideoElement(),this.mountedVideoElement()):this.unmountedVideoElement(),this.slot.appendChild(this.container)}mountedVideoElement(){var e;!this.container||null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)||this.container.appendChild(this.videoElement),super.initVideoElement(),this.videoElement.id="video_".concat(this.trackId),this.videoElement.className="agora_video_player",this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.left="0",this.videoElement.style.top="0"}unmountedVideoElement(){var e;if(null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)){super.resetVideoElement();try{this.container&&this.container.removeChild(this.videoElement)}catch(e){}this.videoElement=document.createElement("video")}}resetVideoElement(){var e;null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)&&(super.resetVideoElement(),this.cacheVideoElement=this.videoElement,this.videoElement=document.createElement("video"))}getContainerElement(){return this.container}}function yC(e){const t={};e.facingMode&&(t.facingMode=e.facingMode),e.cameraId&&(t.deviceId={exact:e.cameraId});const i=UE(e.encoderConfig);return t.width=i.width,t.height=i.height,!np()&&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 AC(e){const t={};e.screenSourceType&&(t.mediaSource=e.screenSourceType),e.extensionId&&Gh()&&(t.extensionId=e.extensionId);const{displaySurface:i,selfBrowserSurface:n,surfaceSwitching:r,systemAudio:o}=e;(Yh(107)||qh(107)||Jh(93))&&(i&&(Ym(i,"displaySurface",["browser","window","monitor"]),t.displaySurface=i),n?(Ym(n,"selfBrowserSurface",["exclude","include"]),t.selfBrowserSurface=n):t.selfBrowserSurface="include",r&&(Ym(r,"surfaceSwitching",["exclude","include"]),t.surfaceSwitching=r)),(Yh(105)||qh(105)||Jh(91))&&o&&(Ym(o,"systemAudio",["exclude","include"]),t.systemAudio=o),e.electronScreenSourceId&&(t.sourceId=e.electronScreenSourceId);const s=e.encoderConfig?xE(e.encoderConfig):null;
6return t.mandatory={chromeMediaSource:"desktop",maxWidth:s?s.width:void 0,maxHeight:s?s.height:void 0},s&&(s.frameRate&&("number"==typeof s.frameRate?(t.mandatory.maxFrameRate=s.frameRate,t.mandatory.minFrameRate=s.frameRate):(t.mandatory.maxFrameRate=s.frameRate.max||s.frameRate.ideal||s.frameRate.exact||void 0,t.mandatory.minFrameRate=s.frameRate.min||s.frameRate.ideal||s.frameRate.exact||void 0),t.frameRate=s.frameRate),s.width&&(t.width=s.width),s.height&&(t.height=s.height)),t}function OC(e){const t={};if(np()||(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=jE(e.encoderConfig);t.channelCount=i.stereo?2:1,t.sampleRate=i.sampleRate,t.sampleSize=i.sampleSize}return e.microphoneId&&(t.deviceId={exact:e.microphoneId}),op()&&(t.sampleRate=void 0),t}var bC,wC;!function(e){e.COVERED="COVERED",e.POSITION="POSITION",e.SIZE="SIZE",e.STYLE="STYLE"}(bC||(bC={})),function(e){e.UNMOUNTED="UNMOUNTED",e.INVALID_HTML_ELEMENT="INVALID_HTML_ELEMENT"}(wC||(wC={}));var NC,DC,PC,LC,kC,MC,UC,xC,VC,FC,jC,BC,GC,WC,HC,KC,YC,qC,JC,XC,zC,QC,ZC,$C,ey,ty,iy,ny,ry,oy,sy,ay,cy,dy,uy=new class{constructor(){_p(this,"_clientSize",null),_p(this,"getClientWidth",()=>document.documentElement?document.documentElement.clientWidth:document.body.clientWidth),_p(this,"getClientHeight",()=>document.documentElement?document.documentElement.clientHeight:document.body.clientHeight),_p(this,"getStyle",e=>window.getComputedStyle(e,null)),_p(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}),_p(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}),_p(this,"checkActualCssVisibleIncludeInherit",e=>this.checkPropertyUpToAllParentNodes(e,this.checkCssVisibleProperty)),_p(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)}}),_p(this,"checkActualSize",()=>{const{width:e,height:t,clientMin:i}=this._clientSize;return this.checkSizeIsVisible(e,t,i)}),_p(this,"elementFromPoint",(e,t)=>document.elementFromPoint?document.elementFromPoint(e,t):null),_p(this,"checkCoverForAPoint",(e,t,i)=>{const n=this.elementFromPoint(e,t);return null!==n&&n!==i}),_p(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]}),_p(this,"checkElementCover",e=>this.getPointPositionList().map(t=>this.checkCoverForAPoint(t.x,t.y,e)).filter(e=>!!e).length>6),_p(this,"checkSizeIsVisible",(e,t,i)=>(e>50||i/e<=10)&&(t>50||i/t<=10)),_p(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)}),_p(this,"returnHiddenResult",e=>(this._clientSize=null,{visible:!1,reason:e})),_p(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(bC.COVERED);{const e=this.checkActualSize(),t=this.checkSizeOfPartInClient();return e&&!t?this.returnHiddenResult(bC.POSITION):e?(this._clientSize=null,{visible:!0}):this.returnHiddenResult(bC.SIZE)}}return this.returnHiddenResult(bC.STYLE)}return this.returnHiddenResult(wC.UNMOUNTED)}return this.returnHiddenResult(wC.INVALID_HTML_ELEMENT)}),_p(this,"checkElementIsMountedOnDom",e=>this.checkPropertyUpToAllParentNodes(e,e=>"HTML"!==e.nodeName.toUpperCase()?null!==e.parentElement:!!document.documentElement))}};function ly(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 hy(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
vendor: 7,369 bytes, line 6
6t%2?ly(Object(i),!0).forEach((function(t){_p(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):ly(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let py=(NC=Ig({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),DC=oR(),PC=Ig({argsMap:e=>[e.getTrackId()]}),LC=bg("LocalVideoTrack","_enabledMutex"),kC=Ig({argsMap:(e,t)=>[e.getTrackId(),t]}),MC=oR(),UC=bg("LocalVideoTrack","_enabledMutex"),xC=Ig({argsMap:(e,t)=>[e.getTrackId(),t]}),VC=oR(),FC=Ig({argsMap:(e,t)=>[e.getTrackId(),t]}),jC=oR(),BC=oR(),GC=Ig({argsMap:(e,t,i)=>[e.getTrackId(),t,i]}),WC=oR(),HC=oR(),KC=oR(),YC=oR(),qC=oR(),JC=oR(),XC=oR(),zC=Ig({argsMap:(e,t)=>[e.getTrackId(),t.name]}),QC=Ig({argsMap:e=>[e.getTrackId()]}),ZC=Ig({argsMap:e=>[e.getTrackId()]}),$C=Ig({argsMap:(e,t,i)=>[e.getTrackId(),t.label,i]}),ZT((ey=class e extends wg{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==sf.PLAYING)}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}get __className__(){return"LocalVideoTrack"}constructor(e,t,i,n,r,o){if(super(e,r),_p(this,"trackMediaType","video"),_p(this,"_player",void 0),_p(this,"_videoVisibleTimer",null),_p(this,"_previousVideoVisibleStatus",void 0),_p(this,"_clearPreviousVideoVisibleStatus",()=>this._previousVideoVisibleStatus=void 0),_p(this,"_encoderConfig",void 0),_p(this,"_scalabiltyMode",{numSpatialLayers:1,numTemporalLayers:1}),_p(this,"_optimizationMode",void 0),_p(this,"_videoHeight",void 0),_p(this,"_videoWidth",void 0),_p(this,"_forceBitrateLimit",void 0),_p(this,"_enabled",!0),_p(this,"processorDestination",void 0),_p(this,"_processorContext",void 0),Wh()){const{width:t,height:i}=e.getSettings();this._videoWidth=t,this._videoHeight=i}else this.updateMediaStreamTrackResolution();this._encoderConfig=t,this._scalabiltyMode=i,this._optimizationMode=n,this._hints=o||[],-1===this._hints.indexOf(lS.SCREEN_TRACK)&&this.updateBitrateFromProfile(),t&&-1!==this._hints.indexOf(lS.CUSTOM_TRACK)&&this.setEncoderConfiguration(t),this.processorContext=new fR(this.getTrackId(),"local"),this.processorDestination=new mR(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:(OE.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}OE.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=hy(hy(hy({},this._getDefaultPlayerConfig()),t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new IC(i):this._player=new CC(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(_S.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}},GE("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,OE.debug("[".concat(this.getTrackId(),"] stop video playback")))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(OE.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){this._originMediaStreamTrack.enabled=!1;try{await JI(this,uS.NEED_DISABLE_TRACK,this)}catch(e){throw OE.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}return t||(this._enabled=!1),void OE.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}this._originMediaStreamTrack.enabled=!0;try{await JI(this,uS.NEED_ENABLE_TRACK,this)}catch(e){throw OE.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}OE.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,OE.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await JI(this,uS.NEED_MUTE_TRACK,this):await JI(this,uS.NEED_UNMUTE_TRACK,this))}async setEncoderConfiguration(e,t){if(!this._enabled)throw new SE(fE.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if(e=UE(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),e.width||e.height||e.frameRate){const t=yC({encoderConfig:e});(Wh()||Kh()||tp())&&(t.deviceId=void 0),OE.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(t));try{await this._originMediaStreamTrack.applyConstraints(t),this.updateMediaStreamTrackResolution()}catch(e){const t=new SE(fE.UNEXPECTED_ERROR,e.toString());throw OE.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}}this._encoderConfig=e,-1===this._hints.indexOf(lS.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await JI(this,uS.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw()}}getStats(){iv(()=>{OE.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")},"localVideoTrackGetStatsWarning");const e=XI(this,uS.GET_STATS);return e||hy({},jf)}async setBeautyEffect(e){OE.error("LocalVideoTrack.setBeautyEffect was deprecated, please migrate to agora-extension-beauty-effect")}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameImage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this._player?this._player.getCurrentFrameToUint8Array(e,t):await SC(e)}clone(t,i,n,r){const o=this._mediaStreamTrack.clone();return new e(o,t,i,n,r)}async setBitrateLimit(e){if(OE.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 JI(this,uS.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw()}}}async setOptimizationMode(e){if("motion"!==e&&"detail"!==e&&"balanced"!==e)return void OE.error(fE.INVALID_PARAMS,"optimization mode must be motion, detail or balanced");const t=this._optimizationMode;try{this._optimizationMode=e,await JI(this,uS.SET_OPTIMIZATION_MODE,this)}catch(e){throw this._optimizationMode=t,OE.error("[".concat(this.getTrackId(),"] set optimization mode failed"),e.toString()),e}OE.info("[".concat(this.getTrackId(),"] set optimization mode success (").concat(e,")"))}
6setScalabiltyMode(e){if(1===e.numSpatialLayers&&1!==e.numTemporalLayers)return OE.error(fE.INVALID_PARAMS,"scalability mode currently not supported, no SVC."),void(this._scalabiltyMode={numSpatialLayers:1,numTemporalLayers:1});this._scalabiltyMode=e,OE.info("[".concat(this.getTrackId(),"] set scalability mode success (").concat(e,")"))}updateMediaStreamTrackResolution(){KI(this._originMediaStreamTrack).then(e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t}).catch(HI)}_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=GE("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,OE.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=uy.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=vg.reportApiInvoke(null,{tag:Ef.TRACER,name:_f.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 SE(fE.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}async renewMediaStreamTrack(e){}pipe(e){if(this.processor===e)return e;if(e._source)throw new SE(fE.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 SE(fE.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if("video"!==e.kind)throw new SE(fE.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(e,t,!0),this.updateMediaStreamTrackResolution()}bindProcessorDestinationEvents(){this.processorDestination.on(NS.ON_TRACK,async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),await JI(this,uS.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await JI(this,uS.NEED_REPLACE_TRACK,this))})}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(NS.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(DS.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(DS.REQUEST_CONSTRAINTS)}}).prototype,"play",[NC,DC],Object.getOwnPropertyDescriptor(ey.prototype,"play"),ey.prototype),ZT(ey.prototype,"stop",[PC],Object.getOwnPropertyDescriptor(ey.prototype,"stop"),ey.prototype),ZT(ey.prototype,"setEnabled",[LC,kC,MC],Object.getOwnPropertyDescriptor(ey.prototype,"setEnabled"),ey.prototype),ZT(ey.prototype,"setMuted",[UC,xC,VC],Object.getOwnPropertyDescriptor(ey.prototype,"setMuted"),ey.prototype),ZT(ey.prototype,"setEncoderConfiguration",[FC,jC],Object.getOwnPropertyDescriptor(ey.prototype,"setEncoderConfiguration"),ey.prototype),ZT(ey.prototype,"getStats",[BC],Object.getOwnPropertyDescriptor(ey.prototype,"getStats"),ey.prototype),ZT(ey.prototype,"setBeautyEffect",[GC,WC],Ob
vendor: 4,332 bytes, line 6
6ject.getOwnPropertyDescriptor(ey.prototype,"setBeautyEffect"),ey.prototype),ZT(ey.prototype,"getCurrentFrameData",[HC],Object.getOwnPropertyDescriptor(ey.prototype,"getCurrentFrameData"),ey.prototype),ZT(ey.prototype,"getCurrentFrameImage",[KC],Object.getOwnPropertyDescriptor(ey.prototype,"getCurrentFrameImage"),ey.prototype),ZT(ey.prototype,"setBitrateLimit",[YC],Object.getOwnPropertyDescriptor(ey.prototype,"setBitrateLimit"),ey.prototype),ZT(ey.prototype,"setOptimizationMode",[qC],Object.getOwnPropertyDescriptor(ey.prototype,"setOptimizationMode"),ey.prototype),ZT(ey.prototype,"setScalabiltyMode",[JC],Object.getOwnPropertyDescriptor(ey.prototype,"setScalabiltyMode"),ey.prototype),ZT(ey.prototype,"updateMediaStreamTrackResolution",[XC],Object.getOwnPropertyDescriptor(ey.prototype,"updateMediaStreamTrackResolution"),ey.prototype),ZT(ey.prototype,"pipe",[zC],Object.getOwnPropertyDescriptor(ey.prototype,"pipe"),ey.prototype),ZT(ey.prototype,"unpipe",[QC],Object.getOwnPropertyDescriptor(ey.prototype,"unpipe"),ey.prototype),ZT(ey.prototype,"close",[ZC],Object.getOwnPropertyDescriptor(ey.prototype,"close"),ey.prototype),ZT(ey.prototype,"replaceTrack",[$C],Object.getOwnPropertyDescriptor(ey.prototype,"replaceTrack"),ey.prototype),ey),_y=(ty=Ig({argsMap:(e,t)=>[e.getTrackId(),t]}),iy=oR(),ny=bg("CameraVideoTrack","_enabledMutex"),ry=Ig({argsMap:(e,t)=>[e.getTrackId(),t]}),oy=oR(),sy=Ig({argsMap:(e,t)=>[e.getTrackId(),t]}),ay=oR(),cy=Ig({argsMap:e=>[e.getTrackId()]}),ZT((dy=class extends py{get __className__(){return"CameraVideoTrack"}constructor(e,t,i,n,r,o){super(e,UE(t.encoderConfig),n,r,o),_p(this,"_config",void 0),_p(this,"_originalConstraints",void 0),_p(this,"_constraints",void 0),_p(this,"_enabled",!0),_p(this,"_deviceName","default"),_p(this,"tryResumeVideoForIOS15WeChat",async()=>{Qh()&&!ep()&&ip()&&this._enabled&&!this._isClosed&&(OE.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=UE(this._config.encoderConfig),Lg.on(yg.IOS_15_INTERRUPTION_END,this.tryResumeVideoForIOS15WeChat),Lg.on(yg.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15WeChat),this.bindProcessorContextEvents()}async setDevice(e){if(OE.info("[".concat(this.getTrackId(),"] set device to ").concat(e)),this._enabled)try{const t=await iR.getDeviceById(e),i={};i.video=hy({},this._constraints),i.video.deviceId={exact:e},i.video.facingMode=void 0,this._originMediaStreamTrack.stop();let n=null;try{n=await Zg(i,this.getTrackId())}catch(e){throw OE.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),n=await Zg({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 OE.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await iR.getDeviceById(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw OE.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}OE.info("[".concat(this.getTrackId(),"] setDevice success"))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(OE.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{const e=await Zg({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1)}await JI(this,uS.NEED_ENABLE_TRACK,this)}catch(e){throw OE.error("[".concat(this.getTrackId(),"] setEnabled true error"),e.toString()),e}this.updateMediaStreamTrackResolution(),OE.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 JI(this,uS.NEED_DISABLE_TRACK,this)}catch(e){throw OE.error("[".concat(this.getTrackId(),"] setEnabled to fal
6se error"),e.toString()),e}OE.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new SE(fE.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");e=UE(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=ev(this._config);i.encoderConfig=e;const n=yC(i);(Wh()||Kh()||tp())&&(n.deviceId=void 0),OE.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 SE(fE.UNEXPECTED_ERROR,e.toString());throw OE.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(lS.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await JI(this,uS.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw()}}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((Kh()||tp())&&this._enabled&&!this._isClosed&&Lg.duringInterruption){const e=async()=>{Lg.off(yg.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(OE.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};Lg.on(yg.IOS_INTERRUPTION_END,e)}else OE.debug("[".concat(this.getTrackId(),"] track ended")),this.emit(_S.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,i=iR.searchDeviceIdByName(this._deviceName);if(i&&!t.deviceId&&(t.deviceId={exact:i}),this._enabled){const e=await Zg({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),Lg.off(yg.IOS_15_INTERRUPTION_END,this.tryResumeVideoForIOS15WeChat),Lg.off(yg.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15WeChat)}bindProcessorContextEvents(){this.processorContext.on(DS.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(DS.REQUEST_CONSTRAINTS,async e=>{e(this._originMediaStreamTrack.getSettings())})}}).prototype,"setDevice",[ty,iy],Object.getOwnPropertyDescriptor(dy.prototype,"setDevice"),dy.prototype),ZT(dy.prototype,"setEnabled",[ny,ry,oy],Object.getOwnPropertyDescriptor(dy.prototype,"setEnabled"),dy.prototype),ZT(dy.prototype,"setEncoderConfiguration",[sy,ay],Object.getOwnPropertyDescriptor(dy.prototype,"setEncoderConfiguration"),dy.prototype),ZT(dy.prototype,"close",[cy],Object.getOwnPropertyDescriptor(dy.prototype,"close"),dy.prototype),dy);class Ey{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){_p(this,"uid",void 0),_p(this,"_uintid",void 0),_p(this,"_trust_in_room_",!0),_p(this,"_trust_audio_enabled_state_",!0),_p(this,"_trust_video_enabled_state_",!0),_p(this,"_trust_audio_mute_state_",!0),_p(this,"_trust_video_mute_state_",!0),_p(this,"_audio_muted_",!1),_p(this,"_video_muted_",!1),_p(this,"_audio_enabled_",!0),_p(this,"_video_enabled_",!0),_p(this,"_audio_added_",!1),_p(this,"_video_added_",!1),_p(this,"_trust_video_stream_added_state_",!0),_p(this,"_trust_audio_stream_added_state_",!0),_p(this,"_audioTrack",void 0),_p(this,"_videoTrack",void 0),_p(this,"_audioSSRC",void 0),_p(this,"_videoSSRC",void 0),_p(this,"_audioOrtc",void 0),_p(this,"_videoOrtc",void 0),_p(this,"_cname",void 0),_p(this,"_rtxSsrcId",void 0),this.uid=e,this._uintid=t}}var my=fl,fy=pd,Sy=Rd;Ii({target:"Promise",stat:!0},{try:function(e){var t=fy.f(this),i=Sy(e);return(i.error?t.reject:t.resolve)(i.value),t.promise}});var Ty=my,gy=Ii,Ry=h,Iy=i,vy=GS,Cy=q,yy=Fe,Ay=wi,Oy=im,by=zS,wy=DT,Ny=ae,Dy=rt("isConcatSpreadable"),Py=9007199254740991,Ly="Maximum allowed index exceeded",ky=Ry.TypeError,My=Ny>=51||!Iy((function(){var e=[];return e[Dy]=!1,e.concat()[0]!==e})),Uy=wy("concat"),xy=function(e){if(!Cy(e))return!1;
vendor: 4,880 bytes, line 6
6var t=e[Dy];return void 0!==t?!!t:vy(e)};gy({target:"Array",proto:!0,forced:!My||!Uy},{concat:function(e){var t,i,n,r,o,s=yy(this),a=by(s,0),c=0;for(t=-1,n=arguments.length;t<n;t++)if(xy(o=-1===t?s:arguments[t])){if(c+(r=Ay(o))>Py)throw ky(Ly);for(i=0;i<r;i++,c++)i in o&&Oy(a,c,o[i])}else{if(c>=Py)throw ky(Ly);Oy(a,c++,o)}return a.length=c,a}});var Vy={},Fy=k,jy=K,By=Pn.f,Gy=cm,Wy="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];Vy.f=function(e){return Wy&&"Window"==Fy(e)?function(e){try{return By(e)}catch(e){return Gy(Wy)}}(e):By(jy(e))};var Hy={},Ky=rt;Hy.f=Ky;var Yy=J,qy=Ge,Jy=Hy,Xy=Ht.f,zy=function(e){var t=Yy.Symbol||(Yy.Symbol={});qy(t,e)||Xy(t,e,{value:Jy.f(e)})},Qy=Ii,Zy=h,$y=$,eA=f,tA=v,iA=d,nA=g,rA=ue,oA=i,sA=Ge,aA=GS,cA=S,dA=q,uA=u,lA=fe,hA=zt,pA=Fe,_A=K,EA=Et,mA=No,fA=N,SA=Pr,TA=hr,gA=Pn,RA=Vy,IA=Zn,vA=T,CA=Ht,yA=dr,AA=C,OA=pc,bA=xs,wA=Ne.exports,NA=Gn,DA=qe,PA=rt,LA=Hy,kA=zy,MA=ta,UA=ws,xA=rT.forEach,VA=pn("hidden"),FA="Symbol",jA=PA("toPrimitive"),BA=UA.set,GA=UA.getterFor(FA),WA=Object.prototype,HA=Zy.Symbol,KA=HA&&HA.prototype,YA=Zy.TypeError,qA=Zy.QObject,JA=$y("JSON","stringify"),XA=vA.f,zA=CA.f,QA=RA.f,ZA=AA.f,$A=iA([].push),eO=wA("symbols"),tO=wA("op-symbols"),iO=wA("string-to-symbol-registry"),nO=wA("symbol-to-string-registry"),rO=wA("wks"),oO=!qA||!qA.prototype||!qA.prototype.findChild,sO=nA&&oA((function(){return 7!=SA(zA({},"a",{get:function(){return zA(this,"a",{value:7}).a}})).a}))?function(e,t,i){var n=XA(WA,t);n&&delete WA[t],zA(e,t,i),n&&e!==WA&&zA(WA,t,n)}:zA,aO=function(e,t){var i=eO[e]=SA(KA);return BA(i,{type:FA,tag:e,description:t}),nA||(i.description=t),i},cO=function(e,t,i){e===WA&&cO(tO,t,i),hA(e);var n=EA(t);return hA(i),sA(eO,n)?(i.enumerable?(sA(e,VA)&&e[VA][n]&&(e[VA][n]=!1),i=SA(i,{enumerable:fA(0,!1)})):(sA(e,VA)||zA(e,VA,fA(1,{})),e[VA][n]=!0),sO(e,n,i)):zA(e,n,i)},dO=function(e,t){hA(e);var i=_A(t),n=TA(i).concat(pO(i));return xA(n,(function(t){nA&&!tA(uO,i,t)||cO(e,t,i[t])})),e},uO=function(e){var t=EA(e),i=tA(ZA,this,t);return!(this===WA&&sA(eO,t)&&!sA(tO,t))&&(!(i||!sA(this,t)||!sA(eO,t)||sA(this,VA)&&this[VA][t])||i)},lO=function(e,t){var i=_A(e),n=EA(t);if(i!==WA||!sA(eO,n)||sA(tO,n)){var r=XA(i,n);return!r||!sA(eO,n)||sA(i,VA)&&i[VA][n]||(r.enumerable=!0),r}},hO=function(e){var t=QA(_A(e)),i=[];return xA(t,(function(e){sA(eO,e)||sA(NA,e)||$A(i,e)})),i},pO=function(e){var t=e===WA,i=QA(t?tO:_A(e)),n=[];return xA(i,(function(e){!sA(eO,e)||t&&!sA(WA,e)||$A(n,eO[e])})),n};(rA||(bA(KA=(HA=function(){if(uA(KA,this))throw YA("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?mA(arguments[0]):void 0,t=DA(e),i=function(e){this===WA&&tA(i,tO,e),sA(this,VA)&&sA(this[VA],t)&&(this[VA][t]=!1),sO(this,t,fA(1,e))};return nA&&oO&&sO(WA,t,{configurable:!0,set:i}),aO(t,e)}).prototype,"toString",(function(){return GA(this).tag})),bA(HA,"withoutSetter",(function(e){return aO(DA(e),e)})),AA.f=uO,CA.f=cO,yA.f=dO,vA.f=lO,gA.f=RA.f=hO,IA.f=pO,LA.f=function(e){return aO(PA(e),e)},nA&&zA(KA,"description",{configurable:!0,get:function(){return GA(this).description}})),Qy({global:!0,wrap:!0,forced:!rA,sham:!rA},{Symbol:HA}),xA(TA(rO),(function(e){kA(e)})),Qy({target:FA,stat:!0,forced:!rA},{for:function(e){var t=mA(e);if(sA(iO,t))return iO[t];var i=HA(t);return iO[t]=i,nO[i]=t,i},keyFor:function(e){if(!lA(e))throw YA(e+" is not a symbol");if(sA(nO,e))return nO[e]},useSetter:function(){oO=!0},useSimple:function(){oO=!1}}),Qy({target:"Object",stat:!0,forced:!rA,sham:!nA},{create:function(e,t){return void 0===t?SA(e):dO(SA(e),t)},defineProperty:cO,defineProperties:dO,getOwnPropertyDescriptor:lO}),Qy({target:"Object",stat:!0,forced:!rA},{getOwnPropertyNames:hO,getOwnPropertySymbols:pO}),Qy({target:"Object",stat:!0,forced:oA((function(){IA.f(1)}))},{getOwnPropertySymbols:function(e){return IA.f(pA(e))}}),JA)&&Qy({target:"JSON",stat:!0,forced:!rA||oA((function(){var e=HA();return"[null]"!=JA([e])||"{}"!=JA({a:e})||"{}"!=JA(Object(e))}))},{stringify:function(e,t,i){var n=OA(arguments),r=t;if((dA(t)||void 0!==e)&&!lA(e))return aA(t)||(t=function(e,t){if(cA(r)&&(t=tA(r,this,e,t)),!lA(t))return t}),n[1]=t,eA(JA,null,n)}});if(!KA[jA]){var _O=KA.valueOf;bA(KA,jA,(function(e){return tA(_O,this)}))}MA(HA,FA),NA[VA]=!0,zy("asyncIterator"),zy("hasInstance"),zy("isConcatSpreadable"),zy("iterator"),zy("match"),zy("matchAll"),zy("replace"),zy("search"),zy("species"),zy("split"),zy("toPrimitive"),zy("toStringTag"),zy("unscopables"),ta(h.JSON,"JSON",!0);var EO=J.Symbol;zy("asyncDispose"),zy("dispose"),zy("matcher"),zy("metadata"),zy("observable"),zy("patternMatch"),zy("replaceAll");var mO=EO,fO=Hy.f("asyncIterator"),SO=fO;function TO(e){this.wrapped=e}function gO(e){var t,i;function n(t,i){try{var o=e[t](i),s=o.value,a=s instanceof TO;Ty.resolve(a?s.wrapped:s).then((function(e){a?n("return"===t?"return":"next",e):r
6(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 Ty((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 RO(e){return function(){return new gO(e.apply(this,arguments))}}function IO(e){return new TO(e)}gO.prototype["function"==typeof mO&&SO||"@@asyncIterator"]=function(){return this},gO.prototype.next=function(e){return this._invoke("next",e)},gO.prototype.throw=function(e){return this._invoke("throw",e)},gO.prototype.return=function(e){return this._invoke("return",e)};var vO=Hy.f("iterator");function CO(e,t){var i={},n=!1;function r(i,r){return n=!0,r=new Ty((function(t){t(e[i](r))})),{done:!1,value:t(r)}}return i[void 0!==mO&&vO||"@@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 yO=fO,AO={exports:{}};function OO(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 bO(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?OO(Object(i),!0).forEach((function(t){_p(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):OO(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function wO(e,t,i,n,r,o,s){let a=[],c=[],d=[],u=[],l=!1,h=!1;if(AO.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}}
6function NO(e){const t=AO.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 DO(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 PO(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:{}}],OE.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:{}}),OE.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:GO(e.rtpCapabilities),setup:s,cname:i}}function LO(e,t,i){const n=[],r=[];return e.forEach(e=>{let{ssrcId:o,rtx:s}=e;const a=GI(8,"track-"),c={ssrcId:o,attributes:bO({label:a,mslabel:i=i||GI(10,""),msid:"".concat(i," ").concat(a)},t&&{cname:t})};if(n.push(c),void 0!==s){const e={ssrcId:s,attributes:bO({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 kO(e,t){t instanceof _I&&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 MO(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 UO(e,t){if(!(t instanceof py&&t._encoderConfig&&-1===t._hints.indexOf(lS.SCREEN_TRACK)))return;const i=t._encoderConfig;FS().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))}),FS().supportMinBitrate&&!t._hints.includes(lS.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(GE("X_GOOGLE_START_BITRATE")||Math.floor(i.bitrateMax)))})}function xO(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 VO(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)))}
6)(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 FO(e,t,i){if(Hh())return;if("video"!==e.media.mediaType)return;if(!(t instanceof py))return;if("vp9"!==i&&"vp8"!==i)return;if("vp8"===i&&!GE("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:ev(r.attributes)}),s.ssrcIds.push(r.ssrcId+t),o&&(e.attributes.ssrcs.push({ssrcId:o.ssrcIds[1]+t,attributes:ev(r.attributes)}),e.attributes.ssrcGroups.push({semantic:"FID",ssrcIds:[r.ssrcId+t,o.ssrcIds[1]+t]}));e.attributes.ssrcGroups.unshift(s)}async function jO(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=wO(s,e,t,i,n,r,"sendonly"),c=wO(s,e,t,i,n,r,"recvonly"),d={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},u={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},l={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(BO(a,c,"videoExtensions",d,u,l),BO(a,c,"videoCodecs",d,u,l),BO(a,c,"audioExtensions",d,u,l),BO(a,c,"audioCodecs",d,u,l),GE("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){OE.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&&GE("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 BO(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)}
6),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 GO(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 WO(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});
vendor: 22,238 bytes, line 6
6const 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(";
6").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.ke
vendor: 4,291 bytes, line 6
6y),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="";
6return 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=>
6"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)})()}(AO);class HO{constructor(e){_p(this,"sessionDesc",void 0),_p(this,"localCapabilities",void 0),_p(this,"rtpCapabilities",void 0),_p(this,"candidates",void 0),_p(this,"iceParameters",void 0),_p(this,"dtlsParameters",void 0),_p(this,"setup",void 0),_p(this,"currentMidIndex",void 0),_p(this,"cname",void 0),e=ev(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,remoteSetup:o,localCapabilities:s,sdkCodec:a,cname:c}=e,d=AO.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 AO.exports.print(this.sessionDesc)}send(e,t,i){const{ssrcs:n,ssrcGroups:r}=LO(t,this.cname),o=this.sessionDesc.mediaDescriptions.find(t=>e===CS.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=ev(e),this.iceParameters=e,this.sessionDesc.mediaDescriptions.forEach(t=>
6{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=ev(e);return kO(i,t),UO(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===CS.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=ev(e);return MO(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 KO(e){if(Array.isArray(e))return e.map(e=>e);if(!YO(e))return e;const t={};for(const i in e)YO(e[i])||Array.isArray(e[i])?t[i]=KO(e[i]):t[i]=e[i];return t}function YO(e){return!("object"!=typeof e||Array.isArray(e)||!e)}function qO(){const e=navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]*/i);return e&&e[0]?Number(e[0].split("/")[1]):null}function JO(e){if(!window.RTCStatsReport)return!1;return e.getStats()instanceof Sl}class XO{constructor(e){_p(this,"input",[]),_p(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 zO={address:"unknown",candidateType:"unknown",id:"unknown",port:0,priority:0,protocol:"unknown",type:"unknown"},QO={timestamp:0,bitrate:{actualEncoded:0,transmit:0},sendPacketLossRate:0,recvPacketLossRate:0,videoRecv:[],videoSend:[],audioRecv:[],audioSend:[],selectedCandidatePair:{id:"unknown",localCandidate:zO,remoteCandidate:zO}},ZO={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},$O={firsCount:0,nacksCount:0,plisCount:0,frameCount:0,bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,qpSumPerFrame:0},eb={bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0},tb={jitterBufferMs:0,jitterMs:0,bytes:0,packetsLost:0,packetLostRate:0,packets:0,ssrc:0,receivedFrames:0,droppedFrames:0,concealedSamples:0};class ib{constructor(e,t){_p(this,"onFirstVideoReceived",void 0),_p(this,"onFirstVideoDecoded",void 0),_p(this,"onFirstAudioReceived",void 0),_p(this,"onFirstVideoDecodedTimeout",void 0),_p(this,"onFirstAudioDecoded",void 0),_p(this,"onSelectedLocalCandidateChanged",void 0),_p(this,"onSelectedRemoteCandidateChanged",void 0),_p(this,"videoIsReady",!1),_p(this,"videoIsReady2",{}),_p(this,"pc",void 0),_p(this,"options",void 0),_p(this,"intervalTimer",void 0),_p(this,"stats",KO(QO)),_p(this,"isFirstVideoReceived",{}),_p(this,"isFirstVideoDecoded",{}),_p(this,"isFirstAudioReceived",{}),_p(this,"isFirstAudioDecoded",{}),_p(this,"isFirstVideoDecodedTimeout",{}),_p(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","audioSen
6d","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 nb(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 rb(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?nb(Object(i),!0).forEach((function(t){_p(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):nb(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class ob extends ib{constructor(){super(...arguments),_p(this,"_stats",QO),_p(this,"lastDecodeVideoReceiverStats",new Map)}async updateStats(){const e=await this._getStats(),t=this.statsResponsesToObjects(e);this._stats=KO(QO);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=KO($O);t.codec=e.googCodecName,t.adaptionChangeReason="none",e.googCpuLimitedResolution&&(t.adaptionChangeReason="cpu"),e.googBandwidthLimitedResolution&&(t.adaptionChangeReason="bandwidth"),t.avgEncodeMs=Number(e.googAvgEncodeMs),t.inputFrame={width:Number(e.googFrameWidthInput)||Number(e.googFrameWidthSent),height:Number(e.googFrameHeightInput)||Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},t.sentFrame={width:Number(e.googFrameWidthSent),height:Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},t.firsCount=Number(e.googFirReceived),t.nacksCount=Number(e.googNacksReceived),t.pl
vendor: 4,416 bytes, line 6
6isCount=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=KO(ZO),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:rb({},t),lts:Date.now()}),this._stats.videoRecv.push(t);break}case"audio_recv":{const t=KO(tb);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=KO(eb);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.audioSen
6d.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 sb(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 ab(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?sb(Object(i),!0).forEach((function(t){_p(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):sb(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class cb extends ib{constructor(){super(...arguments),_p(this,"_stats",QO),_p(this,"report",void 0),_p(this,"lastDecodeVideoReceiverStats",new Map),_p(this,"lastVideoFramesRecv",new Map),_p(this,"lastVideoFramesSent",new Map),_p(this,"lastVideoFramesDecode",new Map),_p(this,"lastVideoJBDelay",new Map),_p(this,"lastAudioJBDelay",new Map),_p(this,"mediaBytesSent",new Map),_p(this,"mediaBytesRetransmit",new Map),_p(this,"mediaBytesTargetEncode",new Map),_p(this,"lastEncoderMs",new Map)}async updateStats(){this.report=await this.pc.getStats(),this._stats=KO(QO),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=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime)}),this._stats.audioSend.forEach(t=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime)}),this._stats.selectedCandidatePair.id=e.id,e.localCandidateId){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(ab({},t),ab({},this.stats.selectedCandidatePair.localCandidate)),e.type===Lh.REMOTE_CANDIDATE&&this.stats.selectedCandidatePair.remoteCandidate.id!==t.id&&this.onSelectedRemoteCandidateChanged&&this.onSelectedRemoteCandidateChanged(ab({},t),ab({},this.stats.selectedCandidatePair.remoteCandidate)))}processAudioInboundStats(e){let t=this._stats.audioRecv.find(t=>t.ssrc===e.ssrc);t||(t=KO(tb),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=KO(ZO),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.
vendor: 5,366 bytes, line 6
6ssrc),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:ab({},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=KO($O),this._stats.videoSend.push(t));const i=this.mediaBytesSent.get(e.ssrc);if(i)i.add(e.bytesSent);else{const t=new XO(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 XO(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 XO(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=KO(eb),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(pR(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}
6),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 db extends ib{updateStats(){return Sl.resolve()}}function ub(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=qO();return o?o<76?new ob(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,first
6VideoDecodedTimeout:r}):new cb(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):JO(e)?new cb(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new db(e,{updateInterval:t,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r})}var lb;function hb(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 pb(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?hb(Object(i),!0).forEach((function(t){_p(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):hb(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let _b=(ZT((lb=class e extends xS{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),_p(this,"store",void 0),_p(this,"peerConnection",void 0),_p(this,"remoteSDP",void 0),_p(this,"initialOffer",void 0),_p(this,"statsFilter",void 0),_p(this,"useRTX",!1),_p(this,"localCapabilities",void 0),_p(this,"localCandidateCount",0),_p(this,"allCandidatesReceived",!1),_p(this,"establishPromise",void 0),_p(this,"mutex",new Og("P2PConnection-mutex")),this.store=i,this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.statsFilter=ub(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=NO(e.sdp),i=wO(e.sdp,!this.useRTX,GE("FILTER_VIDEO_FEC"),GE("FILTER_AUDIO_FEC"),["opus"]);return this.localCapabilities=i,this.initialOffer=e,pb(pb({},t),{},{rtpCapabilities:{send:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},recv:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},sendrecv:i},offerSDP:e.sdp})}catch(e){throw new SE(fE.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 HO({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 SE(fE.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}send(e,t){var i=this;return RO((function*(){const n=yield IO(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 IO(i.peerConnection.createOffer()),s=AO.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);
6i.remoteSDP.receive(e,t,c);const u=i.remoteSDP.toString();return yield IO(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield IO(i.applySendEncodings(r,e)),yield IO(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 SE(fE.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 SE(fE.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 SE(fE.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 SE(fE.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();
6t.encodings.forEach(e=>e.active=!1),e.setParameters(t)}})}catch(e){throw new SE(fE.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 SE(fE.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(){var e=this;return RO((function*(){const t=yield IO(e.mutex.lock("From P2PConnection.restartICE"));try{const i=yield IO(e.peerConnection.createOffer({iceRestart:!0}));if(!i.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const n=NO(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 IO(e.peerConnection.setLocalDescription(i)),yield IO(e.peerConnection.setRemoteDescription({type:"answer",sdp:o}))}catch(e){OE.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 SE(fE.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,OE.debug("[pc-".concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,OE.debug("[pc-".concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))},GE("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&&(Uf(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),GE("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEac
6h(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(!FS().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 py)switch(o._optimizationMode){case"motion":s.degradationPreference="maintain-framerate";break;case"detail":s.degradationPreference="maintain-resolution";break;default:s.degradationPreference="balanced"}if(GE("DSCP_TYPE")&&rp()){const e=GE("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){OE.debug("Apply RTPSendEncodings failed.")}}mungSendOfferSDP(e,t){const i=AO.exports.parse(e);return t.forEach((e,t)=>{const n=e._mediaStreamTrack,r=i.mediaDescriptions.find(e=>e.attributes.mid===n.kind);r&&kO(r,e)}),AO.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 SE(fE.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(FS().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}}}).prototype,"connect",[Eb],Object.getOwnPropertyDescriptor(lb.prototype,"connect"),lb.prototype),ZT(lb.prototype,"stopSending",[Eb],Object.getOwnPropertyDescriptor(lb.prototype,"stopSending"),lb.prototype),ZT(lb.prototype,"receive",[Eb],Object.getOwnPropertyDescriptor(lb.prototype,"receive"),lb.prototype),ZT(lb.prototype,"stopReceiving",[Eb],Object.getOwnPropertyDescriptor(lb.prototype,"stopReceiving"),lb.prototype),ZT(lb.prototype,"muteRemote",[Eb],Object.getOwnPropertyDescriptor(lb.prototype,"muteRemote"),lb.prototype),ZT(lb.prototype,"unmuteRemote",[Eb],Object.getOwnPropertyDescriptor(lb.prototype,"unmuteRemote"),lb.prototype),ZT(lb.prototype,"muteLocal",[Eb],Object.getOwnPropertyDescriptor(lb.prototype,"muteLocal"),lb.prototype),ZT(lb.prototype,"unmuteLocal",[Eb],Object.getOwnPropertyDescriptor(lb.prototype,"unmuteLocal"),lb.prototype),ZT(lb.prototype,"close",[Eb],Object.getOwnPropertyDescriptor(lb.prototype,"close"),lb.prototype),ZT(lb.prototype,"updateEncoderConfig",[Eb],Object.getOwnPropertyDescriptor(lb.prototype,"updateEncoderConfig"),lb.prototype),ZT(lb.prototype,"updateSendParameters",[Eb],Object.getOwnPropertyDescriptor(lb.prototype,"updateSendParameters"),lb.prototype),ZT(lb.prototype,"replaceTrack",[Eb],Object.getOwnPropertyDescriptor(lb.prototype,"replaceTrack"),lb.prototype),ZT(lb.prototype,"getRemoteSSRC",[Eb],Object.getOwnPropertyDescriptor(lb.prototype,"getRemoteSSRC"),lb.prototype),lb);function Eb(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 mb="9",fb=4e4;class Sb{get localCapabilities(){return ev(this._localCapabilities)}get rtpCapabilities(){return ev(this._rtpCapabilities)}get candidates(){return ev(this._candidates)}get iceParameters(){return ev(this._iceParameters)}get dtlsParameters(){return ev(this._dtlsParameters)}constructor(e){_p(this,"sessionDesc",void 0),_p(this,"_localCapabilities",void 0),_p(this,"_rtpCapabilities",void 0),_p(this,"_candidates",void 0),_p(this,"_iceParameters",void 0),_p(this,"_dtlsParameters",void 0),_p(this,"setup",void 0),_p(this,"currentMidIndex",void 0),_p(this,"cname",void 0),_p(this,"firefoxSsrcMidMap",new Map),e=ev(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,remoteSetup:o,localCapabilities:s,cname:a}=e,c=AO.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.
6icePwd,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,GE("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=LO([{ssrcId:fb,rtx:GE("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,WO(e),GE("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=LO([{ssrcId:2e4}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}}this.sessionDesc=c,this.currentMidIndex=c.mediaDescriptions.length-1}preloadRemoteMedia(){const e=GE("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+fb,{ssrcs:a,ssrcGroups:c}=LO([{ssrcId:e}],this.cname),{ssrcs:d,ssrcGroups:u}=LO([{ssrcId:s,rtx:GE("USE_RTX")?s+1:void 0}],this.cname);this.sessionDesc.mediaDescriptions.push({media:{mediaType:"video",port:mb,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:mb,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 AO.exports.print(this.sessionDesc)}send(e,t,i,n){const{ssrcs:r,ssrcGroups:o}=LO(t,this.cname,GE("SYNC_GROUP")?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()||Xh())||zh()?(i=this.createOrRecycleSendMedia(e,r,o,"sendonly",n),this.updateBundleMids()):(i=ev(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()||zh()?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.");
6t.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=ev(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===CS.VIDEO){var u,l;if(GE("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"])===GE("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(GE("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)OE.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&&(OE.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===CS.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const p="".concat(this.currentMidIndex);let _={media:{mediaType:s,port:mb,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===CS.VIDEO?o.videoCodecs:o.audioCodecs,a=e===CS.VIDEO?o.videoExtensions:o.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:mb,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=ev(e);return MO(n),kO(n,t),UO(n,t),xO(n),VO(n,i,this.localCapabilities.send),n}mungSendMediaDesc(e,t){const i=ev(e);return VO(i,t,this.localCapabilities.recv),WO(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 Tb;function gb(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 Rb(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
6t%2?gb(Object(i),!0).forEach((function(t){_p(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):gb(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let Ib=(ZT((Tb=class e extends xS{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),_p(this,"store",void 0),_p(this,"peerConnection",void 0),_p(this,"remoteSDP",void 0),_p(this,"initialOffer",void 0),_p(this,"transportEventReceiver",void 0),_p(this,"statsFilter",void 0),_p(this,"useRTX",GE("USE_RTX")),_p(this,"localCapabilities",void 0),_p(this,"localCandidateCount",0),_p(this,"allCandidatesReceived",!1),_p(this,"establishPromise",void 0),_p(this,"mutex",new Og("P2PConnection-mutex")),this.store=i,this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.statsFilter=ub(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=NO(e.sdp),i=await jO(!this.useRTX,GE("FILTER_VIDEO_FEC"),GE("FILTER_AUDIO_FEC"));return this.localCapabilities=GO(i),this.initialOffer=e,Rb(Rb({},t),{},{rtpCapabilities:i,offerSDP:e.sdp})}catch(e){throw new SE(fE.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.");
6this.remoteSDP=new Sb({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:n,remoteSetup:r,localCapabilities:this.localCapabilities,cname:o});const s=this.remoteSDP.toString(),a=AO.exports.parse(this.initialOffer.sdp),c=a.mediaDescriptions.find(e=>"audio"===e.media.mediaType);c&&WO(c);const d=AO.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),GE("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 SE(fE.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}send(e,t,i){var n=this;return RO((function*(){const r=yield IO(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===GE("SIMULCAST")&&(yield IO(n.applySimulcastForFirefox(o,e)));const s=yield IO(n.peerConnection.createOffer()),a=n.remoteSDP.predictReceivingMids(e.length),c=n.mungSendOfferSDP(s.sdp,e,a),d=AO.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 DO(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 IO(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield IO(n.peerConnection.setRemoteDescription({type:"answer",sdp:o})),yield IO(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 IO(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield IO(n.applySimulcastEncodings(o,e)),yield IO(n.applySendEncodings(o,e)),null==p||p(h),yield IO(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 SE?e:new SE(fE.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 SE(fE.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}),OE.debug("[P2PConnection] receive ".concat(e," by exchanging SDP."))}else OE.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 SE(fE.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),OE.debug("[P2PConnection] batchReceive by exchanging SDP.")}else OE.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 SE(fE.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 SE(fE.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 SE(fE.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 SE(fE.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=>
6t.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 SE(fE.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 SE(fE.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(){var e=this;return RO((function*(){const t=yield IO(e.mutex.lock("From P2PConnection.restartICE"));try{const i=yield IO(e.peerConnection.createOffer({iceRestart:!0}));if(!i.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const n=NO(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 IO(e.peerConnection.setLocalDescription(i)),null==s||s(o),yield IO(e.peerConnection.setRemoteDescription({type:"answer",sdp:o}))}catch(e){OE.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 SE(fE.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,OE.debug("[pc-".concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,OE.debug("[pc-".concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))},GE("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&&(Uf(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),GE("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),GE("FORCE_TURN_TCP")?i.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEac
6h(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(OI(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!GE("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;const i=null===(t=e.transport)||void 0===t?void 0:t.iceTransport.state;var n;i&&(null===(n=this.onICETransportStateChange)||void 0===n||n.call(this,i))}))}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(!FS().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 py){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(lS.LOW_STREAM))null!==(o=u._encoderConfig)&&void 0!==o&&o.frameRate&&(t.maxFramerate=wI(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(GE("DSCP_TYPE")&&rp()){const e=GE("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){OE.debug("Apply RTPSendEncodings failed.")}}mungSendOfferSDP(e,t,i){const n=AO.exports.parse(e);return t.forEach((e,t)=>{const r=i[t],o=n.mediaDescriptions.find(e=>e.attributes.mid===r);o&&(kO(o,e),FO(o,e,this.store.codec))}),AO.exports.print(n)}mungReceiveAnswerSDP(e,t,i){const n=AO.exports.parse(e),r=n.mediaDescriptions.find(e=>e.attributes.mid===t);return r&&i===CS.AUDIO&&"audio"===r.media.mediaType&&WO(r),AO.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 py&&!c._hints.includes(lS.LOW_STREAM)&&null!==(i=c._encoderConfig)&&void 0!==i&&i.bitrateMax&&(null===(n=c._encoderConfig)||void 0===n?void 0:n.bitrateMax)>
vendor: 8,564 bytes, line 6
6200&&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 py&&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 py&&GE("SIMULCAST")&&"vp8"===this.store.codec&&!e._hints.includes(lS.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(GE("SDP_LOGGING"))return OE.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(FS().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}}}).prototype,"connect",[vb],Object.getOwnPropertyDescriptor(Tb.prototype,"connect"),Tb.prototype),ZT(Tb.prototype,"receive",[vb],Object.getOwnPropertyDescriptor(Tb.prototype,"receive"),Tb.prototype),ZT(Tb.prototype,"batchReceive",[vb],Object.getOwnPropertyDescriptor(Tb.prototype,"batchReceive"),Tb.prototype),ZT(Tb.prototype,"stopReceiving",[vb],Object.getOwnPropertyDescriptor(Tb.prototype,"stopReceiving"),Tb.prototype),ZT(Tb.prototype,"muteRemote",[vb],Object.getOwnPropertyDescriptor(Tb.prototype,"muteRemote"),Tb.prototype),ZT(Tb.prototype,"unmuteRemote",[vb],Object.getOwnPropertyDescriptor(Tb.prototype,"unmuteRemote"),Tb.prototype),ZT(Tb.prototype,"muteLocal",[vb],Object.getOwnPropertyDescriptor(Tb.prototype,"muteLocal"),Tb.prototype),ZT(Tb.prototype,"unmuteLocal",[vb],Object.getOwnPropertyDescriptor(Tb.prototype,"unmuteLocal"),Tb.prototype),ZT(Tb.prototype,"close",[vb],Object.getOwnPropertyDescriptor(Tb.prototype,"close"),Tb.prototype),ZT(Tb.prototype,"updateEncoderConfig",[vb],Object.getOwnPropertyDescriptor(Tb.prototype,"updateEncoderConfig"),Tb.prototype),ZT(Tb.prototype,"updateSendParameters",[vb],Object.getOwnPropertyDescriptor(Tb.prototype,"updateSendParameters"),Tb.prototype),ZT(Tb.prototype,"replaceTrack",[vb],Object.getOwnPropertyDescriptor(Tb.prototype,"replaceTrack"),Tb.prototype),ZT(Tb.prototype,"getRemoteSSRC",[vb],Object.getOwnPropertyDescriptor(Tb.prototype,"getRemoteSSRC"),Tb.prototype),Tb);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 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=wI(t.width),n.height=wI(t.height);const r=wI(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 SE(fE.UNEXPECTED_ERROR,"can not get canvas context");const a=FS(),c=n.captureStream(a.supportRequestFrame?0:r).getVideoTracks()[0],d=Fg(()=>(()=>{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&&(OE.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),OE.debug("clean low stream renderer")},c}var yb,Ab,Ob,bb,wb,Nb,Db,Pb,Lb,kb,Mb,Ub;function xb(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 Vb(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?xb(Object(i),!0).forEach((function(t){_p(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):xb(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class Fb extends Cg{getUserId(){return this._userId}constructor(e,t,i,n){super(e,"track-".concat(e.kind,"-").concat(t,"-").concat(n.clientId,"_").concat(GI(5,""))),_p(this,"_userId",void 0),_p(this,"_uintId",void 0),_p(this,"_isDestroyed",!1),_p(this,"store",void 0),_p(this,"processor",void 0),_p(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,OE.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}let jb=(yb=Ig({argsMap:(e,t,i)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),Ab=Ig({argsMap:e=>[e.getTrackId()]}),Ob=Ig({argsMap:(e,t)=>[e.getTrackId(),t.name]}),bb=Ig({argsMap:e=>[e.getTrackId()]}),ZT((wb=class extends Fb{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==sf.PLAYING)}get __className__(){return"RemoteVideoTrack"}constructor(e,t,i,n){super(e,t,i,n),_p(this,"_videoVisibleTimer",null),_p(this,"_previousVideoVisibleStatus",void 0),_p(this,"_clearPreviousVideoVisibleStatus",()=>this._previousVideoVisibleStatus=void 0),_p(this,"trackMediaType","video"),_p(this,"_videoWidth",void 0),_p(this,"_videoHeight",void 0),_p(this,"_player",void 0),_p(this,"processorDestination",void 0),_p(this,"processorContext",void 0),this.updateMediaStreamTrackResolution(),this.processorContext=new fR(this.getTrackId(),"remote"),this.processorDestination=new mR(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){iv(()=>{OE.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")},"remoteVideoTrackGetStatsWarning");return XI(this,uS.GET_STATS)||Vb({},Wf)}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:(OE.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}OE.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const i=Vb(Vb({fit:"cover"},t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(i):(e instanceof HTMLVideoElement?this._player=new IC(i):this._player=new CC(i),this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.emit(ES.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();
6this.emit(ES.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}},GE("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,OE.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){KI(this._originMediaStreamTrack).then(e=>{let[t,i]=e;this._videoHeight=i,this._videoWidth=t}).catch(HI)}_updatePlayerSource(){OE.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=uy.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=vg.reportApiInvoke(null,{tag:Ef.TRACER,name:_f.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 SE(fE.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}pipe(e){if(this.processor===e)return e;if(e._source)throw new SE(fE.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(NS.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(NS.ON_TRACK)}_destroy(){super._destroy(),this.unbindProcessorDestinationEvents()}}).prototype,"play",[yb],Object.getOwnPropertyDescriptor(wb.prototype,"play"),wb.prototype),ZT(wb.prototype,"stop",[Ab],Object.getOwnPropertyDescriptor(wb.prototype,"stop"),wb.prototype),ZT(wb.prototype,"pipe",[Ob],Object.getOwnPropertyDescriptor(wb.prototype,"pipe"),wb.prototype),ZT(wb.prototype,"unpipe",[bb],Object.getOwnPropertyDescriptor(wb.prototype,"unpipe"),wb.prototype),wb),Bb=(Nb=Ig({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),Db=Ig({argsMap:(e,t)=>[e.getTrackId(),t]}),Pb=Ig({argsMap:e=>[e.getTrackId()]}),Lb=Ig({argsMap:e=>[e.getTrackId()]}),kb=Ig({argsMap:(e,t)=>[e.getTrackId(),t.name]}
vendor: 5,292 bytes, line 6
6),Mb=Ig({argsMap:e=>[e.getTrackId()]}),ZT((Ub=class extends Fb{get isPlaying(){return this._useAudioElement?rR.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}constructor(e,t,i,n){super(e,t,i,n),_p(this,"trackMediaType","audio"),_p(this,"_source",void 0),_p(this,"_useAudioElement",!0),_p(this,"_volume",100),_p(this,"processorContext",void 0),_p(this,"processorDestination",void 0),_p(this,"_played",!1),_p(this,"_bypassWebAudio",!1),GE("DISABLE_WEBAUDIO")?(this._source=new gR,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new Gg(e,!0),GE("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once(Lf.RECEIVE_TRACK_BUFFER,()=>{this.emit(ES.FIRST_FRAME_DECODED)}),this.processorContext=new TR(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new SR(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(Lf.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(Lf.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(Lf.ON_AUDIO_BUFFER),this._source.on(Lf.ON_AUDIO_BUFFER,t=>e(t))}setVolume(e){this._volume=e,this._useAudioElement?rR.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement)throw new SE(fE.NOT_SUPPORTED,"your browser does not support setting the audio output device");await rR.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getStats(){iv(()=>{OE.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")},"remoteAudioTrackGetStatsWarning");return XI(this,uS.GET_STATS)||Vb({},Bf)}play(){OE.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement?(OE.debug("[".concat(this.getTrackId(),"] use audio element to play")),rR.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):this._source.play()}stop(){OE.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?rR.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];OE.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&rR.updateTrack(this.getTrackId(),this._mediaStreamTrack)}pipe(e){if(this._bypassWebAudio)throw new SE(fE.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new SE(fE.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 SE(fE.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(NS.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(NS.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(NS.ON_TRACK),this.processorDestination.removeAllListeners(NS.ON_NODE)}}).prototype,"setVolume",[Nb],Object.getOwnPropertyDescriptor(Ub.prototype,"setVolume"),Ub.prototype),ZT(Ub.prototype,"setPlaybackDevice",[Db],Object.getOwnPropertyDescriptor(Ub.prototype,"setPlaybackDevice"),Ub.prototype),ZT(Ub.prototype,"play",[Pb],Object.getOwnPropertyDescriptor(Ub.prototype,"play"),Ub.prototype),ZT(Ub.prototype,"stop",[Lb],Object.getOwnPropertyDescriptor(Ub.prototype,"stop"),Ub.prototype),ZT(Ub.prototype,"pipe",[kb],Object.getOwnPropertyDescriptor(Ub.prototype,"pipe"),Ub.prototype),ZT(Ub.prototype,"unpipe",[Mb],Object.getOwnPropertyDescriptor(Ub.prototype,"unpipe"),Ub.prototype),Ub);function Gb(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 Wb(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
6t%2?Gb(Object(i),!0).forEach((function(t){_p(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Gb(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}class Hb extends EE{constructor(){super(),_p(this,"uplinkStatsUploadInterval",void 0),_p(this,"uplinkStatsUploadSlowInterval",void 0),_p(this,"uplinkRelatedStatsUploadInterval",void 0),_p(this,"uplinkDenoiserStatsUploadInterval",void 0),_p(this,"transportStatsUploadInterval",void 0),_p(this,"uplinkExtensionStatsUploadInterval",void 0),_p(this,"downlinkExtensionStatsUploadInterval",void 0),_p(this,"extensionUsageStatsUploadInterval",void 0),_p(this,"downlinkStatsUploadInterval",void 0),_p(this,"downlinkStatsUploadSlowInterval",void 0),_p(this,"downlinkRelatedStatsUploadInterval",void 0),_p(this,"lastStats",void 0),_p(this,"uploadUnplinkStarted",!1),_p(this,"uploadDownlinkStarted",!1),_p(this,"uploadTransportStarted",!1),_p(this,"uploadExtensionUsageStarted",!1),_p(this,"requestStats",void 0),_p(this,"requestLocalMedia",void 0),_p(this,"requestRemoteMedia",void 0),_p(this,"requestAllTracks",void 0),_p(this,"requestVideoIsReady",void 0),_p(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)},1e3))}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:GE("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(CS.VIDEO)&&e.videoTrack&&(s=s.concat(await e.videoTrack.getProcessorUsage())),t.has(CS.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+GE("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,Nf.EXTENSION_USAGE_STATS,{usageStats:o,sendTs:u})},GE("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){$I(()=>{var t;null===(t=this.requestUpload)||void 0===t||t.call(this,Nf.TRANSPORT_STATS,function(e){const t={connectionType:100,googRtt:e.rtt};
6if("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 yS.LocalVideoLowTrack:case yS.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:GI(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=af[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===yS.LocalVideoTrack?DI(r[0].ssrcId,e,n):null;t&&$I(()=>{var e;return null===(e=this.requestUpload)||void 0===e?void 0:e.call(this,Nf.PUBLISH_STATS,{stream_type:i===yS.LocalVideoLowTrack?"low":"high",stats:Wb(Wb({},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,Nf.PUBLISH_STATS,{stream_type:i===yS.LocalVideoLowTrack?"low":"high",stats:s})},1e3);break}case yS.LocalAudioTrack:{const t=function(e,t,i){const n=t.audioSend.find(t=>t.ssrc===e);if(!n)return null;const r={id:GI(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&&$I(()=>{var e;return null===(e=this.requestUpload)||void 0===e?void 0:e.call(this,Nf.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===yS.LocalVideoLowTrack||t===yS.LocalVideoTrack}).forEach(t=>{let[i,{ssrcs:n}]=t;const r=DI(n[0].ssrcId,e);r&&$I(()=>{var e;return null===(e=this.requestUpload)||void 0===e?void 0:e.call(this,Nf.PUBLISH_STATS,{stream_type:i===yS.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===yS.LocalVideoLowTrack||t===yS.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&&$I(()=>{var e;null===(e=this.requestUpload)||void 0===e||e.call(this,Nf.PUBLISH_RELATED_STATS,{stream_type:i===yS.LocalVideoLowTrack?"low":"high",stats:r})})})}uploadDenoiserStats(e){for(let r=0;r<e.length;r++){const o=e[r];if(o instanceof EI){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,Nf.DENOISER_STATS,e)))}}}uploadExtensionStats(e){for(let t=0;t<e.length;
6t++){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(CS.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:GI(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"===CI.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=af[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&&$I(()=>{var e;return null===(e=this.requestUpload)||void 0===e?void 0:e.call(this,Nf.SUBSCRIBE_STATS,{stream_id:r.uid,stats:n})})}if(o.has(CS.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:GI(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=af[rR.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&&$I(()=>{var e;return null===(e=this.requestUpload)||void 0===e?void 0:e.call(this,Nf.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))||[]).forEac
6h(i=>{let[n,r]=i;if(r.has(CS.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=vI.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&&$I(()=>{var e;null===(e=this.requestUpload)||void 0===e||e.call(this,Nf.SUBSCRIBE_RELATED_STATS,{stream_id:n.uid,stats:r})})}if(r.has(CS.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=vI.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&&$I(()=>{var e;null===(e=this.requestUpload)||void 0===e||e.call(this,Nf.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(CS.VIDEO)&&t.videoTrack){t.videoTrack.getProcessorStats().forEac
6h(e=>{var t;null===(t=this.requestUpload)||void 0===t||t.call(this,e.type,e.stats)})}if(i.has(CS.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 Kb="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",Yb="9",qb=2e4,Jb=4e4;class Xb{get localCapabilities(){return ev(this._localCapabilities)}get rtpCapabilities(){return ev(this._rtpCapabilities)}get candidates(){return ev(this._candidates)}get iceParameters(){return ev(this._iceParameters)}get dtlsParameters(){return ev(this._dtlsParameters)}constructor(e){_p(this,"sessionDesc",void 0),_p(this,"_localCapabilities",void 0),_p(this,"_rtpCapabilities",void 0),_p(this,"_candidates",void 0),_p(this,"_iceParameters",void 0),_p(this,"_dtlsParameters",void 0),_p(this,"setup",void 0),_p(this,"currentMidIndex",void 0),_p(this,"cname",void 0),_p(this,"firefoxSsrcMidMap",new Map),e=ev(e);const{remoteIceParameters:t,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,remoteSetup:o,localCapabilities:s,cname:a}=e,c=AO.exports.parse(Kb);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,GE("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=LO([{ssrcId:Jb,rtx:GE("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,WO(e),GE("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=LO([{ssrcId:qb}],this.cname);e.attributes.ssrcs=t,e.attributes.ssrcGroups=i}}this.sessionDesc=c,this.currentMidIndex=c.mediaDescriptions.length-1}
6updateRemoteRTPCapabilities(e){const t=AO.exports.parse(Kb);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,GE("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=LO([{ssrcId:Jb,rtx:GE("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,GE("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:t,ssrcGroups:i}=LO([{ssrcId:qb}],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+qb,s=2*o+Jb,{ssrcs:a,ssrcGroups:c}=LO([{ssrcId:e}],this.cname),{ssrcs:d,ssrcGroups:u}=LO([{ssrcId:s,rtx:GE("USE_RTX")?s+1:void 0}],this.cname);this.sessionDesc.mediaDescriptions.push({media:{mediaType:"video",port:Yb,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:Yb,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 AO.exports.print(this.sessionDesc)}send(e,t,i,n){const{ssrcs:r,ssrcGroups:o}=LO(t,this.cname,GE("SYNC_GROUP")?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()||Xh()?(i=this.createOrRecycleSendMedia(e,r,o,"sendonly",n),this.updateBundleMids()):(i=ev(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.");
6t.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=ev(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===CS.VIDEO){var u,l;if(GE("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"])===GE("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(GE("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)OE.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&&(OE.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===CS.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const p="".concat(this.currentMidIndex);let _={media:{mediaType:s,port:Yb,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===CS.VIDEO?o.videoCodecs:o.audioCodecs,a=e===CS.VIDEO?o.videoExtensions:o.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:Yb,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=ev(e);return MO(n),kO(n,t),UO(n,t),xO(n),VO(n,i,this.localCapabilities.send),n}mungSendMediaDesc(e,t){const i=ev(e);return VO(i,t,this.localCapabilities.recv),WO(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 zb;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]:{};
6t%2?Qb(Object(i),!0).forEach((function(t){_p(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}let $b=(ZT((zb=class e extends xS{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),_p(this,"store",void 0),_p(this,"peerConnection",void 0),_p(this,"remoteSDP",void 0),_p(this,"initialOffer",void 0),_p(this,"transportEventReceiver",void 0),_p(this,"statsFilter",void 0),_p(this,"useRTX",GE("USE_RTX")),_p(this,"localCapabilities",void 0),_p(this,"localCandidateCount",0),_p(this,"allCandidatesReceived",!1),_p(this,"establishPromise",void 0),_p(this,"mutex",new Og("NVExtentionsConnection-mutex")),_p(this,"rtcMedia",void 0),this.store=t,this.peerConnection=i,this.statsFilter=ub(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=NO(e.sdp),i=await jO(!this.useRTX,GE("FILTER_VIDEO_FEC"),GE("FILTER_AUDIO_FEC"));return this.localCapabilities=i,this.initialOffer=e,Zb(Zb({},t),{},{rtpCapabilities:i,offerSDP:e.sdp})}catch(e){throw new SE(fE.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 Xb({remoteIceParameters:e,remoteDtlsParameters:t,candidates:i,remoteRTPCapabilities:n,remoteSetup:r,localCapabilities:GO(this.localCapabilities),cname:o});const s=this.remoteSDP.toString(),a=AO.exports.parse(this.initialOffer.sdp),c=a.mediaDescriptions.find(e=>"audio"===e.media.mediaType);c&&WO(c);const d=AO.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 SE(fE.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),OE.debug("[NVExtentionsConnection] updateRemoteRTPCapabilities by exchanging SDP.")}send(e,t,i){var n=this;return RO((function*(){const r=yield IO(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===GE("SIMULCAST")&&(yield IO(n.applySimulcastForFirefox(o,e)));const s=yield IO(n.peerConnection.createOffer()),a=n.remoteSDP.predictReceivingMids(e.length),c=n.mungSendOfferSDP(s.sdp,e,a),d=AO.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 DO(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 IO(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield IO(n.peerConnection.setRemoteDescription({type:"answer",sdp:o})),yield IO(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 IO(n.peerConnection.setLocalDescription({type:"offer",sdp:c})),yield IO(n.applySimulcastEncodings(o,e)),yield IO(n.applySendEncodings(o,e)),null==p||p(h),yield IO(n.peerConnection.setRemoteDescription({type:"answer",sdp:h})),o.map((e,t)=>{const i=a[t];return{localSSRC:u[t],id:i,transceiver:e}})}
6catch(e){throw e instanceof SE?e:new SE(fE.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 SE(fE.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}),OE.debug("[NVExtentionsConnection] receive ".concat(e," by exchanging SDP."))}else OE.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 SE(fE.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),OE.debug("[NVExtentionsConnection] batchReceive by exchanging SDP.")}else OE.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 SE(fE.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 SE(fE.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 SE(fE.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 SE(fE.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=>
6t.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 SE(fE.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 SE(fE.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(){var e=this;return RO((function*(){const t=yield IO(e.mutex.lock("From NVExtentionsConnection.restartICE"));try{const i=yield IO(e.peerConnection.createOffer({iceRestart:!0}));if(!i.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const n=NO(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 IO(e.peerConnection.setLocalDescription(i)),null==s||s(o),yield IO(e.peerConnection.setRemoteDescription({type:"answer",sdp:o}))}catch(e){OE.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 SE(fE.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 Zb(Zb({},NO(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,OE.debug("[pc-".concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,OE.debug("[pc-".concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))},GE("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&&(Uf(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),GE("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),GE("FORCE_TURN_TCP")?i.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEac
6h(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(OI(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!GE("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(!FS().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 py){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(lS.LOW_STREAM))null!==(o=u._encoderConfig)&&void 0!==o&&o.frameRate&&(t.maxFramerate=wI(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(GE("DSCP_TYPE")&&rp()){const e=GE("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){OE.debug("Apply RTPSendEncodings failed.")}}mungSendOfferSDP(e,t,i){const n=AO.exports.parse(e);return t.forEach((e,t)=>{const r=i[t],o=n.mediaDescriptions.find(e=>e.attributes.mid===r);o&&(kO(o,e),FO(o,e,this.store.codec))}),AO.exports.print(n)}mungReceiveAnswerSDP(e,t,i){const n=AO.exports.parse(e),r=n.mediaDescriptions.find(e=>e.attributes.mid===t);return r&&i===CS.AUDIO&&"audio"===r.media.mediaType&&WO(r),AO.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 py&&!c._hints.includes(lS.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 py&&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 py&&GE("SIMULCAST")&&"vp8"===this.store.codec&&
vendor: 4,264 bytes, line 6
6!e._hints.includes(lS.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(GE("SDP_LOGGING"))return OE.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(FS().supportPCSetConfiguration){const i=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(i)}}}).prototype,"connect",[ew],Object.getOwnPropertyDescriptor(zb.prototype,"connect"),zb.prototype),ZT(zb.prototype,"updateRemoteConnect",[ew],Object.getOwnPropertyDescriptor(zb.prototype,"updateRemoteConnect"),zb.prototype),ZT(zb.prototype,"receive",[ew],Object.getOwnPropertyDescriptor(zb.prototype,"receive"),zb.prototype),ZT(zb.prototype,"batchReceive",[ew],Object.getOwnPropertyDescriptor(zb.prototype,"batchReceive"),zb.prototype),ZT(zb.prototype,"stopReceiving",[ew],Object.getOwnPropertyDescriptor(zb.prototype,"stopReceiving"),zb.prototype),ZT(zb.prototype,"muteRemote",[ew],Object.getOwnPropertyDescriptor(zb.prototype,"muteRemote"),zb.prototype),ZT(zb.prototype,"unmuteRemote",[ew],Object.getOwnPropertyDescriptor(zb.prototype,"unmuteRemote"),zb.prototype),ZT(zb.prototype,"muteLocal",[ew],Object.getOwnPropertyDescriptor(zb.prototype,"muteLocal"),zb.prototype),ZT(zb.prototype,"unmuteLocal",[ew],Object.getOwnPropertyDescriptor(zb.prototype,"unmuteLocal"),zb.prototype),ZT(zb.prototype,"close",[ew],Object.getOwnPropertyDescriptor(zb.prototype,"close"),zb.prototype),ZT(zb.prototype,"updateEncoderConfig",[ew],Object.getOwnPropertyDescriptor(zb.prototype,"updateEncoderConfig"),zb.prototype),ZT(zb.prototype,"updateSendParameters",[ew],Object.getOwnPropertyDescriptor(zb.prototype,"updateSendParameters"),zb.prototype),ZT(zb.prototype,"replaceTrack",[ew],Object.getOwnPropertyDescriptor(zb.prototype,"replaceTrack"),zb.prototype),ZT(zb.prototype,"getRemoteSSRC",[ew],Object.getOwnPropertyDescriptor(zb.prototype,"getRemoteSSRC"),zb.prototype),zb);function ew(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 tw;function iw(e){var t,i,n,r=2;for("undefined"!=typeof Symbol&&(i=yO,n=Symbol.iterator);r--;){if(i&&null!=(t=e[i]))return t.call(e);if(n&&null!=(t=e[n]))return new nw(t.call(e));i="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function nw(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(nw=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 nw(e)}let rw=(ZT((tw=class e extends xS{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),_p(this,"store",void 0),_p(this,"peerConnection",void 0),_p(this,"cname",void 0),_p(this,"mutex",new Og("DataChannelConnection-mutex")),_p(this,"dataChannel",void 0),_p(this,"_p2pConnection",void 0),_p(this,"establishPromise",void 0),_p(this,"_nvMedia",void 0),this.store=i,this.store.dcId=this.store.dcId+1,this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}
vendor: 8,618 bytes, line 6
6),this.dataChannel=this.peerConnection.createDataChannel("agora-signal",{ordered:!1,maxPacketLifeTime:50}),this.dataChannel.binaryType="arraybuffer",this._p2pConnection=new $b(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 SE(fE.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 RO((function*(){const r=yield IO(n.mutex.lock("From DataChannelConnection.send"));try{return yield*CO(iw(n._p2pConnection.send(e,t,i)),IO)}finally{r()}}))()}async stopSending(e,t){return this._p2pConnection.stopSending(e,t)}async receive(e,t,i,n){return this._nvMedia?(OE.debug("[DataChannelConnection] receive ".concat(e," by DataChannel.")),await this._nvMedia.reveiveByRTCMedia(e,t,this.cname)):(OE.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 RO((function*(){return yield*CO(iw(e._p2pConnection.restartICE()),IO)}))()}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(GE("SDP_LOGGING"))return OE.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&&(Uf(t.turnServer.servers)?i.iceServers=t.turnServer.servers:(i.iceServers&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),GE("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&t.turnServer.serversFromGateway&&i.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),GE("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(OI(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!GE("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",[ow],Object.getOwnPropertyDescriptor(tw.prototype,"connect"),tw.prototype),ZT(tw.prototype,"receive",[ow],Object.getOwnPropertyDescriptor(tw.prototype,"receive"),tw.prototype),ZT(tw.prototype,"stopReceiving",[ow],Object.getOwnPropertyDescriptor(tw.prototype,"stopReceiving"),tw.prototype),ZT(tw.prototype,"muteRemote",[ow],Object.getOwnPropertyDescriptor(tw.prototype,"muteRemote"),tw.prototype),ZT(tw.prototype,"unmuteRemote",[ow],Object.getOwnPropertyDescriptor(tw.prototype,"unmuteRemote"),tw.prototype),ZT(tw.prototype,"muteLocal",[ow],Object.getOwnPropertyDescriptor(tw.prototype,"muteLocal"),tw.prototype),ZT(tw.prototype,"unmuteLocal",[ow],Object.getOwnPropertyDescriptor(tw.prototype,"unmuteLocal"),tw.prototype),ZT(tw.prototype,"close",[ow],Object.getOwnPropertyDescriptor(tw.prototype,"close"),tw.prototype),ZT(tw.prototype,"updateEncoderConfig",[ow],Object.getOwnPropertyDescriptor(tw.prototype,"updateEncoderConfig"),tw.prototype),ZT(tw.prototype,"updateSendParameters",[ow],Object.getOwnPropertyDescriptor(tw.prototype,"updateSendParameters"),tw.prototype),ZT(tw.prototype,"replaceTrack",[ow],Object.getOwnPropertyDescriptor(tw.prototype,"replaceTrack"),tw.prototype),ZT(tw.prototype,"getRemoteSSRC",[ow],Object.getOwnPropertyDescriptor(tw.prototype,"getRemoteSSRC"),tw.prototype),tw);function ow(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 sw;function aw(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 cw(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
6t%2?aw(Object(i),!0).forEach((function(t){_p(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):aw(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function dw(e){var t,i,n,r=2;for("undefined"!=typeof Symbol&&(i=yO,n=Symbol.iterator);r--;){if(i&&null!=(t=e[i]))return t.call(e);if(n&&null!=(t=e[n]))return new uw(t.call(e));i="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function uw(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(uw=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 uw(e)}let lw=(ZT((sw=class extends EE{get state(){return this._state}set state(e){const t=this._state;this._state=e,this.emit(OS.StateChange,t,this._state)}constructor(e,t){super(),_p(this,"store",void 0),_p(this,"statsUploader",void 0),_p(this,"connection",void 0),_p(this,"localTrackMap",new Map),_p(this,"remoteUserMap",new Map),_p(this,"pendingLocalTracks",[]),_p(this,"pendingRemoteTracks",[]),_p(this,"statsCollector",void 0),_p(this,"isPlanB",!1),_p(this,"shouldForwardP2PCreation",void 0),_p(this,"iceFailedCount",0),_p(this,"dtlsFailedCount",0),_p(this,"mutex",new Og("P2PChannel-mutex")),_p(this,"_state",AS.Disconnected),_p(this,"handleMuteLocalTrack",async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleMuteLocalTrack");try{if(!this.connection||this.state!==AS.Connected)return void i(new SE(fE.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 JI(this,OS.RequestMuteLocal,s),t()}catch(e){i(e)}finally{n()}}),_p(this,"handleUnmuteLocalTrack",async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleUnmuteLocalTrack");try{if(!this.connection||this.state!==AS.Connected)return void i(new SE(fE.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(),FS().supportDualStreamEncoding){const i=e._mediaStreamTrack.clone();t.track._mediaStreamTrack=i,t.track._originMediaStreamTrack=i}else{const i=Cb(e,zI(this,OS.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 JI(this,OS.RequestUnmuteLocal,s),t()}catch(e){i(e)}finally{n()}}),_p(this,"handleUpdateVideoEncoder",async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleSetVideoEncoder");try{const i=this.localTrackMap.get(yS.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==AS.Connected)return void t();const{id:r,track:o}=i;await this.connection.updateSendParameters(r,o),await this.connection.updateEncoderConfig(r,o),this.emit(OS.UpdateVideoEncoder,o),t()}catch(e){i(e)}finally{n()}}),_p(this,"handleSetOptimizationMode",async(e,t,i)=>{const n=await this.mutex.lock("Locking from P2PChannel.handleSetOptimizationMode");try{const i=this.localTrackMap.get(yS.LocalVideoTrack);if(!this.connection||!i||i.track!==e||this.state!==AS.Connected)return;const{id:r,track:o}=i;await this.connection.updateSendParameters(r,o),t()}catch(e){i(e)}finally{n()}}),_p(this,"handleReplaceTrack",async(e,t,i,n)=>{let r;OE.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!==AS.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]===yS.LocalVideoTrack&&FS().supportDualStreamEncoding){const t=this.localTrackMap.get(yS.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()}}),_p(this,"handleGetLocalVideoStats",e=>{e(this.statsCollector.getLocalVideoTrackStats())}),_p(this,"handleGetLocalAudioStats",e=>{e(this.statsCollector.getLocalAudioTrackStats())}),_p(this,"handleGetRemoteVideoStats",e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid]),_p(this,"handleGetRemoteAudioStats",e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid]),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new Hb,this.bindStatsUploaderEvents(),this.isPlanB=!FS().supportUnifiedPlan||GE("CHROME_FORCE_PLAN_B")&&rp(),this.shouldForwardP2PCreation=GE("FORWARD_P2P_CREATION")&&FS().supportPCSetConfiguration,this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new rw({},this.store):this.isPlanB?new _b({},this.store):new Ib({},this.store),this.bindConnectionEvents(this.connection))}async startP2PConnection(e,t){if(this.state=AS.New,this.shouldForwardP2PCreation||(this.connection=this.store.useDataChannel?new rw(e,this.store):this.isPlanB?new _b(e,this.store):new Ib(e,this.store),this.bindConnectionEvents(this.connection)),!this.connection)throw new SE(fE.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 SE(fE.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");this.connection instanceof rw?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=AS.Connected)}async preConnect(e,t,i,n,r,o){if(!this.connection)throw new SE(fE.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=AS.Connected,s}
6getEstablishParams(){if(this.connection instanceof rw)return this.connection.getP2PConnectionParams();throw new Error("Only DataChannelConnection needs to obtain establishParams")}publish(e,t,i){var n=this;return RO((function*(){const r=yield IO(n.mutex.lock("From P2PChannel.publish"));try{if(!n.connection||n.state!==AS.Connected){if(n.state===AS.Disconnected)throw new SE(fE.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,gI.markPublishStart(n.store.clientId,n.store.pubId);const o=n.filterTobePublishedTracks(e,t,i);if(0===o.length)return void(yield IO(n.tryToUnmuteAudio(e)));yield*CO(dw(n.doPublish(n.connection,o)),IO)}finally{r()}}))()}doPublish(e,t){var i=this;return RO((function*(){t.forEach(e=>{let{track:t,type:n}=e;const r=Date.now();i.store.publish(t.getTrackId(),n===yS.LocalAudioTrack?"audio":"video",r)}),i.bindLocalTrackEvents(t);const n=yield IO(e.send(t.map(e=>{let{track:t}=e;return t}),i.store.codec,i.store.audioCodec)),r=(yield IO(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)===fE.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 IO(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===yS.LocalAudioTrack?"audio":"video",void 0,r)})}))()}publishLowStream(e){var t=this;return RO((function*(){if(!t.connection||t.state!==AS.Connected)return;const i=yield IO(t.mutex.lock("Locking from P2PChannel.publishLowStream"));try{const r=t.localTrackMap.get(yS.LocalVideoTrack);if(!r)throw new SE(fE.UNEXPECTED_ERROR,"Could not find high stream");if(t.localTrackMap.has(yS.LocalVideoLowTrack))throw new SE(fE.UNEXPECTED_ERROR,"[".concat(t.store.clientId,"] Can't publish low stream when stream already publish"));const o=[{track:t.getLowVideoTrack(r.track,e),type:yS.LocalVideoLowTrack}];if(yield*CO(dw(t.doPublish(t.connection,o)),IO),r.track.muted||!r.track.enabled){var n;const e=null===(n=t.localTrackMap.get(yS.LocalVideoLowTrack))||void 0===n?void 0:n.id;void 0!==e&&(yield IO(t.connection.muteLocal([e])))}}finally{i()}}))()}async republish(){this.pendingLocalTracks.length>0&&(OE.debug("Emit P2PChannelEvents.RequestRePublish to republish tracks."),await qI(this,OS.RequestRePublish,this.pendingLocalTracks),this.emit(OS.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!==CS.AUDIO||t._audio_added_&&t._audioSSRC)&&(i!==CS.VIDEO||t._video_added_&&t._videoSSRC)||this.pendingRemoteTracks.splice(e,1)}if(e)await qI(this,OS.RequestReSubscribe,this.pendingRemoteTracks);else for(const{user:e,kind:t}of this.pendingRemoteTracks)await this.subscribe(e,t,t===CS.VIDEO?e._videoSSRC:e._audioSSRC);this.pendingRemoteTracks.forEach(e=>{let{user:t}=e;this.emit(OS.MediaReconnectEnd,t.uid)}),this.pendingRemoteTracks=[]}async unpublish(e){if(!this.connection||this.state!==AS.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!==AS.Connected)return;const e=this.localTrackMap.get(yS.LocalVideoLowTrack);if(!e)return;e.track.close();const t=[[yS.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}}
6)),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!==AS.Connected)throw new SE(fE.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 SE(fE.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===CS.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(s):(e._audioTrack=new Bb(s,e.uid,e._uintid,this.store),OE.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 jb(s,e.uid,e._uintid,this.store),OE.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(OS.MediaReconnectEnd,e.uid))}async massSubscribe(e){return this.massSubscribeNoLock(e)}async massSubscribeNoLock(e){if(!this.connection||this.state!==AS.Connected)throw new SE(fE.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===CS.AUDIO?(n._audioTrack?n._audioTrack._updateOriginMediaStreamTrack(o):(n._audioTrack=new Bb(o,n.uid,n._uintid,this.store),OE.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 jb(o,n.uid,n._uintid,this.store),OE.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(OS.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===AS.Connected||i||n.forEach(t=>{let{kind:i}=t;var n;if(i===CS.AUDIO)null===(n=e._audioTrack)||void 0===n||n._destroy(),e._audioTrack=void 0;else if(i===CS.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0}}),!this.connection||this.state!==AS.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
6=>{let[t,{kind:n}]=e;var r,o;n===CS.VIDEO&&t._videoSSRC&&(null===(r=this.connection)||void 0===r||r.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(n===CS.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),i||(null===(o=t._videoTrack)||void 0===o||o._destroy(),t._videoTrack=void 0);else if(n===CS.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!==AS.Connected)return void t.forEach(e=>{let{user:t,kind:i}=e;var n;if(i===CS.AUDIO)null===(n=t._audioTrack)||void 0===n||n._destroy(),t._audioTrack=void 0;else if(i===CS.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===CS.VIDEO&&t._videoSSRC&&(null===(n=this.connection)||void 0===n||n.setStatsRemoteVideoIsReady(t._videoSSRC,!1));if(i===CS.VIDEO)this.unbindRemoteTrackEvents(t._videoTrack),null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0;else if(i===CS.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 OE.warning("P2PChannel.muteRemote has no remote user ".concat(e.uid,"."));if(!i.get(t))return void OE.warning("P2PChannel.muteRemote has no remote user ".concat(e.uid," media type ").concat(t,"."));const n=t===CS.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 OE.warning("P2PChannel.unmuteRemote has no remote user ".concat(e.uid,"."));i.get(t)||OE.warning("P2PChannel.unmuteRemote has no remote user ".concat(e.uid," media type ").concat(t,"."))}getAllTracks(e){const t=this.localTrackMap.get(yS.LocalAudioTrack);if((null==t?void 0:t.track)instanceof fI){const i=t.track;return Array.from(this.localTrackMap.entries()).filter(e=>{let[t]=e;return t!==yS.LocalAudioTrack}).filter(t=>{let[i]=t;return!(e&&i===yS.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===yS.LocalVideoLowTrack)}).map(e=>{let[,{track:t}]=e;return t})}reportPublishEvent(e,t,i,n,r){if(e){const i=this.localTrackMap.get(yS.LocalAudioTrack),o=n?this.localTrackMap.get(yS.LocalVideoLowTrack):this.localTrackMap.get(yS.LocalVideoTrack);vg.publish(this.store.sessionId,{eventElapse:gI.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(lS.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 _I),a=n?null===(o=this.localTrackMap.get(yS.LocalVideoTrack))||void 0===o?void 0:o.track:i.find(e=>e instanceof py);vg.publish(this.store.sessionId,{eventElapse:gI.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(lS.SCREEN_TRACK)),audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,i,n){const r=n===CS.VIDEO?i._videoSSRC:i._audioSSRC;r&&vg.subscribe(this.store.sessionId,{succ:e,ec:t,video:n===CS.VIDEO,audio:n===CS.AUDIO,peerid:i.uid,subscribeRequestid:n===CS.VIDEO?i._videoSSRC:i._audioSSRC,p2pid:this.store.p2pId,eventElapse:gI.measureFromSubscribeStart(this.store.clientId,r)})}reset(){OE.debug("P2PChannel.reset"),this.mutex=new Og("P2PChannel-mutex"),this.connection&&(this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new rw({},this.store):this.isPlanB?new _b({},this.store):new Ib({},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=AS.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(yS.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(yS.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 py||t&&t.track instanceof _I?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(sg(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(yS.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=Hm(e).call(e,(e,t)=>e.level-t.level),e}async disconnectForReconnect(){this.connection&&(OE.debug("P2PChannel.disconnectForReconnect closing P2PConnection"),this.state=AS.Reconnecting,GE("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEac
6h(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 rw({},this.store):this.isPlanB?new _b({},this.store):new Ib({},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 yS.LocalVideoTrack:i._hints.includes(lS.LOW_STREAM)?i.close():this.pendingLocalTracks.push(i);break;case yS.LocalAudioTrack:i instanceof fI?this.pendingLocalTracks=this.pendingLocalTracks.concat(i.trackList):this.pendingLocalTracks.push(i);break;case yS.LocalVideoLowTrack:}}),this.emit(OS.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(sg(i).call(i)).forEach(e=>{this.setPendingRemoteMedia(t,e)}),this.emit(OS.MediaReconnectStart,t.uid)}),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),this.statsUploader.stopUploadUplinkStats(),this.statsUploader.stopUploadDownlinkStats(),this.statsUploader.stopUploadTransportStats(),OE.debug("P2PChannel disconnected, waiting to reconnect."))}hasPendingRemoteMedia(e,t){for(const i of this.pendingRemoteTracks){const{user:n,kind:r}=i;if((e instanceof Ey?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 RO((function*(){if(!e.connection||e.state!==AS.Connected||e.connection instanceof rw)return;const t=yield IO(e.mutex.lock("From P2PChannel.restartICE"));try{yield*CO(dw(e.connection.restartICE()),IO)}finally{t()}}))()}getUplinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats(),t=this.localTrackMap.get(yS.LocalVideoTrack),i=this.localTrackMap.get(yS.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=XI(this,OS.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(lS.SCREEN_TRACK)){const t=h._encoderConfig.bitrateMax,i=e.bitrate.actualEncoded;if(t&&i){const e=(1e3*t-i)/(1e3*t);return XE[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=XI(this,OS.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=FS(),o=this.getAllTracks();e=ZI(e=e.filter(e=>-1===o.indexOf(e)));let s=!1,a=!1;for(const o of e){if(o instanceof py&&(this.localTrackMap.has(yS.LocalVideoTrack)||s?new SE(fE.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(n.push({track:o,type:yS.LocalVideoTrack}),s=!0),t)){const e=this.getLowVideoTrack(o,i);n.push({track:e,type:yS.LocalVideoLowTrack})}if(o instanceof _I){const e=this.localTrackMap.get(yS.LocalAudioTrack);if(e){if(!(e.track instanceof fI))throw new SE(fE.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 SE(fE.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===yS.LocalAudioTrack});if(!(e.track instanceof fI))throw new SE(fE.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 SE(fE.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(o)}else{if(!r.webAudioMediaStreamDest||o instanceof fI||o._bypassWebAudio)n.push({track:o,type:yS.LocalAudioTrack});else{const e=new fI;e.addAudioTrack(o),n.push({track:e,type:yS.LocalAudioTrack})}a=!0}}}return n}filterTobeUnpublishedTracks(e){const t=[],i=this.getAllTracks();
6e=ZI(e=e.filter(e=>-1!==i.indexOf(e)));for(const i of e){if(i instanceof _I){const e=this.localTrackMap.get(yS.LocalAudioTrack);if(!e)continue;e.track instanceof fI?(e.track.removeAudioTrack(i),this.unbindLocalAudioTrackEvents(i),0===e.track.trackList.length&&(t.push([yS.LocalAudioTrack,e]),e.track.close())):t.push([yS.LocalAudioTrack,e])}if(i instanceof py){const e=this.localTrackMap.get(yS.LocalVideoTrack);if(!e)continue;t.push([yS.LocalVideoTrack,e]);const i=this.localTrackMap.get(yS.LocalVideoLowTrack);i&&t.push([yS.LocalVideoLowTrack,i])}}return t}bindLocalTrackEvents(e){e.forEach(e=>{let{track:t,type:i}=e;switch(i){case yS.LocalVideoTrack:t.addListener(uS.GET_STATS,this.handleGetLocalVideoStats),t.addListener(uS.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(uS.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(uS.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(uS.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.addListener(uS.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(uS.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(uS.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case yS.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);break;case yS.LocalVideoLowTrack:}})}bindLocalAudioTrackEvents(e,t){e instanceof fI?e.trackList.forEach(e=>{e.addListener(uS.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(uS.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(uS.GET_STATS,this.handleGetLocalAudioStats),e.addListener(uS.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(uS.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)}):(e.addListener(uS.GET_STATS,this.handleGetLocalAudioStats),e.addListener(uS.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(uS.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(uS.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(uS.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||e.addListener(uS.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 yS.LocalVideoTrack:t.off(uS.GET_STATS,this.handleGetLocalVideoStats),t.off(uS.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(uS.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(uS.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(uS.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),t.off(uS.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(uS.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(uS.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case yS.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);break;case yS.LocalVideoLowTrack:}})}unbindLocalAudioTrackEvents(e){e instanceof fI?e.trackList.forEach(e=>{e.off(uS.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(uS.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(uS.GET_STATS,this.handleGetLocalAudioStats),e.off(uS.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(uS.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)}):(e.off(uS.GET_STATS,this.handleGetLocalAudioStats),e.off(uS.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(uS.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(uS.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(uS.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(uS.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof jb&&t.addListener(uS.GET_STATS,t=>{t(this.handleGetRemoteVideoStats(e))}),t instanceof Bb&&t.addListener(uS.GET_STATS,t=>{t(this.handleGetRemoteAudioStats(e))})}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(uS.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t,i]=e;i.has(CS.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),i.has(CS.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack)})}createGatewayPublishMessage(e,t){return e.map((e,i)=>{let n,r,{track:o,type:s}=e;switch(s){case yS.LocalAudioTrack:n=sS.Audio,r={dtx:o instanceof EI&&o._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case yS.LocalVideoTrack:n=o._hints.includes(lS.SCREEN_TRACK)?sS.Screen:sS.High,r=cw(cw({},NI(o)),{},{codec:this.store.codec});break;case yS.LocalVideoLowTrack:n=sS.Low,r=cw(cw({},NI(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 yS.LocalVideoTrack:t=n._hints.includes(lS.SCREEN_TRACK)?sS.Screen:sS.High;break;case yS.LocalAudioTrack:t=sS.Audio;break;case yS.LocalVideoLowTrack:t=sS.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})})}
6withdrawLocalTracks(e){e.forEach(e=>{let[t]=e;this.localTrackMap.delete(t)})}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{if(OE.info("[p2pId: ".concat(this.store.p2pId,"]: P2PConnection.onConnectionStateChange(").concat(t,")")),this.emit(OS.PeerConnectionStateChange,t),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),"disconnected"===t&&"disconnected"===e.iceConnectionState)return setTimeout(()=>{if("disconnected"===e.iceConnectionState&&GE("ICE_RESTART")){"CONNECTED"===XI(this,OS.QueryClientConnectionState)&&this.emit(OS.RequestRestartICE)}},800),void setTimeout(()=>{"disconnected"===e.peerConnectionState&&(OE.debug("P2PConnection disconnected timeout 4000ms, force reconnect"),setTimeout(()=>this.emit(OS.P2PLost),0),this.iceFailedCount+=1,this.requestReconnect())},4e3);"failed"===t&&(OE.debug("P2PConnection state failed, force reconnect"),setTimeout(()=>this.emit(OS.P2PLost),0),this.iceFailedCount+=1,await this.requestReconnect())},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),OE.info("[p2pId: ".concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),vg.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:Ef.TRACER}).onSuccess(),this.emit(OS.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{OE.info("[p2pId: ".concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{OE.info("[p2pId: ".concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{OE.info("[p2pId: ".concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},e.onFirstAudioDecoded=e=>{var t;const i=Array.from(sg(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(ES.FIRST_FRAME_DECODED),vg.firstRemoteFrame(this.store.sessionId,uf.FIRST_AUDIO_DECODE,lf.FIRST_AUDIO_DECODE,{peer:i._uintid,subscribeElapse:gI.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;const i=Array.from(sg(t=this.remoteUserMap).call(t)).find(t=>t._audioSSRC===e);i&&vg.firstRemoteFrame(this.store.sessionId,uf.FIRST_AUDIO_RECEIVED,lf.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:gI.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(sg(t=this.remoteUserMap).call(t)).find(t=>t._videoSSRC===e);i&&vg.firstRemoteFrame(this.store.sessionId,uf.FIRST_VIDEO_RECEIVED,lf.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:gI.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(OS.ConnectionTypeChange,i),OE.info("[p2pId: ".concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(UI(t))," -> ").concat(JSON.stringify(UI(e)),")"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{OE.info("[p2pId: ".concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(UI(t))," -> ").concat(JSON.stringify(UI(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(yS.LocalAudioTrack);if(e instanceof _I&&(null==i?void 0:i.track)instanceof fI)return i.track.isActive||t.push([yS.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]===yS.LocalVideoTrack)){const e=this.localTrackMap.get(yS.LocalVideoLowTrack);e&&t.push([yS.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){const t=[],i=this.localTrackMap.get(yS.LocalAudioTrack);if(e instanceof _I&&(null==i?void 0:i.track)instanceof fI)return i.track.isActive&&t.push([yS.LocalAudioTrack,i]),t;const n=Array.from(this.localTrackMap.entries()).find(t=>{let[,{track:i}]=t;return e===i});if(n)if(n[0]===yS.LocalVideoTrack){t.push(n);const e=this.localTrackMap.get(yS.LocalVideoLowTrack);e&&t.push([yS.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 yS.LocalAudioTrack:t=sS.Audio;break;case yS.LocalVideoTrack:t=n._hints.includes(lS.SCREEN_TRACK)?sS.Screen:sS.High;break;case yS.LocalVideoLowTrack:t=sS.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 yS.LocalAudioTrack:t=sS.Audio;break;case yS.LocalVideoTrack:t=n._hints.includes(lS.SCREEN_TRACK)?sS.Screen:sS.High;break;case yS.LocalVideoLowTrack:t=sS.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}])}
6else 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 CS.VIDEO:return void(i._videoSSRC&&t.push({stream_type:CS.VIDEO,ssrcId:i._videoSSRC}));case CS.AUDIO:return void(i._audioSSRC&&t.push({stream_type:CS.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===CS.VIDEO?e|=cS.Video:e|=cS.Audio,t.set(i,e)}else n===CS.VIDEO?t.set(i,cS.Video):t.set(i,cS.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(yS.LocalVideoTrack),i=this.localTrackMap.get(yS.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 _I){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 JI(this,OS.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(OS.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 jI(gE(this.dtlsFailedCount,TE)),this.emit(OS.RequestReconnect)}async reconnectP2P(){const e=Array.from(this.localTrackMap.entries()),t=this.createGatewayUnpublishMessage(e);Array.from(this.remoteUserMap.entries()),t.length>0&&await qI(this,OS.RequestUnpublishForReconnectPC,t),this.disconnectForReconnect(),this.emit(OS.RequestReconnectPC)}canPublishLowStream(){return this.localTrackMap.has(yS.LocalVideoTrack)||this.pendingLocalTracks.some(e=>e instanceof py)}throwIfTrackTypeNotMatch(e){if(e.filter(e=>e instanceof py).length>1)throw new SE(fE.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter(e=>e instanceof _I).length>1&&(e.some(e=>e instanceof _I&&e._bypassWebAudio)||!FS().webAudioMediaStreamDest))throw new SE(fE.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 py&&this.pendingLocalTracks.some(e=>e instanceof py))throw new SE(fE.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof _I&&this.pendingLocalTracks.some(e=>e instanceof _I)&&(!FS().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some(e=>e instanceof _I&&e._bypassWebAudio)))throw new SE(fE.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=FS().supportDualStreamEncoding,n=cw(cw({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=i?e._mediaStreamTrack.clone():Cb(e,n);const o=GI(8,"track-low-"),s=new py(r,cw(cw({},i&&{scaleResolutionDownBy:MI(n,e)}),{},{frameRate:n.framerate,bitrateMax:n.bitrate,bitrateMin:n.bitrate}),void 0,void 0,o);return s._hints.push(lS.LOW_STREAM),e.addListener(uS.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(sg(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);vg.firstRemoteVideoDecode(this.store.sessionId,uf.FIRST_VIDEO_DECODE,lf.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:i,subscribeElapse:gI.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){OE.debug("[P2PChannel] reset connection to ".concat(e)),this.state===AS.Connected?(OE.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===dS.datachannel?new rw({},this.store):this.isPlanB?new _b({},this.store):new Ib({},this.store),this.bindConnectionEvents(this.connection)))}}).prototype,"startP2PConnection",[hw],Object.getOwnPropertyDescriptor(sw.prototype,"startP2PConnection"),sw.prototype),ZT(sw.prototype,"connect",[hw],Object.getOwnPropertyDescriptor(sw.prototype,"connect"),sw.prototype),ZT(sw.prototype,"preConnect",[hw],Object.getOwnPropertyDescriptor(sw.prototype,"preConnect"),sw.prototype),ZT(sw.prototype,"unpublish",[hw],Object.getOwnPropertyDescriptor(sw.prototype,"unpublish"),sw.prototype),ZT(sw.prototype,"unpublishLowStream",[hw],Object.getOwnPropertyDescriptor(sw.prototype,"unpublishLowStream"),sw.prototype),ZT(sw.prototype,"subscribe",[hw],Object.getOwnPropertyDescriptor(sw.prototype,"subscribe"),sw.prototype),ZT(sw.prototype,"massSubscribe",[hw],Object.getOwnPropertyDescriptor(sw.prototype,"massSubscribe"),sw.prototype),ZT(sw.prototype,"unsubscribe",[hw],Object.getOwnPropertyDescriptor(sw.prototype,"unsubscribe"),sw.prototype),ZT(sw.prototype,"massUnsubscribe",[hw],Object.getOwnPropertyDescriptor(sw.prototype,"massUnsubscribe"),sw.prototype),ZT(sw.prototype,"muteRemote",[hw],Object.getOwnPropertyDescriptor(sw.prototype,"muteRemote"),sw.prototype),ZT(sw.prototype,"unmuteRemote",[hw],Object.getOwnPropertyDescriptor(sw.prototype,"unmuteRemote"),sw.prototype),ZT(sw.prototype,"hasRemoteMediaWithLock",[hw],Object.getOwnPropertyDescriptor(sw.prototype,"hasRemoteMediaWithLock"),sw.prototype),ZT(sw.prototype,"disconnectForReconnect",[hw],Object.getOwnPropertyDescriptor(sw.prototype,"disconnectForReconnect"),sw.prototype),ZT(sw.prototype,"updateBitrateLimit",[hw],Object.getOwnPropertyDescriptor(sw.prototype,"updateBitrateLimit"),sw.prototype),ZT(sw.prototype,"remoteMediaSsrcChanged",[hw],Object.getOwnPropertyDescriptor(sw.prototype,"remoteMediaSsrcChanged"),sw.prototype),sw);function hw(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 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}function _w(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
vendor: 17,698 bytes, line 6
6t%2?pw(Object(i),!0).forEach((function(t){_p(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}var Ew;!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"}(Ew||(Ew={}));class mw{constructor(e,t,i,n){_p(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 Ew.SET_SESSION_ID:return _w(_w({},e),{},{sessionId:t.sessionId});case Ew.SET_P2P_ID:return _w(_w({},e),{},{p2pId:t.p2pId});case Ew.SET_UID:return _w(_w({},e),{},{uid:t.uid});case Ew.SET_PUB_ID:return _w(_w({},e),{},{pubId:t.pubId});case Ew.KEY_METRIC_CLIENT_CREATED:return _w(_w({},e),{},{keyMetrics:_w(_w({},e.keyMetrics),{},{clientCreated:t.metric})});case Ew.KEY_METRIC_JOIN_START:return _w(_w({},e),{},{keyMetrics:_w(_w({},e.keyMetrics),{},{joinStart:t.metric})});case Ew.AVOID_JOIN_START:return _w(_w({},e),{},{avoidJoinStart:t.avoidJoinStart});case Ew.KEY_METRIC_JOIN_END:return _w(_w({},e),{},{keyMetrics:_w(_w({},e.keyMetrics),{},{joinEnd:t.metric})});case Ew.KEY_METRIC_REQUEST_AP_START:return _w(_w({},e),{},{keyMetrics:_w(_w({},e.keyMetrics),{},{requestAPStart:t.metric})});case Ew.KEY_METRIC_REQUEST_AP_END:return _w(_w({},e),{},{keyMetrics:_w(_w({},e.keyMetrics),{},{requestAPEnd:t.metric})});case Ew.KEY_METRIC_JOIN_GATEWAY_START:return _w(_w({},e),{},{keyMetrics:_w(_w({},e.keyMetrics),{},{joinGatewayStart:t.metric})});case Ew.KEY_METRIC_JOIN_GATEWAY_END:return _w(_w({},e),{},{keyMetrics:_w(_w({},e.keyMetrics),{},{joinGatewayEnd:t.metric})});case Ew.KEY_METRIC_PEER_CONNECTION_START:return _w(_w({},e),{},{keyMetrics:_w(_w({},e.keyMetrics),{},{peerConnectionStart:t.metric})});case Ew.KEY_METRIC_PEER_CONNECTION_END:return _w(_w({},e),{},{keyMetrics:_w(_w({},e.keyMetrics),{},{peerConnectionEnd:t.metric})});case Ew.KEY_METRIC_SIGNAL_CHANNEL_OPEN:return _w(_w({},e),{},{keyMetrics:_w(_w({},e.keyMetrics),{},{signalChannelOpen:t.metric})});case Ew.KEY_METRIC_ICE_CONNECTION_END:return _w(_w({},e),{},{keyMetrics:_w(_w({},e.keyMetrics),{},{iceConnectionEnd:t.metric})});case Ew.KEY_METRIC_PUBLISH:{const i=e.keyMetrics.publish,n=i.findIndex(e=>e.trackId===t.metric.trackId);return-1!==n?(i[n]=_w(_w({},i[n]),t.metric),_w(_w({},e),{},{keyMetrics:_w(_w({},e.keyMetrics),{},{publish:[...i]})})):_w(_w({},e),{},{keyMetrics:_w(_w({},e.keyMetrics),{},{publish:[...e.keyMetrics.publish,t.metric]})})}case Ew.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]=_w(_w({},i[n]),t.metric),_w(_w({},e),{},{keyMetrics:_w(_w({},e.keyMetrics),{},{subscribe:[...i]})})):_w(_w({},e),{},{keyMetrics:_w(_w({},e.keyMetrics),{},{subscribe:[...e.keyMetrics.subscribe,t.metric]})})}case Ew.SET_CLOUD_PROXY_SERVER_MODE:return e.cloudProxyServerMode=t.mode,e;case Ew.RECORD_JOIN_CHANNEL_SERVICE:return"number"!=typeof t.index?e.joinChannelServiceRecords=[...e.joinChannelServiceRecords,t.record]:(e.joinChannelServiceRecords[t.index]=_w(_w({},e.joinChannelServiceRecords[t.index]),t.record),e.joinChannelServiceRecords=[...e.joinChannelServiceRecords]),e;case Ew.RESET_JOIN_CHANNEL_SERVICE_RECORDS:return e.joinChannelServiceRecords=[],e;case Ew.RESET_KEY_METRICS:return e.keyMetrics={publish:[],subscribe:[]},e;case Ew.SET_USE_DATACHANNEL:return _w(_w({},e),{},{useDataChannel:t.val});default:return e}}(this.state,e)}set sessionId(e){this.dispatch({type:Ew.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:Ew.SET_P2P_ID,p2pId:e})}get p2pId(){return this.state.p2pId}set dcId(e){this.dispatch({type:Ew.SET_DC_ID,dcId:e})}get dcId(){return this.state.dcId}set uid(e){this.dispatch({type:Ew.SET_UID,uid:e})}get uid(){return this.state.uid}set pubId(e){this.dispatch({type:Ew.SET_PUB_ID,pubId:e})}get pubId(){return this.state.pubId}set cloudProxyServerMode(e){this.dispatch({type:Ew.SET_CLOUD_PROXY_SERVER_MODE,mode:e})}get cloudProxyServerMode(){return this.state.cloudProxyServerMode}set useDataChannel(e){this.dispatch({type:Ew.SET_USE_DATACHANNEL,val:e})}get useDataChannel(){return this.state.useDataChannel}clientCreated(){this.dispatch({type:Ew.KEY_METRIC_CLIENT_CREATED,metric:Date.now()})}joinStart(){this.dispatch({type:Ew.KEY_METRIC_JOIN_START,metric:Date.now()})}joinEnd(){this.dispatch({type:Ew.KEY_METRIC_JOIN_END,metric:Date.now()})}requestAPStart(){this.dispatch({type:Ew.KEY_METRIC_REQUEST_AP_START,metric:Date.now()})}requestAPEnd(){this.dispatch({type:Ew.KEY_METRIC_REQUEST_AP_END,metric:Date.now()})}joinGatewayStart(){this.dispatch({type:Ew.KEY_METRIC_JOIN_GATEWAY_START,metric:Date.now()})}joinGatewayEnd(){this.dispatch({type:Ew.KEY_METRIC_JOIN_GATEWAY_END,metric:Date.now()})}peerConnectionStart(){this.dispatch({type:Ew.KEY_METRIC_PEER_CONNECTION_START,metric:Date.now()})}peerConnectionEnd(){this.dispatch({type:Ew.KEY_METRIC_PEER_CONNECTION_END,metric:Date.now()})}signalChannelOpen(){this.dispatch({type:Ew.KEY_METRIC_SIGNAL_CHANNEL_OPEN,metric:Date.now()})}iceConnectionEnd(){this.dispatch({type:Ew.KEY_METRIC_ICE_CONNECTION_END,metric:Date.now()})}publish(e,t,i,n){this.dispatch({type:Ew.KEY_METRIC_PUBLISH,metric:_w(_w({trackId:e,type:t},i&&{publishStart:i}),n&&{publishEnd:n})})}subscribe(e,t,i,n,r,o,s){this.dispatch({type:Ew.KEY_METRIC_SUBSCRIBE,metric:_w(_w(_w(_w(_w({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:Ew.KEY_METRIC_SUBSCRIBE,metric:_w(_w(_w({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:Ew.RECORD_JOIN_CHANNEL_SERVICE,record:_w(_w({},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:Ew.RECORD_JOIN_CHANNEL_SERVICE,record:e,index:t}),t)}catch(e){return 0}}resetJoinChannelServiceRecords(){this.dispatch({type:Ew.RESET_JOIN_CHANNEL_SERVICE_RECORDS})}resetKeyMetrics(){this.dispatch({type:Ew.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:Ew.AVOID_JOIN_START,avoidJoinStart:e})}}let fw;const Sw=()=>"HTTPS"===(fw||fw||(fw=(window.location.protocol.split(":")[0]||"").toUpperCase(),fw)),Tw=()=>void 0!==window.isSecureContext;function gw(e){let t=Dw();return function(e,t){let i=e.appId;void 0!==i&&(Kw(t,10),Vw(t,i));let n=e.cid;void 0!==n&&(Kw(t,16),Kw(t,n));let r=e.cname;void 0!==r&&(Kw(t,26),Vw(t,r));let o=e.deviceId;void 0!==o&&(Kw(t,34),Vw(t,o));let s=e.elapse;void 0!==s&&(Kw(t,40),Yw(t,s));let a=e.fileSize;void 0!==a&&(Kw(t,48),Yw(t,ww(a)));let c=e.height;void 0!==c&&(Kw(t,56),Yw(t,ww(c)));let d=e.jpg;void 0!==d&&(Kw(t,66),Kw(t,d.length),function(e,t){let i=Mw(e,t.length);e.bytes.set(t,i)}(t,d));let u=e.networkType;void 0!==u&&(Kw(t,72),Yw(t,ww(u)));let l=e.osType;void 0!==l&&(Kw(t,80),Yw(t,ww(l)));let h=e.requestId;void 0!==h&&(Kw(t,90),Vw(t,h));let p=e.sdkVersion;void 0!==p&&(Kw(t,98),Vw(t,p));let _=e.sequence;void 0!==_&&(Kw(t,104),Yw(t,ww(_)));let E=e.sid;void 0!==E&&(Kw(t,114),Vw(t,E));let m=e.timestamp;void 0!==m&&(Kw(t,120),Yw(t,m));let f=e.uid;void 0!==f&&(Kw(t,128),Kw(t,f));let S=e.vid;void 0!==S&&(Kw(t,136),Kw(t,S));let T=e.width;void 0!==T&&(Kw(t,144),Yw(t,ww(T)));let g=e.service;void 0!==g&&(Kw(t,152),Kw(t,g));let R=e.callbackData;void 0!==R&&(Kw(t,162),Vw(t,R));let I=e.jpgEncryption;void 0!==I&&(Kw(t,168),Kw(t,I));let v=e.requestType;void 0!==v&&(Kw(t,176),Kw(t,v));let C=e.scorePorn;void 0!==C&&(Kw(t,185),Ww(t,C));let y=e.scoreSexy;void 0!==y&&(Kw(t,193),Ww(t,y));let A=e.scoreNeutral;void 0!==A&&(Kw(t,201),Ww(t,A));let O=e.scene;void 0!==O&&(Kw(t,208),Kw(t,O));let b=e.ossFilePrefix;void 0!==b&&(Kw(t,218),Vw(t,b));let w=e.serviceVendor;if(void 0!==w)for(let e of w){Kw(t,226);let i=Dw();vw(e,i),Kw(t,i.limit),Fw(t,i),Pw(i)}}(e,t),function(e){let t=e.bytes,i=e.limit;return t.length===i?t:t.subarray(0,i)}(t)}function Rw(e){return function(e){let t={};e:for(;!kw(e);){let i=Hw(e);switch(i>>>3){case 0:break e;case 1:t.code=Hw(e);break;case 2:t.msg=xw(e,Hw(e));break;case 3:{let i=Cw(e);t.data=Iw(e),e.limit=i;break}default:yw(e,7&i)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function Iw(e){let t={};e:for(;!kw(e);){let i=Hw(e);switch(i>>>3){case 0:break e;case 1:t.requestId=xw(e,Hw(e));break;case 2:t.requestType=Hw(e)>>>0;break;case 3:t.scorePorn=Gw(e);break;case 4:t.scoreSexy=Gw(e);break;case 5:t.scoreNeutral=Gw(e);break;case 6:t.requestScene=Hw(e)>>>0;break;case 7:t.scene=Hw(e)>>>0;break;default:yw(e,7&i)}}return t}function vw(e,t){let i=e.service;void 0!==i&&(Kw(t,8),Kw(t,i));let n=e.vendor;void 0!==n&&(Kw(t,16),Kw(t,n));let r=e.token;void 0!==r&&(Kw(t,26),Vw(t,r));let o=e.callbackUrl;void 0!==o&&(Kw(t,34),Vw(t,o))}function Cw(e){let t=Hw(e),i=e.limit;return e.limit=e.offset+t,i}function yw(e,t){switch(t){case 0:for(;128&jw(e););break;case 2:Lw(e,Hw(e));break;case 5:Lw(e,4);break;case 1:Lw(e,8);break;default:throw new Error("Unimplemented type: "+t)}}let Aw=new Float32Array(1);new Uint8Array(Aw.buffer);let Ow=new Float64Array(1),bw=new Uint8Array(Ow.buffer);function ww(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let Nw=[];function Dw(){const e=Nw.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function Pw(e){Nw.push(e)}function Lw(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function kw(e){return e.offset>=e.limit}function Mw(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 Uw(e,t){let i=e.offset;if(i+t>e.limit)throw new Error("Read past limit");return e.offset+=t,i}function xw(e,t){let i=Uw(e,t),n=String.fromCharCode,r=e.bytes,o="�",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 Vw(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}Kw(e,n);let r=Mw(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 Fw(e,t){let i=Mw(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 jw(e){return e.bytes[Uw(e,1)]}function Bw(e,t){let i=Mw(e,1);e.bytes[i]=t}function Gw(e){let t=Uw(e,8),i=e.bytes;return bw[0]=i[t++],bw[1]=i[t++],bw[2]=i[t++],bw[3]=i[t++],bw[4]=i[t++],bw[5]=i[t++],bw[6]=i[t++],bw[7]=i[t++],Ow[0]}function Ww(e,t){let i=Mw(e,8),n=e.bytes;Ow[0]=t,n[i++]=bw[0],n[i++]=bw[1],n[i++]=bw[2],n[i++]=bw[3],n[i++]=bw[4],n[i++]=bw[5],n[i++]=bw[6],n[i++]=bw[7]}function Hw(e){let t,i=0,n=0;do{t=jw(e),i<32&&(n|=(127&t)<<i),i+=7}while(128&t);return n}function Kw(e,t){for(t>>>=0;t>=128;)Bw(e,127&t|128),t>>>=7;Bw(e,t)}function Yw(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=Mw(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 qw=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 Jw(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 Xw=new Map([["moderation",1],["supervise",2]]);
6class zw extends EE{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(kS.CONNECTION_STATE_CHANGE,t,e)}get inspectType(){return this._inspectType}set inspectType(e){var t;this._inspectMode=zi(t=e.map(e=>Xw.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(),_p(this,"name","AgoraRTCVideoContentInspect"),_p(this,"_connectionState",PS.CONNECTING),_p(this,"_innerConnectionState",void 0),_p(this,"sequence",0),_p(this,"inspectStartTime",void 0),_p(this,"workerManagerConnection",void 0),_p(this,"workerConnection",void 0),_p(this,"workerMessageLengthLimit",void 0),_p(this,"inspectIntervalMinimum",void 0),_p(this,"qualityRatio",void 0),_p(this,"_connectInfo",void 0),_p(this,"_cancelTokenSource",pE.CancelToken.source()),_p(this,"_retryConfig",void 0),_p(this,"wmSequence",0),_p(this,"inspectInterval",void 0),_p(this,"inspectTimer",null),_p(this,"ossFilePrefix",void 0),_p(this,"extraInfo",void 0),_p(this,"_inspectType",void 0),_p(this,"_inspectMode",void 0),_p(this,"_quality",1),_p(this,"qualityTimer",null),_p(this,"_inspectId",void 0),_p(this,"_needWorkUrlOnly",!1),_p(this,"inspectImage",()=>{if(this.connectionState!==PS.CONNECTED)throw new SE(fE.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===PS.CONNECTED?this.requestToInspectImage():OE.debug("[".concat(this._inspectId,"] Inspect State is not connected , "),this.connectionState)},this.inspectInterval<this.inspectIntervalMinimum?this.inspectIntervalMinimum:this.inspectInterval),this.requestToInspectImage()}),this._inspectId=GI(5,"inspect-"),this.workerMessageLengthLimit=GE("VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT"),this.inspectIntervalMinimum=GE("VIDEO_INSPECT_INTERVAL_MINIMUM"),this.qualityRatio=GE("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 _v("worker-manager-"+this._inspectId,TE),this.on(kS.STATE_CHANGE,(e,t)=>{this._innerConnectionState=e,OE.debug("[".concat(this._inspectId,"] Inspect operation :").concat(LS[e]," ").concat(t||""))}),this.handleWorkerManagerEvents(),this.workerConnection=new _v("worker-"+this._inspectId,TE),this.handleWorkerEvents()}async init(e,t){this.emit(kS.STATE_CHANGE,LS.CONNECT_AP),this._connectInfo=e;const i=this._cancelTokenSource.token;return this._retryConfig=t,new Sl((n,r)=>{this.on(kS.CONNECTION_STATE_CHANGE,(e,t)=>{t===PS.CONNECTED&&n()}),this.requestAP(e,i,t).then(e=>{this.connectWorkerManager(e)}).catch(e=>{r(e)})})}async requestAP(e,t,i){const n=GE("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;zv++;const u="image_moderation_api",l={service_name:u,json_body:JSON.stringify({appId:r,areaCode:o,cname:s,command:"allocateEdge",requestId:zv,seq:zv,sid:a,token:c,ts:Date.now(),uid:d+""})};let h,p,_=e[0];return RE(async()=>{h=Date.now();const e=await lg(_,{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 SE(fE.UNEXPECTED_RESPONSE,"image inspect ap error, code"+e.code,{retry:!0,responseTime:p});throw OE.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new SE(fE.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw OE.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new SE(fE.UNEXPECTED_RESPONSE,"image inspect ap empty server",{c
6ode:t.code,responseTime:p});throw OE.error(e.toString()),e}const n=GE("VIDEO_INSPECT_WORKER_MANAGER_HOST"),r=GE("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)=>(vg.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)=>(vg.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:u,responseTime:p,serverIp:e[i%e.length]}),!!(t.code!==fE.OPERATION_ABORTED&&t.code!==fE.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(i+1)%e.length],!0)),n)}(n,e,t,i);this.emit(kS.STATE_CHANGE,LS.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(kS.STATE_CHANGE,LS.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(e,1e4)}async connectWorker(e){await this.workerConnection.init([e])}handleWorkerManagerEvents(){this.workerManagerConnection.on(Hf.CONNECTED,async()=>{this.emit(kS.STATE_CHANGE,LS.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.17.2",sid:this._connectInfo.sid,seq:this.wmSequence,ts:Number(Date.now()),requestId:Math.floor(1e12*Math.random()),allocate:!0,clientRequest:{command:"join"}},!0)}),this.workerManagerConnection.on(Hf.CLOSED,()=>{this._innerConnectionState<LS.GET_WORKER_MANAGER_RESPONSE&&OE.debug("[".concat(this._inspectId,"] Inspect worker manager is closed before connecting worker"))}),this.workerManagerConnection.on(Hf.FAILED,()=>{this._innerConnectionState<LS.GET_WORKER_MANAGER_RESPONSE&&OE.debug("[".concat(this._inspectId,"] Connecting inspect worker manager is failed before connecting worker"))}),this.workerManagerConnection.on(Hf.RECONNECTING,()=>{this._innerConnectionState<LS.GET_WORKER_MANAGER_RESPONSE&&OE.debug("[".concat(this._inspectId,"] Inspect worker manager is reconnecting before connecting worker"))}),this.workerManagerConnection.on(Hf.ON_MESSAGE,async e=>{this.emit(kS.STATE_CHANGE,LS.GET_WORKER_MANAGER_RESPONSE);const t=this.workerManagerConnection.url;this.workerManagerConnection.close();const i=JSON.parse(e.data);if(200!==i.code)throw OE.error("[".concat(this._inspectId,"] Unexpected code ").concat(i.code," from worker manager")),new SE(fE.UNEXPECTED_RESPONSE,"response code of worker is unexpected",i);if(!(i.serverResponse&&i.serverResponse.portWss&&t))throw OE.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(i))),new SE(fE.UNEXPECTED_RESPONSE,"response content of worker is unexpected",i);{const e=GE("VIDEO_INSPECT_WORKER_PORT")||i.serverResponse.portWss,n=t.replace(/:\d+\/?$/,":".concat(e));this.emit(kS.STATE_CHANGE,LS.CONNECT_WORKER,n),this._needWorkUrlOnly?this.emit(kS.REQUEST_NEW_WORKER_URL,n):await this.connectWorker(n)}}),this.workerManagerConnection.on(Hf.WILL_RECONNECT,(e,t)=>{t(e)}),this.workerManagerConnection.on(Hf.REQUEST_NEW_URLS,(e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)})}handleWorkerEvents(){this.workerConnection.on(Hf.CONNECTED,async()=>{this.emit(kS.STATE_CHANGE,LS.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=PS.CONNECTED}),this.workerConnection.on(Hf.ON_MESSAGE,async e=>{if(e.data instanceof ArrayBuffer){const i=Rw(new Uint8Array(e.data));if(GE("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")&&OE.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(kS.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}
6,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(kS.INSPECT_RESULT,r)}else this.emit(kS.INSPECT_RESULT,void 0,new SE(fE.UNEXPECTED_RESPONSE,i.code+"","There is an unexpected data on message"))}else this.emit(kS.INSPECT_RESULT,void 0,new SE(fE.UNEXPECTED_RESPONSE,i.code+"",i.msg))}else OE.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit(kS.INSPECT_RESULT,void 0,new SE(fE.UNEXPECTED_RESPONSE,"invalid worker message type"))}),this.workerConnection.on(Hf.CLOSED,()=>{this.connectionState=PS.CLOSED}),this.workerConnection.on(Hf.FAILED,()=>{this.connectionState=PS.CLOSED}),this.workerConnection.on(Hf.RECONNECTING,()=>{this.connectionState=this.connectionState===PS.CONNECTED?PS.RECONNECTING:PS.CONNECTING}),this.workerConnection.on(Hf.WILL_RECONNECT,(e,t)=>{"recover"===e&&t(e),t("tryNext")}),this.workerConnection.on(Hf.REQUEST_NEW_URLS,(e,t)=>{this.workerManagerConnection.close(),this.once(kS.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=XI(this,kS.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(kS.INSPECT_RESULT,void 0,new SE(fE.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(kS.INSPECT_RESULT,void 0,new SE(fE.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 qw(e.buffer,t,i))(d,i,n),l=this.sequence+"-"+r+"-"+a+"-"+c+"-"+GI(12,""),h={appId:i,cid:r,cname:n,deviceId:"",elapse:zw.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.2",sequence:this.sequence,sid:s,timestamp:zw.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=gw(h);if(p.byteLength<this.workerMessageLengthLimit){if(GE("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?Jw(Object(i),!0).forEach((function(t){_p(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Jw(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({},h);delete e.jpg,OE.debug("[".concat(this._inspectId,"] Request message for worker of inspect content "),JSON.stringify(e))}return p}
6{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=pE.CancelToken.source(),this.workerManagerConnection&&this.workerManagerConnection.close(),this.workerConnection&&this.workerConnection.close(),this.inspectTimer&&window.clearInterval(this.inspectTimer),this.inspectTimer=null,this.connectionState=PS.CLOSED,this.emit(kS.STATE_CHANGE,LS.CLOSED)}}var Qw,Zw,$w,eN,tN,iN,nN,rN,oN,sN,aN,cN,dN,uN,lN,hN,pN,_N,EN,mN,fN,SN,TN,gN,RN,IN,vN,CN,yN,AN,ON,bN,wN,NN,DN,PN,LN,kN,MN;function UN(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 xN(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?UN(Object(i),!0).forEach((function(t){_p(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):UN(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}let VN=(Qw=Ig(),Zw=Ig({argsMap:(e,t)=>(Array.isArray(t)||(t=[t]),t.map(e=>e?Object(e).toString():"null"))}),$w=Ig({argsMap:(e,t)=>(t||(t=[]),Array.isArray(t)||(t=[t]),t.map(e=>e.getTrackId()))}),eN=Ig({argsMap:(e,t,i)=>[t.uid,i]}),tN=Ig({argsMap:(e,t)=>t.map(e=>{let{user:t,mediaType:i}=e;return[null==t?void 0:t.uid,i]})}),iN=Ig({argsMap:(e,t,i)=>[t.uid,i]}),nN=Ig({argsMap:(e,t)=>t.map(e=>{let{user:t,mediaType:i}=e;return{uid:null==t?void 0:t.uid,mediaType:i}})}),rN=Ig(),oN=Ig(),sN=Ig(),aN=Ig(),cN=Ig(),dN=Ig(),uN=Ig(),lN=Ig(),hN=Ig(),pN=Ig(),_N=Ig(),EN=Ig(),mN=Ig(),fN=Ig(),SN=Ig({argsMap:(e,t)=>[t]}),TN=Ig(),gN=Ig(),RN=Ig(),IN=Ig(),vN=Ig(),CN=Ig(),yN=Ig(),AN=Ig(),ON=Ig(),bN=Ig(),wN=Ig({argsMap:(e,t)=>(Array.isArray(t)||(t=[t]),[JSON.stringify(t)])}),NN=Ig(),DN=Ig(),PN=Ig(),LN=Ig({reportResult:!0}),kN=Ig(),ZT((MN=class extends EE{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(),_p(this,"store",void 0),_p(this,"_uid",void 0),_p(this,"_channelName",void 0),_p(this,"_uintUid",void 0),_p(this,"_users",[]),_p(this,"_codec",void 0),_p(this,"_mode",void 0),_p(this,"_config",void 0),_p(this,"_clientId",void 0),_p(this,"_appId",void 0),_p(this,"_sessionId",null),_p(this,"_key",void 0),_p(this,"_joinInfo",void 0),_p(this,"_gateway",void 0),_p(this,"_statsCollector",void 0),_p(this,"_configDistribute",void 0),_p(this,"_leaveMutex",new Og("client-leave")),_p(this,"_publishMutex",new Og("client-publish")),_p(this,"_renewTokenMutex",new Og("client-renewtoken")),_p(this,"_subscribeMutex",new Og("client-subscribe")),_p(this,"_encryptionMode","none"),_p(this,"_encryptionSecret",null),_p(this,"_encryptionSalt",null),_p(this,"_proxyServer",void 0),_p(this,"_turnServer",{servers:[],mode:"auto"}),_p(this,"_cloudProxyServerMode","disabled"),_p(this,"_isDualStreamEnabled",!1),_p(this,"_defaultStreamFallbackType",void 0),_p(this,"_lowStreamParameter",void 0),_p(this,"_streamFallbackTypeCacheMap",new Map),_p(this,"_remoteStreamTypeCacheMap",new Map),_p(this,"_axiosCancelSource",pE.CancelToken.source()),_p(this,"_audioVolumeIndicationInterval",void 0),_p(this,"_networkQualityInterval",void 0),_p(this,"_userOfflineTimeout",void 0),_p(this,"_streamRemovedTimeout",void 0),_p(this,"_injectStreamingClient",void 0),_p(this,"_liveTranscodeStreamingClient",void 0),_p(this,"_liveRawStreamingClient",void 0),_p(this,"_channelMediaRelayClient",void 0),_p(this,"_networkQualitySensitivity","normal"),_p(this,"_p2pCh
6annel",void 0),_p(this,"_useLocalAccessPoint",!1),_p(this,"_setLocalAPVersion",void 0),_p(this,"_joinAndNotLeaveYet",!1),_p(this,"_numberOfJoinCount",0),_p(this,"_remoteDefaultVideoStreamType",void 0),_p(this,"_inspect",void 0),_p(this,"_license",void 0),_p(this,"_handleLocalTrackEnable",(e,t,i)=>{this.publish(e,!1).then(t).catch(i)}),_p(this,"_handleLocalTrackDisable",(e,t,i)=>{this.unpublish(e).then(t).catch(i)}),_p(this,"_handleUserOnline",e=>{if(GE("BLOCK_LOCAL_CLIENT")&&ZE(e.uid,this.channelName))return void OE.debug("[".concat(e.uid,"] will be ignored in local"));this.isStringUID&&"string"!=typeof e.uid&&OE.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 Ey(e.uid,e.uint_id||e.uid);this._users.push(t),OE.debug("[".concat(this._clientId,"] user online"),e.uid),this.emit(yf.USER_JOINED,t)}}),_p(this,"_handleUserOffline",e=>{if(GE("BLOCK_LOCAL_CLIENT")&&ZE(e.uid,this.channelName))return;const t=this._users.find(t=>t.uid===e.uid);t&&(this._handleRemoveStream(e),QI(this._users,t),this._remoteStreamTypeCacheMap.delete(t.uid),this._streamFallbackTypeCacheMap.delete(t.uid),OE.debug("[".concat(this._clientId,"] user offline"),e.uid,"reason:",e.reason),this.emit(yf.USER_LEAVED,t,e.reason))}),_p(this,"_handleAddAudioOrVideoStream",(e,t,i,n,r,o,s)=>{if(GE("BLOCK_LOCAL_CLIENT")&&ZE(t,this.channelName))return;const a=this._users.find(e=>e.uid===t);if(!a)return void OE.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));OE.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&&(OE.info("[".concat(this._clientId,"] remote user ").concat(a.uid," published ").concat(e)),this.emit(yf.USER_PUBLISHED,a,e)),"video"===e?vg.onGatewayStream(this._sessionId,uf.ON_ADD_VIDEO_STREAM,lf.ON_ADD_VIDEO_STREAM,{peer:r||t}):vg.onGatewayStream(this._sessionId,uf.ON_ADD_AUDIO_STREAM,lf.ON_ADD_AUDIO_STREAM,{peer:r||t}),this._p2pChannel.remoteMediaSsrcChanged(a,e,i).then(t=>{if(t)return OE.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=>{OE.error("[".concat(this._clientId,"] resubscribe error"),e.toString())}))}),this._p2pChannel.hasPendingRemoteMedia(a,e)&&(OE.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(a.uid," after reconnect.")),this._subscribe(a,e,!0).catch(e=>{OE.error("[".concat(this._clientId,"] resubscribe error"),e.toString())}))}),_p(this,"_handleRemoveStream",e=>{if(GE("BLOCK_LOCAL_CLIENT")&&ZE(e.uid,this.channelName))return;const t=this._users.find(t=>t.uid===e.uid);if(!t)return void OE.warning("[".concat(this._clientId,"] can not find target user!(on_remove_stream)"));OE.debug("[".concat(this._clientId,"] stream removed with uid ").concat(e.uid));let i=()=>{};t.hasAudio&&t.hasVideo?i=()=>{OE.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.emit(yf.USER_UNPUBLISHED,t,"audio"),OE.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.emit(yf.USER_UNPUBLISHED,t,"video")}:t.hasVideo?i=()=>{OE.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.emit(yf.USER_UNPUBLISHED,t,"video")}:t.hasAudio&&(i=()=>{OE.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.emit(yf.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,vg.onGatewayStream(this._sessionId,uf.ON_REMOVE_STREAM,lf.ON_REMOVE_STREAM,{peer:e.uint_id||e.uid}),i()}),_p(this,"_handleSetStreamLocalEnable",(e,t,i)=>{if(GE("BLOCK_LOCAL_CLIENT")&&ZE(t,this.channelName))return;const n=this._users.find(e=>e.uid===t);if(!n)return void OE.error("[".concat(this._clientId,"] can not find target user!(disable_local)"));OE.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";OE.debug("[".concat(this._clientId,"] user-info-updated, uid: ").concat(t,", msg: ").concat(e)),this.emit
6(yf.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";OE.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(t,", msg: ").concat(e)),this.emit(yf.USER_INFO_UPDATED,t,e)}}const o="audio"===e?n.hasAudio:n.hasVideo;return r!==o?!r&&o?(OE.info("[".concat(this._clientId,"] remote user ").concat(t," published ").concat(e)),void this.emit(yf.USER_PUBLISHED,n,e)):("video"===e&&n._videoTrack&&n._videoTrack._destroy(),"audio"===e&&n._audioTrack,this._p2pChannel.muteRemote(n,e),OE.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished ").concat(e)),void this.emit(yf.USER_UNPUBLISHED,n,e)):void 0}),_p(this,"_handleMuteStream",(e,t,i)=>{if(GE("BLOCK_LOCAL_CLIENT")&&ZE(e,this.channelName))return;OE.debug("[".concat(this._clientId,"] receive mute message"),e,t,i);const n=this._users.find(t=>t.uid===e);if(!n)return void OE.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";OE.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.emit(yf.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";OE.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.emit(yf.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)?(OE.info("[".concat(this._clientId,"] remote user ").concat(e," published ").concat(t)),void this.emit(yf.USER_PUBLISHED,n,t)):void OE.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),OE.info("[".concat(this._clientId,"] remote user ").concat(e," unpublished ").concat(t)),this.emit(yf.USER_UNPUBLISHED,n,t)}}),_p(this,"_handleP2PLost",async e=>{OE.debug("[".concat(this._clientId,"] receive p2p lost"),e),parseInt(e.p2pid,10)===this.store.p2pId?await this._p2pChannel.requestReconnect():OE.warning("P2PLost stream not found",e)}),_p(this,"_handleTokenWillExpire",()=>{OE.debug("[".concat(this._clientId,"] received message onTokenPrivilegeWillExpire")),this.emit(yf.ON_TOKEN_PRIVILEGE_WILL_EXPIRE)}),_p(this,"_handleBeforeUnload",e=>{"beforeunload"===e.type&&void 0!==e.returnValue&&""!==e.returnValue||(this.leave(),OE.info("[".concat(this._clientId,"] auto leave onbeforeunload or pagehide")))}),_p(this,"_handleUpdateNetworkQuality",()=>{if("normal"===this._networkQualitySensitivity)return;if(navigator&&void 0!==navigator.onLine&&!navigator.onLine)return void this.emit(yf.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6});const e={downlinkNetworkQuality:0,uplinkNetworkQuality:0};e.uplinkNetworkQuality=this._p2pChannel.getUplinkNetworkQuality(),e.downlinkNetworkQuality=this._p2pChannel.getDownlinkNetworkQuality(),this.emit(yf.NETWORK_QUALITY,e)}),this._codec=e.codec,this._mode=e.mode,this._clientId=GI(5,"client-"),this.store=new mw(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),OE.info("[".concat(this._clientId,"] Initializing AgoraRTC client v").concat(wE," build: ").concat(bE,", mode: ").concat(this._mode,", codec: ").concat(this._codec)),e.clientRoleOptions)try{Vf(e.clientRoleOptions),t=Object.assign({},e.clientRoleOptions)}catch(e){OE.warning("[".concat(this._clientId,"] ").concat(e.toString()))}this._statsCollector=new vI(this.store),this._statsCollector.onStatsException=(e,t,i)=>{OE.debug("[".concat(this._clientId,"] receive exception msg, code: ").concat(e,", msg: ").concat(t,", uid: ").concat(i)),this.emit
6(yf.EXCEPTION,{code:e,msg:t,uid:i})},this._statsCollector.onUploadPublishDuration=(e,t,i,n)=>{const r=this._users.find(t=>t.uid===e);r&&vg.peerPublishStatus(this._sessionId,{subscribeElapse:n,audioPublishDuration:t,videoPublishDuration:i,peer:r._uintid})},this.store.useDataChannel=FS().supportDataChannel&&GE("SIGNAL_CHANNEL"),this._gateway=new bv(this.store,{clientId:this._clientId,mode:this._mode,codec:this._codec,websocketRetryConfig:e.websocketRetryConfig||TE,httpRetryConfig:e.httpRetryConfig||TE,forceWaitGatewayResponse:void 0===e.forceWaitGatewayResponse||e.forceWaitGatewayResponse,statsCollector:this._statsCollector,role:e.role,clientRoleOptions:t}),this._config=e,this._configDistribute=new aC,this._p2pChannel=new lw(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=Sw(),a=Tw()?window.isSecureContext:"Browser Not Support";if(!Tw()&&!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";OE.warning(e)}const c=WI();"DISCONNECTED"===this.connectionState&&(this.store.avoidJoinStart=Math.round(Date.now()),OE.debug("[".concat(this._clientId,"] set avoidJoinStart to ").concat(this.store.avoidJoinStart)));const d=vg.reportApiInvoke(c,{name:_f.JOIN,options:[e,t,i,n],states:{isHttps:s,isSecureContext:a},tag:Ef.TRACER});vg.setAppId(e);try{if(!i&&null!==i)throw new SE(fE.INVALID_PARAMS,"Invalid token: ".concat(i,". If you don not use token, set it to null"));i&&Xm(i,"token",1,2047),Xm(e,"appid",1,2047),Qm(t),n&&Zm(n),r&&Xm(r,"optionalInfo",1,2047)}catch(e){throw d.onError(e),e}if(OE.info("[".concat(this._clientId,"] start join channel ").concat(t,", join number: ").concat(o)),this._leaveMutex.isLocked){OE.debug("[".concat(this._clientId,"] join: waiting leave operation"));(await this._leaveMutex.lock())(),OE.debug("[".concat(this._clientId,"] join: continue"))}if(this._joinAndNotLeaveYet=!0,"DISCONNECTED"!==this.connectionState){const e=new SE(fE.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=xN({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=nv("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=fg(e),r=await window.crypto.subtle.encrypt({name:"RSA-OAEP"},i,n);return rv(new Uint8Array(r))})(this._encryptionSecret),!this._joinAndNotLeaveYet)throw new SE(fE.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&&vg.joinChannelTimeout(this._sessionId,5)},5e3);try{let n;const r=u.cloudProxyServer;if(["proxy3","proxy4","proxy5"].includes(r)){const e=GE("PROXY_SERVER_TYPE3");Array.isArray(e)?u.proxyServer=e[0]:u.proxyServer=e}if(vg.setProxyServer(u.proxyServer),OE.setProxyServer(u.proxyServer),this.store.requestAPStart(),u.stringUid&&!u.uid){const e=await $v(u.stringUid,u,this._axiosCancelSource.token,this._config.httpRetryConfig||TE,this.store);OE.debug("getUserAccount Success ".concat(u.stringUid," => ").concat(e)),u.uid=e,n=await Zv(u,this._axiosCancelSource.token,this._config.httpRetryConfig||TE,!0,this.store)}else n=await Zv(u,this._axiosCancelSource.token,this._config.httpRetryConfig||TE,!0,this.store);if(!this._joinAndNotLeaveYet)throw new SE(fE.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this.store.requestAPEnd(),setTimeout(()=>{this._configDistribute.startGetConfigDistribute(u,this._axiosCancelSource.token),this._configDistribute.on(IS.UPDATE_BITRATE_LIMIT,e=>{this._p2pChannel.updateBitrateLimit(e)})},0),this._key=i||e;const o=n.gatewayInfo;this._joinInfo=xN(xN({},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 SE(fE.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 OE.info("[".concat(this._clientId,"] Joining channel success: channel: ").concat(t,",").concat(a)),setTimeout(()=>{OE.startUpload()},5e3),this.store.joinEnd(),h=this,zE.includes(h)||zE.push(h),s}catch(e){const t=Array.isArray(e)?e[0]:e;throw OE.error("[".concat(this._clientId,"] join number: ").concat(o,", Joining channel failed, rollback"),t),t.code!==fE.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 SE(fE.INVALID_OPERATION);return this._gateway.join(this._joinInfo,this._key,!("disabled"!==this._joinInfo.cloudProxyServer||this._joinInfo.proxyServer||!GE("JOIN_WITH_FALLBACK_SIGNAL_PROXY"))).then(e=>e).catch(e=>{if(e.code===fE.INIT_WEBSOCKET_TIMEOUT)return this._gateway.leave(!0,Cf.FALLBACK),e;if(e.code===fE.INIT_DATACHANNEL_TIMEOUT)return this._gateway.leave(!0,Cf.FALLBACK),e;throw e}).then(e=>{if(e instanceof SE){if(e.code===fE.INIT_WEBSOCKET_TIMEOUT){if(OE.info("[".concat(this._clientId,"] join timeout, fallback to proxy")),!this._joinInfo||!this._key)throw new SE(fE.INVALID_OPERATION);this._joinInfo.cloudProxyServer="fallback",this._cloudProxyServerMode="fallback",this.store.cloudProxyServerMode="fallback";const e=GE("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(".");
6e.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=GE("LOG_UPLOAD_SERVER").match(/.+:(\d{1,5})$/);t&&t[1]&&"443"!==t[1]&&OE.setProxyServer(this._joinInfo.proxyServer),"443"!==GE("STATS_COLLECTOR_PORT").toString()&&vg.setProxyServer(this._joinInfo.proxyServer);return vg.reportApiInvoke(this._sessionId,{name:_f.JOIN_FALLBACK_TO_PROXY,options:[this._joinInfo.proxyServer],tag:Ef.TRACER}).onSuccess(),this.emit(yf.JOIN_FALLBACK_TO_PROXY,this._joinInfo.proxyServer),GE("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&this._joinInfo.turnServer.servers.forEach(e=>{"forceturn"in e&&(e.forceturn=!0)}),this._gateway.join(this._joinInfo,this._key)}if(OE.info("[".concat(this._clientId,"] join by datachannel timeout, fallback to websocket")),!this._joinInfo||!this._key)throw new SE(fE.INVALID_OPERATION);return vg.reportApiInvoke(this._sessionId,{name:_f.DATACHANNEL_FAILBACK,options:[this.store.clientId],tag:Ef.TRACER}).onSuccess(),this._joinGateway()}return e}).then(e=>e)}async leave(){OE.info("[".concat(this._clientId,"] Leaving channel")),window.removeEventListener(Wh()?"beforeunload":"pagehide",this._handleBeforeUnload),this._reset(),function(e){const t=zE.indexOf(e);-1!==t&&zE.splice(t,1)}(this);const e=await this._leaveMutex.lock();if("DISCONNECTED"===this.connectionState)return OE.info("[".concat(this._clientId,"] Leaving channel repeated, success")),void e();await this._gateway.leave("CONNECTED"!==this.connectionState),OE.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 SE(fE.INVALID_PARAMS,"track list is empty");if("audience"===this._gateway.role)throw new SE(fE.INVALID_OPERATION,"audience can not publish stream");for(const i of e){if(!(i instanceof wg))throw new SE(fE.INVALID_PARAMS,"parameter is not local track");if(!i._enabled&&t)throw new SE(fE.TRACK_IS_DISABLED,"can not publish a disabled track: ".concat(i.getTrackId()))}OE.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 py&&t&&e.setBitrateLimit(t.uplink)});const i=await this._publishMutex.lock();try{await this._publishHighStream(e),OE.info("[".concat(this._clientId,"] Publish success, id ").concat(e.map(e=>"".concat(e.getTrackId()," "))))}catch(e){throw OE.error("[".concat(this._clientId,"] publish error"),e.toString()),e}finally{i()}}async unpublish(e){if(!this._joinInfo||void 0===this._uid)throw new SE(fE.INVALID_OPERATION,"Can't unpublish stream, haven't joined yet!");e?Array.isArray(e)||(e=[e]):e=this._p2pChannel.getAllTracks(!0),OE.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),OE.info("[".concat(this._clientId,"] Unpublish success,tracks ").concat(e.map(e=>"".concat(e.getTrackId()))))}catch(e){throw OE.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(Ym(t,"mediaType",["audio","video"]),!this._joinInfo)throw new SE(fE.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new SE(fE.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));if(!this._users.find(t=>t===e)){const t=new SE(fE.INVALID_REMOTE_USER,"user is not in the channel");throw OE.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 SE(fE.INVALID_REMOTE_USER,"user is not published");throw OE.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 SE(fE.REMOTE_USER_IS_NOT_PUBLISHED);throw OE.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?CS.AUDIO:CS.VIDEO,ssrcId:n},a=await this._subscribeMutex.lock();OE.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{gI.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)!==fE.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}OE.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch(e=>{OE.warning("[".concat(this._clientId,"] auto set fallback failed"),e)});const i="audio"===t?e._audioTrack:e._videoTrack;if(!i)throw new SE(fE.UNEXPECTED_ERROR,"can not find remote track in user object");return i}catch(t){throw OE.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{a()}}async massSubscribe(e){if(zm(e,"subscribeList"),!this._joinInfo)throw new SE(fE.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new SE(fE.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const t=Date.now(),i=new Map,n=await this._subscribeMutex.lock();OE.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(Ym(s,"mediaType",["audio","video"]),!o){const e=new SE(fE.INVALID_PARAMS,"user property does not exist in subscribeList item");throw OE.error("[".concat(this._clientId,"] user property does not exist in subscribeList item")),e}if(!this._users.find(e=>e===o)){const i=new SE(fE.INVALID_REMOTE_USER,"user is not in the channel");OE.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 SE(fE.REMOTE_USER_IS_NOT_PUBLISHED);OE.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=cS.Video|cS.LwoVideo,c=i.get(o);if(c){if("video"===s?c&a:c&cS.Audio){e.splice(t,1),OE.warning("repeat massSubscribe user:".concat(o.uid,", mediaType:").concat(s," twice"));continue}i.set(o,c|("video"===s?a:cS.Audio))}else i.set(o,"video"===s?a:cS.Audio)}for(let t=e.length-1;t>=0;t--){const n=e[t],{user:r,mediaType:o}=n,s=cS.Video|cS.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^cS.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&cS.Audio&&(r.audio_ssrc=i._audioSSRC),n&cS.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===CS.VIDEO?t._videoSSRC:t._audioSSRC,rtxSsrcId:t._rtxSsrcId}}));const i=new Map;if(a.length>0){const e=await this._gateway.subscribeAll(a,!0);
vendor: 6,258 bytes, line 6
6((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=CS.VIDEO:n.audio_error_code&&(t=CS.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=hv(i);OE.error("user:".concat(e.user.uid," mediaType:").concat(e.mediaType," has massSubscribe error ").concat(t.desc)),e.error=new SE(fE.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;vg.subscribe(this.store.sessionId,{succ:!!e.error,ec:(null===(i=e.error)||void 0===i?void 0:i.code)||null,video:e.mediaType===CS.VIDEO,audio:e.mediaType===CS.AUDIO,peerid:e.user.uid,subscribeRequestid:e.mediaType===CS.VIDEO?e.user._videoSSRC:e.user._audioSSRC,p2pid:this.store.p2pId,eventElapse:Math.floor(performance.now()-t)},!0)}),OE.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&&Ym(t,"mediaType",["audio","video"]),!this._joinInfo)throw new SE(fE.INVALID_OPERATION,"Can't unsubscribe stream, haven't joined yet!");if(!this._users.find(t=>t===e)){const t=new SE(fE.INVALID_REMOTE_USER,"user is not in the channel");throw OE.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}OE.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),OE.info("[".concat(this._clientId,"] unsubscribe success uid: ").concat(e.uid,", mediaType: ").concat(t))}catch(t){if(t.code===fE.DISCONNECT_P2P)return void OE.warning("disconnecting p2p, abort unsubscribe request.");throw OE.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}}async massUnsubscribe(e){if(zm(e,"unsubscribeList"),!this._joinInfo)throw new SE(fE.INVALID_OPERATION,"Can't unsubscribeAll stream, haven't joined yet!");OE.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 SE(fE.INVALID_PARAMS,"user property does not exist in unsubscribeList item");throw OE.error("[".concat(this._clientId,"] user property does not exist in unsubscribeList item")),e}Ym(r,"mediaType",["video","audio",void 0]);if(!this._users.find(e=>e===n)){OE.warning("[".concat(this._clientId,"] can not unsubscribe ").concat(n.uid,", user is not in the channel")),e.splice(i,1);continue}const o=cS.Video|cS.LwoVideo;if(t.has(n)){const s=t.get(n);let a;switch(r){case"video":a=s&o;break;case"audio":a=s&cS.Audio;break;default:a=s&(cS.Audio|o)}if(a){OE.warning("repeat massUnsubscribe user:".concat(n.uid,",mediaType:").concat(r," twice.")),e.splice(i,1);continue}r?"audio"===r?t.set(n,s|cS.Audio):"video"===r&&t.set(n,s|o):t.set(n,s|cS.Audio|o)}else r?"audio"===r?t.set(n,cS.Audio):"video"===r&&t.set(n,o):t.set(n,cS.Audio|o)}try{const t=await this._p2pChannel.massUnsubscribe(e);t&&await this._gateway.massUnsubscribe(t),OE.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===fE.DISCONNECT_P2P)return void OE.warning("disconnecting p2p, abort unsubscribe request.");throw OE.error("[".concat(this._clientId,"] massUnsubscribe error"),e.toString()),e}}setLowStreamParameter(e){!function(e){if(!e)throw new SE(fE.INVALID_PARAMS);$m(e.width)||Jm(e.width,"streamParameter.width"),$m(e.height)||Jm(e.height,"streamParameter.height"),$m(e.framerate)||Jm(e.framerate,"streamParameter.framerate"),$m(e.bitrate)||qm(e.bitrate,"streamParameter.bitrate")}(e),(!e.width&&e.height||e.width&&!e.height)&&OE.warning("[".concat(this._clientId,"] The width and height parameters take effect only when both are set")),OE.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(!FS().supportDualStream)throw vg.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),new SE(fE.NOT_SUPPORTED,"Your browser is not support dual stream");if(this._isDualStreamEnabled)throw new SE(fE.INVALID_OPERATION,"Dual stream is already enabled");if(this._p2pChannel.canPublishLowStream())try{await this._publishLowStream()}catch(e){throw vg.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),e}this._isDualStreamEnabled=!0,vg.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!0}),OE.info("[".concat(this._clientId,"] enable dual stream"))}async disableDualStream(){if(this._isDualStreamEnabled){if(!this._joinInfo)throw new SE(fE.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if(this._p2pChannel.getLocalMedia(yS.LocalVideoLowTrack))try{const e=await this._p2pChannel.unpublishLowStream();e&&await this._gateway.unpublish(e,this._joinInfo.stringUid||this._joinInfo.uid)}catch(e){throw vg.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!1}),e}this._isDualStreamEnabled=!1,vg.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!0}),OE.info("[".concat(this._clientId,"] disable dual stream"))}}
vendor: 4,626 bytes, line 6
6async setClientRole(e,t){if(function(e){Ym(e,"role",["audience","host"])}(e),t&&Vf(t),"rtc"===this._mode)throw OE.warning("[".concat(this._clientId,"]rtc mode can not use setClientRole")),new SE(fE.INVALID_OPERATION,"rtc mode can not use setClientRole");if(t&&t.level&&"host"===e)throw new SE(fE.INVALID_OPERATION,"host mode can not set audience latency level");if("audience"===e&&this._p2pChannel.hasLocalMedia())throw new SE(fE.INVALID_OPERATION,"can not set client role to audience when publishing stream");await this._gateway.setClientRole(e,t),OE.info("[".concat(this._clientId,"] set client role to ").concat(e,", level: ").concat(t&&t.level))}setProxyServer(e,t){if(Xm(e,"proxyServer"),!t){if("DISCONNECTED"!==this.connectionState)throw new SE(fE.INVALID_OPERATION,"Set proxy server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new SE(fE.INVALID_OPERATION,"You have already set the proxy")}this._proxyServer=e,vg.setProxyServer(this._proxyServer),OE.setProxyServer(this._proxyServer),OE.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 SE(fE.INVALID_OPERATION,"Set turn server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new SE(fE.INVALID_OPERATION,"You have already set the proxy")}if(Uf(e))return this._turnServer={servers:e,mode:"original-manual"},void OE.info("[".concat(this._clientId,"] Set original turnserver ").concat(t?"by initialize call":""," success: ").concat(e.map(e=>e.urls).join(","),"."));e.forEach(e=>xf(e)),this._turnServer={servers:e,mode:"manual"},OE.info("[".concat(this._clientId,"] Set turnserver ").concat(t?"by initialize call":""," success."))}setLicense(e){if("DISCONNECTED"!==this.connectionState){throw new SE(fE.INVALID_OPERATION,"you should set license before join channel")}if(Xm(e,"license",32,32),!/^[A-Za-z\d]+$/.test(e))throw new SE(fE.INVALID_PARAMS,"license should only contains characters from A-Z a-z 0-9");this._license=e,OE.info("[".concat(this._clientId,"] set license success"),e)}startProxyServer(e){if("DISCONNECTED"!==this.connectionState)throw new SE(fE.INVALID_OPERATION,"Start proxy server before join channel");if(this._proxyServer||"manual"===this._turnServer.mode||this._useLocalAccessPoint)throw new SE(fE.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 SE(fE.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 SE(fE.INVALID_PARAMS,"proxy server mode must be ".concat(t.join("|")))}this._cloudProxyServerMode=i,this.store.cloudProxyServerMode=i,OE.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode)}stopProxyServer(){if("DISCONNECTED"!==this.connectionState)throw new SE(fE.INVALID_OPERATION,"Stop proxy server after leave channel");vg.setProxyServer(),OE.setProxyServer(),this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled",OE.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 SE(fE.INVALID_PARAMS,"accessPoints is required.");zm(e.accessPoints.serverList,"accessPoints.serverList"),Xm(e.accessPoints.domain,"accessPoints.domain");const t=(e,t)=>{qm(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 SE(fE.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");GE("CLOSE_AFB_FOR_LOCAL_AP")&&(BE("JOIN_WITH_FALLBACK_SIGNAL_PROXY",!1),BE("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,BE("WEBCS_DOMAIN",s),BE("WEBCS_DOMAIN_BACKUP_LIST",s),BE("GATEWAY_DOMAINS",[r]),e.report&&e.report.hostname&&Array.isArray(e.report.hostname)&&e.report.hostname.length?(zm(e.report.hostname,"report.hostname"),BE("EVENT_REPORT_DOMAIN",e.report.hostname[0]),BE("EVENT_REPORT_BACKUP_DOMAIN",e.report.hostname[1]||e.report.hostname[0])
6):(BE("EVENT_REPORT_DOMAIN",o[0]),BE("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),BE("STATS_COLLECTOR_PORT",a),e.report?BE("ENABLE_EVENT_REPORT",!0):BE("ENABLE_EVENT_REPORT",!1);let c="";e.log&&e.log.hostname&&Array.isArray(e.log.hostname)&&e.log.hostname.length?(zm(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),BE("LOG_UPLOAD_SERVER","".concat(c,":").concat(d));let u=[];e.cds&&e.cds.hostname&&Array.isArray(e.cds.hostname)&&e.cds.hostname.length?(zm(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),BE("CDS_AP",u.map(e=>"".concat(e,":").concat(l))),e.cds?BE("ENABLE_CONFIG_DISTRIBUTE",!0):BE("ENABLE_CONFIG_DISTRIBUTE",!1),OE.info("set local access point v2 success")}setLocalAccessPoints(e,t){if(zm(e,"serverList"),Xm(t,"domain"),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new SE(fE.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,BE("WEBCS_DOMAIN",e),BE("WEBCS_DOMAIN_BACKUP_LIST",e),BE("GATEWAY_DOMAINS",[t]),BE("EVENT_REPORT_DOMAIN",e[0]),BE("EVENT_REPORT_BACKUP_DOMAIN",e[1]||e[0]),BE("LOG_UPLOAD_SERVER","".concat(e[0],":6444")),OE.info("set local access point success")}async setRemoteDefaultVideoStreamType(e){if(Ym(e,"streamType",[0,1]),this._remoteDefaultVideoStreamType=e,this._joinInfo)try{await this._gateway.setDefaultRemoteVideoStreamType(e),this._joinInfo.defaultVideoStream=this._remoteDefaultVideoStreamType}catch(e){throw OE.error("[".concat(this._clientId,"] set default remote video stream type error"),e.toString()),e}else OE.debug("haven't joined yet, cache remoteDefaultVideoStreamType ".concat(e))}async setRemoteVideoStreamType(e,t){Ym(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 OE.error("[".concat(this._clientId,"] set remote video stream type error"),e.toString()),e}OE.info("[".concat(this._clientId,"] set remote ").concat(e," video stream type to ").concat(t)),this._remoteStreamTypeCacheMap.set(e,t)}async setStreamFallbackOption(e,t){Ym(t,"fallbackType",[0,1,2]);try{await this._gateway.setStreamFallbackOption(e,t)}catch(e){throw OE.error("[".concat(this._clientId,"] set stream fallback option"),e.toString()),e}OE.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){Ym(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),Xm(t,"secret");if(["aes-128-gcm2","aes-256-gcm2"].includes(e)){if(!i||!(i instanceof Uint8Array&&32===i.length))throw new SE(fE.INVALID_PARAMS,"salt must be an Uint8Array and exactly equal to 32 bytes")}else if(i)throw new SE(fE.INVALID_PARAMS,"current encrypt mode does not need salt");new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*,.<>?/:;'\"|{}\\[\\]])(?=.{8,})").test(t)||OE.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=rv(i))}async renewToken(e){if(Xm(e,"token",1,2047),!this._key||!this._joinInfo)throw new SE(fE.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(GE("USE_NEW_TOKEN")){OE.debug("start renew token with ticket from unilbs");const t=await rC(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||TE);OE.debug("[".concat(this._clientId,"] get ticket from unilbs success")),await this._gateway.renewToken({token:e,ticket:t})}else OE.debug("start renew token without ticket"),await this._gateway.renewToken({token:e});OE.debug("[".concat(this._clientId,"] renewToken success"))}catch(e){throw this._key=t,this._joinInfo.token=t,OE.error("[".concat(this._clientId,"] renewToken failed"),e.toString()),e}finally{i()}}enableAudioVolumeIndicator(){this._audioVolumeIndicationInterval?OE.warning("you have already enabled audio volume indicator!"):this._audioVolumeIndicationInterval=window.setInterval(()=>{const e=this._p2pChannel.getAudioLevels();
6this.emit(yf.VOLUME_INDICATOR,e)},GE("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 SE(fE.LIVE_STREAMING_INVALID_RAW_STREAM,"raw streaming is only support h264");if(!this._p2pChannel.hasLocalMedia())throw new SE(fE.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 SE(fE.LIVE_STREAMING_TASK_CONFLICT);const i=t?Kf.TRANSCODE:Kf.RAW;return this._createLiveStreamingClient(i).startLiveStreamingTask(e,i)}setLiveTranscoding(e){return this._createLiveStreamingClient(Kf.TRANSCODE).setTranscodingConfig(e)}async stopLiveStreaming(e){const t=[this._liveRawStreamingClient,this._liveTranscodeStreamingClient].filter(t=>t&&t.hasUrl(e));if(!t.length)throw new SE(fE.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 SE(fE.INVALID_OPERATION,"can not addInjectStreamUrl, no joininfo");const i=this._createLiveStreamingClient(Kf.INJECT);i.setInjectStreamConfig(t,0),await i.startLiveStreamingTask(e,Kf.INJECT)}async removeInjectStreamUrl(){var e;const t=this._createLiveStreamingClient(Kf.INJECT),i=Array.from(pR(e=t.streamingTasks).call(e)).find(e=>e.mode===Kf.INJECT);if(!this._joinInfo||!i)throw new SE(fE.INVALID_OPERATION,"can remove addInjectStreamUrl, no joininfo or inject task");await t.stopLiveStreamingTask(i.url)}async startChannelMediaRelay(e){EC(e);const t=this._createChannelMediaRelayClient();await t.startChannelMediaRelay(e)}async updateChannelMediaRelay(e){EC(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 SE(fE.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 SE(fE.INVALID_PARAMS,"stream message out of range.");return this._gateway.signal.request(wf.DATA_STREAM,{payload:rv(e)},!t)}sendMetadata(e){if(!this._joinInfo)throw new SE(fE.INVALID_OPERATION,"can not send metadata, not joined");if(new Blob([e]).size>1024)throw new SE(fE.METADATA_OUT_OF_RANGE);return this._gateway.signal.request(wf.SEND_METADATA,{session_id:this._joinInfo.sid,metadata:rv(e)})}async sendCustomReportMessage(e){if(Array.isArray(e)||(e=[e]),e.forEach(cf),!this._joinInfo)throw new SE(fE.INVALID_OPERATION,"can not send custom report, not joined");await vg.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){Ym(t.spatialLayer,"spatialLayer",[0,1,2,3]),Ym(t.temporalLayer,"temporalLayer",[0,1,2,3]);try{await this._gateway.pickSVCLayer(e,t)}catch(e){throw OE.error("[".concat(this._clientId,"] pick SVC layer failed"),e.toString()),e}}_reset(){if(OE.debug("[".concat(this._clientId,"] reset client")),this._axiosCancelSource.cancel(),this._axiosCancelSource=pE.CancelToken.source(),this._streamFallbackTypeCacheMap=new Map,this._remoteStreamTypeCacheMap=new Map,this._configDistribute.stopGetConfigDistribute(),this._joinInfo=void 0,this._proxyServer=void 0,this._defaultStreamFallbackType=void 0,this._sessionId=null,this.store.sessionId=null,this._statsCollector.reset(),this._key=void 0,this._appId=void 0,this._uid=void 0,this.store.uid=void 0,this._channelName=void 0,this._encryptionMode="none",this._encryptionSecret=null,this._encryptionSalt=null,this._users.forEac
6h(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 Og("client-publish"),this._subscribeMutex=new Og("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||WI();e?OE.debug("[".concat(this._clientId,"] new Session ").concat(i)):OE.debug("[".concat(this._clientId,"] renewSession ").concat(this._sessionId," => ").concat(i)),this._sessionId=i,this.store.sessionId=i,t?vg.sessionInit(this._sessionId,{lts:(new Date).getTime(),cname:t.channel,appid:t.appId,mode:this._mode}):this._joinInfo?vg.sessionInit(this._sessionId,{lts:(new Date).getTime(),cname:this._joinInfo.cname,a
6ppid:this._joinInfo.appId,mode:this._mode}):this._gateway.joinInfo&&vg.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 SE(fE.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new SE(fE.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&GE("FORCE_TURN")&&!GE("TURN_ENABLE_TCP")&&!GE("TURN_ENABLE_UDP"))throw new SE(fE.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");OE.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!==fE.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 py&&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)===fE.WS_ABORT)return;throw t}}async _publishLowStream(){if(!this._joinInfo||void 0===this._uid)throw new SE(fE.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new SE(fE.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));OE.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!==fE.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)===fE.WS_ABORT)return;throw e}}_createLiveStreamingClient(e){if(!this._joinInfo||!this._appId){return new SE(fE.INVALID_OPERATION,"can not create live streaming client, please join channel first").throw()}const t=()=>new pC(this._joinInfo,this._config.websocketRetryConfig||TE,this._config.httpRetryConfig||TE),i=e=>{e.onLiveStreamError=(e,t)=>{vg.reportApiInvoke(this._sessionId,{name:_f.ON_LIVE_STREAM_ERROR,options:[e,t],tag:Ef.TRACER}).onSuccess(),this.emit(yf.LIVE_STREAMING_ERROR,e,t)},e.onLiveStreamWarning=(e,t)=>{vg.reportApiInvoke(this._sessionId,{name:_f.ON_LIVE_STREAM_WARNING,options:[e,t],tag:Ef.TRACER}).onSuccess(),this.emit(yf.LIVE_STREAMING_WARNING,e,t)},e.on($f.REQUEST_WORKER_MANAGER_LIST,(e,t,i)=>{if(!this._joinInfo)return i(new SE(fE.INVALID_OPERATION,"can not find join info to get worker manager"));iC(e,this._joinInfo,this._axiosCancelSource.token,TE).then(t).catch(i)})};switch(e){case Kf.RAW:return this._liveRawStreamingClient||(this._liveRawStreamingClient=t(),i(this._liveRawStreamingClient)),this._liveRawStreamingClient;case Kf.TRANSCODE:return this._liveTranscodeStreamingClient||(this._liveTranscodeStreamingClient=t(),i(this._liveTranscodeStreamingClient)),this._liveTranscodeStreamingClient;case Kf.INJECT:return this._injectStreamingClient||(this._injectStreamingClient=t(),this._injectStreamingClient.on($f.REQUEST_WORKER_MANAGER_LIST,(e,t,i)=>{if(!this._joinInfo)return i(new SE(fE.INVALID_OPERATION,"can not find join info to get worker manager"));iC(e,this._joinInfo,this._axiosCancelSource.token,TE).then(t).cat
6ch(i)}),this._injectStreamingClient.onInjectStatusChange=(e,t,i)=>{this.emit(yf.INJECT_STREAM_STATUS,e,t,i)}),this._injectStreamingClient}}_createChannelMediaRelayClient(){if(!this._joinInfo){return new SE(fE.INVALID_OPERATION,"can not create channel media relay client, please join channel first").throw()}return this._channelMediaRelayClient||(this._channelMediaRelayClient=new fC(this._joinInfo,this._clientId,this._config.websocketRetryConfig||TE,this._config.httpRetryConfig||TE),this._channelMediaRelayClient.on("state",e=>{e===rS.RELAY_STATE_FAILURE&&this._channelMediaRelayClient&&this._channelMediaRelayClient.dispose(),this.emit(yf.CHANNEL_MEDIA_RELAY_STATE,e)}),this._channelMediaRelayClient.on("event",e=>{this.emit(yf.CHANNEL_MEDIA_RELAY_EVENT,e)})),this._channelMediaRelayClient}_handleGatewayEvents(){this._gateway.on(aS.DISCONNECT_P2P,async()=>{await this._p2pChannel.disconnectForReconnect()}),this._gateway.on(aS.CONNECTION_STATE_CHANGE,(e,t,i)=>{var n;if(i===Cf.FALLBACK)return;const r=()=>{this.emit(yf.CONNECTION_STATE_CHANGE,e,t,i)};if(vg.reportApiInvoke(this._sessionId||(null===(n=this._gateway.joinInfo)||void 0===n?void 0:n.sid)||null,{name:_f.CONNECTION_STATE_CHANGE,options:[e,t,i],tag:Ef.TRACER}).onSuccess(JSON.stringify({cur:e,prev:t,reason:i})),OE.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;
6this._streamFallbackTypeCacheMap.forEach((e,t)=>{this._gateway.setStreamFallbackOption(t,e).catch(e=>{OE.warning("[".concat(this._clientId,"] auto set stream fallback option failed"),e)})}),this._remoteStreamTypeCacheMap.forEach((e,t)=>{this._gateway.setRemoteVideoStreamType(t,e).catch(e=>{OE.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(()=>{OE.debug("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway connected"))}).catch(e=>{OE.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=>{OE.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_||(OE.debug("[".concat(this._clientId,"] auto dispatch audio unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,"audio",!1)),e._trust_video_mute_state_||(OE.debug("[".concat(this._clientId,"] auto dispatch video unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,"video",!1)),e._trust_audio_enabled_state_||(OE.debug("[".concat(this._clientId,"] auto dispatch enable local audio ").concat(e.uid)),this._handleSetStreamLocalEnable("audio",e.uid,!0)),e._trust_video_enabled_state_||(OE.debug("[".concat(this._clientId,"] auto dispatch enable local video ").concat(e.uid)),this._handleSetStreamLocalEnable("video",e.uid,!0)),e._trust_video_stream_added_state_||(OE.debug("[".concat(this._clientId,"] auto dispatch reset video stream added ").concat(e.uid)),this._handleResetAddStream(e,"video")),e._trust_audio_stream_added_state_||(OE.debug("[".concat(this._clientId,"] auto dispatch reset audio stream added ").concat(e.uid)),this._handleResetAddStream(e,"audio")),e._video_added_||e._audio_added_||(OE.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(aS.REQUEST_NEW_GATEWAY_LIST,(e,t)=>{if(!this._joinInfo)return t(new SE(fE.UNEXPECTED_ERROR,"can not recover, no join info"));Qv(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||TE,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(aS.NETWORK_QUALITY,e=>{"normal"===this._networkQualitySensitivity&&this.emit(yf.NETWORK_QUALITY,e)}),this._gateway.on(aS.STREAM_TYPE_CHANGE,(e,t)=>{this.emit(yf.STREAM_TYPE_CHANGED,e,t);vg.reportApiInvoke(this._sessionId,{name:_f.STREAM_TYPE_CHANGE,options:[e,t],tag:Ef.TRACER}).onSuccess(JSON.stringify({uid:e,streamType:t}))}),this._gateway.on(aS.IS_P2P_DISCONNECTED,e=>{this._p2pChannel.isP2PDisconnected()?e(!0):this._p2pChannel.hasLocalMedia()||this._p2pChannel.hasRemoteMedia()?e(!1):e(!0)}),this._gateway.on(aS.NEED_RENEW_SESSION,()=>{this._startSession()}),this._gateway.on(aS.REQUEST_P2P_CONNECTION_PARAMS,async(e,t,i)=>{try{t(await this._p2pChannel.startP2PConnection(e))}catch(e){i(e)}}),this._gateway.on(aS.JOIN_RESPONSE,(e,t)=>{const{dtlsParameters:i,iceParameters:n,candidates:r,rtpCapabilities:o,setup:s,cname:a}=PO(e.ortc,t);this._p2pChannel.connect(n,i,r,o,s,a)}),this._gateway.on(aS.REQUEST_DC_CONNECTION_PARAMS,e=>{e(this._p2pChannel.getEstablishParams())}),this._gateway.on(aS.RESET_SIGNAL,e=>{this._p2pChannel.resetConnection(e),this._handleGatewaySignalEvents()}),this._gateway.on(aS.DATACHANNEL_FAILBACK,()=>{this._joinGateway()}),this._gateway.on(aS.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:{}}],OE.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:{}}),OE.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=GE("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(Df.ON_USER_ONLINE,this._handleUserOnline),this._gateway.signal.on(Df.ON_USER_OFFLINE,this._handleUserOffline),this._gateway.signal.on(Df.ON_ADD_AUDIO_STREAM,e=>this._handleAddAudioOrVideoStream("audio",e.uid,e.ssrcId,e.cname,e.uint_id,e.ortc)),this._gateway.signal.on(Df.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(Df.ON_REMOVE_STREAM,this._handleRemoveStream),this._gateway.signal.on(Df.ON_P2P_LOST,this._handleP2PLost),this._gateway.signal.on(Df.MUTE_AUDIO,e=>this._handleMuteStream(e.uid,"audio",!0)),this._gateway.signal.on(Df.UNMUTE_AUDIO,e=>this._handleMuteStream(e.uid,"audio",!1)),this._gateway.signal.on(Df.MUTE_VIDEO,e=>this._handleMuteStream(e.uid,"video",!0)),this._gateway.signal.on(Df.UNMUTE_VIDEO,e=>this._handleMuteStream(e.uid,"video",!1)),this._gateway.signal.on(Df.RECEIVE_METADATA,e=>{const t=nv(e.metadata);
6this.emit(yf.RECEIVE_METADATA,e.uid,t)}),this._gateway.signal.on(Df.ON_DATA_STREAM,e=>{e.seq&&delete e.seq,e.payload=nv(e.payload),this.emit(yf.STREAM_MESSAGE,e.uid,e.payload),this.onStreamMessage&&this.onStreamMessage(e)}),this._gateway.signal.on(Df.ON_CRYPT_ERROR,()=>{iv(()=>{OE.warning("[".concat(this._clientId,"] on crypt error")),this.emit(yf.CRYPT_ERROR)},this._sessionId)}),this._gateway.signal.on(Df.ON_TOKEN_PRIVILEGE_WILL_EXPIRE,this._handleTokenWillExpire),this._gateway.signal.on(Df.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{OE.warning("[".concat(this._clientId,"] received message onTokenPrivilegeDidExpire, please get new token and join again")),this._gateway.leave(!0),this.emit(yf.ON_TOKEN_PRIVILEGE_DID_EXPIRE),this._reset()}),this._gateway.signal.on(Df.ON_STREAM_FALLBACK_UPDATE,e=>{OE.debug("[".concat(this._clientId,"] stream fallback peerId: ").concat(e.stream_id,", attr: ").concat(e.stream_type)),this.emit(yf.STREAM_FALLBACK,e.stream_id,1===e.stream_type?"fallback":"recover")}),this._gateway.signal.on(Df.ON_PUBLISH_STREAM,e=>{this.uid===this._uid&&(this._p2pChannel.reportPublishEvent(!0,null,void 0,!1,JSON.stringify({proxy:e.proxy})),OE.info("[".concat(this._clientId,"] on publish stream, ").concat(JSON.stringify(e))))}),this._gateway.signal.on(Df.ENABLE_LOCAL_VIDEO,e=>{this._handleSetStreamLocalEnable("video",e.uid,!0)}),this._gateway.signal.on(Df.DISABLE_LOCAL_VIDEO,e=>{this._handleSetStreamLocalEnable("video",e.uid,!1)}),this._gateway.signal.on(bf.REQUEST_TIMEOUT,(e,t)=>{if(this._joinInfo)switch(e){case wf.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===sS.Audio}),a=e.some(e=>{let{stream_type:t}=e;return t!==sS.Audio}),c=e.some(e=>{let{stream_type:t}=e;return t===sS.Screen||t===sS.ScreenLow});"offer"===t.state&&vg.publish(this._joinInfo.sid,{eventElapse:gI.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:!1,ec:fE.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===sS.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!==sS.Audio}))||void 0===r||null===(o=r.ssrcs[0])||void 0===o?void 0:o.ssrcId.toString():void 0})}break}case wf.SUBSCRIBE:(t=t)&&vg.subscribe(this._joinInfo.sid,{succ:!1,ec:fE.TIMEOUT,audio:t.stream_type===CS.AUDIO,video:t.stream_type===CS.VIDEO,peerid:t.stream_id,subscribeRequestid:t.ssrcId,p2pid:this.store.p2pId,eventElapse:gI.measureFromSubscribeStart(this.store.clientId,t.ssrcId)})}}),this._gateway.signal.on(Df.ON_P2P_OK,e=>{this.uid,this._uid}),this._gateway.signal.on(Df.ON_PUBLISHED_USER_LIST,e=>{if(null==e||!e.users)return;GE("BLOCK_LOCAL_CLIENT")&&(e.users=e.users.filter(e=>!ZE(e.audio_ssrc,this.channelName)));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 Ey(n.stream_id,n.stream_id),this._users.push(e),0===this.getListeners(yf.PUBLISHED_USER_LIST).length&&(OE.debug("[".concat(this._clientId,"] user online"),n.stream_id),this.emit(yf.USER_JOINED,e)));const r=cS.Audio&n.stream_type,o=(cS.Video|cS.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(yf.PUBLISHED_USER_LIST).length&&(OE.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published audio")),this.emit(yf.USER_PUBLISHED,e,"audio")),o&&!a&&0===this.getListeners(yf.PUBLISHED_USER_LIST).length&&(OE.info("[".concat(this._clientId,"] remote user ").concat(e.uid," published video")),this.emit(yf.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&&(OE.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=>{OE.error("[".concat(this._clientId,"] mass resubscribe error"),e.toString())})),this.getListeners(yf.PUBLISHED_USER_LIST).length>0?(OE.info("[".concat(this._clientId,"] client emit user-list event, users: ").concat(t.map(e=>
6e.uid).join(", "))),this.emit(yf.PUBLISHED_USER_LIST,t)):OE.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(OS.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===fE.DISCONNECT_P2P?t():i(e)}else t()}),this._p2pChannel.on(OS.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===fE.DISCONNECT_P2P?t():i(e)}else t()}),this._p2pChannel.on(OS.RequestRePublish,(e,t,i)=>{this.publish(e,!1).then(t).catch(i)}),this._p2pChannel.on(OS.RequestReSubscribe,async(e,t,i)=>{try{for(const{user:t,kind:i}of e)i===CS.VIDEO?await this.subscribe(t,"video"):await this.subscribe(t,"audio");t()}catch(e){i(e)}}),this._p2pChannel.on(OS.RequestUploadStats,(e,t)=>{this._gateway.uploadStats(e,t)}),this._p2pChannel.on(OS.MediaReconnectStart,e=>{this.emit(yf.MEDIA_RECONNECT_START,e)}),this._p2pChannel.on(OS.MediaReconnectEnd,e=>{this.emit(yf.MEDIA_RECONNECT_END,e)}),this._p2pChannel.on(OS.NeedSignalRTT,e=>{e(this._gateway.getSignalRTT())}),this._p2pChannel.on(OS.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(OS.RequestReconnect,async()=>{this._gateway.reconnect()}),this._p2pChannel.on(OS.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}=PO(r,o);await this._p2pChannel.connect(a,s,c,d,u,l),await this._p2pChannel.republish(),await this._p2pChannel.reSubscribe()}),this._p2pChannel.on(OS.RequestUnpublishForReconnectPC,async(e,t,i)=>{this._joinInfo&&void 0!==this._uid?(await this._gateway.unpublish(e,this._uid),t()):i()}),this._p2pChannel.on(OS.P2PLost,()=>{this.emit(yf.P2P_LOST,this.store.uid)}),this._p2pChannel.on(OS.UpdateVideoEncoder,e=>{e._encoderConfig&&this._gateway.setVideoProfile(e._encoderConfig)}),this._p2pChannel.on(OS.ConnectionTypeChange,e=>{this.emit(yf.IS_USING_CLOUD_PROXY,e)}),this._p2pChannel.on(OS.RequestLowStreamParameter,e=>{e(this._lowStreamParameter||{width:160,height:120,framerate:15,bitrate:50})}),this._p2pChannel.on(OS.QueryClientConnectionState,e=>{e(this.connectionState)})}getKeyMetrics(){return this.store.keyMetrics}async enableContentInspect(e){if("CONNECTED"!==this.connectionState||!this._joinInfo)throw new SE(fE.INVALID_OPERATION,"[".concat(this._clientId,"] Client did not join channel"));if(this._inspect)throw new SE(fE.INVALID_OPERATION,"[".concat(this._clientId,"] Inspect content service already in connecting/connected state"));if(!e)throw new SE(fE.INVALID_PARAMS,"[".concat(this._clientId,"] inspectConfig is necessary"));if(!e.inspectType||!Array.isArray(e.inspectType))throw new SE(fE.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 SE(fE.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 SE(fE.INVALID_PARAMS,"[".concat(this._clientId,"] inspectConfig.extraInfo length cannot exceed 1024 bytes"));try{const t=new zw(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},TE)}catch(e){throw Array.isArray(e)?e[0]:e}}async disableContentInspect(){if(!this._inspect)throw new SE(fE.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(kS.CONNECTION_STATE_CHANGE,(t,i)=>
6{switch(this.emit(yf.CONTENT_INSPECT_CONNECTION_STATE_CHANGE,t,i),i){case PS.CONNECTED:if("CONNECTED"!==this.connectionState)return void this.emit(yf.CONTENT_INSPECT_ERROR,new SE(fE.OPERATION_ABORTED,"Content inspect was cancelled because it left the channel"));e.inspectImage()}}),e.on(kS.INSPECT_RESULT,(e,t)=>{var i;if((null==t?void 0:t.code)===fE.INVALID_OPERATION&&"DISCONNECTED"===this.connectionState)return OE.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(yf.CONTENT_INSPECT_RESULT,e,t)}),e.on(kS.CLIENT_LOCAL_VIDEO_TRACK,e=>{e(this.localTracks.filter(e=>"video"===e.trackMediaType)[0])})}getJoinChannelServiceRecords(){return OE.debug("getJoinChannelServiceRecords"),this.store.joinChannelServiceRecords}async setPublishAudioFilterEnabled(e){Km(e,"enabled"),BE("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",[Qw],Object.getOwnPropertyDescriptor(MN.prototype,"leave"),MN.prototype),ZT(MN.prototype,"publish",[Zw],Object.getOwnPropertyDescriptor(MN.prototype,"publish"),MN.prototype),ZT(MN.prototype,"unpublish",[$w],Object.getOwnPropertyDescriptor(MN.prototype,"unpublish"),MN.prototype),ZT(MN.prototype,"subscribe",[eN],Object.getOwnPropertyDescriptor(MN.prototype,"subscribe"),MN.prototype),ZT(MN.prototype,"massSubscribe",[tN],Object.getOwnPropertyDescriptor(MN.prototype,"massSubscribe"),MN.prototype),ZT(MN.prototype,"unsubscribe",[iN],Object.getOwnPropertyDescriptor(MN.prototype,"unsubscribe"),MN.prototype),ZT(MN.prototype,"massUnsubscribe",[nN],Object.getOwnPropertyDescriptor(MN.prototype,"massUnsubscribe"),MN.prototype),ZT(MN.prototype,"setLowStreamParameter",[rN],Object.getOwnPropertyDescriptor(MN.prototype,"setLowStreamParameter"),MN.prototype),ZT(MN.prototype,"enableDualStream",[oN],Object.getOwnPropertyDescriptor(MN.prototype,"enableDualStream"),MN.prototype),ZT(MN.prototype,"disableDualStream",[sN],Object.getOwnPropertyDescriptor(MN.prototype,"disableDualStream"),MN.prototype),ZT(MN.prototype,"setClientRole",[aN],Object.getOwnPropertyDescriptor(MN.prototype,"setClientRole"),MN.prototype),ZT(MN.prototype,"setProxyServer",[cN],Object.getOwnPropertyDescriptor(MN.prototype,"setProxyServer"),MN.prototype),ZT(MN.prototype,"setTurnServer",[dN],Object.getOwnPropertyDescriptor(MN.prototype,"setTurnServer"),MN.prototype),ZT(MN.prototype,"setLicense",[uN],Object.getOwnPropertyDescriptor(MN.prototype,"setLicense"),MN.prototype),ZT(MN.prototype,"startProxyServer",[lN],Object.getOwnPropertyDescriptor(MN.prototype,"startProxyServer"),MN.prototype),ZT(MN.prototype,"stopProxyServer",[hN],Object.getOwnPropertyDescriptor(MN.prototype,"stopProxyServer"),MN.prototype),ZT(MN.prototype,"setLocalAccessPointsV2",[pN],Object.getOwnPropertyDescriptor(MN.prototype,"setLocalAccessPointsV2"),MN.prototype),ZT(MN.prototype,"setLocalAccessPoints",[_N],Object.getOwnPropertyDescriptor(MN.prototype,"setLocalAccessPoints"),MN.prototype),ZT(MN.prototype,"setRemoteDefaultVideoStreamType",[EN],Object.getOwnPropertyDescriptor(MN.prototype,"setRemoteDefaultVideoStreamType"),MN.prototype),ZT(MN.prototype,"setRemoteVideoStreamType",[mN],Object.getOwnPropertyDescriptor(MN.prototype,"setRemoteVideoStreamType"),MN.prototype),ZT(MN.prototype,"setStreamFallbackOption",[fN],Object.getOwnPropertyDescriptor(MN.prototype,"setStreamFallbackOption"),MN.prototype),ZT(MN.prototype,"setEncryptionConfig",[SN],Object.getOwnPropertyDescriptor(MN.prototype,"setEncryptionConfig"),MN.prototype),ZT(MN.prototype,"renewToken",[TN],Object.getOwnPropertyDescriptor(MN.prototype,"renewToken"),MN.prototype),ZT(MN.prototype,"enableAudioVolumeIndicator",[gN],Object.getOwnPropertyDescriptor(MN.prototype,"enableAudioVolumeIndicator"),MN.prototype),ZT(MN.prototype,"startLiveStreaming",[RN],Object.getOwnPropertyDescriptor(MN.prototype,"startLiveStreaming"),MN.prototype),ZT(MN.prototype,"setLiveTranscoding",[IN],Object.getOwnPropertyDescriptor(MN.prototype,"setLiveTranscoding"),MN.prototype),ZT(MN.prototype,"stopLiveStreaming",[vN],Object.getOwnPropertyDescriptor(MN.prototype,"stopLiveStreaming"),MN.prototype),ZT(MN.prototype,"addInjectStreamUrl",[CN],Object.getOwnPropertyDescriptor(MN.prototype,"addInjectStreamUrl"),MN.prototype),ZT(MN.prototype,"removeInjectStreamUrl",[yN],Object.getOwnPropertyDescriptor(MN.prototype,"removeInjectStreamUrl"),MN.prototype),ZT(MN.prototype,"startChannelMediaRelay",[AN],Ob
6ject.getOwnPropertyDescriptor(MN.prototype,"startChannelMediaRelay"),MN.prototype),ZT(MN.prototype,"updateChannelMediaRelay",[ON],Object.getOwnPropertyDescriptor(MN.prototype,"updateChannelMediaRelay"),MN.prototype),ZT(MN.prototype,"stopChannelMediaRelay",[bN],Object.getOwnPropertyDescriptor(MN.prototype,"stopChannelMediaRelay"),MN.prototype),ZT(MN.prototype,"sendCustomReportMessage",[wN],Object.getOwnPropertyDescriptor(MN.prototype,"sendCustomReportMessage"),MN.prototype),ZT(MN.prototype,"pickSVCLayer",[NN],Object.getOwnPropertyDescriptor(MN.prototype,"pickSVCLayer"),MN.prototype),ZT(MN.prototype,"enableContentInspect",[DN],Object.getOwnPropertyDescriptor(MN.prototype,"enableContentInspect"),MN.prototype),ZT(MN.prototype,"disableContentInspect",[PN],Object.getOwnPropertyDescriptor(MN.prototype,"disableContentInspect"),MN.prototype),ZT(MN.prototype,"getJoinChannelServiceRecords",[LN],Object.getOwnPropertyDescriptor(MN.prototype,"getJoinChannelServiceRecords"),MN.prototype),ZT(MN.prototype,"setPublishAudioFilterEnabled",[kN],Object.getOwnPropertyDescriptor(MN.prototype,"setPublishAudioFilterEnabled"),MN.prototype),MN);class FN extends Bg{set currentState(e){e!==this._currentState&&(this._currentState=e,this.emit(Lf.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(),_p(this,"audioBuffer",void 0),_p(this,"sourceNode",void 0),_p(this,"startPlayTime",0),_p(this,"startPlayOffset",0),_p(this,"pausePlayTime",0),_p(this,"options",void 0),_p(this,"currentLoopCount",0),_p(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):OE.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 jN=new Map;async function BN(e,t){let i=null;if("string"==typeof e){const t=jN.get(e);if(t)return OE.debug("use cached audio resource: ",e),t;try{i=(await RE(()=>pE.get(e,{responseType:"arraybuffer"}),void 0,void 0,{maxRetryCount:3})).data}catch(e){throw new SE(fE.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 SE(fE.READ_LOCAL_AUDIO_FILE_ERROR))},n.onerror=()=>{i(new SE(fE.READ_LOCAL_AUDIO_FILE_ERROR))},n.readAsArrayBuffer(e)});i=await t}const n=await function(e){const t=Mg();return new Sl((i,n)=>{t.decodeAudioData(e,e=>{i(e)},e=>{n(new SE(fE.DECODE_AUDIO_FILE_FAILED,e.toString()))})})}(i);return"string"==typeof e&&t&&jN.set(e,n),n}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 WN(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
6t%2?GN(Object(i),!0).forEach((function(t){_p(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}function HN(e,t,i,n){i.optimizationMode&&(n&&n.width&&n.height?(i.encoderConfig=WN(WN({},n),{},{bitrateMin:n.bitrateMin,bitrateMax:n.bitrateMax}),"motion"!==i.optimizationMode&&"detail"!==i.optimizationMode||(t.contentHint=i.optimizationMode,t.contentHint===i.optimizationMode?OE.debug("[".concat(e,"] set content hint to"),i.optimizationMode):OE.debug("[".concat(e,"] set content hint failed")))):OE.warning("[".concat(e,"] can not apply optimization mode bitrate config, no encoderConfig")))}const KN=Mh().name;function YN(e,t,i,n){let r,o=0,s=null;return new Sl((a,c)=>{setTimeout(()=>{r&&(r(),a(o))},t),r=Fg(()=>{!function(){o>n&&r&&(r(),a(o));const t=i.getContext("2d");if(!t){const e=new SE(fE.UNEXPECTED_ERROR,"can not get canvas 2d context.");return OE.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 qN{constructor(e,t){_p(this,"id",0),_p(this,"element",void 0),_p(this,"peerPair",void 0),_p(this,"context",void 0),_p(this,"audioPlayerElement",void 0),_p(this,"audioTrack",void 0),qN.count+=1,this.id=qN.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 SE(fE.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 SE(fE.LOCAL_AEC_ERROR,e.toString()).print()}if(!t){throw new SE(fE.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(){OE.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 JN,XN;_p(qN,"count",0);const zN=window.AudioContext||window.webkitAudioContext;const QN=new(JN=Ig({report:vg}),ZT((XN=class{constructor(){_p(this,"units",[]),_p(this,"context",void 0)}processExternalMediaAEC(e){if(!this._doesEnvironmentNeedAEC())return OE.debug("the system does not need to process local aec"),-1;this.context||(this.context=new zN);let t=this.units.find(t=>t&&t.getElement()===e);return t||(t=new qN(e,this.context),this.units.push(t)),t.startEchoCancellation(),OE.debug("start processing local audio echo cancellation, id is",t.id),t.id}_doesEnvironmentNeedAEC(){return Mh().name!==Nh.SAFARI}}).prototype,"processExternalMediaAEC",[JN],Object.getOwnPropertyDescriptor(XN.prototype,"processExternalMediaAEC"),XN.prototype),XN);BE("PROCESS_ID","process-".concat(GI(8,""),"-").concat(GI(4,""),"-").concat(GI(4,""),"-").concat(GI(4,""),"-").concat(GI(12,""))),function(){const e=Mh();VS.getDisplayMedia=function(e){if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)return!0;return!1}(),VS.getStreamFromExtension=e.name===Nh.CHROME&&Number(e.version)>34,VS.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}(),VS.supportMinBitrate=e.name===Nh.CHROME||e.name===Nh.EDGE,VS.supportSetRtpSenderParameters=function(){const e=Mh();if(!window.RTCRtpSender||!window.RTCRtpSender.prototype.setParameters||!window.RTCRtpSender.prototype.getParameters)return!1;return!!rp()||(!(!Wh()&&!Fh())||e.name===Nh.FIREFOX&&Number(e.version)>=64)}(),e.name===Nh.SAFARI&&(Number(e.version)>=14?VS.supportDualStream=!0:VS.supportDualStream=!1),VS.webAudioMediaStreamDest=function(){const e=Mh();if(e.name===Nh.SAFARI&&Number(e.version)<12)return!1;return!0}(),VS.supportReplaceTrack=function(){if(!window.RTCRtpSender)return!1;if("function"==typeof RTCRtpSender.prototype.replaceTrack)return!0;return!1}(),VS.supportWebGL="undefined"!=typeof WebGLRenderingContext,VS.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,rp()||(VS.webAudioWithAEC=!0),VS.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}(),VS.supportDualStreamEncoding=function(){const e=Mh();if(GE("DISABLE_WEBAUDIO"))return!0;return"Safari"===e.name&&Number(e.version)>=14||!!("Chrome"===e.name&&/Windows/i.test(e.os||"")&&Number(e.version)>=100&&GE("CHROME_DUAL_STREAM_USE_ENCODING"))}(),VS.supportDataChannel=function(){if(Yh(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}(),VS.supportPCSetConfiguration=!Hh()&&!!RTCPeerConnection.prototype.setConfiguration,OE.info("browser compatibility",JSON.stringify(VS),JSON.stringify(e))}(),function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void OE.error("Error loading sdk config",e.message)}if(e)try{const t=JSON.parse(window.atob(e)),i=Date.now();OE.debug("Loading global parameters from cache",t),Object.keys(t).forEach(e
6=>{if(Object.prototype.hasOwnProperty.call(WE,e)){const{value:n,expires:r}=t[e];if(r&&r<=i)return;HE[e]=n,WE[e]=n}})}catch(t){OE.error("Error loading mutableParamsCache: ".concat(e),t.message)}}(),Array.isArray(HE.AREAS)&&HE.AREAS.length>0&&xv(HE.AREAS,!0);const ZN={__CLIENT_LIST__:zE,__TRACK_LIST__:QE,VERSION:wE,BUILD:bE,setParameter:(e,t,i)=>{OE.debug("setParameter key:".concat(e,", value:").concat(JSON.stringify(t))),BE(e,t,i)},getParameter:GE,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 SE(fE.CREATE_OFFER_FAILED,e.toString&&e.toString()).print()}return e},checkSystemRequirements:function(){const e=vg.reportApiInvoke(null,{name:_f.CHECK_SYSTEM_REQUIREMENTS,options:[],tag:Ef.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 OE.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),(ip()||Mh().name===Nh.QQ)&&(i=!0),OE.debug("checkSystemRequirements, api:",t,"browser",i);const r=t&&i;return e.onSuccess(r),r},getDevices:function(e){return iR.enumerateDevices(!0,!0,e)},getMicrophones:function(e){return iR.getRecordingDevices(e)},getCameras:function(e){return iR.getCamerasDevices(e)},getElectronScreenSources:Kg,getPlaybackDevices:function(e){return iR.getSpeakers(e)},createClient:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{codec:"vp8",audioCodec:"opus",mode:"rtc"};const t=vg.reportApiInvoke(null,{name:_f.CREATE_CLIENT,options:[e],tag:Ef.TRACER});try{Mf(e)}catch(e){throw t.onError(e),e}return void 0===e.audioCodec&&(e.audioCodec="opus"),t.onSuccess(),new VN(xN(xN({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=vg.reportApiInvoke(null,{tag:Ef.TRACER,name:_f.CREATE_CAM_VIDEO_TRACK,options:[WN({},e)]}),i=yC(e),n=GI(8,"track-cam-");let r=null;OE.info("start create camera video track with config",JSON.stringify(e),"trackId",n);try{r=(await Zg({video:i},n)).getVideoTracks()[0]||null}catch(e){throw t.onError(e),e}if(!r){const e=new SE(fE.UNEXPECTED_ERROR,"can not find track in media stream");return t.onError(e),e.throw()}e.optimizationMode&&HN(n,r,e,UE(e.encoderConfig));const o=new _y(r,e,i,e.scalabiltyMode?VE(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,n);return t.onSuccess(o.getTrackId()),OE.info("create camera video success, trackId:",n),o},createCustomVideoTrack:function(e){const t=vg.reportApiInvoke(null,{tag:Ef.TRACER,name:_f.CREATE_CUSTOM_VIDEO_TRACK,options:[e]}),i=new py(e.mediaStreamTrack,{width:e.width,height:e.height,frameRate:e.frameRate,bitrateMax:e.bitrateMax,bitrateMin:e.bitrateMin},e.scalabiltyMode?VE(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,GI(8,"track-cus-"),[lS.CUSTOM_TRACK]);return t.onSuccess(i.getTrackId()),OE.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=vg.reportApiInvoke(null,{tag:Ef.TRACER,name:_f.CREATE_SCREEN_VIDEO_TRACK,options:[WN({},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=AC(e),r=GI(8,"track-scr-v-");let o=null,s=null;const a=FS();if(!a.supportShareAudio&&"enable"===t){const e=new SE(fE.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return i.onError(e),e.throw()}OE.info("start create screen video track with config",e,"withAudio",t,"trackId",r);try{const e=await Zg({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 SE(fE.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 SE(fE.SHARE_AUDIO_NOT_ALLOWED);return i.onError(e),e.throw()}e.optimizationMode||(e.optimizationMode="detail"),e.optimizationMode&&(HN(r,o,e,e.encoderConfig&&xE(e.encoderConfig)),e.encoderConfig&&"string"!=typeof e.encoderConfig&&(e.encoderConfig.bitrateMin=e.encoderConfig.bitrateMax));const c=new py(o,e.encoderConfig?xE(e.encoderConfig):{}
6,e.scalabiltyMode?VE(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,r,[lS.SCREEN_TRACK]);if(!s)return i.onSuccess(c.getTrackId()),OE.info("create screen video track success","video:",c.getTrackId()),c;const d=new _I(s,void 0,GI(8,"track-scr-a-"),!1,!0);return i.onSuccess([c.getTrackId(),d.getTrackId()]),OE.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=vg.reportApiInvoke(null,{tag:Ef.TRACER,name:_f.CREATE_MIC_AND_CAM_TRACKS,options:[e,t]}),n=yC(t),r=OC(e),o=GI(8,"track-mic-"),s=GI(8,"track-cam-");let a=null,c=null;OE.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 Zg({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 SE(fE.UNEXPECTED_ERROR,"can not find tracks in media stream");return i.onError(e),e.throw()}t.optimizationMode&&HN(s,c,t,UE(t.encoderConfig));const d=new EI(a,e,r,o),u=new _y(c,t,n,t.scalabiltyMode?VE(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,s);return i.onSuccess([d.getTrackId(),u.getTrackId()]),OE.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=vg.reportApiInvoke(null,{tag:Ef.TRACER,name:_f.CREATE_MIC_AUDIO_TRACK,options:[e]}),i=OC(e),n=GI(8,"track-mic-");let r=null;OE.info("start create microphone audio track with config",JSON.stringify(e),"trackId",n);try{r=(await Zg({audio:i},n)).getAudioTracks()[0]||null}catch(e){throw t.onError(e),e}if(!r){const e=new SE(fE.UNEXPECTED_ERROR,"can not find track in media stream");return t.onError(e),e.throw()}const o=new EI(r,e,i,n);return t.onSuccess(o.getTrackId()),OE.info("create microphone audio track success, trackId:",n),o},createCustomAudioTrack:function(e){const t=vg.reportApiInvoke(null,{tag:Ef.TRACER,name:_f.CREATE_CUSTOM_AUDIO_TRACK,options:[e]}),i=new _I(e.mediaStreamTrack,e.encoderConfig?jE(e.encoderConfig):{},GI(8,"track-cus-"),!1,!0);return OE.info("create custom audio track success with config",e,"trackId",i.getTrackId()),t.onSuccess(i.getTrackId()),i},createBufferSourceAudioTrack:async function(e){const t=vg.reportApiInvoke(null,{tag:Ef.TRACER,name:_f.CREATE_BUFFER_AUDIO_TRACK,options:[e]});if(GE("DISABLE_WEBAUDIO"))throw new SE(fE.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");const i=GI(8,"track-buf-");OE.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 BN(e.source,e.cacheOnlineFile)}catch(e){return t.onError(e),e.throw()}const r=new FN(e.source),o=new mI(n,r,e.encoderConfig?jE(e.encoderConfig):{},i);return OE.info("create buffer source audio track success, trackId:",i),t.onSuccess(o.getTrackId()),o},setAppType:function(e){if(OE.debug("setAppType: ".concat(e)),!(Number.isInteger(e)&&e>=0))throw OE.debug("Invalid appType"),new SE(fE.INVALID_PARAMS,"invalid app type",e);BE("APP_TYPE",Math.floor(e))},setLogLevel:function(e){OE.setLogLevel(e)},enableLogUpload:function(){GE("USE_NEW_LOG")?BE("UPLOAD_LOG",!0):OE.enableLogUpload()},disableLogUpload:function(){GE("USE_NEW_LOG")?BE("UPLOAD_LOG",!1):OE.disableLogUpload()},createChannelMediaRelayConfiguration:function(){return new _C},checkAudioTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const i=vg.reportApiInvoke(null,{tag:Ef.TRACER,name:_f.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof _I||e instanceof Bb)){const e=new SE(fE.INVALID_TRACK,"the parameter is not a audio track");return i.onError(e),e.throw()}t&&t<1e3&&(t=1e3);const n=e instanceof _I?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};OE.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=vg.reportApiInvoke(null,{tag:Ef.TRACER,name:_f.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof py||e instanceof jb)){const e=new SE(fE.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 py?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=ne
6w 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 YN(s,t,a,n),d=Date.now()-e}catch(e){throw i.onError(e),e}KN===Nh.SAFARI&&(s.pause(),s.remove()),s.srcObject=null;const u=c>n,l={duration:d,changedPicNum:c,deviceLabel:r,result:u};return OE.info("[track-".concat(e.getTrackId(),"] check video track active completed. ").concat(JSON.stringify(l))),i.onSuccess(l),u},setArea:xv,audioElementPlayCenter:rR,processExternalMediaAEC:function(e){QN.processExternalMediaAEC(e)},registerExtensions:function(e){e.forEach(e=>{const t=e;t.__registered__=!0,t.logger.hookLog=OE.extLog,t.reporter.hookApiInvoke=vg.extApiInvoke,t.parameters&&Object.keys(t.parameters).forEach(e=>{t.parameters[e]=GE(e)})})},ChannelMediaRelayError:oS,ChannelMediaRelayEvent:nS,ChannelMediaRelayState:rS,RemoteStreamFallbackType:pS,RemoteStreamType:hS,ConnectionDisconnectedReason:Cf,AudienceLatencyLevelType:vf,AREAS:mS},$N=window||document;return Object.defineProperties(ZN,{onAudioAutoplayFailed:{get:()=>Eg.onAudioAutoplayFailed,set:e=>{Eg.onAudioAutoplayFailed=e}},onAutoplayFailed:{get:()=>Eg.onAutoplayFailed,set:e=>{Eg.onAutoplayFailed=e}},_onSecurityPolicyViolation:{value:void 0,writable:!0},_cspEventHandlerPointer:{value:void 0,writable:!0},onSecurityPolicyViolation:{get:()=>ZN._onSecurityPolicyViolation,set(e){if(ZN._onSecurityPolicyViolation=e,!$N)return;const t=e=>{if(!(e&&e.blockedURI&&ZN.onSecurityPolicyViolation))return;const t=e.blockedURI;GE("CSP_DETECTED_HOSTNAME_LIST").some(e=>t.includes(e))&&ZN.onSecurityPolicyViolation&&"function"==typeof ZN.onSecurityPolicyViolation&&ZN.onSecurityPolicyViolation(e)},i=ZN._cspEventHandlerPointer;i&&$N.removeEventListener("securitypolicyviolation",i),e&&"function"==typeof e&&$N.addEventListener("securitypolicyviolation",t),ZN._cspEventHandlerPointer=t}}}),iR.on(ff.CAMERA_DEVICE_CHANGED,e=>{OE.info("camera device changed",JSON.stringify(e)),ZN.onCameraChanged&&ZN.onCameraChanged(e)}),iR.on(ff.RECORDING_DEVICE_CHANGED,e=>{OE.info("microphone device changed",JSON.stringify(e)),ZN.onMicrophoneChanged&&ZN.onMicrophoneChanged(e)}),iR.on(ff.PLAYOUT_DEVICE_CHANGED,e=>{OE.debug("playout device changed",JSON.stringify(e)),ZN.onPlaybackDeviceChanged&&ZN.onPlaybackDeviceChanged(e)}),rR.onAutoplayFailed=()=>{OE.info("detect audio element autoplay failed"),Eg.onAudioAutoplayFailed&&Eg.onAudioAutoplayFailed()},Lg.on("autoplay-failed",()=>{OE.info("detect webaudio autoplay failed"),Eg.onAudioAutoplayFailed&&Eg.onAudioAutoplayFailed()}),window&&(window.__ARTC__=ZN),ZN}));
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.