trtc-sdk-v5 5.11.1-beta.4 → 5.11.1-beta.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/cross-room/package.json +1 -1
- package/plugins/custom-encryption/package.json +1 -1
- package/plugins/device-detector/device-detector.esm.js +2 -2
- package/plugins/device-detector/device-detector.umd.js +1 -1
- package/plugins/device-detector/package.json +1 -1
- package/plugins/small-stream-auto-switcher/package.json +1 -1
- package/plugins/video-decoder/package.json +1 -1
- package/plugins/video-effect/basic-beauty/package.json +1 -1
- package/plugins/video-effect/beauty/package.json +1 -1
- package/plugins/video-effect/video-mixer/package.json +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/plugins/voice-changer/package.json +1 -1
- package/trtc.es5.js +1 -0
- package/trtc.esm.js +2 -2
- package/trtc.js +1 -1
package/trtc.es5.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var factory;factory=function(){function e(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function t(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function n(e,n,r){return n=l(n),function(e,n){if(n&&("object"==typeof n||"function"==typeof n))return n;if(void 0!==n)throw new TypeError("Derived constructors may only return object or undefined");return t(e)}(e,h()?Reflect.construct(n,r||[],l(e).constructor):n.apply(e,r))}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t,n){if(h())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&m(i,n.prototype),i}function a(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,k(r.key),r)}}function o(e,t,n){return t&&a(e.prototype,t),n&&a(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function s(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=S(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,a=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw a}}}}function c(e,t,n){return(t=k(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function u(){return u="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,n){var r=_(e,t);if(r){var i=Object.getOwnPropertyDescriptor(r,t);return i.get?i.get.call(arguments.length<3?e:n):i.value}},u.apply(null,arguments)}function l(e){return l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},l(e)}function d(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&m(e,t)}function h(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(h=function(){return!!e})()}function f(){f=function(){return t};var e,t={},n=Object.prototype,r=n.hasOwnProperty,i=Object.defineProperty||function(e,t,n){e[t]=n.value},a="function"==typeof Symbol?Symbol:{},o=a.iterator||"@@iterator",s=a.asyncIterator||"@@asyncIterator",c=a.toStringTag||"@@toStringTag";function u(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{u({},"")}catch(e){u=function(e,t,n){return e[t]=n}}function l(e,t,n,r){var a=t&&t.prototype instanceof g?t:g,o=Object.create(a.prototype),s=new N(r||[]);return i(o,"_invoke",{value:A(e,n,s)}),o}function d(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}t.wrap=l;var h="suspendedStart",p="suspendedYield",m="executing",v="completed",_={};function g(){}function y(){}function E(){}var k={};u(k,o,(function(){return this}));var T=Object.getPrototypeOf,S=T&&T(T(x([])));S&&S!==n&&r.call(S,o)&&(k=S);var I=E.prototype=g.prototype=Object.create(k);function b(e){["next","throw","return"].forEach((function(t){u(e,t,(function(e){return this._invoke(t,e)}))}))}function R(e,t){function n(i,a,o,s){var c=d(e[i],e,a);if("throw"!==c.type){var u=c.arg,l=u.value;return l&&"object"==typeof l&&r.call(l,"__await")?t.resolve(l.__await).then((function(e){n("next",e,o,s)}),(function(e){n("throw",e,o,s)})):t.resolve(l).then((function(e){u.value=e,o(u)}),(function(e){return n("throw",e,o,s)}))}s(c.arg)}var a;i(this,"_invoke",{value:function(e,r){function i(){return new t((function(t,i){n(e,r,t,i)}))}return a=a?a.then(i,i):i()}})}function A(t,n,r){var i=h;return function(a,o){if(i===m)throw Error("Generator is already running");if(i===v){if("throw"===a)throw o;return{value:e,done:!0}}for(r.method=a,r.arg=o;;){var s=r.delegate;if(s){var c=C(s,r);if(c){if(c===_)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(i===h)throw i=v,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);i=m;var u=d(t,n,r);if("normal"===u.type){if(i=r.done?v:p,u.arg===_)continue;return{value:u.arg,done:r.done}}"throw"===u.type&&(i=v,r.method="throw",r.arg=u.arg)}}}function C(t,n){var r=n.method,i=t.iterator[r];if(i===e)return n.delegate=null,"throw"===r&&t.iterator.return&&(n.method="return",n.arg=e,C(t,n),"throw"===n.method)||"return"!==r&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+r+"' method")),_;var a=d(i,t.iterator,n.arg);if("throw"===a.type)return n.method="throw",n.arg=a.arg,n.delegate=null,_;var o=a.arg;return o?o.done?(n[t.resultName]=o.value,n.next=t.nextLoc,"return"!==n.method&&(n.method="next",n.arg=e),n.delegate=null,_):o:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,_)}function w(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function D(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function N(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(w,this),this.reset(!0)}function x(t){if(t||""===t){var n=t[o];if(n)return n.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var i=-1,a=function n(){for(;++i<t.length;)if(r.call(t,i))return n.value=t[i],n.done=!1,n;return n.value=e,n.done=!0,n};return a.next=a}}throw new TypeError(typeof t+" is not iterable")}return y.prototype=E,i(I,"constructor",{value:E,configurable:!0}),i(E,"constructor",{value:y,configurable:!0}),y.displayName=u(E,c,"GeneratorFunction"),t.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===y||"GeneratorFunction"===(t.displayName||t.name))},t.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,E):(e.__proto__=E,u(e,c,"GeneratorFunction")),e.prototype=Object.create(I),e},t.awrap=function(e){return{__await:e}},b(R.prototype),u(R.prototype,s,(function(){return this})),t.AsyncIterator=R,t.async=function(e,n,r,i,a){void 0===a&&(a=Promise);var o=new R(l(e,n,r,i),a);return t.isGeneratorFunction(n)?o:o.next().then((function(e){return e.done?e.value:o.next()}))},b(I),u(I,c,"Generator"),u(I,o,(function(){return this})),u(I,"toString",(function(){return"[object Generator]"})),t.keys=function(e){var t=Object(e),n=[];for(var r in t)n.push(r);return n.reverse(),function e(){for(;n.length;){var r=n.pop();if(r in t)return e.value=r,e.done=!1,e}return e.done=!0,e}},t.values=x,N.prototype={constructor:N,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=e,this.done=!1,this.delegate=null,this.method="next",this.arg=e,this.tryEntries.forEach(D),!t)for(var n in this)"t"===n.charAt(0)&&r.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=e)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var n=this;function i(r,i){return s.type="throw",s.arg=t,n.next=r,i&&(n.method="next",n.arg=e),!!i}for(var a=this.tryEntries.length-1;a>=0;--a){var o=this.tryEntries[a],s=o.completion;if("root"===o.tryLoc)return i("end");if(o.tryLoc<=this.prev){var c=r.call(o,"catchLoc"),u=r.call(o,"finallyLoc");if(c&&u){if(this.prev<o.catchLoc)return i(o.catchLoc,!0);if(this.prev<o.finallyLoc)return i(o.finallyLoc)}else if(c){if(this.prev<o.catchLoc)return i(o.catchLoc,!0)}else{if(!u)throw Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return i(o.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var i=this.tryEntries[n];if(i.tryLoc<=this.prev&&r.call(i,"finallyLoc")&&this.prev<i.finallyLoc){var a=i;break}}a&&("break"===e||"continue"===e)&&a.tryLoc<=t&&t<=a.finallyLoc&&(a=null);var o=a?a.completion:{};return o.type=e,o.arg=t,a?(this.method="next",this.next=a.finallyLoc,_):this.complete(o)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),_},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),D(n),_}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var i=r.arg;D(n)}return i}}throw Error("illegal catch attempt")},delegateYield:function(t,n,r){return this.delegate={iterator:x(t),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=e),_}},t}function p(e,t,n,r){return p="undefined"!=typeof Reflect&&Reflect.set?Reflect.set:function(e,t,n,r){var i,a=_(e,t);if(a){if((i=Object.getOwnPropertyDescriptor(a,t)).set)return i.set.call(r,n),!0;if(!i.writable)return!1}if(i=Object.getOwnPropertyDescriptor(r,t)){if(!i.writable)return!1;i.value=n,Object.defineProperty(r,t,i)}else c(r,t,n);return!0},p(e,t,n,r)}function m(e,t){return m=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},m(e,t)}function v(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,a,o,s=[],c=!0,u=!1;try{if(a=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){u=!0,i=e}finally{try{if(!c&&null!=n.return&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw i}}return s}}(e,t)||S(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=l(e)););return e}function g(e,t,n,r){var i=u(l(1&r?e.prototype:e),t,n);return 2&r&&"function"==typeof i?function(e){return i.apply(n,e)}:i}function y(e,t,n,r,i,a){return function(e,t,n,r,i){if(!p(e,t,n,r||e)&&i)throw new TypeError("failed to set property");return n}(l(a?e.prototype:e),t,n,r,i)}function E(t){return function(t){if(Array.isArray(t))return e(t)}(t)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(t)||S(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function k(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function T(e){return T="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},T(e)}function S(t,n){if(t){if("string"==typeof t)return e(t,n);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,n):void 0}}function I(e){var t="function"==typeof Map?new Map:void 0;return I=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return i(e,arguments,l(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),m(n,e)},I(e)}var b,R;b=void 0,R=function(){var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},a=function(e){return e&&e.Math===Math&&e},u=a("object"==("undefined"==typeof globalThis?"undefined":T(globalThis))&&globalThis)||a("object"==("undefined"==typeof window?"undefined":T(window))&&window)||a("object"==("undefined"==typeof self?"undefined":T(self))&&self)||a("object"==T(e)&&e)||a("object"==T(e)&&e)||function(){return this}()||Function("return this")(),l={},h=function(t){try{return!!t()}catch(e){return!0}},p=!h((function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]})),m=!h((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),_=m,k=Function.prototype.call,S=_?k.bind(k):function(){return k.apply(k,arguments)},b={},R={}.propertyIsEnumerable,A=Object.getOwnPropertyDescriptor,C=A&&!R.call({1:2},1);b.f=C?function(e){var t=A(this,e);return!!t&&t.enumerable}:R;var w,D,N=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},x=m,O=Function.prototype,P=O.call,M=x&&O.bind.bind(P,P),L=x?M:function(e){return function(){return P.apply(e,arguments)}},V=L,U=V({}.toString),F=V("".slice),B=function(e){return F(U(e),8,-1)},H=h,W=B,j=Object,G=L("".split),J=H((function(){return!j("z").propertyIsEnumerable(0)}))?function(e){return"String"===W(e)?G(e,""):j(e)}:j,K=function(e){return null==e},Y=K,z=TypeError,q=function(e){if(Y(e))throw new z("Can't call method on "+e);return e},X=J,Q=q,Z=function(e){return X(Q(e))},$="object"==("undefined"==typeof document?"undefined":T(document))&&document.all,ee=void 0===$&&void 0!==$?function(e){return"function"==typeof e||e===$}:function(e){return"function"==typeof e},te=ee,ne=function(e){return"object"==T(e)?null!==e:te(e)},re=u,ie=ee,ae=function(e,t){return arguments.length<2?(n=re[e],ie(n)?n:void 0):re[e]&&re[e][t];var n},oe=L({}.isPrototypeOf),se=u.navigator,ce=se&&se.userAgent,ue=ce?String(ce):"",le=u,de=ue,he=le.process,fe=le.Deno,pe=he&&he.versions||fe&&fe.version,me=pe&&pe.v8;me&&(D=(w=me.split("."))[0]>0&&w[0]<4?1:+(w[0]+w[1])),!D&&de&&(!(w=de.match(/Edge\/(\d+)/))||w[1]>=74)&&(w=de.match(/Chrome\/(\d+)/))&&(D=+w[1]);var ve=D,_e=ve,ge=h,ye=u.String,Ee=!!Object.getOwnPropertySymbols&&!ge((function(){var e=Symbol("symbol detection");return!ye(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&_e&&_e<41})),ke=Ee&&!Symbol.sham&&"symbol"==T(Symbol.iterator),Te=ae,Se=ee,Ie=oe,be=Object,Re=ke?function(e){return"symbol"==T(e)}:function(e){var t=Te("Symbol");return Se(t)&&Ie(t.prototype,be(e))},Ae=String,Ce=function(t){try{return Ae(t)}catch(e){return"Object"}},we=ee,De=Ce,Ne=TypeError,xe=function(e){if(we(e))return e;throw new Ne(De(e)+" is not a function")},Oe=xe,Pe=K,Me=function(e,t){var n=e[t];return Pe(n)?void 0:Oe(n)},Le=S,Ve=ee,Ue=ne,Fe=TypeError,Be={exports:{}},He=u,We=Object.defineProperty,je=function(e,t){try{We(He,e,{value:t,configurable:!0,writable:!0})}catch(n){He[e]=t}return t},Ge=u,Je=je,Ke="__core-js_shared__",Ye=Be.exports=Ge[Ke]||Je(Ke,{});(Ye.versions||(Ye.versions=[])).push({version:"3.40.0",mode:"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.40.0/LICENSE",source:"https://github.com/zloirock/core-js"});var ze=Be.exports,qe=ze,Xe=function(e,t){return qe[e]||(qe[e]=t||{})},Qe=q,Ze=Object,$e=function(e){return Ze(Qe(e))},et=$e,tt=L({}.hasOwnProperty),nt=Object.hasOwn||function(e,t){return tt(et(e),t)},rt=L,it=0,at=Math.random(),ot=rt(1..toString),st=function(e){return"Symbol("+(void 0===e?"":e)+")_"+ot(++it+at,36)},ct=Xe,ut=nt,lt=st,dt=Ee,ht=ke,ft=u.Symbol,pt=ct("wks"),mt=ht?ft.for||ft:ft&&ft.withoutSetter||lt,vt=function(e){return ut(pt,e)||(pt[e]=dt&&ut(ft,e)?ft[e]:mt("Symbol."+e)),pt[e]},_t=S,gt=ne,yt=Re,Et=Me,kt=TypeError,Tt=vt("toPrimitive"),St=function(e,t){if(!gt(e)||yt(e))return e;var n,r=Et(e,Tt);if(r){if(void 0===t&&(t="default"),n=_t(r,e,t),!gt(n)||yt(n))return n;throw new kt("Can't convert object to primitive value")}return void 0===t&&(t="number"),function(e,t){var n,r;if("string"===t&&Ve(n=e.toString)&&!Ue(r=Le(n,e)))return r;if(Ve(n=e.valueOf)&&!Ue(r=Le(n,e)))return r;if("string"!==t&&Ve(n=e.toString)&&!Ue(r=Le(n,e)))return r;throw new Fe("Can't convert object to primitive value")}(e,t)},It=St,bt=Re,Rt=function(e){var t=It(e,"string");return bt(t)?t:t+""},At=ne,Ct=u.document,wt=At(Ct)&&At(Ct.createElement),Dt=function(e){return wt?Ct.createElement(e):{}},Nt=Dt,xt=!p&&!h((function(){return 7!==Object.defineProperty(Nt("div"),"a",{get:function(){return 7}}).a})),Ot=p,Pt=S,Mt=b,Lt=N,Vt=Z,Ut=Rt,Ft=nt,Bt=xt,Ht=Object.getOwnPropertyDescriptor;l.f=Ot?Ht:function(e,t){if(e=Vt(e),t=Ut(t),Bt)try{return Ht(e,t)}catch(n){}if(Ft(e,t))return Lt(!Pt(Mt.f,e,t),e[t])};var Wt={},jt=p&&h((function(){return 42!==Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),Gt=ne,Jt=String,Kt=TypeError,Yt=function(e){if(Gt(e))return e;throw new Kt(Jt(e)+" is not an object")},zt=p,qt=xt,Xt=jt,Qt=Yt,Zt=Rt,$t=TypeError,en=Object.defineProperty,tn=Object.getOwnPropertyDescriptor,nn="enumerable",rn="configurable",an="writable";Wt.f=zt?Xt?function(e,t,n){if(Qt(e),t=Zt(t),Qt(n),"function"==typeof e&&"prototype"===t&&"value"in n&&an in n&&!n[an]){var r=tn(e,t);r&&r[an]&&(e[t]=n.value,n={configurable:rn in n?n[rn]:r[rn],enumerable:nn in n?n[nn]:r[nn],writable:!1})}return en(e,t,n)}:en:function(e,t,n){if(Qt(e),t=Zt(t),Qt(n),qt)try{return en(e,t,n)}catch(a){}if("get"in n||"set"in n)throw new $t("Accessors not supported");return"value"in n&&(e[t]=n.value),e};var on=Wt,sn=N,cn=p?function(e,t,n){return on.f(e,t,sn(1,n))}:function(e,t,n){return e[t]=n,e},un={exports:{}},ln=p,dn=nt,hn=Function.prototype,fn=ln&&Object.getOwnPropertyDescriptor,pn=dn(hn,"name"),mn={EXISTS:pn,PROPER:pn&&"something"===function(){}.name,CONFIGURABLE:pn&&(!ln||ln&&fn(hn,"name").configurable)},vn=ee,_n=ze,gn=L(Function.toString);vn(_n.inspectSource)||(_n.inspectSource=function(e){return gn(e)});var yn,En,kn,Tn=_n.inspectSource,Sn=ee,In=u.WeakMap,bn=Sn(In)&&/native code/.test(String(In)),Rn=st,An=Xe("keys"),Cn=function(e){return An[e]||(An[e]=Rn(e))},wn={},Dn=bn,Nn=u,xn=ne,On=cn,Pn=nt,Mn=ze,Ln=Cn,Vn=wn,Un="Object already initialized",Fn=Nn.TypeError,Bn=Nn.WeakMap;if(Dn||Mn.state){var Hn=Mn.state||(Mn.state=new Bn);Hn.get=Hn.get,Hn.has=Hn.has,Hn.set=Hn.set,yn=function(e,t){if(Hn.has(e))throw new Fn(Un);return t.facade=e,Hn.set(e,t),t},En=function(e){return Hn.get(e)||{}},kn=function(e){return Hn.has(e)}}else{var Wn=Ln("state");Vn[Wn]=!0,yn=function(e,t){if(Pn(e,Wn))throw new Fn(Un);return t.facade=e,On(e,Wn,t),t},En=function(e){return Pn(e,Wn)?e[Wn]:{}},kn=function(e){return Pn(e,Wn)}}var jn={set:yn,get:En,has:kn,enforce:function(e){return kn(e)?En(e):yn(e,{})},getterFor:function(e){return function(t){var n;if(!xn(t)||(n=En(t)).type!==e)throw new Fn("Incompatible receiver, "+e+" required");return n}}},Gn=L,Jn=h,Kn=ee,Yn=nt,zn=p,qn=mn.CONFIGURABLE,Xn=Tn,Qn=jn.enforce,Zn=jn.get,$n=String,er=Object.defineProperty,tr=Gn("".slice),nr=Gn("".replace),rr=Gn([].join),ir=zn&&!Jn((function(){return 8!==er((function(){}),"length",{value:8}).length})),ar=String(String).split("String"),or=un.exports=function(e,t,n){"Symbol("===tr($n(t),0,7)&&(t="["+nr($n(t),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),n&&n.getter&&(t="get "+t),n&&n.setter&&(t="set "+t),(!Yn(e,"name")||qn&&e.name!==t)&&(zn?er(e,"name",{value:t,configurable:!0}):e.name=t),ir&&n&&Yn(n,"arity")&&e.length!==n.arity&&er(e,"length",{value:n.arity});try{n&&Yn(n,"constructor")&&n.constructor?zn&&er(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(u){}var r=Qn(e);return Yn(r,"source")||(r.source=rr(ar,"string"==typeof t?t:"")),e};Function.prototype.toString=or((function(){return Kn(this)&&Zn(this).source||Xn(this)}),"toString");var sr=un.exports,cr=ee,ur=Wt,lr=sr,dr=je,hr=function(e,t,n,r){r||(r={});var i=r.enumerable,a=void 0!==r.name?r.name:t;if(cr(n)&&lr(n,a,r),r.global)i?e[t]=n:dr(t,n);else{try{r.unsafe?e[t]&&(i=!0):delete e[t]}catch(h){}i?e[t]=n:ur.f(e,t,{value:n,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},fr={},pr=Math.ceil,mr=Math.floor,vr=Math.trunc||function(e){var t=+e;return(t>0?mr:pr)(t)},_r=vr,gr=function(e){var t=+e;return t!=t||0===t?0:_r(t)},yr=gr,Er=Math.max,kr=Math.min,Tr=function(e,t){var n=yr(e);return n<0?Er(n+t,0):kr(n,t)},Sr=gr,Ir=Math.min,br=function(e){var t=Sr(e);return t>0?Ir(t,9007199254740991):0},Rr=br,Ar=function(e){return Rr(e.length)},Cr=Z,wr=Tr,Dr=Ar,Nr=function(e){return function(t,n,r){var i=Cr(t),a=Dr(i);if(0===a)return!e&&-1;var o,s=wr(r,a);if(e&&n!=n){for(;a>s;)if((o=i[s++])!=o)return!0}else for(;a>s;s++)if((e||s in i)&&i[s]===n)return e||s||0;return!e&&-1}},xr={includes:Nr(!0),indexOf:Nr(!1)},Or=nt,Pr=Z,Mr=xr.indexOf,Lr=wn,Vr=L([].push),Ur=function(e,t){var n,r=Pr(e),i=0,a=[];for(n in r)!Or(Lr,n)&&Or(r,n)&&Vr(a,n);for(;t.length>i;)Or(r,n=t[i++])&&(~Mr(a,n)||Vr(a,n));return a},Fr=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Br=Ur,Hr=Fr.concat("length","prototype");fr.f=Object.getOwnPropertyNames||function(e){return Br(e,Hr)};var Wr={};Wr.f=Object.getOwnPropertySymbols;var jr=ae,Gr=fr,Jr=Wr,Kr=Yt,Yr=L([].concat),zr=jr("Reflect","ownKeys")||function(e){var t=Gr.f(Kr(e)),n=Jr.f;return n?Yr(t,n(e)):t},qr=nt,Xr=zr,Qr=l,Zr=Wt,$r=function(e,t,n){for(var r=Xr(t),i=Zr.f,a=Qr.f,o=0;o<r.length;o++){var s=r[o];qr(e,s)||n&&qr(n,s)||i(e,s,a(t,s))}},ei=h,ti=ee,ni=/#|\.prototype\./,ri=function(e,t){var n=ai[ii(e)];return n===si||n!==oi&&(ti(t)?ei(t):!!t)},ii=ri.normalize=function(e){return String(e).replace(ni,".").toLowerCase()},ai=ri.data={},oi=ri.NATIVE="N",si=ri.POLYFILL="P",ci=ri,ui=u,li=l.f,di=cn,hi=hr,fi=je,pi=$r,mi=ci,vi=function(e,t){var n,r,i,a,o,s=e.target,c=e.global,u=e.stat;if(n=c?ui:u?ui[s]||fi(s,{}):ui[s]&&ui[s].prototype)for(r in t){if(a=t[r],i=e.dontCallGetSet?(o=li(n,r))&&o.value:n[r],!mi(c?r:s+(u?".":"#")+r,e.forced)&&void 0!==i){if(T(a)==T(i))continue;pi(a,i)}(e.sham||i&&i.sham)&&di(a,"sham",!0),hi(n,r,a,e)}},_i={};_i[vt("toStringTag")]="z";var gi="[object z]"===String(_i),yi=ee,Ei=B,ki=vt("toStringTag"),Ti=Object,Si="Arguments"===Ei(function(){return arguments}()),Ii=gi?Ei:function(e){var t,n,r;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=function(e,t){try{return e[t]}catch(n){}}(t=Ti(e),ki))?n:Si?Ei(t):"Object"===(r=Ei(t))&&yi(t.callee)?"Arguments":r},bi=Ii,Ri=String,Ai=function(e){if("Symbol"===bi(e))throw new TypeError("Cannot convert a Symbol value to a string");return Ri(e)},Ci=sr,wi=Wt,Di=function(e,t,n){return n.get&&Ci(n.get,t,{getter:!0}),n.set&&Ci(n.set,t,{setter:!0}),wi.f(e,t,n)},Ni=vi,xi=p,Oi=L,Pi=nt,Mi=ee,Li=oe,Vi=Ai,Ui=Di,Fi=$r,Bi=u.Symbol,Hi=Bi&&Bi.prototype;if(xi&&Mi(Bi)&&(!("description"in Hi)||void 0!==Bi().description)){var Wi={},ji=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:Vi(arguments[0]),t=Li(Hi,this)?new Bi(e):void 0===e?Bi():Bi(e);return""===e&&(Wi[t]=!0),t};Fi(ji,Bi),ji.prototype=Hi,Hi.constructor=ji;var Gi="Symbol(description detection)"===String(Bi("description detection")),Ji=Oi(Hi.valueOf),Ki=Oi(Hi.toString),Yi=/^Symbol\((.*)\)[^)]+$/,zi=Oi("".replace),qi=Oi("".slice);Ui(Hi,"description",{configurable:!0,get:function(){var e=Ji(this);if(Pi(Wi,e))return"";var t=Ki(e),n=Gi?qi(t,7,-1):zi(t,Yi,"$1");return""===n?void 0:n}}),Ni({global:!0,constructor:!0,forced:!0},{Symbol:ji})}var Xi={},Qi=Ur,Zi=Fr,$i=Object.keys||function(e){return Qi(e,Zi)},ea=p,ta=jt,na=Wt,ra=Yt,ia=Z,aa=$i;Xi.f=ea&&!ta?Object.defineProperties:function(e,t){ra(e);for(var n,r=ia(t),i=aa(t),a=i.length,o=0;a>o;)na.f(e,n=i[o++],r[n]);return e};var oa,sa=ae("document","documentElement"),ca=Yt,ua=Xi,la=Fr,da=wn,ha=sa,fa=Dt,pa="prototype",ma="script",va=Cn("IE_PROTO"),_a=function(){},ga=function(e){return"<"+ma+">"+e+"</"+ma+">"},ya=function(e){e.write(ga("")),e.close();var t=e.parentWindow.Object;return e=null,t},Ea=function(){try{oa=new ActiveXObject("htmlfile")}catch(u){}var e,t,n;Ea="undefined"!=typeof document?document.domain&&oa?ya(oa):(t=fa("iframe"),n="java"+ma+":",t.style.display="none",ha.appendChild(t),t.src=String(n),(e=t.contentWindow.document).open(),e.write(ga("document.F=Object")),e.close(),e.F):ya(oa);for(var r=la.length;r--;)delete Ea[pa][la[r]];return Ea()};da[va]=!0;var ka=Object.create||function(e,t){var n;return null!==e?(_a[pa]=ca(e),n=new _a,_a[pa]=null,n[va]=e):n=Ea(),void 0===t?n:ua.f(n,t)},Ta=vt,Sa=ka,Ia=Wt.f,ba=Ta("unscopables"),Ra=Array.prototype;void 0===Ra[ba]&&Ia(Ra,ba,{configurable:!0,value:Sa(null)});var Aa=function(e){Ra[ba][e]=!0},Ca=xr.includes,wa=Aa;vi({target:"Array",proto:!0,forced:h((function(){return!Array(1).includes()}))},{includes:function(e){return Ca(this,e,arguments.length>1?arguments[1]:void 0)}}),wa("includes");var Da,Na,xa,Oa={},Pa=!h((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Ma=nt,La=ee,Va=$e,Ua=Pa,Fa=Cn("IE_PROTO"),Ba=Object,Ha=Ba.prototype,Wa=Ua?Ba.getPrototypeOf:function(e){var t=Va(e);if(Ma(t,Fa))return t[Fa];var n=t.constructor;return La(n)&&t instanceof n?n.prototype:t instanceof Ba?Ha:null},ja=h,Ga=ee,Ja=ne,Ka=Wa,Ya=hr,za=vt("iterator"),qa=!1;[].keys&&("next"in(xa=[].keys())?(Na=Ka(Ka(xa)))!==Object.prototype&&(Da=Na):qa=!0);var Xa=!Ja(Da)||ja((function(){var e={};return Da[za].call(e)!==e}));Xa&&(Da={}),Ga(Da[za])||Ya(Da,za,(function(){return this}));var Qa={IteratorPrototype:Da,BUGGY_SAFARI_ITERATORS:qa},Za=Wt.f,$a=nt,eo=vt("toStringTag"),to=function(e,t,n){e&&!n&&(e=e.prototype),e&&!$a(e,eo)&&Za(e,eo,{configurable:!0,value:t})},no=Qa.IteratorPrototype,ro=ka,io=N,ao=to,oo=Oa,so=function(){return this},co=function(e,t,n,r){var i=t+" Iterator";return e.prototype=ro(no,{next:io(+!r,n)}),ao(e,i,!1),oo[i]=so,e},uo=L,lo=xe,ho=ne,fo=String,po=TypeError,mo=ne,vo=q,_o=function(e){if(function(e){return ho(e)||null===e}(e))return e;throw new po("Can't set "+fo(e)+" as a prototype")},go=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,n={};try{(e=function(e,t,n){try{return uo(lo(Object.getOwnPropertyDescriptor(e,t)[n]))}catch(a){}}(Object.prototype,"__proto__","set"))(n,[]),t=n instanceof Array}catch(a){}return function(n,r){return vo(n),_o(r),mo(n)?(t?e(n,r):n.__proto__=r,n):n}}():void 0),yo=vi,Eo=S,ko=ee,To=co,So=Wa,Io=go,bo=to,Ro=cn,Ao=hr,Co=Oa,wo=mn.PROPER,Do=mn.CONFIGURABLE,No=Qa.IteratorPrototype,xo=Qa.BUGGY_SAFARI_ITERATORS,Oo=vt("iterator"),Po="keys",Mo="values",Lo="entries",Vo=function(){return this},Uo=function(e,t,n,r,i,a,o){To(n,t,r);var s,c,u,l=function(e){if(e===i&&m)return m;if(!xo&&e&&e in f)return f[e];switch(e){case Po:case Mo:case Lo:return function(){return new n(this,e)}}return function(){return new n(this)}},d=t+" Iterator",h=!1,f=e.prototype,p=f[Oo]||f["@@iterator"]||i&&f[i],m=!xo&&p||l(i),v="Array"===t&&f.entries||p;if(v&&(s=So(v.call(new e)))!==Object.prototype&&s.next&&(So(s)!==No&&(Io?Io(s,No):ko(s[Oo])||Ao(s,Oo,Vo)),bo(s,d,!0)),wo&&i===Mo&&p&&p.name!==Mo&&(Do?Ro(f,"name",Mo):(h=!0,m=function(){return Eo(p,this)})),i)if(c={values:l(Mo),keys:a?m:l(Po),entries:l(Lo)},o)for(u in c)(xo||h||!(u in f))&&Ao(f,u,c[u]);else yo({target:t,proto:!0,forced:xo||h},c);return f[Oo]!==m&&Ao(f,Oo,m,{name:i}),Co[t]=m,c},Fo=function(e,t){return{value:e,done:t}},Bo=Z,Ho=Aa,Wo=Oa,jo=jn,Go=Wt.f,Jo=Uo,Ko=Fo,Yo=p,zo="Array Iterator",qo=jo.set,Xo=jo.getterFor(zo),Qo=Jo(Array,"Array",(function(e,t){qo(this,{type:zo,target:Bo(e),index:0,kind:t})}),(function(){var e=Xo(this),t=e.target,n=e.index++;if(!t||n>=t.length)return e.target=null,Ko(void 0,!0);switch(e.kind){case"keys":return Ko(n,!1);case"values":return Ko(t[n],!1)}return Ko([n,t[n]],!1)}),"values"),Zo=Wo.Arguments=Wo.Array;if(Ho("keys"),Ho("values"),Ho("entries"),Yo&&"values"!==Zo.name)try{Go(Zo,"name",{value:"values"})}catch(Lj){}var $o=xe,es=$e,ts=J,ns=Ar,rs=TypeError,is="Reduce of empty array with no initial value",as=function(e){return function(t,n,r,i){var a=es(t),o=ts(a),s=ns(a);if($o(n),0===s&&r<2)throw new rs(is);var c=e?s-1:0,u=e?-1:1;if(r<2)for(;;){if(c in o){i=o[c],c+=u;break}if(c+=u,e?c<0:s<=c)throw new rs(is)}for(;e?c>=0:s>c;c+=u)c in o&&(i=n(i,o[c],c,a));return i}},os={left:as(!1),right:as(!0)},ss=h,cs=function(e,t){var n=[][e];return!!n&&ss((function(){n.call(null,t||function(){return 1},1)}))},us=u,ls=ue,ds=B,hs=function(e){return ls.slice(0,e.length)===e},fs=hs("Bun/")?"BUN":hs("Cloudflare-Workers")?"CLOUDFLARE":hs("Deno/")?"DENO":hs("Node.js/")?"NODE":us.Bun&&"string"==typeof Bun.version?"BUN":us.Deno&&"object"==T(Deno.version)?"DENO":"process"===ds(us.process)?"NODE":us.window&&us.document?"BROWSER":"REST",ps="NODE"===fs,ms=os.left;vi({target:"Array",proto:!0,forced:!ps&&ve>79&&ve<83||!cs("reduce")},{reduce:function(e){var t=arguments.length;return ms(this,e,t,t>1?arguments[1]:void 0)}});var vs=os.right;vi({target:"Array",proto:!0,forced:!ps&&ve>79&&ve<83||!cs("reduceRight")},{reduceRight:function(e){return vs(this,e,arguments.length,arguments.length>1?arguments[1]:void 0)}});var _s=B,gs=Array.isArray||function(e){return"Array"===_s(e)},ys=vi,Es=gs,ks=L([].reverse),Ts=[1,2];ys({target:"Array",proto:!0,forced:String(Ts)===String(Ts.reverse())},{reverse:function(){return Es(this)&&(this.length=this.length),ks(this)}});var Ss=Ce,Is=TypeError,bs=L([].slice),Rs=bs,As=Math.floor,Cs=function(e,t){var n=e.length;if(n<8)for(var r,i,a=1;a<n;){for(i=a,r=e[a];i&&t(e[i-1],r)>0;)e[i]=e[--i];i!==a++&&(e[i]=r)}else for(var o=As(n/2),s=Cs(Rs(e,0,o),t),c=Cs(Rs(e,o),t),u=s.length,l=c.length,d=0,h=0;d<u||h<l;)e[d+h]=d<u&&h<l?t(s[d],c[h])<=0?s[d++]:c[h++]:d<u?s[d++]:c[h++];return e},ws=Cs,Ds=ue.match(/firefox\/(\d+)/i),Ns=!!Ds&&+Ds[1],xs=/MSIE|Trident/.test(ue),Os=ue.match(/AppleWebKit\/(\d+)\./),Ps=!!Os&&+Os[1],Ms=vi,Ls=L,Vs=xe,Us=$e,Fs=Ar,Bs=function(e,t){if(!delete e[t])throw new Is("Cannot delete property "+Ss(t)+" of "+Ss(e))},Hs=Ai,Ws=h,js=ws,Gs=cs,Js=Ns,Ks=xs,Ys=ve,zs=Ps,qs=[],Xs=Ls(qs.sort),Qs=Ls(qs.push),Zs=Ws((function(){qs.sort(void 0)})),$s=Ws((function(){qs.sort(null)})),ec=Gs("sort"),tc=!Ws((function(){if(Ys)return Ys<70;if(!(Js&&Js>3)){if(Ks)return!0;if(zs)return zs<603;var e,t,n,r,i="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:n=3;break;case 68:case 71:n=4;break;default:n=2}for(r=0;r<47;r++)qs.push({k:t+r,v:n})}for(qs.sort((function(e,t){return t.v-e.v})),r=0;r<qs.length;r++)t=qs[r].k.charAt(0),i.charAt(i.length-1)!==t&&(i+=t);return"DGBEFHACIJK"!==i}}));Ms({target:"Array",proto:!0,forced:Zs||!$s||!ec||!tc},{sort:function(e){void 0!==e&&Vs(e);var t=Us(this);if(tc)return void 0===e?Xs(t):Xs(t,e);var n,r,i=[],a=Fs(t);for(r=0;r<a;r++)r in t&&Qs(i,t[r]);for(js(i,function(e){return function(t,n){return void 0===n?-1:void 0===t?1:void 0!==e?+e(t,n)||0:Hs(t)>Hs(n)?1:-1}}(e)),n=Fs(i),r=0;r<n;)t[r]=i[r++];for(;r<a;)Bs(t,r++);return t}});var nc="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,rc=hr,ic=function(e,t,n){for(var r in t)rc(e,r,t[r],n);return e},ac=oe,oc=TypeError,sc=function(e,t){if(ac(t,e))return e;throw new oc("Incorrect invocation")},cc=gr,uc=br,lc=RangeError,dc=function(e){if(void 0===e)return 0;var t=cc(e),n=uc(t);if(t!==n)throw new lc("Wrong length or index");return n},hc=Math.sign||function(e){var t=+e;return 0===t||t!=t?t:t<0?-1:1},fc=4503599627370496,pc=hc,mc=Math.abs,vc=function(e,t,n,r){var i=+e,a=mc(i),o=pc(i);if(a<r)return o*function(e){return e+fc-fc}(a/r/t)*r*t;var s=(1+t/2220446049250313e-31)*a,c=s-(s-a);return c>n||c!=c?Infinity*o:o*c},_c=Math.fround||function(e){return vc(e,1.1920928955078125e-7,34028234663852886e22,11754943508222875e-54)},gc=Array,yc=Math.abs,Ec=Math.pow,kc=Math.floor,Tc=Math.log,Sc=Math.LN2,Ic={pack:function(e,t,n){var r,i,a,o=gc(n),s=8*n-t-1,c=(1<<s)-1,u=c>>1,l=23===t?Ec(2,-24)-Ec(2,-77):0,d=e<0||0===e&&1/e<0?1:0,h=0;for((e=yc(e))!=e||Infinity===e?(i=e!=e?1:0,r=c):(r=kc(Tc(e)/Sc),e*(a=Ec(2,-r))<1&&(r--,a*=2),(e+=r+u>=1?l/a:l*Ec(2,1-u))*a>=2&&(r++,a/=2),r+u>=c?(i=0,r=c):r+u>=1?(i=(e*a-1)*Ec(2,t),r+=u):(i=e*Ec(2,u-1)*Ec(2,t),r=0));t>=8;)o[h++]=255&i,i/=256,t-=8;for(r=r<<t|i,s+=t;s>0;)o[h++]=255&r,r/=256,s-=8;return o[h-1]|=128*d,o},unpack:function(e,t){var n,r=e.length,i=8*r-t-1,a=(1<<i)-1,o=a>>1,s=i-7,c=r-1,u=e[c--],l=127&u;for(u>>=7;s>0;)l=256*l+e[c--],s-=8;for(n=l&(1<<-s)-1,l>>=-s,s+=t;s>0;)n=256*n+e[c--],s-=8;if(0===l)l=1-o;else{if(l===a)return n?NaN:u?-Infinity:Infinity;n+=Ec(2,t),l-=o}return(u?-1:1)*n*Ec(2,l-t)}},bc=$e,Rc=Tr,Ac=Ar,Cc=function(e){for(var t=bc(this),n=Ac(t),r=arguments.length,i=Rc(r>1?arguments[1]:void 0,n),a=r>2?arguments[2]:void 0,o=void 0===a?n:Rc(a,n);o>i;)t[i++]=e;return t},wc=ee,Dc=ne,Nc=go,xc=function(e,t,n){var r,i;return Nc&&wc(r=t.constructor)&&r!==n&&Dc(i=r.prototype)&&i!==n.prototype&&Nc(e,i),e},Oc=u,Pc=L,Mc=p,Lc=nc,Vc=cn,Uc=Di,Fc=ic,Bc=h,Hc=sc,Wc=gr,jc=br,Gc=dc,Jc=_c,Kc=Ic,Yc=Wa,zc=go,qc=Cc,Xc=bs,Qc=xc,Zc=$r,$c=to,eu=jn,tu=mn.PROPER,nu=mn.CONFIGURABLE,ru="ArrayBuffer",iu="DataView",au="prototype",ou="Wrong index",su=eu.getterFor(ru),cu=eu.getterFor(iu),uu=eu.set,lu=Oc[ru],du=lu,hu=du&&du[au],fu=Oc[iu],pu=fu&&fu[au],mu=Object.prototype,vu=Oc.Array,_u=Oc.RangeError,gu=Pc(qc),yu=Pc([].reverse),Eu=Kc.pack,ku=Kc.unpack,Tu=function(e){return[255&e]},Su=function(e){return[255&e,e>>8&255]},Iu=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},bu=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},Ru=function(e){return Eu(Jc(e),23,4)},Au=function(e){return Eu(e,52,8)},Cu=function(e,t,n){Uc(e[au],t,{configurable:!0,get:function(){return n(this)[t]}})},wu=function(e,t,n,r){var i=cu(e),a=Gc(n),o=!!r;if(a+t>i.byteLength)throw new _u(ou);var s=i.bytes,c=a+i.byteOffset,u=Xc(s,c,c+t);return o?u:yu(u)},Du=function(e,t,n,r,i,a){var o=cu(e),s=Gc(n),c=r(+i),u=!!a;if(s+t>o.byteLength)throw new _u(ou);for(var l=o.bytes,d=s+o.byteOffset,h=0;h<t;h++)l[d+h]=c[u?h:t-h-1]};if(Lc){var Nu=tu&&lu.name!==ru;Bc((function(){lu(1)}))&&Bc((function(){new lu(-1)}))&&!Bc((function(){return new lu,new lu(1.5),new lu(NaN),1!==lu.length||Nu&&!nu}))?Nu&&nu&&Vc(lu,"name",ru):((du=function(e){return Hc(this,hu),Qc(new lu(Gc(e)),this,du)})[au]=hu,hu.constructor=du,Zc(du,lu)),zc&&Yc(pu)!==mu&&zc(pu,mu);var xu=new fu(new du(2)),Ou=Pc(pu.setInt8);xu.setInt8(0,2147483648),xu.setInt8(1,2147483649),!xu.getInt8(0)&&xu.getInt8(1)||Fc(pu,{setInt8:function(e,t){Ou(this,e,t<<24>>24)},setUint8:function(e,t){Ou(this,e,t<<24>>24)}},{unsafe:!0})}else hu=(du=function(e){Hc(this,hu);var t=Gc(e);uu(this,{type:ru,bytes:gu(vu(t),0),byteLength:t}),Mc||(this.byteLength=t,this.detached=!1)})[au],pu=(fu=function(e,t,n){Hc(this,pu),Hc(e,hu);var r=su(e),i=r.byteLength,a=Wc(t);if(a<0||a>i)throw new _u("Wrong offset");if(a+(n=void 0===n?i-a:jc(n))>i)throw new _u("Wrong length");uu(this,{type:iu,buffer:e,byteLength:n,byteOffset:a,bytes:r.bytes}),Mc||(this.buffer=e,this.byteLength=n,this.byteOffset=a)})[au],Mc&&(Cu(du,"byteLength",su),Cu(fu,"buffer",cu),Cu(fu,"byteLength",cu),Cu(fu,"byteOffset",cu)),Fc(pu,{getInt8:function(e){return wu(this,1,e)[0]<<24>>24},getUint8:function(e){return wu(this,1,e)[0]},getInt16:function(e){var t=wu(this,2,e,arguments.length>1&&arguments[1]);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=wu(this,2,e,arguments.length>1&&arguments[1]);return t[1]<<8|t[0]},getInt32:function(e){return bu(wu(this,4,e,arguments.length>1&&arguments[1]))},getUint32:function(e){return bu(wu(this,4,e,arguments.length>1&&arguments[1]))>>>0},getFloat32:function(e){return ku(wu(this,4,e,arguments.length>1&&arguments[1]),23)},getFloat64:function(e){return ku(wu(this,8,e,arguments.length>1&&arguments[1]),52)},setInt8:function(e,t){Du(this,1,e,Tu,t)},setUint8:function(e,t){Du(this,1,e,Tu,t)},setInt16:function(e,t){Du(this,2,e,Su,t,arguments.length>2&&arguments[2])},setUint16:function(e,t){Du(this,2,e,Su,t,arguments.length>2&&arguments[2])},setInt32:function(e,t){Du(this,4,e,Iu,t,arguments.length>2&&arguments[2])},setUint32:function(e,t){Du(this,4,e,Iu,t,arguments.length>2&&arguments[2])},setFloat32:function(e,t){Du(this,4,e,Ru,t,arguments.length>2&&arguments[2])},setFloat64:function(e,t){Du(this,8,e,Au,t,arguments.length>2&&arguments[2])}});$c(du,ru),$c(fu,iu);var Pu={ArrayBuffer:du,DataView:fu},Mu=ae,Lu=Di,Vu=p,Uu=vt("species"),Fu=function(e){var t=Mu(e);Vu&&t&&!t[Uu]&&Lu(t,Uu,{configurable:!0,get:function(){return this}})},Bu=Fu,Hu="ArrayBuffer",Wu=Pu[Hu];vi({global:!0,constructor:!0,forced:u[Hu]!==Wu},{ArrayBuffer:Wu}),Bu(Hu);var ju=B,Gu=L,Ju=function(e){if("Function"===ju(e))return Gu(e)},Ku=vi,Yu=Ju,zu=h,qu=Yt,Xu=Tr,Qu=br,Zu=Pu.ArrayBuffer,$u=Pu.DataView,el=$u.prototype,tl=Yu(Zu.prototype.slice),nl=Yu(el.getUint8),rl=Yu(el.setUint8);Ku({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:zu((function(){return!new Zu(2).slice(1,void 0).byteLength}))},{slice:function(e,t){if(tl&&void 0===t)return tl(qu(this),e);for(var n=qu(this).byteLength,r=Xu(e,n),i=Xu(void 0===t?n:t,n),a=new Zu(Qu(i-r)),o=new $u(this),s=new $u(a),c=0;r<i;)rl(s,c++,nl(o,r++));return a}});var il=L,al=h,ol=ee,sl=Ii,cl=Tn,ul=function(){},ll=ae("Reflect","construct"),dl=/^\s*(?:class|function)\b/,hl=il(dl.exec),fl=!dl.test(ul),pl=function(e){if(!ol(e))return!1;try{return ll(ul,[],e),!0}catch(Lj){return!1}},ml=function(e){if(!ol(e))return!1;switch(sl(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return fl||!!hl(dl,cl(e))}catch(Lj){return!0}};ml.sham=!0;var vl,_l,gl,yl,El=!ll||al((function(){var e;return pl(pl.call)||!pl(Object)||!pl((function(){e=!0}))||e}))?ml:pl,kl=El,Tl=Ce,Sl=TypeError,Il=function(e){if(kl(e))return e;throw new Sl(Tl(e)+" is not a constructor")},bl=Yt,Rl=Il,Al=K,Cl=vt("species"),wl=function(e,t){var n,r=bl(e).constructor;return void 0===r||Al(n=bl(r)[Cl])?t:Rl(n)},Dl=m,Nl=Function.prototype,xl=Nl.apply,Ol=Nl.call,Pl="object"==("undefined"==typeof Reflect?"undefined":T(Reflect))&&Reflect.apply||(Dl?Ol.bind(xl):function(){return Ol.apply(xl,arguments)}),Ml=xe,Ll=m,Vl=Ju(Ju.bind),Ul=function(e,t){return Ml(e),void 0===t?e:Ll?Vl(e,t):function(){return e.apply(t,arguments)}},Fl=TypeError,Bl=function(e,t){if(e<t)throw new Fl("Not enough arguments");return e},Hl=/(?:ipad|iphone|ipod).*applewebkit/i.test(ue),Wl=u,jl=Pl,Gl=Ul,Jl=ee,Kl=nt,Yl=h,zl=sa,ql=bs,Xl=Dt,Ql=Bl,Zl=Hl,$l=ps,ed=Wl.setImmediate,td=Wl.clearImmediate,nd=Wl.process,rd=Wl.Dispatch,id=Wl.Function,ad=Wl.MessageChannel,od=Wl.String,sd=0,cd={},ud="onreadystatechange";Yl((function(){vl=Wl.location}));var ld=function(e){if(Kl(cd,e)){var t=cd[e];delete cd[e],t()}},dd=function(e){return function(){ld(e)}},hd=function(e){ld(e.data)},fd=function(e){Wl.postMessage(od(e),vl.protocol+"//"+vl.host)};ed&&td||(ed=function(e){Ql(arguments.length,1);var t=Jl(e)?e:id(e),n=ql(arguments,1);return cd[++sd]=function(){jl(t,void 0,n)},_l(sd),sd},td=function(e){delete cd[e]},$l?_l=function(e){nd.nextTick(dd(e))}:rd&&rd.now?_l=function(e){rd.now(dd(e))}:ad&&!Zl?(yl=(gl=new ad).port2,gl.port1.onmessage=hd,_l=Gl(yl.postMessage,yl)):Wl.addEventListener&&Jl(Wl.postMessage)&&!Wl.importScripts&&vl&&"file:"!==vl.protocol&&!Yl(fd)?(_l=fd,Wl.addEventListener("message",hd,!1)):_l=ud in Xl("script")?function(e){zl.appendChild(Xl("script"))[ud]=function(){zl.removeChild(this),ld(e)}}:function(e){setTimeout(dd(e),0)});var pd={set:ed,clear:td},md=u,vd=p,_d=Object.getOwnPropertyDescriptor,gd=function(e){if(!vd)return md[e];var t=_d(md,e);return t&&t.value},yd=function(){this.head=null,this.tail=null};yd.prototype={add:function(e){var t={item:e,next:null},n=this.tail;n?n.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item}};var Ed,kd,Td,Sd,Id,bd=yd,Rd=/ipad|iphone|ipod/i.test(ue)&&"undefined"!=typeof Pebble,Ad=/web0s(?!.*chrome)/i.test(ue),Cd=u,wd=gd,Dd=Ul,Nd=pd.set,xd=bd,Od=Hl,Pd=Rd,Md=Ad,Ld=ps,Vd=Cd.MutationObserver||Cd.WebKitMutationObserver,Ud=Cd.document,Fd=Cd.process,Bd=Cd.Promise,Hd=wd("queueMicrotask");if(!Hd){var Wd=new xd,jd=function(){var e,t;for(Ld&&(e=Fd.domain)&&e.exit();t=Wd.get();)try{t()}catch(Lj){throw Wd.head&&Ed(),Lj}e&&e.enter()};Od||Ld||Md||!Vd||!Ud?!Pd&&Bd&&Bd.resolve?((Sd=Bd.resolve(void 0)).constructor=Bd,Id=Dd(Sd.then,Sd),Ed=function(){Id(jd)}):Ld?Ed=function(){Fd.nextTick(jd)}:(Nd=Dd(Nd,Cd),Ed=function(){Nd(jd)}):(kd=!0,Td=Ud.createTextNode(""),new Vd(jd).observe(Td,{characterData:!0}),Ed=function(){Td.data=kd=!kd}),Hd=function(e){Wd.head||Ed(),Wd.add(e)}}var Gd=Hd,Jd=function(e){try{return{error:!1,value:e()}}catch(Lj){return{error:!0,value:Lj}}},Kd=u.Promise,Yd=u,zd=Kd,qd=ee,Xd=ci,Qd=Tn,Zd=vt,$d=fs,eh=ve;zd&&zd.prototype;var th=Zd("species"),nh=!1,rh=qd(Yd.PromiseRejectionEvent),ih=Xd("Promise",(function(){var e=Qd(zd),t=e!==String(zd);if(!t&&66===eh)return!0;if(!eh||eh<51||!/native code/.test(e)){var n=new zd((function(e){e(1)})),r=function(e){e((function(){}),(function(){}))};if((n.constructor={})[th]=r,!(nh=n.then((function(){}))instanceof r))return!0}return!(t||"BROWSER"!==$d&&"DENO"!==$d||rh)})),ah={CONSTRUCTOR:ih,REJECTION_EVENT:rh,SUBCLASSING:nh},oh={},sh=xe,ch=TypeError,uh=function(e){var t,n;this.promise=new e((function(e,r){if(void 0!==t||void 0!==n)throw new ch("Bad Promise constructor");t=e,n=r})),this.resolve=sh(t),this.reject=sh(n)};oh.f=function(e){return new uh(e)};var lh,dh,hh,fh=vi,ph=ps,mh=u,vh=S,_h=hr,gh=go,yh=to,Eh=Fu,kh=xe,Th=ee,Sh=ne,Ih=sc,bh=wl,Rh=pd.set,Ah=Gd,Ch=Jd,wh=bd,Dh=jn,Nh=Kd,xh=oh,Oh="Promise",Ph=ah.CONSTRUCTOR,Mh=ah.REJECTION_EVENT,Lh=ah.SUBCLASSING,Vh=Dh.getterFor(Oh),Uh=Dh.set,Fh=Nh&&Nh.prototype,Bh=Nh,Hh=Fh,Wh=mh.TypeError,jh=mh.document,Gh=mh.process,Jh=xh.f,Kh=Jh,Yh=!!(jh&&jh.createEvent&&mh.dispatchEvent),zh="unhandledrejection",qh=function(e){var t;return!(!Sh(e)||!Th(t=e.then))&&t},Xh=function(e,t){var n,r,i,a=t.value,o=1===t.state,s=o?e.ok:e.fail,c=e.resolve,u=e.reject,l=e.domain;try{s?(o||(2===t.rejection&&tf(t),t.rejection=1),!0===s?n=a:(l&&l.enter(),n=s(a),l&&(l.exit(),i=!0)),n===e.promise?u(new Wh("Promise-chain cycle")):(r=qh(n))?vh(r,n,c,u):c(n)):u(a)}catch(Lj){l&&!i&&l.exit(),u(Lj)}},Qh=function(e,t){e.notified||(e.notified=!0,Ah((function(){for(var n,r=e.reactions;n=r.get();)Xh(n,e);e.notified=!1,t&&!e.rejection&&$h(e)})))},Zh=function(e,t,n){var r,i;Yh?((r=jh.createEvent("Event")).promise=t,r.reason=n,r.initEvent(e,!1,!0),mh.dispatchEvent(r)):r={promise:t,reason:n},!Mh&&(i=mh["on"+e])?i(r):e===zh&&function(e,t){try{1===arguments.length?console.error(e):console.error(e,t)}catch(Lj){}}("Unhandled promise rejection",n)},$h=function(e){vh(Rh,mh,(function(){var t,n=e.facade,r=e.value;if(ef(e)&&(t=Ch((function(){ph?Gh.emit("unhandledRejection",r,n):Zh(zh,n,r)})),e.rejection=ph||ef(e)?2:1,t.error))throw t.value}))},ef=function(e){return 1!==e.rejection&&!e.parent},tf=function(e){vh(Rh,mh,(function(){var t=e.facade;ph?Gh.emit("rejectionHandled",t):Zh("rejectionhandled",t,e.value)}))},nf=function(e,t,n){return function(r){e(t,r,n)}},rf=function(e,t,n){e.done||(e.done=!0,n&&(e=n),e.value=t,e.state=2,Qh(e,!0))},af=function(e,t,n){if(!e.done){e.done=!0,n&&(e=n);try{if(e.facade===t)throw new Wh("Promise can't be resolved itself");var r=qh(t);r?Ah((function(){var n={done:!1};try{vh(r,t,nf(af,n,e),nf(rf,n,e))}catch(Lj){rf(n,Lj,e)}})):(e.value=t,e.state=1,Qh(e,!1))}catch(Lj){rf({done:!1},Lj,e)}}};if(Ph&&(Hh=(Bh=function(e){Ih(this,Hh),kh(e),vh(lh,this);var t=Vh(this);try{e(nf(af,t),nf(rf,t))}catch(Lj){rf(t,Lj)}}).prototype,(lh=function(e){Uh(this,{type:Oh,done:!1,notified:!1,parent:!1,reactions:new wh,rejection:!1,state:0,value:null})}).prototype=_h(Hh,"then",(function(e,t){var n=Vh(this),r=Jh(bh(this,Bh));return n.parent=!0,r.ok=!Th(e)||e,r.fail=Th(t)&&t,r.domain=ph?Gh.domain:void 0,0===n.state?n.reactions.add(r):Ah((function(){Xh(r,n)})),r.promise})),dh=function(){var e=new lh,t=Vh(e);this.promise=e,this.resolve=nf(af,t),this.reject=nf(rf,t)},xh.f=Jh=function(e){return e===Bh||void 0===e?new dh(e):Kh(e)},Th(Nh)&&Fh!==Object.prototype)){hh=Fh.then,Lh||_h(Fh,"then",(function(e,t){var n=this;return new Bh((function(e,t){vh(hh,n,e,t)})).then(e,t)}),{unsafe:!0});try{delete Fh.constructor}catch(Lj){}gh&&gh(Fh,Hh)}fh({global:!0,constructor:!0,wrap:!0,forced:Ph},{Promise:Bh}),yh(Bh,Oh,!1),Eh(Oh);var of=Oa,sf=vt("iterator"),cf=Array.prototype,uf=function(e){return void 0!==e&&(of.Array===e||cf[sf]===e)},lf=Ii,df=Me,hf=K,ff=Oa,pf=vt("iterator"),mf=function(e){if(!hf(e))return df(e,pf)||df(e,"@@iterator")||ff[lf(e)]},vf=S,_f=xe,gf=Yt,yf=Ce,Ef=mf,kf=TypeError,Tf=function(e,t){var n=arguments.length<2?Ef(e):t;if(_f(n))return gf(vf(n,e));throw new kf(yf(e)+" is not iterable")},Sf=S,If=Yt,bf=Me,Rf=function(e,t,n){var r,i;If(e);try{if(!(r=bf(e,"return"))){if("throw"===t)throw n;return n}r=Sf(r,e)}catch(Lj){i=!0,r=Lj}if("throw"===t)throw n;if(i)throw r;return If(r),n},Af=Ul,Cf=S,wf=Yt,Df=Ce,Nf=uf,xf=Ar,Of=oe,Pf=Tf,Mf=mf,Lf=Rf,Vf=TypeError,Uf=function(e,t){this.stopped=e,this.result=t},Ff=Uf.prototype,Bf=function(e,t,n){var r,i,a,o,s,c,u,l=n&&n.that,d=!(!n||!n.AS_ENTRIES),h=!(!n||!n.IS_RECORD),f=!(!n||!n.IS_ITERATOR),p=!(!n||!n.INTERRUPTED),m=Af(t,l),v=function(e){return r&&Lf(r,"normal",e),new Uf(!0,e)},_=function(e){return d?(wf(e),p?m(e[0],e[1],v):m(e[0],e[1])):p?m(e,v):m(e)};if(h)r=e.iterator;else if(f)r=e;else{if(!(i=Mf(e)))throw new Vf(Df(e)+" is not iterable");if(Nf(i)){for(a=0,o=xf(e);o>a;a++)if((s=_(e[a]))&&Of(Ff,s))return s;return new Uf(!1)}r=Pf(e,i)}for(c=h?e.next:r.next;!(u=Cf(c,r)).done;){try{s=_(u.value)}catch(Lj){Lf(r,"throw",Lj)}if("object"==T(s)&&s&&Of(Ff,s))return s}return new Uf(!1)},Hf=vt("iterator"),Wf=!1;try{var jf=0,Gf={next:function(){return{done:!!jf++}},return:function(){Wf=!0}};Gf[Hf]=function(){return this},Array.from(Gf,(function(){throw 2}))}catch(Lj){}var Jf=function(e,t){try{if(!t&&!Wf)return!1}catch(Lj){return!1}var n=!1;try{var r={};r[Hf]=function(){return{next:function(){return{done:n=!0}}}},e(r)}catch(Lj){}return n},Kf=Kd,Yf=ah.CONSTRUCTOR||!Jf((function(e){Kf.all(e).then(void 0,(function(){}))})),zf=S,qf=xe,Xf=oh,Qf=Jd,Zf=Bf;vi({target:"Promise",stat:!0,forced:Yf},{all:function(e){var t=this,n=Xf.f(t),r=n.resolve,i=n.reject,a=Qf((function(){var n=qf(t.resolve),a=[],o=0,s=1;Zf(e,(function(e){var c=o++,u=!1;s++,zf(n,t,e).then((function(e){u||(u=!0,a[c]=e,--s||r(a))}),i)})),--s||r(a)}));return a.error&&i(a.value),n.promise}});var $f=vi,ep=ah.CONSTRUCTOR,tp=Kd,np=ae,rp=ee,ip=hr,ap=tp&&tp.prototype;if($f({target:"Promise",proto:!0,forced:ep,real:!0},{catch:function(e){return this.then(void 0,e)}}),rp(tp)){var op=np("Promise").prototype.catch;ap.catch!==op&&ip(ap,"catch",op,{unsafe:!0})}var sp=S,cp=xe,up=oh,lp=Jd,dp=Bf;vi({target:"Promise",stat:!0,forced:Yf},{race:function(e){var t=this,n=up.f(t),r=n.reject,i=lp((function(){var i=cp(t.resolve);dp(e,(function(e){sp(i,t,e).then(n.resolve,r)}))}));return i.error&&r(i.value),n.promise}});var hp=oh;vi({target:"Promise",stat:!0,forced:ah.CONSTRUCTOR},{reject:function(e){var t=hp.f(this);return(0,t.reject)(e),t.promise}});var fp=Yt,pp=ne,mp=oh,vp=function(e,t){if(fp(e),pp(t)&&t.constructor===e)return t;var n=mp.f(e);return(0,n.resolve)(t),n.promise},_p=vi,gp=ah.CONSTRUCTOR,yp=vp;ae("Promise"),_p({target:"Promise",stat:!0,forced:gp},{resolve:function(e){return yp(this,e)}});var Ep=vi,kp=Kd,Tp=h,Sp=ae,Ip=ee,bp=wl,Rp=vp,Ap=hr,Cp=kp&&kp.prototype;if(Ep({target:"Promise",proto:!0,real:!0,forced:!!kp&&Tp((function(){Cp.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=bp(this,Sp("Promise")),n=Ip(e);return this.then(n?function(n){return Rp(t,e()).then((function(){return n}))}:e,n?function(n){return Rp(t,e()).then((function(){throw n}))}:e)}}),Ip(kp)){var wp=Sp("Promise").prototype.finally;Cp.finally!==wp&&Ap(Cp,"finally",wp,{unsafe:!0})}var Dp=ne,Np=B,xp=vt("match"),Op=function(e){var t;return Dp(e)&&(void 0!==(t=e[xp])?!!t:"RegExp"===Np(e))},Pp=Yt,Mp=function(){var e=Pp(this),t="";return e.hasIndices&&(t+="d"),e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.unicodeSets&&(t+="v"),e.sticky&&(t+="y"),t},Lp=S,Vp=nt,Up=oe,Fp=Mp,Bp=RegExp.prototype,Hp=function(e){var t=e.flags;return void 0!==t||"flags"in Bp||Vp(e,"flags")||!Up(Bp,e)?t:Lp(Fp,e)},Wp=h,jp=u.RegExp,Gp=Wp((function(){var e=jp("a","y");return e.lastIndex=2,null!==e.exec("abcd")})),Jp=Gp||Wp((function(){return!jp("a","y").sticky})),Kp=Gp||Wp((function(){var e=jp("^r","gy");return e.lastIndex=2,null!==e.exec("str")})),Yp={BROKEN_CARET:Kp,MISSED_STICKY:Jp,UNSUPPORTED_Y:Gp},zp=Wt.f,qp=h,Xp=u.RegExp,Qp=qp((function(){var e=Xp(".","s");return!(e.dotAll&&e.test("\n")&&"s"===e.flags)})),Zp=h,$p=u.RegExp,em=Zp((function(){var e=$p("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),tm=p,nm=u,rm=L,im=ci,am=xc,om=cn,sm=ka,cm=fr.f,um=oe,lm=Op,dm=Ai,hm=Hp,fm=Yp,pm=function(e,t,n){n in e||zp(e,n,{configurable:!0,get:function(){return t[n]},set:function(e){t[n]=e}})},mm=hr,vm=h,_m=nt,gm=jn.enforce,ym=Fu,Em=Qp,km=em,Tm=vt("match"),Sm=nm.RegExp,Im=Sm.prototype,bm=nm.SyntaxError,Rm=rm(Im.exec),Am=rm("".charAt),Cm=rm("".replace),wm=rm("".indexOf),Dm=rm("".slice),Nm=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,xm=/a/g,Om=/a/g,Pm=new Sm(xm)!==xm,Mm=fm.MISSED_STICKY,Lm=fm.UNSUPPORTED_Y;if(im("RegExp",tm&&(!Pm||Mm||Em||km||vm((function(){return Om[Tm]=!1,Sm(xm)!==xm||Sm(Om)===Om||"/a/i"!==String(Sm(xm,"i"))}))))){for(var Vm=function(e,t){var n,r,i,a,o,s,c=um(Im,this),u=lm(e),l=void 0===t,d=[],h=e;if(!c&&u&&l&&e.constructor===Vm)return e;if((u||um(Im,e))&&(e=e.source,l&&(t=hm(h))),e=void 0===e?"":dm(e),t=void 0===t?"":dm(t),h=e,Em&&"dotAll"in xm&&(r=!!t&&wm(t,"s")>-1)&&(t=Cm(t,/s/g,"")),n=t,Mm&&"sticky"in xm&&(i=!!t&&wm(t,"y")>-1)&&Lm&&(t=Cm(t,/y/g,"")),km&&(a=function(e){for(var t,n=e.length,r=0,i="",a=[],o=sm(null),s=!1,c=!1,u=0,l="";r<=n;r++){if("\\"===(t=Am(e,r)))t+=Am(e,++r);else if("]"===t)s=!1;else if(!s)switch(!0){case"["===t:s=!0;break;case"("===t:if(i+=t,"?:"===Dm(e,r+1,r+3))continue;Rm(Nm,Dm(e,r+1))&&(r+=2,c=!0),u++;continue;case">"===t&&c:if(""===l||_m(o,l))throw new bm("Invalid capture group name");o[l]=!0,a[a.length]=[l,u],c=!1,l="";continue}c?l+=t:i+=t}return[i,a]}(e),e=a[0],d=a[1]),o=am(Sm(e,t),c?this:Im,Vm),(r||i||d.length)&&(s=gm(o),r&&(s.dotAll=!0,s.raw=Vm(function(e){for(var t,n=e.length,r=0,i="",a=!1;r<=n;r++)"\\"!==(t=Am(e,r))?a||"."!==t?("["===t?a=!0:"]"===t&&(a=!1),i+=t):i+="[\\s\\S]":i+=t+Am(e,++r);return i}(e),n)),i&&(s.sticky=!0),d.length&&(s.groups=d)),e!==h)try{om(o,"source",""===h?"(?:)":h)}catch(Lj){}return o},Um=cm(Sm),Fm=0;Um.length>Fm;)pm(Vm,Sm,Um[Fm++]);Im.constructor=Vm,Vm.prototype=Im,mm(nm,"RegExp",Vm,{constructor:!0})}ym("RegExp");var Bm=S,Hm=L,Wm=Ai,jm=Mp,Gm=Yp,Jm=ka,Km=jn.get,Ym=Qp,zm=em,qm=Xe("native-string-replace",String.prototype.replace),Xm=RegExp.prototype.exec,Qm=Xm,Zm=Hm("".charAt),$m=Hm("".indexOf),ev=Hm("".replace),tv=Hm("".slice),nv=function(){var e=/a/,t=/b*/g;return Bm(Xm,e,"a"),Bm(Xm,t,"a"),0!==e.lastIndex||0!==t.lastIndex}(),rv=Gm.BROKEN_CARET,iv=void 0!==/()??/.exec("")[1];(nv||iv||rv||Ym||zm)&&(Qm=function(e){var t,n,r,i,a,o,s,c=this,u=Km(c),l=Wm(e),d=u.raw;if(d)return d.lastIndex=c.lastIndex,t=Bm(Qm,d,l),c.lastIndex=d.lastIndex,t;var h=u.groups,f=rv&&c.sticky,p=Bm(jm,c),m=c.source,v=0,_=l;if(f&&(p=ev(p,"y",""),-1===$m(p,"g")&&(p+="g"),_=tv(l,c.lastIndex),c.lastIndex>0&&(!c.multiline||c.multiline&&"\n"!==Zm(l,c.lastIndex-1))&&(m="(?: "+m+")",_=" "+_,v++),n=new RegExp("^(?:"+m+")",p)),iv&&(n=new RegExp("^"+m+"$(?!\\s)",p)),nv&&(r=c.lastIndex),i=Bm(Xm,f?n:c,_),f?i?(i.input=tv(i.input,v),i[0]=tv(i[0],v),i.index=c.lastIndex,c.lastIndex+=i[0].length):c.lastIndex=0:nv&&i&&(c.lastIndex=c.global?i.index+i[0].length:r),iv&&i&&i.length>1&&Bm(qm,i[0],n,(function(){for(a=1;a<arguments.length-2;a++)void 0===arguments[a]&&(i[a]=void 0)})),i&&h)for(i.groups=o=Jm(null),a=0;a<h.length;a++)o[(s=h[a])[0]]=i[s[1]];return i});var av=Qm;vi({target:"RegExp",proto:!0,forced:/./.exec!==av},{exec:av});var ov=gr,sv=Ai,cv=q,uv=RangeError,lv=L,dv=br,hv=Ai,fv=q,pv=lv((function(e){var t=sv(cv(this)),n="",r=ov(e);if(r<0||Infinity===r)throw new uv("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))1&r&&(n+=t);return n})),mv=lv("".slice),vv=Math.ceil,_v=function(e){return function(t,n,r){var i,a,o=hv(fv(t)),s=dv(n),c=o.length,u=void 0===r?" ":hv(r);return s<=c||""===u?o:((a=pv(u,vv((i=s-c)/u.length))).length>i&&(a=mv(a,0,i)),e?o+a:a+o)}},gv={start:_v(!1),end:_v(!0)},yv=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(ue),Ev=gv.start;vi({target:"String",proto:!0,forced:yv},{padStart:function(e){return Ev(this,e,arguments.length>1?arguments[1]:void 0)}});var kv=S,Tv=hr,Sv=av,Iv=h,bv=vt,Rv=cn,Av=bv("species"),Cv=RegExp.prototype,wv=L,Dv=gr,Nv=Ai,xv=q,Ov=wv("".charAt),Pv=wv("".charCodeAt),Mv=wv("".slice),Lv=function(e){return function(t,n){var r,i,a=Nv(xv(t)),o=Dv(n),s=a.length;return o<0||o>=s?e?"":void 0:(r=Pv(a,o))<55296||r>56319||o+1===s||(i=Pv(a,o+1))<56320||i>57343?e?Ov(a,o):r:e?Mv(a,o,o+2):i-56320+(r-55296<<10)+65536}},Vv={codeAt:Lv(!1),charAt:Lv(!0)},Uv=Vv.charAt,Fv=L,Bv=$e,Hv=Math.floor,Wv=Fv("".charAt),jv=Fv("".replace),Gv=Fv("".slice),Jv=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Kv=/\$([$&'`]|\d{1,2})/g,Yv=function(e,t,n,r,i,a){var o=n+e.length,s=r.length,c=Kv;return void 0!==i&&(i=Bv(i),c=Jv),jv(a,c,(function(a,c){var u;switch(Wv(c,0)){case"$":return"$";case"&":return e;case"`":return Gv(t,0,n);case"'":return Gv(t,o);case"<":u=i[Gv(c,1,-1)];break;default:var l=+c;if(0===l)return a;if(l>s){var d=Hv(l/10);return 0===d?a:d<=s?void 0===r[d-1]?Wv(c,1):r[d-1]+Wv(c,1):a}u=r[l-1]}return void 0===u?"":u}))},zv=S,qv=Yt,Xv=ee,Qv=B,Zv=av,$v=TypeError,e_=Pl,t_=S,n_=L,r_=h,i_=Yt,a_=ee,o_=K,s_=gr,c_=br,u_=Ai,l_=q,d_=function(e,t,n){return t+(n?Uv(e,t).length:1)},h_=Me,f_=Yv,p_=function(e,t){var n=e.exec;if(Xv(n)){var r=zv(n,e,t);return null!==r&&qv(r),r}if("RegExp"===Qv(e))return zv(Zv,e,t);throw new $v("RegExp#exec called on incompatible receiver")},m_=vt("replace"),v_=Math.max,__=Math.min,g_=n_([].concat),y_=n_([].push),E_=n_("".indexOf),k_=n_("".slice),T_=function(e){return void 0===e?e:String(e)},S_="$0"==="a".replace(/./,"$0"),I_=!!/./[m_]&&""===/./[m_]("a","$0"),b_=!r_((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));!function(e,t,n,r){var i=bv(e),a=!Iv((function(){var t={};return t[i]=function(){return 7},7!==""[e](t)})),o=a&&!Iv((function(){var t=!1,n=/a/;return"split"===e&&((n={}).constructor={},n.constructor[Av]=function(){return n},n.flags="",n[i]=/./[i]),n.exec=function(){return t=!0,null},n[i](""),!t}));if(!a||!o||n){var s=/./[i],c=t(i,""[e],(function(e,t,n,r,i){var o=t.exec;return o===Sv||o===Cv.exec?a&&!i?{done:!0,value:kv(s,t,n,r)}:{done:!0,value:kv(e,n,t,r)}:{done:!1}}));Tv(String.prototype,e,c[0]),Tv(Cv,i,c[1])}r&&Rv(Cv[i],"sham",!0)}("replace",(function(e,t,n){var r=I_?"$":"$0";return[function(e,n){var r=l_(this),i=o_(e)?void 0:h_(e,m_);return i?t_(i,e,r,n):t_(t,u_(r),e,n)},function(e,i){var a=i_(this),o=u_(e);if("string"==typeof i&&-1===E_(i,r)&&-1===E_(i,"$<")){var s=n(t,a,o,i);if(s.done)return s.value}var c=a_(i);c||(i=u_(i));var u,l=a.global;l&&(u=a.unicode,a.lastIndex=0);for(var d,h=[];null!==(d=p_(a,o))&&(y_(h,d),l);)""===u_(d[0])&&(a.lastIndex=d_(o,c_(a.lastIndex),u));for(var f="",p=0,m=0;m<h.length;m++){for(var v,_=u_((d=h[m])[0]),g=v_(__(s_(d.index),o.length),0),y=[],E=1;E<d.length;E++)y_(y,T_(d[E]));var k=d.groups;if(c){var T=g_([_],y,g,o);void 0!==k&&y_(T,k),v=u_(e_(i,void 0,T))}else v=f_(_,o,g,y,k,i);g>=p&&(f+=k_(o,p,g)+v,p=g+_.length)}return f+k_(o,p)}]}),!b_||!S_||I_);var R_="\t\n\v\f\r \u2028\u2029\ufeff",A_=q,C_=Ai,w_=R_,D_=L("".replace),N_=RegExp("^["+w_+"]+"),x_=RegExp("(^|[^"+w_+"])["+w_+"]+$"),O_=function(e){return function(t){var n=C_(A_(t));return 1&e&&(n=D_(n,N_,"")),2&e&&(n=D_(n,x_,"$1")),n}},P_={start:O_(1),end:O_(2),trim:O_(3)},M_=mn.PROPER,L_=h,V_=R_,U_=P_.trim;vi({target:"String",proto:!0,forced:function(e){return L_((function(){return!!V_[e]()||"
"!=="
"[e]()||M_&&V_[e].name!==e}))}("trim")},{trim:function(){return U_(this)}});var F_,B_,H_,W_={exports:{}},j_=nc,G_=p,J_=u,K_=ee,Y_=ne,z_=nt,q_=Ii,X_=Ce,Q_=cn,Z_=hr,$_=Di,eg=oe,tg=Wa,ng=go,rg=vt,ig=st,ag=jn.enforce,og=jn.get,sg=J_.Int8Array,cg=sg&&sg.prototype,ug=J_.Uint8ClampedArray,lg=ug&&ug.prototype,dg=sg&&tg(sg),hg=cg&&tg(cg),fg=Object.prototype,pg=J_.TypeError,mg=rg("toStringTag"),vg=ig("TYPED_ARRAY_TAG"),_g="TypedArrayConstructor",gg=j_&&!!ng&&"Opera"!==q_(J_.opera),yg=!1,Eg={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},kg={BigInt64Array:8,BigUint64Array:8},Tg=function(e){var t=tg(e);if(Y_(t)){var n=og(t);return n&&z_(n,_g)?n[_g]:Tg(t)}},Sg=function(e){if(!Y_(e))return!1;var t=q_(e);return z_(Eg,t)||z_(kg,t)};for(F_ in Eg)(H_=(B_=J_[F_])&&B_.prototype)?ag(H_)[_g]=B_:gg=!1;for(F_ in kg)(H_=(B_=J_[F_])&&B_.prototype)&&(ag(H_)[_g]=B_);if((!gg||!K_(dg)||dg===Function.prototype)&&(dg=function(){throw new pg("Incorrect invocation")},gg))for(F_ in Eg)J_[F_]&&ng(J_[F_],dg);if((!gg||!hg||hg===fg)&&(hg=dg.prototype,gg))for(F_ in Eg)J_[F_]&&ng(J_[F_].prototype,hg);if(gg&&tg(lg)!==hg&&ng(lg,hg),G_&&!z_(hg,mg))for(F_ in yg=!0,$_(hg,mg,{configurable:!0,get:function(){return Y_(this)?this[vg]:void 0}}),Eg)J_[F_]&&Q_(J_[F_],vg,F_);var Ig={NATIVE_ARRAY_BUFFER_VIEWS:gg,TYPED_ARRAY_TAG:yg&&vg,aTypedArray:function(e){if(Sg(e))return e;throw new pg("Target is not a typed array")},aTypedArrayConstructor:function(e){if(K_(e)&&(!ng||eg(dg,e)))return e;throw new pg(X_(e)+" is not a typed array constructor")},exportTypedArrayMethod:function(e,t,n,r){if(G_){if(n)for(var i in Eg){var a=J_[i];if(a&&z_(a.prototype,e))try{delete a.prototype[e]}catch(Lj){try{a.prototype[e]=t}catch(h){}}}hg[e]&&!n||Z_(hg,e,n?t:gg&&cg[e]||t,r)}},exportTypedArrayStaticMethod:function(e,t,n){var r,i;if(G_){if(ng){if(n)for(r in Eg)if((i=J_[r])&&z_(i,e))try{delete i[e]}catch(Lj){}if(dg[e]&&!n)return;try{return Z_(dg,e,n?t:gg&&dg[e]||t)}catch(Lj){}}for(r in Eg)!(i=J_[r])||i[e]&&!n||Z_(i,e,t)}},getTypedArrayConstructor:Tg,isView:function(e){if(!Y_(e))return!1;var t=q_(e);return"DataView"===t||z_(Eg,t)||z_(kg,t)},isTypedArray:Sg,TypedArray:dg,TypedArrayPrototype:hg},bg=u,Rg=h,Ag=Jf,Cg=Ig.NATIVE_ARRAY_BUFFER_VIEWS,wg=bg.ArrayBuffer,Dg=bg.Int8Array,Ng=!Cg||!Rg((function(){Dg(1)}))||!Rg((function(){new Dg(-1)}))||!Ag((function(e){new Dg,new Dg(null),new Dg(1.5),new Dg(e)}),!0)||Rg((function(){return 1!==new Dg(new wg(2),1,void 0).length})),xg=ne,Og=Math.floor,Pg=Number.isInteger||function(e){return!xg(e)&&isFinite(e)&&Og(e)===e},Mg=gr,Lg=RangeError,Vg=RangeError,Ug=function(e,t){var n=function(e){var t=Mg(e);if(t<0)throw new Lg("The argument can't be less than 0");return t}(e);if(n%t)throw new Vg("Wrong offset");return n},Fg=Math.round,Bg=Ii,Hg=St,Wg=TypeError,jg=function(e){var t=Hg(e,"number");if("number"==typeof t)throw new Wg("Can't convert number to bigint");return BigInt(t)},Gg=Ul,Jg=S,Kg=Il,Yg=$e,zg=Ar,qg=Tf,Xg=mf,Qg=uf,Zg=Ig.aTypedArrayConstructor,$g=jg,ey=function(e){var t,n,r,i,a,o,s,c,u=Kg(this),l=Yg(e),d=arguments.length,h=d>1?arguments[1]:void 0,f=void 0!==h,p=Xg(l);if(p&&!Qg(p))for(c=(s=qg(l,p)).next,l=[];!(o=Jg(c,s)).done;)l.push(o.value);for(f&&d>2&&(h=Gg(h,arguments[2])),n=zg(l),i=function(e){var t=Bg(e);return"BigInt64Array"===t||"BigUint64Array"===t}(r=new(Zg(u))(n)),t=0;n>t;t++)a=f?h(l[t],t):l[t],r[t]=i?$g(a):+a;return r},ty=gs,ny=El,ry=ne,iy=vt("species"),ay=Array,oy=Ul,sy=J,cy=$e,uy=Ar,ly=function(e,t){return new(function(e){var t;return ty(e)&&(t=e.constructor,(ny(t)&&(t===ay||ty(t.prototype))||ry(t)&&null===(t=t[iy]))&&(t=void 0)),void 0===t?ay:t}(e))(0===t?0:t)},dy=L([].push),hy=function(e){var t=1===e,n=2===e,r=3===e,i=4===e,a=6===e,o=7===e,s=5===e||a;return function(c,u,l,d){for(var h,f,p=cy(c),m=sy(p),v=uy(m),_=oy(u,l),g=0,y=d||ly,E=t?y(c,v):n||o?y(c,0):void 0;v>g;g++)if((s||g in m)&&(f=_(h=m[g],g,p),e))if(t)E[g]=f;else if(f)switch(e){case 3:return!0;case 5:return h;case 6:return g;case 2:dy(E,h)}else switch(e){case 4:return!1;case 7:dy(E,h)}return a?-1:r||i?i:E}},fy={forEach:hy(0),map:hy(1),filter:hy(2),some:hy(3),every:hy(4),find:hy(5),findIndex:hy(6),filterReject:hy(7)},py=Ar,my=vi,vy=u,_y=S,gy=p,yy=Ng,Ey=Ig,ky=Pu,Ty=sc,Sy=N,Iy=cn,by=Pg,Ry=br,Ay=dc,Cy=Ug,wy=Rt,Dy=nt,Ny=Ii,xy=ne,Oy=Re,Py=ka,My=oe,Ly=go,Vy=fr.f,Uy=ey,Fy=fy.forEach,By=Fu,Hy=Di,Wy=Wt,jy=l,Gy=function(e,t,n){for(var r=0,i=arguments.length>2?n:py(t),a=new e(i);i>r;)a[r]=t[r++];return a},Jy=xc,Ky=jn.get,Yy=jn.set,zy=jn.enforce,qy=Wy.f,Xy=jy.f,Qy=vy.RangeError,Zy=ky.ArrayBuffer,$y=Zy.prototype,eE=ky.DataView,tE=Ey.NATIVE_ARRAY_BUFFER_VIEWS,nE=Ey.TYPED_ARRAY_TAG,rE=Ey.TypedArray,iE=Ey.TypedArrayPrototype,aE=Ey.isTypedArray,oE="BYTES_PER_ELEMENT",sE="Wrong length",cE=function(e,t){Hy(e,t,{configurable:!0,get:function(){return Ky(this)[t]}})},uE=function(e){var t;return My($y,e)||"ArrayBuffer"===(t=Ny(e))||"SharedArrayBuffer"===t},lE=function(e,t){return aE(e)&&!Oy(t)&&t in e&&by(+t)&&t>=0},dE=function(e,t){return t=wy(t),lE(e,t)?Sy(2,e[t]):Xy(e,t)},hE=function(e,t,n){return t=wy(t),!(lE(e,t)&&xy(n)&&Dy(n,"value"))||Dy(n,"get")||Dy(n,"set")||n.configurable||Dy(n,"writable")&&!n.writable||Dy(n,"enumerable")&&!n.enumerable?qy(e,t,n):(e[t]=n.value,e)};gy?(tE||(jy.f=dE,Wy.f=hE,cE(iE,"buffer"),cE(iE,"byteOffset"),cE(iE,"byteLength"),cE(iE,"length")),my({target:"Object",stat:!0,forced:!tE},{getOwnPropertyDescriptor:dE,defineProperty:hE}),W_.exports=function(e,t,n){var r=e.match(/\d+/)[0]/8,i=e+(n?"Clamped":"")+"Array",a="get"+e,o="set"+e,s=vy[i],c=s,u=c&&c.prototype,l={},d=function(e,t){qy(e,t,{get:function(){return function(e,t){var n=Ky(e);return n.view[a](t*r+n.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,i){var a=Ky(e);a.view[o](t*r+a.byteOffset,n?function(e){var t=Fg(e);return t<0?0:t>255?255:255&t}(i):i,!0)}(this,t,e)},enumerable:!0})};tE?yy&&(c=t((function(e,t,n,i){return Ty(e,u),Jy(xy(t)?uE(t)?void 0!==i?new s(t,Cy(n,r),i):void 0!==n?new s(t,Cy(n,r)):new s(t):aE(t)?Gy(c,t):_y(Uy,c,t):new s(Ay(t)),e,c)})),Ly&&Ly(c,rE),Fy(Vy(s),(function(e){e in c||Iy(c,e,s[e])})),c.prototype=u):(c=t((function(e,t,n,i){Ty(e,u);var a,o,s,l=0,h=0;if(xy(t)){if(!uE(t))return aE(t)?Gy(c,t):_y(Uy,c,t);a=t,h=Cy(n,r);var f=t.byteLength;if(void 0===i){if(f%r)throw new Qy(sE);if((o=f-h)<0)throw new Qy(sE)}else if((o=Ry(i)*r)+h>f)throw new Qy(sE);s=o/r}else s=Ay(t),a=new Zy(o=s*r);for(Yy(e,{buffer:a,byteOffset:h,byteLength:o,length:s,view:new eE(a)});l<s;)d(e,l++)})),Ly&&Ly(c,rE),u=c.prototype=Py(iE)),u.constructor!==c&&Iy(u,"constructor",c),zy(u).TypedArrayConstructor=c,nE&&Iy(u,nE,i);var h=c!==s;l[i]=c,my({global:!0,constructor:!0,forced:h,sham:!tE},l),oE in c||Iy(c,oE,r),oE in u||Iy(u,oE,r),By(i)}):W_.exports=function(){};var fE=W_.exports;fE("Float32",(function(e){return function(t,n,r){return e(this,t,n,r)}})),fE("Uint8",(function(e){return function(t,n,r){return e(this,t,n,r)}}));var pE=Cc,mE=jg,vE=Ii,_E=S,gE=h,yE=Ig.aTypedArray,EE=Ig.exportTypedArrayMethod,kE=L("".slice);EE("fill",(function(e){var t=arguments.length;yE(this);var n="Big"===kE(vE(this),0,3)?mE(e):+e;return _E(pE,this,n,t>1?arguments[1]:void 0,t>2?arguments[2]:void 0)}),gE((function(){var e=0;return new Int8Array(2).fill({valueOf:function(){return e++}}),1!==e}))),(0,Ig.exportTypedArrayStaticMethod)("from",ey,Ng);var TE=u,SE=S,IE=Ig,bE=Ar,RE=Ug,AE=$e,CE=h,wE=TE.RangeError,DE=TE.Int8Array,NE=DE&&DE.prototype,xE=NE&&NE.set,OE=IE.aTypedArray,PE=IE.exportTypedArrayMethod,ME=!CE((function(){var e=new Uint8ClampedArray(2);return SE(xE,e,{length:1,0:3},1),3!==e[1]})),LE=ME&&IE.NATIVE_ARRAY_BUFFER_VIEWS&&CE((function(){var e=new DE(2);return e.set(1),e.set("2",1),0!==e[0]||2!==e[1]}));PE("set",(function(e){OE(this);var t=RE(arguments.length>1?arguments[1]:void 0,1),n=AE(e);if(ME)return SE(xE,this,n,t);var r=this.length,i=bE(n),a=0;if(i+t>r)throw new wE("Wrong length");for(;a<i;)this[t+a]=n[a++]}),!ME||LE);var VE=Ju,UE=h,FE=xe,BE=ws,HE=Ns,WE=xs,jE=ve,GE=Ps,JE=Ig.aTypedArray,KE=Ig.exportTypedArrayMethod,YE=u.Uint16Array,zE=YE&&VE(YE.prototype.sort),qE=!(!zE||UE((function(){zE(new YE(2),null)}))&&UE((function(){zE(new YE(2),{})}))),XE=!!zE&&!UE((function(){if(jE)return jE<74;if(HE)return HE<67;if(WE)return!0;if(GE)return GE<602;var e,t,n=new YE(516),r=Array(516);for(e=0;e<516;e++)t=e%4,n[e]=515-e,r[e]=e-2*t+3;for(zE(n,(function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(n[e]!==r[e])return!0}));KE("sort",(function(e){return void 0!==e&&FE(e),XE?zE(this,e):BE(JE(this),function(e){return function(t,n){return void 0!==e?+e(t,n)||0:n!=n?-1:t!=t?1:0===t&&0===n?1/t>0&&1/n<0?1:-1:t>n}}(e))}),!XE||qE);var QE=vi,ZE=S,$E=L,ek=q,tk=ee,nk=K,rk=Op,ik=Ai,ak=Me,ok=Hp,sk=Yv,ck=vt("replace"),uk=TypeError,lk=$E("".indexOf);$E("".replace);var dk=$E("".slice),hk=Math.max;QE({target:"String",proto:!0},{replaceAll:function(e,t){var n,r,i,a,o,s,c,u,l,d=ek(this),h=0,f="";if(!nk(e)){if(rk(e)&&(n=ik(ek(ok(e))),!~lk(n,"g")))throw new uk("`.replaceAll` does not allow non-global regexes");if(r=ak(e,ck))return ZE(r,e,d,t)}for(i=ik(d),a=ik(e),(o=tk(t))||(t=ik(t)),s=a.length,c=hk(1,s),u=lk(i,a);-1!==u;)l=o?ik(t(a,u,i)):sk(a,i,u,[],void 0,t),f+=dk(i,h,u)+l,h=u+s,u=u+c>i.length?-1:lk(i,a,u+c);return h<i.length&&(f+=dk(i,h)),f}});var fk={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},pk=Dt("span").classList,mk=pk&&pk.constructor&&pk.constructor.prototype,vk=mk===Object.prototype?void 0:mk,_k=fy.forEach,gk=cs("forEach")?[].forEach:function(e){return _k(this,e,arguments.length>1?arguments[1]:void 0)},yk=u,Ek=fk,kk=vk,Tk=gk,Sk=cn,Ik=function(e){if(e&&e.forEach!==Tk)try{Sk(e,"forEach",Tk)}catch(Lj){e.forEach=Tk}};for(var bk in Ek)Ek[bk]&&Ik(yk[bk]&&yk[bk].prototype);Ik(kk);var Rk=u,Ak=fk,Ck=vk,wk=Qo,Dk=cn,Nk=to,xk=vt("iterator"),Ok=wk.values,Pk=function(e,t){if(e){if(e[xk]!==Ok)try{Dk(e,xk,Ok)}catch(Lj){e[xk]=Ok}if(Nk(e,t,!0),Ak[t])for(var n in wk)if(e[n]!==wk[n])try{Dk(e,n,wk[n])}catch(Lj){e[n]=wk[n]}}};for(var Mk in Ak)Pk(Rk[Mk]&&Rk[Mk].prototype,Mk);Pk(Ck,"DOMTokenList");var Lk=Vv.charAt,Vk=Ai,Uk=jn,Fk=Uo,Bk=Fo,Hk="String Iterator",Wk=Uk.set,jk=Uk.getterFor(Hk);Fk(String,"String",(function(e){Wk(this,{type:Hk,string:Vk(e),index:0})}),(function(){var e,t=jk(this),n=t.string,r=t.index;return r>=n.length?Bk(void 0,!0):(e=Lk(n,r),t.index+=e.length,Bk(e,!1))}));var Gk=h,Jk=p,Kk=vt("iterator"),Yk=!Gk((function(){var e=new URL("b?a=1&b=2&c=3","https://a"),t=e.searchParams,n=new URLSearchParams("a=1&a=2&b=3"),r="";return e.pathname="c%20d",t.forEach((function(e,n){t.delete("b"),r+=n+e})),n.delete("a",2),n.delete("b",void 0),!t.size&&!Jk||!t.sort||"https://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[Kk]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("https://тест").host||"#%D0%B1"!==new URL("https://a#б").hash||"a1c3"!==r||"x"!==new URL("https://x",void 0).host})),zk=p,qk=L,Xk=S,Qk=h,Zk=$i,$k=Wr,eT=b,tT=$e,nT=J,rT=Object.assign,iT=Object.defineProperty,aT=qk([].concat),oT=!rT||Qk((function(){if(zk&&1!==rT({b:1},rT(iT({},"a",{enumerable:!0,get:function(){iT(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},n=Symbol("assign detection"),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach((function(e){t[e]=e})),7!==rT({},e)[n]||Zk(rT({},t)).join("")!==r}))?function(e,t){for(var n=tT(e),r=arguments.length,i=1,a=$k.f,o=eT.f;r>i;)for(var s,c=nT(arguments[i++]),u=a?aT(Zk(c),a(c)):Zk(c),l=u.length,d=0;l>d;)s=u[d++],zk&&!Xk(o,c,s)||(n[s]=c[s]);return n}:rT,sT=Yt,cT=Rf,uT=p,lT=Wt,dT=N,hT=Ul,fT=S,pT=$e,mT=function(e,t,n,r){try{return r?t(sT(n)[0],n[1]):t(n)}catch(Lj){cT(e,"throw",Lj)}},vT=uf,_T=El,gT=Ar,yT=function(e,t,n){uT?lT.f(e,t,dT(0,n)):e[t]=n},ET=Tf,kT=mf,TT=Array,ST=L,IT=2147483647,bT=/[^\0-\u007E]/,RT=/[.\u3002\uFF0E\uFF61]/g,AT="Overflow: input needs wider integers to process",CT=RangeError,wT=ST(RT.exec),DT=Math.floor,NT=String.fromCharCode,xT=ST("".charCodeAt),OT=ST([].join),PT=ST([].push),MT=ST("".replace),LT=ST("".split),VT=ST("".toLowerCase),UT=function(e){return e+22+75*(e<26)},FT=function(e,t,n){var r=0;for(e=n?DT(e/700):e>>1,e+=DT(e/t);e>455;)e=DT(e/35),r+=36;return DT(r+36*e/(e+38))},BT=function(e){var t=[];e=function(e){for(var t=[],n=0,r=e.length;n<r;){var i=xT(e,n++);if(i>=55296&&i<=56319&&n<r){var a=xT(e,n++);56320==(64512&a)?PT(t,((1023&i)<<10)+(1023&a)+65536):(PT(t,i),n--)}else PT(t,i)}return t}(e);var n,r,i=e.length,a=128,o=0,s=72;for(n=0;n<e.length;n++)(r=e[n])<128&&PT(t,NT(r));var c=t.length,u=c;for(c&&PT(t,"-");u<i;){var l=IT;for(n=0;n<e.length;n++)(r=e[n])>=a&&r<l&&(l=r);var d=u+1;if(l-a>DT((IT-o)/d))throw new CT(AT);for(o+=(l-a)*d,a=l,n=0;n<e.length;n++){if((r=e[n])<a&&++o>IT)throw new CT(AT);if(r===a){for(var h=o,f=36;;){var p=f<=s?1:f>=s+26?26:f-s;if(h<p)break;var m=h-p,v=36-p;PT(t,NT(UT(p+m%v))),h=DT(m/v),f+=36}PT(t,NT(UT(h))),s=FT(o,d,u===c),o=0,u++}}o++,a++}return OT(t,"")},HT=vi,WT=L,jT=Tr,GT=RangeError,JT=String.fromCharCode,KT=String.fromCodePoint,YT=WT([].join);HT({target:"String",stat:!0,arity:1,forced:!!KT&&1!==KT.length},{fromCodePoint:function(e){for(var t,n=[],r=arguments.length,i=0;r>i;){if(t=+arguments[i++],jT(t,1114111)!==t)throw new GT(t+" is not a valid code point");n[i]=t<65536?JT(t):JT(55296+((t-=65536)>>10),t%1024+56320)}return YT(n,"")}});var zT=vi,qT=u,XT=gd,QT=ae,ZT=S,$T=L,eS=p,tS=Yk,nS=hr,rS=Di,iS=ic,aS=to,oS=co,sS=jn,cS=sc,uS=ee,lS=nt,dS=Ul,hS=Ii,fS=Yt,pS=ne,mS=Ai,vS=ka,_S=N,gS=Tf,yS=mf,ES=Fo,kS=Bl,TS=ws,SS=vt("iterator"),IS="URLSearchParams",bS=IS+"Iterator",RS=sS.set,AS=sS.getterFor(IS),CS=sS.getterFor(bS),wS=XT("fetch"),DS=XT("Request"),NS=XT("Headers"),xS=DS&&DS.prototype,OS=NS&&NS.prototype,PS=qT.TypeError,MS=qT.encodeURIComponent,LS=String.fromCharCode,VS=QT("String","fromCodePoint"),US=parseInt,FS=$T("".charAt),BS=$T([].join),HS=$T([].push),WS=$T("".replace),jS=$T([].shift),GS=$T([].splice),JS=$T("".split),KS=$T("".slice),YS=$T(/./.exec),zS=/\+/g,qS=/^[0-9a-f]+$/i,XS=function(e,t){var n=KS(e,t,t+2);return YS(qS,n)?US(n,16):NaN},QS=function(e){for(var t=0,n=128;n>0&&e&n;n>>=1)t++;return t},ZS=function(e){var t=null;switch(e.length){case 1:t=e[0];break;case 2:t=(31&e[0])<<6|63&e[1];break;case 3:t=(15&e[0])<<12|(63&e[1])<<6|63&e[2];break;case 4:t=(7&e[0])<<18|(63&e[1])<<12|(63&e[2])<<6|63&e[3]}return t>1114111?null:t},$S=function(e){for(var t=(e=WS(e,zS," ")).length,n="",r=0;r<t;){var i=FS(e,r);if("%"===i){if("%"===FS(e,r+1)||r+3>t){n+="%",r++;continue}var a=XS(e,r+1);if(a!=a){n+=i,r++;continue}r+=2;var o=QS(a);if(0===o)i=LS(a);else{if(1===o||o>4){n+="�",r++;continue}for(var s=[a],c=1;c<o&&!(3+ ++r>t||"%"!==FS(e,r));){var u=XS(e,r+1);if(u!=u){r+=3;break}if(u>191||u<128)break;HS(s,u),r+=2,c++}if(s.length!==o){n+="�";continue}var l=ZS(s);null===l?n+="�":i=VS(l)}}n+=i,r++}return n},eI=/[!'()~]|%20/g,tI={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},nI=function(e){return tI[e]},rI=function(e){return WS(MS(e),eI,nI)},iI=oS((function(e,t){RS(this,{type:bS,target:AS(e).entries,index:0,kind:t})}),IS,(function(){var e=CS(this),t=e.target,n=e.index++;if(!t||n>=t.length)return e.target=null,ES(void 0,!0);var r=t[n];switch(e.kind){case"keys":return ES(r.key,!1);case"values":return ES(r.value,!1)}return ES([r.key,r.value],!1)}),!0),aI=function(e){this.entries=[],this.url=null,void 0!==e&&(pS(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===FS(e,0)?KS(e,1):e:mS(e)))};aI.prototype={type:IS,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,n,r,i,a,o,s,c=this.entries,u=yS(e);if(u)for(n=(t=gS(e,u)).next;!(r=ZT(n,t)).done;){if(a=(i=gS(fS(r.value))).next,(o=ZT(a,i)).done||(s=ZT(a,i)).done||!ZT(a,i).done)throw new PS("Expected sequence with length 2");HS(c,{key:mS(o.value),value:mS(s.value)})}else for(var l in e)lS(e,l)&&HS(c,{key:l,value:mS(e[l])})},parseQuery:function(e){if(e)for(var t,n,r=this.entries,i=JS(e,"&"),a=0;a<i.length;)(t=i[a++]).length&&(n=JS(t,"="),HS(r,{key:$S(jS(n)),value:$S(BS(n,"="))}))},serialize:function(){for(var e,t=this.entries,n=[],r=0;r<t.length;)e=t[r++],HS(n,rI(e.key)+"="+rI(e.value));return BS(n,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var oI=function(){cS(this,sI);var e=RS(this,new aI(arguments.length>0?arguments[0]:void 0));eS||(this.size=e.entries.length)},sI=oI.prototype;if(iS(sI,{append:function(e,t){var n=AS(this);kS(arguments.length,2),HS(n.entries,{key:mS(e),value:mS(t)}),eS||this.length++,n.updateURL()},delete:function(e){for(var t=AS(this),n=kS(arguments.length,1),r=t.entries,i=mS(e),a=n<2?void 0:arguments[1],o=void 0===a?a:mS(a),s=0;s<r.length;){var c=r[s];if(c.key!==i||void 0!==o&&c.value!==o)s++;else if(GS(r,s,1),void 0!==o)break}eS||(this.size=r.length),t.updateURL()},get:function(e){var t=AS(this).entries;kS(arguments.length,1);for(var n=mS(e),r=0;r<t.length;r++)if(t[r].key===n)return t[r].value;return null},getAll:function(e){var t=AS(this).entries;kS(arguments.length,1);for(var n=mS(e),r=[],i=0;i<t.length;i++)t[i].key===n&&HS(r,t[i].value);return r},has:function(e){for(var t=AS(this).entries,n=kS(arguments.length,1),r=mS(e),i=n<2?void 0:arguments[1],a=void 0===i?i:mS(i),o=0;o<t.length;){var s=t[o++];if(s.key===r&&(void 0===a||s.value===a))return!0}return!1},set:function(e,t){var n=AS(this);kS(arguments.length,1);for(var r,i=n.entries,a=!1,o=mS(e),s=mS(t),c=0;c<i.length;c++)(r=i[c]).key===o&&(a?GS(i,c--,1):(a=!0,r.value=s));a||HS(i,{key:o,value:s}),eS||(this.size=i.length),n.updateURL()},sort:function(){var e=AS(this);TS(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,n=AS(this).entries,r=dS(e,arguments.length>1?arguments[1]:void 0),i=0;i<n.length;)r((t=n[i++]).value,t.key,this)},keys:function(){return new iI(this,"keys")},values:function(){return new iI(this,"values")},entries:function(){return new iI(this,"entries")}},{enumerable:!0}),nS(sI,SS,sI.entries,{name:"entries"}),nS(sI,"toString",(function(){return AS(this).serialize()}),{enumerable:!0}),eS&&rS(sI,"size",{get:function(){return AS(this).entries.length},configurable:!0,enumerable:!0}),aS(oI,IS),zT({global:!0,constructor:!0,forced:!tS},{URLSearchParams:oI}),!tS&&uS(NS)){var cI=$T(OS.has),uI=$T(OS.set),lI=function(e){if(pS(e)){var t,n=e.body;if(hS(n)===IS)return t=e.headers?new NS(e.headers):new NS,cI(t,"content-type")||uI(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),vS(e,{body:_S(0,mS(n)),headers:_S(0,t)})}return e};if(uS(wS)&&zT({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return wS(e,arguments.length>1?lI(arguments[1]):{})}}),uS(DS)){var dI=function(e){return cS(this,xS),new DS(e,arguments.length>1?lI(arguments[1]):{})};xS.constructor=dI,dI.prototype=xS,zT({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:dI})}}var hI,fI=vi,pI=p,mI=Yk,vI=u,_I=Ul,gI=L,yI=hr,EI=Di,kI=sc,TI=nt,SI=oT,II=function(e){var t=pT(e),n=_T(this),r=arguments.length,i=r>1?arguments[1]:void 0,a=void 0!==i;a&&(i=hT(i,r>2?arguments[2]:void 0));var o,s,c,u,l,d,h=kT(t),f=0;if(!h||this===TT&&vT(h))for(o=gT(t),s=n?new this(o):TT(o);o>f;f++)d=a?i(t[f],f):t[f],yT(s,f,d);else for(s=n?new this:[],l=(u=ET(t,h)).next;!(c=fT(l,u)).done;f++)d=a?mT(u,i,[c.value,f],!0):c.value,yT(s,f,d);return s.length=f,s},bI=bs,RI=Vv.codeAt,AI=Ai,CI=to,wI=Bl,DI={URLSearchParams:oI,getState:AS},NI=jn,xI=NI.set,OI=NI.getterFor("URL"),PI=DI.URLSearchParams,MI=DI.getState,LI=vI.URL,VI=vI.TypeError,UI=vI.parseInt,FI=Math.floor,BI=Math.pow,HI=gI("".charAt),WI=gI(/./.exec),jI=gI([].join),GI=gI(1..toString),JI=gI([].pop),KI=gI([].push),YI=gI("".replace),zI=gI([].shift),qI=gI("".split),XI=gI("".slice),QI=gI("".toLowerCase),ZI=gI([].unshift),$I="Invalid scheme",eb="Invalid host",tb="Invalid port",nb=/[a-z]/i,rb=/[\d+-.a-z]/i,ib=/\d/,ab=/^0x/i,ob=/^[0-7]+$/,sb=/^\d+$/,cb=/^[\da-f]+$/i,ub=/[\0\t\n\r #%/:<>?@[\\\]^|]/,lb=/[\0\t\n\r #/:<>?@[\\\]^|]/,db=/^[\u0000-\u0020]+/,hb=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,fb=/[\t\n\r]/g,pb=function(e){var t,n,r,i;if("number"==typeof e){for(t=[],n=0;n<4;n++)ZI(t,e%256),e=FI(e/256);return jI(t,".")}if("object"==T(e)){for(t="",r=function(e){for(var t=null,n=1,r=null,i=0,a=0;a<8;a++)0!==e[a]?(i>n&&(t=r,n=i),r=null,i=0):(null===r&&(r=a),++i);return i>n?r:t}(e),n=0;n<8;n++)i&&0===e[n]||(i&&(i=!1),r===n?(t+=n?":":"::",i=!0):(t+=GI(e[n],16),n<7&&(t+=":")));return"["+t+"]"}return e},mb={},vb=SI({},mb,{" ":1,'"':1,"<":1,">":1,"`":1}),_b=SI({},vb,{"#":1,"?":1,"{":1,"}":1}),gb=SI({},_b,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),yb=function(e,t){var n=RI(e,0);return n>32&&n<127&&!TI(t,e)?e:encodeURIComponent(e)},Eb={ftp:21,file:null,http:80,https:443,ws:80,wss:443},kb=function(e,t){var n;return 2===e.length&&WI(nb,HI(e,0))&&(":"===(n=HI(e,1))||!t&&"|"===n)},Tb=function(e){var t;return e.length>1&&kb(XI(e,0,2))&&(2===e.length||"/"===(t=HI(e,2))||"\\"===t||"?"===t||"#"===t)},Sb=function(e){return"."===e||"%2e"===QI(e)},Ib={},bb={},Rb={},Ab={},Cb={},wb={},Db={},Nb={},xb={},Ob={},Pb={},Mb={},Lb={},Vb={},Ub={},Fb={},Bb={},Hb={},Wb={},jb={},Gb={},Jb=function(e,t,n){var r,i,a,o=AI(e);if(t){if(i=this.parse(o))throw new VI(i);this.searchParams=null}else{if(void 0!==n&&(r=new Jb(n,!0)),i=this.parse(o,null,r))throw new VI(i);(a=MI(new PI)).bindURL(this),this.searchParams=a}};Jb.prototype={type:"URL",parse:function(e,t,n){var r,i,a,o,s,c=this,u=t||Ib,l=0,d="",h=!1,f=!1,p=!1;for(e=AI(e),t||(c.scheme="",c.username="",c.password="",c.host=null,c.port=null,c.path=[],c.query=null,c.fragment=null,c.cannotBeABaseURL=!1,e=YI(e,db,""),e=YI(e,hb,"$1")),e=YI(e,fb,""),r=II(e);l<=r.length;){switch(i=r[l],u){case Ib:if(!i||!WI(nb,i)){if(t)return $I;u=Rb;continue}d+=QI(i),u=bb;break;case bb:if(i&&(WI(rb,i)||"+"===i||"-"===i||"."===i))d+=QI(i);else{if(":"!==i){if(t)return $I;d="",u=Rb,l=0;continue}if(t&&(c.isSpecial()!==TI(Eb,d)||"file"===d&&(c.includesCredentials()||null!==c.port)||"file"===c.scheme&&!c.host))return;if(c.scheme=d,t)return void(c.isSpecial()&&Eb[c.scheme]===c.port&&(c.port=null));d="","file"===c.scheme?u=Vb:c.isSpecial()&&n&&n.scheme===c.scheme?u=Ab:c.isSpecial()?u=Nb:"/"===r[l+1]?(u=Cb,l++):(c.cannotBeABaseURL=!0,KI(c.path,""),u=Wb)}break;case Rb:if(!n||n.cannotBeABaseURL&&"#"!==i)return $I;if(n.cannotBeABaseURL&&"#"===i){c.scheme=n.scheme,c.path=bI(n.path),c.query=n.query,c.fragment="",c.cannotBeABaseURL=!0,u=Gb;break}u="file"===n.scheme?Vb:wb;continue;case Ab:if("/"!==i||"/"!==r[l+1]){u=wb;continue}u=xb,l++;break;case Cb:if("/"===i){u=Ob;break}u=Hb;continue;case wb:if(c.scheme=n.scheme,i===hI)c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,c.path=bI(n.path),c.query=n.query;else if("/"===i||"\\"===i&&c.isSpecial())u=Db;else if("?"===i)c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,c.path=bI(n.path),c.query="",u=jb;else{if("#"!==i){c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,c.path=bI(n.path),c.path.length--,u=Hb;continue}c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,c.path=bI(n.path),c.query=n.query,c.fragment="",u=Gb}break;case Db:if(!c.isSpecial()||"/"!==i&&"\\"!==i){if("/"!==i){c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,u=Hb;continue}u=Ob}else u=xb;break;case Nb:if(u=xb,"/"!==i||"/"!==HI(d,l+1))continue;l++;break;case xb:if("/"!==i&&"\\"!==i){u=Ob;continue}break;case Ob:if("@"===i){h&&(d="%40"+d),h=!0,a=II(d);for(var m=0;m<a.length;m++){var v=a[m];if(":"!==v||p){var _=yb(v,gb);p?c.password+=_:c.username+=_}else p=!0}d=""}else if(i===hI||"/"===i||"?"===i||"#"===i||"\\"===i&&c.isSpecial()){if(h&&""===d)return"Invalid authority";l-=II(d).length+1,d="",u=Pb}else d+=i;break;case Pb:case Mb:if(t&&"file"===c.scheme){u=Fb;continue}if(":"!==i||f){if(i===hI||"/"===i||"?"===i||"#"===i||"\\"===i&&c.isSpecial()){if(c.isSpecial()&&""===d)return eb;if(t&&""===d&&(c.includesCredentials()||null!==c.port))return;if(o=c.parseHost(d))return o;if(d="",u=Bb,t)return;continue}"["===i?f=!0:"]"===i&&(f=!1),d+=i}else{if(""===d)return eb;if(o=c.parseHost(d))return o;if(d="",u=Lb,t===Mb)return}break;case Lb:if(!WI(ib,i)){if(i===hI||"/"===i||"?"===i||"#"===i||"\\"===i&&c.isSpecial()||t){if(""!==d){var g=UI(d,10);if(g>65535)return tb;c.port=c.isSpecial()&&g===Eb[c.scheme]?null:g,d=""}if(t)return;u=Bb;continue}return tb}d+=i;break;case Vb:if(c.scheme="file","/"===i||"\\"===i)u=Ub;else{if(!n||"file"!==n.scheme){u=Hb;continue}switch(i){case hI:c.host=n.host,c.path=bI(n.path),c.query=n.query;break;case"?":c.host=n.host,c.path=bI(n.path),c.query="",u=jb;break;case"#":c.host=n.host,c.path=bI(n.path),c.query=n.query,c.fragment="",u=Gb;break;default:Tb(jI(bI(r,l),""))||(c.host=n.host,c.path=bI(n.path),c.shortenPath()),u=Hb;continue}}break;case Ub:if("/"===i||"\\"===i){u=Fb;break}n&&"file"===n.scheme&&!Tb(jI(bI(r,l),""))&&(kb(n.path[0],!0)?KI(c.path,n.path[0]):c.host=n.host),u=Hb;continue;case Fb:if(i===hI||"/"===i||"\\"===i||"?"===i||"#"===i){if(!t&&kb(d))u=Hb;else if(""===d){if(c.host="",t)return;u=Bb}else{if(o=c.parseHost(d))return o;if("localhost"===c.host&&(c.host=""),t)return;d="",u=Bb}continue}d+=i;break;case Bb:if(c.isSpecial()){if(u=Hb,"/"!==i&&"\\"!==i)continue}else if(t||"?"!==i)if(t||"#"!==i){if(i!==hI&&(u=Hb,"/"!==i))continue}else c.fragment="",u=Gb;else c.query="",u=jb;break;case Hb:if(i===hI||"/"===i||"\\"===i&&c.isSpecial()||!t&&("?"===i||"#"===i)){if(".."===(s=QI(s=d))||"%2e."===s||".%2e"===s||"%2e%2e"===s?(c.shortenPath(),"/"===i||"\\"===i&&c.isSpecial()||KI(c.path,"")):Sb(d)?"/"===i||"\\"===i&&c.isSpecial()||KI(c.path,""):("file"===c.scheme&&!c.path.length&&kb(d)&&(c.host&&(c.host=""),d=HI(d,0)+":"),KI(c.path,d)),d="","file"===c.scheme&&(i===hI||"?"===i||"#"===i))for(;c.path.length>1&&""===c.path[0];)zI(c.path);"?"===i?(c.query="",u=jb):"#"===i&&(c.fragment="",u=Gb)}else d+=yb(i,_b);break;case Wb:"?"===i?(c.query="",u=jb):"#"===i?(c.fragment="",u=Gb):i!==hI&&(c.path[0]+=yb(i,mb));break;case jb:t||"#"!==i?i!==hI&&("'"===i&&c.isSpecial()?c.query+="%27":c.query+="#"===i?"%23":yb(i,mb)):(c.fragment="",u=Gb);break;case Gb:i!==hI&&(c.fragment+=yb(i,vb))}l++}},parseHost:function(e){var t,n,r;if("["===HI(e,0)){if("]"!==HI(e,e.length-1))return eb;if(t=function(e){var t,n,r,i,a,o,s,c=[0,0,0,0,0,0,0,0],u=0,l=null,d=0,h=function(){return HI(e,d)};if(":"===h()){if(":"!==HI(e,1))return;d+=2,l=++u}for(;h();){if(8===u)return;if(":"!==h()){for(t=n=0;n<4&&WI(cb,h());)t=16*t+UI(h(),16),d++,n++;if("."===h()){if(0===n)return;if(d-=n,u>6)return;for(r=0;h();){if(i=null,r>0){if(!("."===h()&&r<4))return;d++}if(!WI(ib,h()))return;for(;WI(ib,h());){if(a=UI(h(),10),null===i)i=a;else{if(0===i)return;i=10*i+a}if(i>255)return;d++}c[u]=256*c[u]+i,2!=++r&&4!==r||u++}if(4!==r)return;break}if(":"===h()){if(d++,!h())return}else if(h())return;c[u++]=t}else{if(null!==l)return;d++,l=++u}}if(null!==l)for(o=u-l,u=7;0!==u&&o>0;)s=c[u],c[u--]=c[l+o-1],c[l+--o]=s;else if(8!==u)return;return c}(XI(e,1,-1)),!t)return eb;this.host=t}else if(this.isSpecial()){if(e=function(e){var t,n,r=[],i=LT(MT(VT(e),RT,"."),".");for(t=0;t<i.length;t++)n=i[t],PT(r,wT(bT,n)?"xn--"+BT(n):n);return OT(r,".")}(e),WI(ub,e))return eb;if(t=function(e){var t,n,r,i,a,o,s,c=qI(e,".");if(c.length&&""===c[c.length-1]&&c.length--,(t=c.length)>4)return e;for(n=[],r=0;r<t;r++){if(""===(i=c[r]))return e;if(a=10,i.length>1&&"0"===HI(i,0)&&(a=WI(ab,i)?16:8,i=XI(i,8===a?1:2)),""===i)o=0;else{if(!WI(10===a?sb:8===a?ob:cb,i))return e;o=UI(i,a)}KI(n,o)}for(r=0;r<t;r++)if(o=n[r],r===t-1){if(o>=BI(256,5-t))return null}else if(o>255)return null;for(s=JI(n),r=0;r<n.length;r++)s+=n[r]*BI(256,3-r);return s}(e),null===t)return eb;this.host=t}else{if(WI(lb,e))return eb;for(t="",n=II(e),r=0;r<n.length;r++)t+=yb(n[r],mb);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||"file"===this.scheme},includesCredentials:function(){return""!==this.username||""!==this.password},isSpecial:function(){return TI(Eb,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"===this.scheme&&1===t&&kb(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,n=e.username,r=e.password,i=e.host,a=e.port,o=e.path,s=e.query,c=e.fragment,u=t+":";return null!==i?(u+="//",e.includesCredentials()&&(u+=n+(r?":"+r:"")+"@"),u+=pb(i),null!==a&&(u+=":"+a)):"file"===t&&(u+="//"),u+=e.cannotBeABaseURL?o[0]:o.length?"/"+jI(o,"/"):"",null!==s&&(u+="?"+s),null!==c&&(u+="#"+c),u},setHref:function(e){var t=this.parse(e);if(t)throw new VI(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"===e)try{return new Kb(e.path[0]).origin}catch(Lj){return"null"}return"file"!==e&&this.isSpecial()?e+"://"+pb(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(AI(e)+":",Ib)},getUsername:function(){return this.username},setUsername:function(e){var t=II(AI(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var n=0;n<t.length;n++)this.username+=yb(t[n],gb)}},getPassword:function(){return this.password},setPassword:function(e){var t=II(AI(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var n=0;n<t.length;n++)this.password+=yb(t[n],gb)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?pb(e):pb(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,Pb)},getHostname:function(){var e=this.host;return null===e?"":pb(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,Mb)},getPort:function(){var e=this.port;return null===e?"":AI(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""===(e=AI(e))?this.port=null:this.parse(e,Lb))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+jI(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,Bb))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""===(e=AI(e))?this.query=null:("?"===HI(e,0)&&(e=XI(e,1)),this.query="",this.parse(e,jb)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!==(e=AI(e))?("#"===HI(e,0)&&(e=XI(e,1)),this.fragment="",this.parse(e,Gb)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var Kb=function(e){var t=kI(this,Yb),n=wI(arguments.length,1)>1?arguments[1]:void 0,r=xI(t,new Jb(e,!1,n));pI||(t.href=r.serialize(),t.origin=r.getOrigin(),t.protocol=r.getProtocol(),t.username=r.getUsername(),t.password=r.getPassword(),t.host=r.getHost(),t.hostname=r.getHostname(),t.port=r.getPort(),t.pathname=r.getPathname(),t.search=r.getSearch(),t.searchParams=r.getSearchParams(),t.hash=r.getHash())},Yb=Kb.prototype,zb=function(e,t){return{get:function(){return OI(this)[e]()},set:t&&function(e){return OI(this)[t](e)},configurable:!0,enumerable:!0}};if(pI&&(EI(Yb,"href",zb("serialize","setHref")),EI(Yb,"origin",zb("getOrigin")),EI(Yb,"protocol",zb("getProtocol","setProtocol")),EI(Yb,"username",zb("getUsername","setUsername")),EI(Yb,"password",zb("getPassword","setPassword")),EI(Yb,"host",zb("getHost","setHost")),EI(Yb,"hostname",zb("getHostname","setHostname")),EI(Yb,"port",zb("getPort","setPort")),EI(Yb,"pathname",zb("getPathname","setPathname")),EI(Yb,"search",zb("getSearch","setSearch")),EI(Yb,"searchParams",zb("getSearchParams")),EI(Yb,"hash",zb("getHash","setHash"))),yI(Yb,"toJSON",(function(){return OI(this).serialize()}),{enumerable:!0}),yI(Yb,"toString",(function(){return OI(this).serialize()}),{enumerable:!0}),LI){var qb=LI.createObjectURL,Xb=LI.revokeObjectURL;qb&&yI(Kb,"createObjectURL",_I(qb,LI)),Xb&&yI(Kb,"revokeObjectURL",_I(Xb,LI))}CI(Kb,"URL"),fI({global:!0,constructor:!0,forced:!mI,sham:!pI},{URL:Kb});var Qb=S;vi({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return Qb(URL.prototype.toString,this)}});var Zb=!0,$b=!0;function eR(e,t,n){var r=e.match(t);return r&&r.length>=n&&parseInt(r[n],10)}function tR(e,t,n){if(e.RTCPeerConnection){var r=e.RTCPeerConnection.prototype,i=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return i.apply(this,arguments);var a=function(e){var t=n(e);t&&(r.handleEvent?r.handleEvent(t):r(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(r,a),i.apply(this,[e,a])};var a=r.removeEventListener;r.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t])return a.apply(this,arguments);if(!this._eventMap[t].has(n))return a.apply(this,arguments);var r=this._eventMap[t].get(n);return this._eventMap[t].delete(n),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,a.apply(this,[e,r])},Object.defineProperty(r,"on"+t,{get:function(){return this["_on"+t]},set:function(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 nR(e){return"boolean"!=typeof e?new Error("Argument type: "+T(e)+". Please use a boolean."):(Zb=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function rR(e){return"boolean"!=typeof e?new Error("Argument type: "+T(e)+". Please use a boolean."):($b=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function iR(){if("object"==("undefined"==typeof window?"undefined":T(window))){if(Zb)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function aR(e,t){$b&&console.warn(e+" is deprecated, please use "+t+" instead.")}function oR(e){return"[object Object]"===Object.prototype.toString.call(e)}function sR(e){return oR(e)?Object.keys(e).reduce((function(t,n){var r=oR(e[n]),i=r?sR(e[n]):e[n],a=r&&!Object.keys(i).length;return void 0===i||a?t:Object.assign(t,c({},n,i))}),{}):e}function cR(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach((function(r){r.endsWith("Id")?cR(e,e.get(t[r]),n):r.endsWith("Ids")&&t[r].forEach((function(t){cR(e,e.get(t),n)}))})))}function uR(e,t,n){var r=n?"outbound-rtp":"inbound-rtp",i=new Map;if(null===t)return i;var a=[];return e.forEach((function(e){"track"===e.type&&e.trackIdentifier===t.id&&a.push(e)})),a.forEach((function(t){e.forEach((function(n){n.type===r&&n.trackId===t.id&&cR(e,n,i)}))})),i}var lR=iR;function dR(e,t){var n=e&&e.navigator;if(n.mediaDevices){var r=function(e){if("object"!=T(e)||e.mandatory||e.optional)return e;var t={};return Object.keys(e).forEach((function(n){if("require"!==n&&"advanced"!==n&&"mediaSource"!==n){var r="object"==T(e[n])?e[n]:{ideal:e[n]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);var i=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==r.ideal){t.optional=t.optional||[];var a={};"number"==typeof r.ideal?(a[i("min",n)]=r.ideal,t.optional.push(a),(a={})[i("max",n)]=r.ideal,t.optional.push(a)):(a[i("",n)]=r.ideal,t.optional.push(a))}void 0!==r.exact&&"number"!=typeof r.exact?(t.mandatory=t.mandatory||{},t.mandatory[i("",n)]=r.exact):["min","max"].forEach((function(e){void 0!==r[e]&&(t.mandatory=t.mandatory||{},t.mandatory[i(e,n)]=r[e])}))}})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},i=function(e,i){if(t.version>=61)return i(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==T(e.audio)){var a=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])};a((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),a(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=r(e.audio)}if(e&&"object"==T(e.video)){var o=e.video.facingMode;o=o&&("object"==T(o)?o:{ideal:o});var s,c=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!n.mediaDevices.getSupportedConstraints||!n.mediaDevices.getSupportedConstraints().facingMode||c)&&(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?s=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(s=["front"]),s))return n.mediaDevices.enumerateDevices().then((function(t){t=t.filter((function(e){return"videoinput"===e.kind}));var n=t.find((function(e){return s.some((function(t){return e.label.toLowerCase().includes(t)}))}));return!n&&t.length&&s.includes("back")&&(n=t[t.length-1]),n&&(e.video.deviceId=o.exact?{exact:n.deviceId}:{ideal:n.deviceId}),e.video=r(e.video),lR("chrome: "+JSON.stringify(e)),i(e)}));e.video=r(e.video)}return lR("chrome: "+JSON.stringify(e)),i(e)},a=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:function(){return this.name+(this.message&&": ")+this.message}}};if(n.getUserMedia=function(e,t,r){i(e,(function(e){n.webkitGetUserMedia(e,t,(function(e){r&&r(a(e))}))}))}.bind(n),n.mediaDevices.getUserMedia){var o=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(e){return i(e,(function(e){return o(e).then((function(t){if(e.audio&&!t.getAudioTracks().length||e.video&&!t.getVideoTracks().length)throw t.getTracks().forEach((function(e){e.stop()})),new DOMException("","NotFoundError");return t}),(function(e){return Promise.reject(a(e))}))}))}}}}function hR(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function fR(e){if("object"==T(e)&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});var t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){var n=this;return this._ontrackpoly||(this._ontrackpoly=function(t){t.stream.addEventListener("addtrack",(function(r){var i;i=e.RTCPeerConnection.prototype.getReceivers?n.getReceivers().find((function(e){return e.track&&e.track.id===r.track.id})):{track:r.track};var a=new Event("track");a.track=r.track,a.receiver=i,a.transceiver={receiver:i},a.streams=[t.stream],n.dispatchEvent(a)})),t.stream.getTracks().forEach((function(r){var i;i=e.RTCPeerConnection.prototype.getReceivers?n.getReceivers().find((function(e){return e.track&&e.track.id===r.id})):{track:r};var a=new Event("track");a.track=r,a.receiver=i,a.transceiver={receiver:i},a.streams=[t.stream],n.dispatchEvent(a)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else tR(e,"track",(function(e){return e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e}))}function pR(e){if("object"==T(e)&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){var 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()};var n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){var i=n.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i};var r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){r.apply(this,arguments);var t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}var i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){var n=this;this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((function(e){n._senders.push(t(n,e))}))};var a=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){var t=this;this._senders=this._senders||[],a.apply(this,[e]),e.getTracks().forEach((function(e){var n=t._senders.find((function(t){return t.track===e}));n&&t._senders.splice(t._senders.indexOf(n),1)}))}}else if("object"==T(e)&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){var o=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){var e=this,t=o.apply(this,[]);return t.forEach((function(t){return t._pc=e})),t},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get:function(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function mR(e){if(e.RTCPeerConnection){var t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){var e=this,n=Array.prototype.slice.call(arguments),r=n[0],i=n[1],a=n[2];if(arguments.length>0&&"function"==typeof r)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof r))return t.apply(this,[]);var o=function(e){var t={};return e.result().forEach((function(e){var n={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((function(t){n[t]=e.stat(t)})),t[n.id]=n})),t},s=function(e){return new Map(Object.keys(e).map((function(t){return[t,e[t]]})))};return arguments.length>=2?t.apply(this,[function(e){i(s(o(e)))},r]):new Promise((function(n,r){t.apply(e,[function(e){n(s(o(e)))},r])})).then(i,a)}}}function vR(e){if("object"==T(e)&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver){if(!("getStats"in e.RTCRtpSender.prototype)){var t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){var e=this,n=t.apply(this,[]);return n.forEach((function(t){return t._pc=e})),n});var n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){var e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){var e=this;return this._pc.getStats().then((function(t){return uR(t,e.track,!0)}))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){var r=e.RTCPeerConnection.prototype.getReceivers;r&&(e.RTCPeerConnection.prototype.getReceivers=function(){var e=this,t=r.apply(this,[]);return t.forEach((function(t){return t._pc=e})),t}),tR(e,"track",(function(e){return e.receiver._pc=e.srcElement,e})),e.RTCRtpReceiver.prototype.getStats=function(){var e=this;return this._pc.getStats().then((function(t){return uR(t,e.track,!1)}))}}if("getStats"in e.RTCRtpSender.prototype&&"getStats"in e.RTCRtpReceiver.prototype){var i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){var t,n,r,a=arguments[0];return this.getSenders().forEach((function(e){e.track===a&&(t?r=!0:t=e)})),this.getReceivers().forEach((function(e){return e.track===a&&(n?r=!0:n=e),e.track===a})),r||t&&n?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():n?n.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return i.apply(this,arguments)}}}}function _R(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){var e=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((function(t){return e._shimmedLocalStreams[t][0]}))};var t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var r=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?-1===this._shimmedLocalStreams[n.id].indexOf(r)&&this._shimmedLocalStreams[n.id].push(r):this._shimmedLocalStreams[n.id]=[n,r],r};var n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){var t=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((function(e){if(t.getSenders().find((function(t){return t.track===e})))throw new DOMException("Track already exists.","InvalidAccessError")}));var r=this.getSenders();n.apply(this,arguments);var i=this.getSenders().filter((function(e){return-1===r.indexOf(e)}));this._shimmedLocalStreams[e.id]=[e].concat(i)};var r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],r.apply(this,arguments)};var i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){var t=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((function(n){var r=t._shimmedLocalStreams[n].indexOf(e);-1!==r&&t._shimmedLocalStreams[n].splice(r,1),1===t._shimmedLocalStreams[n].length&&delete t._shimmedLocalStreams[n]})),i.apply(this,arguments)}}function gR(e,t){if(e.RTCPeerConnection){if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return _R(e);var n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){var e=this,t=n.apply(this);return this._reverseStreams=this._reverseStreams||{},t.map((function(t){return e._reverseStreams[t.id]}))};var r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){var n=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((function(e){if(n.getSenders().find((function(t){return t.track===e})))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){var i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}r.apply(this,[t])};var i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.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,n){var r=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find((function(e){return e===t})))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find((function(e){return e.track===t})))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var a=this._streams[n.id];if(a)a.addTrack(t),Promise.resolve().then((function(){r.dispatchEvent(new Event("negotiationneeded"))}));else{var o=new e.MediaStream([t]);this._streams[n.id]=o,this._reverseStreams[o.id]=n,this.addStream(o)}return this.getSenders().find((function(e){return e.track===t}))},["createOffer","createAnswer"].forEach((function(t){var n=e.RTCPeerConnection.prototype[t],r=c({},t,(function(){var e=this,t=arguments;return arguments.length&&"function"==typeof arguments[0]?n.apply(this,[function(n){var r=s(e,n);t[0].apply(null,[r])},function(e){t[1]&&t[1].apply(null,e)},arguments[2]]):n.apply(this,arguments).then((function(t){return s(e,t)}))}));e.RTCPeerConnection.prototype[t]=r[t]}));var a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){var n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((function(t){var r=e._reverseStreams[t],i=e._streams[r.id];n=n.replace(new RegExp(r.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:n})}(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};var o=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get:function(){var e=o.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){var t,n=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(e._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{},Object.keys(this._streams).forEach((function(r){n._streams[r].getTracks().find((function(t){return e.track===t}))&&(t=n._streams[r])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function s(e,t){var n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((function(t){var r=e._reverseStreams[t],i=e._streams[r.id];n=n.replace(new RegExp(i.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:n})}}function yR(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){var n=e.RTCPeerConnection.prototype[t],r=c({},t,(function(){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}));e.RTCPeerConnection.prototype[t]=r[t]}))}function ER(e,t){tR(e,"negotiationneeded",(function(e){var n=e.target;if(!(t.version<72||n.getConfiguration&&"plan-b"===n.getConfiguration().sdpSemantics)||"stable"===n.signalingState)return e}))}var kR=Object.freeze({__proto__:null,shimMediaStream:hR,shimOnTrack:fR,shimGetSendersWithDtmf:pR,shimGetStats:mR,shimSenderReceiverGetStats:vR,shimAddTrackRemoveTrackWithNative:_R,shimAddTrackRemoveTrack:gR,shimPeerConnection:yR,fixNegotiationNeeded:ER,shimGetUserMedia:dR,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(n){return t(n).then((function(t){var r=n.video&&n.video.width,i=n.video&&n.video.height,a=n.video&&n.video.frameRate;return n.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:a||3}},r&&(n.video.mandatory.maxWidth=r),i&&(n.video.mandatory.maxHeight=i),e.navigator.mediaDevices.getUserMedia(n)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function TR(e,t){var n=e&&e.navigator,r=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,r){aR("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),n.mediaDevices.getUserMedia(e).then(t,r)},!(t.version>55&&"autoGainControl"in n.mediaDevices.getSupportedConstraints())){var i=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},a=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(e){return"object"==T(e)&&"object"==T(e.audio)&&(e=JSON.parse(JSON.stringify(e)),i(e.audio,"autoGainControl","mozAutoGainControl"),i(e.audio,"noiseSuppression","mozNoiseSuppression")),a(e)},r&&r.prototype.getSettings){var o=r.prototype.getSettings;r.prototype.getSettings=function(){var e=o.apply(this,arguments);return i(e,"mozAutoGainControl","autoGainControl"),i(e,"mozNoiseSuppression","noiseSuppression"),e}}if(r&&r.prototype.applyConstraints){var s=r.prototype.applyConstraints;r.prototype.applyConstraints=function(e){return"audio"===this.kind&&"object"==T(e)&&(e=JSON.parse(JSON.stringify(e)),i(e,"autoGainControl","mozAutoGainControl"),i(e,"noiseSuppression","mozNoiseSuppression")),s.apply(this,[e])}}}}function SR(e){"object"==T(e)&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function IR(e,t){if("object"==T(e)&&(e.RTCPeerConnection||e.mozRTCPeerConnection)){!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){var n=e.RTCPeerConnection.prototype[t],r=c({},t,(function(){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}));e.RTCPeerConnection.prototype[t]=r[t]}));var n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){var e=Array.prototype.slice.call(arguments),i=e[0],a=e[1],o=e[2];return r.apply(this,[i||null]).then((function(e){if(t.version<53&&!a)try{e.forEach((function(e){e.type=n[e.type]||e.type}))}catch(qA){if("TypeError"!==qA.name)throw qA;e.forEach((function(t,r){e.set(r,Object.assign({},t,{type:n[t.type]||t.type}))}))}return e})).then(a,o)}}}function bR(e){if("object"==T(e)&&e.RTCPeerConnection&&e.RTCRtpSender&&(!e.RTCRtpSender||!("getStats"in e.RTCRtpSender.prototype))){var t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){var e=this,n=t.apply(this,[]);return n.forEach((function(t){return t._pc=e})),n});var n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){var e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}}function RR(e){if("object"==T(e)&&e.RTCPeerConnection&&e.RTCRtpSender&&(!e.RTCRtpSender||!("getStats"in e.RTCRtpReceiver.prototype))){var t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){var e=this,n=t.apply(this,[]);return n.forEach((function(t){return t._pc=e})),n}),tR(e,"track",(function(e){return e.receiver._pc=e.srcElement,e})),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}}function AR(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){var t=this;aR("removeStream","removeTrack"),this.getSenders().forEach((function(n){n.track&&e.getTracks().includes(n.track)&&t.removeTrack(n)}))})}function CR(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function wR(e){if("object"==T(e)&&e.RTCPeerConnection){var t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]);var n=(e=E(e)).length>0;n&&e.forEach((function(e){if("rid"in e&&!/^[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")}));var r=t.apply(this,arguments);if(n){var i=r.sender,a=i.getParameters();(!("encodings"in a)||1===a.encodings.length&&0===Object.keys(a.encodings[0]).length)&&(a.encodings=e,i.sendEncodings=e,this.setParametersPromises.push(i.setParameters(a).then((function(){delete i.sendEncodings})).catch((function(){delete i.sendEncodings}))))}return r})}}function DR(e){if("object"==T(e)&&e.RTCRtpSender){var t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){var e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}}function NR(e){if("object"==T(e)&&e.RTCPeerConnection){var t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){var e=arguments,n=this;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((function(){return t.apply(n,e)})).finally((function(){n.setParametersPromises=[]})):t.apply(this,arguments)}}}function xR(e){if("object"==T(e)&&e.RTCPeerConnection){var t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){var e=arguments,n=this;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((function(){return t.apply(n,e)})).finally((function(){n.setParametersPromises=[]})):t.apply(this,arguments)}}}var OR=Object.freeze({__proto__:null,shimOnTrack:SR,shimPeerConnection:IR,shimSenderGetStats:bR,shimReceiverGetStats:RR,shimRemoveStream:AR,shimRTCDataChannel:CR,shimAddTransceiver:wR,shimGetParameters:DR,shimCreateOffer:NR,shimCreateAnswer:xR,shimGetUserMedia:TR,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!n||!n.video){var r=new DOMException("getDisplayMedia without video constraints is undefined");return r.name="NotFoundError",r.code=8,Promise.reject(r)}return!0===n.video?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)})}});function PR(e){if("object"==T(e)&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){var t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){var n=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((function(r){return t.call(n,r,e)})),e.getVideoTracks().forEach((function(r){return t.call(n,r,e)}))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var n=this,r=arguments.length,i=new Array(r>1?r-1:0),a=1;a<r;a++)i[a-1]=arguments[a];return i&&i.forEach((function(e){n._localStreams?n._localStreams.includes(e)||n._localStreams.push(e):n._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){var t=this;this._localStreams||(this._localStreams=[]);var n=this._localStreams.indexOf(e);if(-1!==n){this._localStreams.splice(n,1);var r=e.getTracks();this.getSenders().forEach((function(e){r.includes(e.track)&&t.removeTrack(e)}))}})}}function MR(e){if("object"==T(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:function(){return this._onaddstream},set:function(e){var t=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach((function(e){if(t._remoteStreams||(t._remoteStreams=[]),!t._remoteStreams.includes(e)){t._remoteStreams.push(e);var n=new Event("addstream");n.stream=e,t.dispatchEvent(n)}}))})}});var t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){var e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((function(t){if(e._remoteStreams||(e._remoteStreams=[]),!(e._remoteStreams.indexOf(t)>=0)){e._remoteStreams.push(t);var n=new Event("addstream");n.stream=t,e.dispatchEvent(n)}}))}),t.apply(e,arguments)}}}function LR(e){if("object"==T(e)&&e.RTCPeerConnection){var t=e.RTCPeerConnection.prototype,n=t.createOffer,r=t.createAnswer,i=t.setLocalDescription,a=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){var r=arguments.length>=2?arguments[2]:arguments[0],i=n.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){var n=arguments.length>=2?arguments[2]:arguments[0],i=r.apply(this,[n]);return t?(i.then(e,t),Promise.resolve()):i};var s=function(e,t,n){var r=i.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r};t.setLocalDescription=s,s=function(e,t,n){var r=a.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r},t.setRemoteDescription=s,s=function(e,t,n){var r=o.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r},t.addIceCandidate=s}}function VR(e){var t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){var n=t.mediaDevices,r=n.getUserMedia.bind(n);t.mediaDevices.getUserMedia=function(e){return r(UR(e))}}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,r){t.mediaDevices.getUserMedia(e).then(n,r)}.bind(t))}function UR(e){return e&&void 0!==e.video?Object.assign({},e,{video:sR(e.video)}):e}function FR(e){if(e.RTCPeerConnection){var t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,n){if(e&&e.iceServers){for(var r=[],i=0;i<e.iceServers.length;i++){var a=e.iceServers[i];void 0===a.urls&&a.url?(aR("RTCIceServer.url","RTCIceServer.urls"),(a=JSON.parse(JSON.stringify(a))).urls=a.url,delete a.url,r.push(a)):r.push(e.iceServers[i])}e.iceServers=r}return new t(e,n)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:function(){return t.generateCertificate}})}}function BR(e){"object"==T(e)&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function HR(e){var t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);var n=this.getTransceivers().find((function(e){return"audio"===e.receiver.track.kind}));!1===e.offerToReceiveAudio&&n?"sendrecv"===n.direction?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":"recvonly"===n.direction&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):!0!==e.offerToReceiveAudio||n||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);var r=this.getTransceivers().find((function(e){return"video"===e.receiver.track.kind}));!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function WR(e){"object"!=T(e)||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var jR=Object.freeze({__proto__:null,shimLocalStreamsAPI:PR,shimRemoteStreamsAPI:MR,shimCallbacksAPI:LR,shimGetUserMedia:VR,shimConstraints:UR,shimRTCIceServerUrls:FR,shimTrackEventTransceiver:BR,shimCreateOfferLegacy:HR,shimAudioContext:WR}),GR={exports:{}};!function(e){var t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((function(e){return e.trim()}))},t.splitSections=function(e){return e.split("\nm=").map((function(e,t){return(t>0?"m="+e:e).trim()+"\r\n"}))},t.getDescription=function(e){var n=t.splitSections(e);return n&&n[0]},t.getMediaSections=function(e){var n=t.splitSections(e);return n.shift(),n},t.matchPrefix=function(e,n){return t.splitLines(e).filter((function(e){return 0===e.indexOf(n)}))},t.parseCandidate=function(e){for(var t,n={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" "))[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]},r=8;r<t.length;r+=2)switch(t[r]){case"raddr":n.relatedAddress=t[r+1];break;case"rport":n.relatedPort=parseInt(t[r+1],10);break;case"tcptype":n.tcpType=t[r+1];break;case"ufrag":n.ufrag=t[r+1],n.usernameFragment=t[r+1];break;default:void 0===n[t[r]]&&(n[t[r]]=t[r+1])}return n},t.writeCandidate=function(e){var t=[];t.push(e.foundation);var n=e.component;"rtp"===n?t.push(1):"rtcp"===n?t.push(2):t.push(n),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);var r=e.type;return t.push("typ"),t.push(r),"host"!==r&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){var t=e.substring(9).split(" "),n={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),n.name=t[0],n.clockRate=parseInt(t[1],10),n.channels=3===t.length?parseInt(t[2],10):1,n.numChannels=n.channels,n},t.writeRtpMap=function(e){var t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);var n=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==n?"/"+n:"")+"\r\n"},t.parseExtmap=function(e){var t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){for(var t,n={},r=e.substring(e.indexOf(" ")+1).split(";"),i=0;i<r.length;i++)n[(t=r[i].trim().split("="))[0].trim()]=t[1];return n},t.writeFmtp=function(e){var t="",n=e.payloadType;if(void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){var r=[];Object.keys(e.parameters).forEach((function(t){void 0!==e.parameters[t]?r.push(t+"="+e.parameters[t]):r.push(t)})),t+="a=fmtp:"+n+" "+r.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){var t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){var t="",n=e.payloadType;return void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((function(e){t+="a=rtcp-fb:"+n+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){var t=e.indexOf(" "),n={ssrc:parseInt(e.substring(7,t),10)},r=e.indexOf(":",t);return r>-1?(n.attribute=e.substring(t+1,r),n.value=e.substring(r+1)):n.attribute=e.substring(t+1),n},t.parseSsrcGroup=function(e){var t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((function(e){return parseInt(e,10)}))}},t.getMid=function(e){var n=t.matchPrefix(e,"a=mid:")[0];if(n)return n.substring(6)},t.parseFingerprint=function(e){var t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,n){return{role:"auto",fingerprints:t.matchPrefix(e+n,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){var n="a=setup:"+t+"\r\n";return e.fingerprints.forEach((function(e){n+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),n},t.parseCryptoLine=function(e){var t=e.substring(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"==T(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;var t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},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,n){return t.matchPrefix(e+n,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,n){var r=t.matchPrefix(e+n,"a=ice-ufrag:")[0],i=t.matchPrefix(e+n,"a=ice-pwd:")[0];return r&&i?{usernameFragment:r.substring(12),password:i.substring(10)}:null},t.writeIceParameters=function(e){var 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){var n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=t.splitLines(e)[0].split(" ");n.profile=r[2];for(var i=3;i<r.length;i++){var a=r[i],o=t.matchPrefix(e,"a=rtpmap:"+a+" ")[0];if(o){var s=t.parseRtpMap(o),c=t.matchPrefix(e,"a=fmtp:"+a+" ");switch(s.parameters=c.length?t.parseFmtp(c[0]):{},s.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+a+" ").map(t.parseRtcpFb),n.codecs.push(s),s.name.toUpperCase()){case"RED":case"ULPFEC":n.fecMechanisms.push(s.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((function(e){n.headerExtensions.push(t.parseExtmap(e))}));var u=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return n.codecs.forEach((function(e){u.forEach((function(t){e.rtcpFeedback.find((function(e){return e.type===t.type&&e.parameter===t.parameter}))||e.rtcpFeedback.push(t)}))})),n},t.writeRtpDescription=function(e,n){var r="";r+="m="+e+" ",r+=n.codecs.length>0?"9":"0",r+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=n.codecs.map((function(e){return void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType})).join(" ")+"\r\n",r+="c=IN IP4 0.0.0.0\r\n",r+="a=rtcp:9 IN IP4 0.0.0.0\r\n",n.codecs.forEach((function(e){r+=t.writeRtpMap(e),r+=t.writeFmtp(e),r+=t.writeRtcpFb(e)}));var i=0;return n.codecs.forEach((function(e){e.maxptime>i&&(i=e.maxptime)})),i>0&&(r+="a=maxptime:"+i+"\r\n"),n.headerExtensions&&n.headerExtensions.forEach((function(e){r+=t.writeExtmap(e)})),r},t.parseRtpEncodingParameters=function(e){var n,r=[],i=t.parseRtpParameters(e),a=-1!==i.fecMechanisms.indexOf("RED"),o=-1!==i.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute})),c=s.length>0&&s[0].ssrc,u=t.matchPrefix(e,"a=ssrc-group:FID").map((function(e){return e.substring(17).split(" ").map((function(e){return parseInt(e,10)}))}));u.length>0&&u[0].length>1&&u[0][0]===c&&(n=u[0][1]),i.codecs.forEach((function(e){if("RTX"===e.name.toUpperCase()&&e.parameters.apt){var t={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&n&&(t.rtx={ssrc:n}),r.push(t),a&&((t=JSON.parse(JSON.stringify(t))).fec={ssrc:c,mechanism:o?"red+ulpfec":"red"},r.push(t))}})),0===r.length&&c&&r.push({ssrc:c});var l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,r.forEach((function(e){e.maxBitrate=l}))),r},t.parseRtcpParameters=function(e){var n={},r=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute}))[0];r&&(n.cname=r.value,n.ssrc=r.ssrc);var i=t.matchPrefix(e,"a=rtcp-rsize");n.reducedSize=i.length>0,n.compound=0===i.length;var a=t.matchPrefix(e,"a=rtcp-mux");return n.mux=a.length>0,n},t.writeRtcpParameters=function(e){var 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){var n,r=t.matchPrefix(e,"a=msid:");if(1===r.length)return{stream:(n=r[0].substring(7).split(" "))[0],track:n[1]};var i=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"msid"===e.attribute}));return i.length>0?{stream:(n=i[0].value.split(" "))[0],track:n[1]}:void 0},t.parseSctpDescription=function(e){var n,r=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");i.length>0&&(n=parseInt(i[0].substring(19),10)),isNaN(n)&&(n=65536);var a=t.matchPrefix(e,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:r.fmt,maxMessageSize:n};var o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){var s=o[0].substring(10).split(" ");return{port:parseInt(s[0],10),protocol:s[1],maxMessageSize:n}}},t.writeSctpDescription=function(e,t){var n=[];return n="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&&n.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),n.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,n,r){var i=void 0!==n?n:2;return"v=0\r\no="+(r||"thisisadapterortc")+" "+(e||t.generateSessionId())+" "+i+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,n){for(var r=t.splitLines(e),i=0;i<r.length;i++)switch(r[i]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[i].substring(2)}return n?t.getDirection(n):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){var n=t.splitLines(e)[0].substring(2).split(" ");return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(" ")}},t.parseOLine=function(e){var n=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;for(var n=t.splitLines(e),r=0;r<n.length;r++)if(n[r].length<2||"="!==n[r].charAt(1))return!1;return!0},e.exports=t}(GR);var JR=GR.exports,KR=function(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}(JR),YR=function(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(n){if("default"!==n&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}}))})),Object.freeze(e)}({__proto__:null,default:KR},[JR]);function zR(e){if(!(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)){var t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==T(e)&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){var n=new t(e),r=KR.parseCandidate(e.candidate);for(var i in r)i in n||Object.defineProperty(n,i,{value:r[i]});return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,tR(e,"icecandidate",(function(t){return t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t}))}}function qR(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||tR(e,"icecandidate",(function(e){if(e.candidate){var t=KR.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function XR(e,t){if(e.RTCPeerConnection){"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get:function(){return void 0===this._sctp?null:this._sctp}});var n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76&&"plan-b"===this.getConfiguration().sdpSemantics&&Object.defineProperty(this,"sctp",{get:function(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0}),function(e){if(!e||!e.sdp)return!1;var t=KR.splitSections(e.sdp);return t.shift(),t.some((function(e){var t=KR.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))}(arguments[0])){var e,r=function(e){var t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;var n=parseInt(t[1],10);return n!=n?-1:n}(arguments[0]),i=function(e){var n=65536;return"firefox"===t.browser&&(n=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),n}(r),a=function(e,n){var r=65536;"firefox"===t.browser&&57===t.version&&(r=65535);var i=KR.matchPrefix(e.sdp,"a=max-message-size:");return i.length>0?r=parseInt(i[0].substring(19),10):"firefox"===t.browser&&-1!==n&&(r=2147483637),r}(arguments[0],r);e=0===i&&0===a?Number.POSITIVE_INFINITY:0===i||0===a?Math.max(i,a):Math.min(i,a);var o={};Object.defineProperty(o,"maxMessageSize",{get:function(){return e}}),this._sctp=o}return n.apply(this,arguments)}}}function QR(e){if(e.RTCPeerConnection&&"createDataChannel"in e.RTCPeerConnection.prototype){var t=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){var e=t.apply(this,arguments);return n(e,this),e},tR(e,"datachannel",(function(e){return n(e.channel,e.target),e}))}function n(e,t){var n=e.send;e.send=function(){var r=arguments[0],i=r.length||r.size||r.byteLength;if("open"===e.readyState&&t.sctp&&i>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return n.apply(e,arguments)}}}function ZR(e){if(e.RTCPeerConnection&&!("connectionState"in e.RTCPeerConnection.prototype)){var t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(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((function(e){var n=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(e){var t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;var n=new Event("connectionstatechange",e);t.dispatchEvent(n)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}}))}}function $R(e,t){if(e.RTCPeerConnection&&!("chrome"===t.browser&&t.version>=71||"safari"===t.browser&&t.version>=605)){var n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){var r=t.sdp.split("\n").filter((function(e){return"a=extmap-allow-mixed"!==e.trim()})).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:r}):t.sdp=r}return n.apply(this,arguments)}}}function eA(e,t){if(e.RTCPeerConnection&&e.RTCPeerConnection.prototype){var n=e.RTCPeerConnection.prototype.addIceCandidate;n&&0!==n.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?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}}function tA(e,t){if(e.RTCPeerConnection&&e.RTCPeerConnection.prototype){var n=e.RTCPeerConnection.prototype.setLocalDescription;n&&0!==n.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){var e=this,t=arguments[0]||{};if("object"!=T(t)||t.type&&t.sdp)return n.apply(this,arguments);if(!(t={type:t.type,sdp:t.sdp}).type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":t.type="offer";break;default:t.type="answer"}return t.sdp||"offer"!==t.type&&"answer"!==t.type?n.apply(this,[t]):("offer"===t.type?this.createOffer:this.createAnswer).apply(this).then((function(t){return n.apply(e,[t])}))})}}var nA=Object.freeze({__proto__:null,shimRTCIceCandidate:zR,shimRTCIceCandidateRelayProtocol:qR,shimMaxMessageSize:XR,shimSendThrowTypeError:QR,shimConnectionState:ZR,removeExtmapAllowMixed:$R,shimAddIceCandidateNullOrEmpty:eA,shimParameterlessSetLocalDescription:tA});!function(){var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).window,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},n=iR,r=function(e){var t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;var n=e.navigator;if(n.mozGetUserMedia)t.browser="firefox",t.version=eR(n.userAgent,/Firefox\/(\d+)\./,1);else if(n.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=eR(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!n.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=eR(n.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),i={browserDetails:r,commonShim:nA,extractVersion:eR,disableLog:nR,disableWarnings:rR,sdp:YR};switch(r.browser){case"chrome":if(!kR||!yR||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),i;if(null===r.version)return n("Chrome shim can not determine version, not shimming."),i;n("adapter.js shimming chrome."),i.browserShim=kR,eA(e,r),tA(e),dR(e,r),hR(e),yR(e,r),fR(e),gR(e,r),pR(e),mR(e),vR(e),ER(e,r),zR(e),qR(e),ZR(e),XR(e,r),QR(e),$R(e,r);break;case"firefox":if(!OR||!IR||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),i;n("adapter.js shimming firefox."),i.browserShim=OR,eA(e,r),tA(e),TR(e,r),IR(e,r),SR(e),AR(e),bR(e),RR(e),CR(e),wR(e),DR(e),NR(e),xR(e),zR(e),ZR(e),XR(e,r),QR(e);break;case"safari":if(!jR||!t.shimSafari)return n("Safari shim is not included in this adapter release."),i;n("adapter.js shimming safari."),i.browserShim=jR,eA(e,r),tA(e),FR(e),HR(e),LR(e),PR(e),MR(e),BR(e),VR(e),WR(e),zR(e),qR(e),XR(e,r),QR(e),$R(e,r);break;default:n("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});var rA,iA=Object.create,aA=Object.defineProperty,oA=Object.defineProperties,sA=Object.getOwnPropertyDescriptor,cA=Object.getOwnPropertyDescriptors,uA=Object.getOwnPropertyNames,lA=Object.getOwnPropertySymbols,dA=Object.getPrototypeOf,hA=Object.prototype.hasOwnProperty,fA=Object.prototype.propertyIsEnumerable,pA=Reflect.get,mA=Math.pow,vA=function(e,t,n){return t in e?aA(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n},_A=function(e,t){for(var n in t||(t={}))hA.call(t,n)&&vA(e,n,t[n]);if(lA){var r,i=s(lA(t));try{for(i.s();!(r=i.n()).done;)n=r.value,fA.call(t,n)&&vA(e,n,t[n])}catch(a){i.e(a)}finally{i.f()}}return e},gA=function(e,t){return oA(e,cA(t))},yA=function(e,t){return function(){return t||e((t={exports:{}}).exports,t),t.exports}},EA=function(e,t){for(var n in t)aA(e,n,{get:t[n],enumerable:!0})},kA=function(e,t,n){return n=null!=e?iA(dA(e)):{},function(e,t,n,r){if(t&&"object"==T(t)||"function"==typeof t){var i,a=s(uA(t));try{var o=function(){var n=i.value;!hA.call(e,n)&&void 0!==n&&aA(e,n,{get:function(){return t[n]},enumerable:!(r=sA(t,n))||r.enumerable})};for(a.s();!(i=a.n()).done;)o()}catch(c){a.e(c)}finally{a.f()}}return e}(!t&&e&&e.__esModule?n:aA(n,"default",{value:e,enumerable:!0}),e)},TA=function(e,t,n,r){for(var i,a=r>1?void 0:r?sA(t,n):t,o=e.length-1;o>=0;o--)(i=e[o])&&(a=(r?i(t,n,a):i(a))||a);return r&&a&&aA(t,n,a),a},SA=function(e,t,n){return vA(e,"symbol"!=T(t)?t+"":t,n)},IA=function(e,t,n){return pA(dA(e),n,t)},bA=function(e,t,n){return new Promise((function(r,i){var a=function(e){try{s(n.next(e))}catch(Gx){i(Gx)}},o=function(e){try{s(n.throw(e))}catch(Gx){i(Gx)}},s=function(e){return e.done?r(e.value):Promise.resolve(e.value).then(a,o)};s((n=n.apply(e,t)).next())}))},RA=yA((function(e,t){var n=Object.prototype.hasOwnProperty,r="~";function i(){}function a(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(e,t,n,i,o){if("function"!=typeof n)throw new TypeError("The listener must be a function");var s=new a(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],s]:e._events[c].push(s):(e._events[c]=s,e._eventsCount++),e}function s(e,t){0==--e._eventsCount?e._events=new i:delete e._events[t]}function c(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(r=!1)),c.prototype.eventNames=function(){var e,t,i=[];if(0===this._eventsCount)return i;for(t in e=this._events)n.call(e,t)&&i.push(r?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},c.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,o=new Array(a);i<a;i++)o[i]=n[i].fn;return o},c.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},c.prototype.emit=function(e,t,n,i,a,o){var s=r?r+e:e;if(!this._events[s])return!1;var c,u,l=this._events[s],d=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),d){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,n),!0;case 4:return l.fn.call(l.context,t,n,i),!0;case 5:return l.fn.call(l.context,t,n,i,a),!0;case 6:return l.fn.call(l.context,t,n,i,a,o),!0}for(u=1,c=new Array(d-1);u<d;u++)c[u-1]=arguments[u];l.fn.apply(l.context,c)}else{var h,f=l.length;for(u=0;u<f;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),d){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,n);break;case 4:l[u].fn.call(l[u].context,t,n,i);break;default:if(!c)for(h=1,c=new Array(d-1);h<d;h++)c[h-1]=arguments[h];l[u].fn.apply(l[u].context,c)}}return!0},c.prototype.on=function(e,t,n){return o(this,e,t,n,!1)},c.prototype.once=function(e,t,n){return o(this,e,t,n,!0)},c.prototype.removeListener=function(e,t,n,i){var a=r?r+e:e;if(!this._events[a])return this;if(!t)return s(this,a),this;var o=this._events[a];if(o.fn)o.fn===t&&(!i||o.once)&&(!n||o.context===n)&&s(this,a);else{for(var c=0,u=[],l=o.length;c<l;c++)(o[c].fn!==t||i&&!o[c].once||n&&o[c].context!==n)&&u.push(o[c]);u.length?this._events[a]=1===u.length?u[0]:u:s(this,a)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new i,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=r,c.EventEmitter=c,void 0!==t&&(t.exports=c)})),AA=yA((function(e,t){var n=t.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),(t+=null!=e["network-id"]?" network-id %d":"%v")+(null!=e["network-cost"]?" network-cost %d":"%v")}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",(t+=null!=e.rateNumerator?" rate=%s":"")+(null!=e.rateDenominator?"/%s":"")}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(n).forEach((function(e){n[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))})),CA=yA((function(e){var t=function(e){return String(Number(e))===e?Number(e):e},n=function(e,n,r){var i=e.name&&e.names;e.push&&!n[e.push]?n[e.push]=[]:i&&!n[e.name]&&(n[e.name]={});var a=e.push?{}:i?n[e.name]:n;(function(e,n,r,i){if(i&&!r)n[i]=t(e[1]);else for(var a=0;a<r.length;a+=1)null!=e[a+1]&&(n[r[a]]=t(e[a+1]))})(r.match(e.reg),a,e.names,e.name),e.push&&n[e.push].push(a)},r=AA(),i=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},a=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(i).forEach((function(e){var t=e[0],i=e.slice(2);"m"===t&&(a.push({rtp:[],fmtp:[]}),o=a[a.length-1]);for(var s=0;s<(r[t]||[]).length;s+=1){var c=r[t][s];if(c.reg.test(i))return n(c,o,i)}})),t.media=a,t};var a=function(e,n){var r=n.split(/=(.+)/,2);return 2===r.length?e[r[0]]=t(r[1]):1===r.length&&n.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(a,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var n=[],r=e.split(" ").map(t),i=0;i<r.length;i+=3)n.push({component:r[i],ip:r[i+1],port:r[i+2]});return n},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(a,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var n,r=!1;return"~"!==e[0]?n=t(e):(n=t(e.substring(1,e.length)),r=!0),{scid:n,paused:r}}))}))}})),wA=yA((function(e,t){var n=AA(),r=/%[sdv%]/g,i=function(e){var t=1,n=arguments,i=n.length;return e.replace(r,(function(e){if(t>=i)return e;var r=n[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},a=function(e,t,n){var r=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var a=0;a<t.names.length;a+=1){var o=t.names[a];t.name?r.push(n[t.name][o]):r.push(n[t.names[a]])}else r.push(n[t.name]);return i.apply(null,r)},o=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||o,i=t.innerOrder||s,c=[];return r.forEach((function(t){n[t].forEach((function(n){n.name in e&&null!=e[n.name]?c.push(a(t,n,e)):n.push in e&&null!=e[n.push]&&e[n.push].forEach((function(e){c.push(a(t,n,e))}))}))})),e.media.forEach((function(e){c.push(a("m",n.m[0],e)),i.forEach((function(t){n[t].forEach((function(n){n.name in e&&null!=e[n.name]?c.push(a(t,n,e)):n.push in e&&null!=e[n.push]&&e[n.push].forEach((function(e){c.push(a(t,n,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),DA=yA((function(e){var t=CA(),n=wA(),r=AA();e.grammar=r,e.write=n,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),NA=yA((function(e,t){var n=t.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return null!=e.address?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return null!=e.subtype?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),(t+=null!=e["network-id"]?" network-id %d":"%v")+(null!=e["network-cost"]?" network-cost %d":"%v")}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return null!=e.maxMessageSize?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",(t+=null!=e.rateNumerator?" rate=%s":"")+(null!=e.rateDenominator?"/%s":"")}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(n).forEach((function(e){n[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))})),xA=yA((function(e){var t=function(e){return String(Number(e))===e?Number(e):e},n=function(e,n,r){var i=e.name&&e.names;e.push&&!n[e.push]?n[e.push]=[]:i&&!n[e.name]&&(n[e.name]={});var a=e.push?{}:i?n[e.name]:n;(function(e,n,r,i){if(i&&!r)n[i]=t(e[1]);else for(var a=0;a<r.length;a+=1)null!=e[a+1]&&(n[r[a]]=t(e[a+1]))})(r.match(e.reg),a,e.names,e.name),e.push&&n[e.push].push(a)},r=NA(),i=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},a=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(i).forEach((function(e){var t=e[0],i=e.slice(2);"m"===t&&(a.push({rtp:[],fmtp:[]}),o=a[a.length-1]);for(var s=0;s<(r[t]||[]).length;s+=1){var c=r[t][s];if(c.reg.test(i))return n(c,o,i)}})),t.media=a,t};var a=function(e,n){var r=n.split(/=(.+)/,2);return 2===r.length?e[r[0]]=t(r[1]):1===r.length&&n.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(a,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var n=[],r=e.split(" ").map(t),i=0;i<r.length;i+=3)n.push({component:r[i],ip:r[i+1],port:r[i+2]});return n},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(a,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var n,r=!1;return"~"!==e[0]?n=t(e):(n=t(e.substring(1,e.length)),r=!0),{scid:n,paused:r}}))}))}})),OA=yA((function(e,t){var n=NA(),r=/%[sdv%]/g,i=function(e){var t=1,n=arguments,i=n.length;return e.replace(r,(function(e){if(t>=i)return e;var r=n[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},a=function(e,t,n){var r=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var a=0;a<t.names.length;a+=1){var o=t.names[a];t.name?r.push(n[t.name][o]):r.push(n[t.names[a]])}else r.push(n[t.name]);return i.apply(null,r)},o=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||o,i=t.innerOrder||s,c=[];return r.forEach((function(t){n[t].forEach((function(n){n.name in e&&null!=e[n.name]?c.push(a(t,n,e)):n.push in e&&null!=e[n.push]&&e[n.push].forEach((function(e){c.push(a(t,n,e))}))}))})),e.media.forEach((function(e){c.push(a("m",n.m[0],e)),i.forEach((function(t){n[t].forEach((function(n){n.name in e&&null!=e[n.name]?c.push(a(t,n,e)):n.push in e&&null!=e[n.push]&&e[n.push].forEach((function(e){c.push(a(t,n,e))}))}))}))})),c.join("\r\n")+"\r\n"}})),PA=yA((function(e){var t=xA(),n=OA();e.write=n,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList})),MA=kA(RA()),LA=((rA=LA||{})[rA.INVALID_PARAMETER=4096]="INVALID_PARAMETER",rA[rA.INVALID_OPERATION=4097]="INVALID_OPERATION",rA[rA.NOT_SUPPORTED=4098]="NOT_SUPPORTED",rA[rA.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",rA[rA.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",rA[rA.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",rA[rA.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",rA[rA.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",rA[rA.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",rA[rA.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",rA[rA.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",rA[rA.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",rA[rA.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",rA[rA.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",rA[rA.CLIENT_BANNED=16448]="CLIENT_BANNED",rA[rA.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",rA[rA.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",rA[rA.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",rA[rA.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",rA[rA.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",rA[rA.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",rA[rA.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",rA[rA.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",rA[rA.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",rA[rA.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",rA[rA.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",rA[rA.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",rA[rA.API_CALL_ABORTED=16461]="API_CALL_ABORTED",rA[rA.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",rA[rA.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",rA[rA.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",rA[rA.UNKNOWN=65535]="UNKNOWN",rA),VA=LA,UA=function(e){function i(e){var a;r(this,i);var o=e.name,s=void 0===o?"RtcError":o,c=e.message,u=e.code,l=void 0===u?VA.UNKNOWN:u,d=e.extraCode,h=void 0===d?0:d,f=e.constraint,p="<".concat(function(e){for(var t in VA)if(VA[t]===e)return t;return"UNKNOWN"}(l)," 0x").concat(l.toString(16),">"),m="".concat(c).concat(f?" constraint: ".concat(f):"").concat(null!=c&&c.includes(p)?"":" ".concat(p));return a=n(this,i,[m]),SA(t(a),"code"),SA(t(a),"extraCode"),SA(t(a),"message"),SA(t(a),"originMessage"),SA(t(a),"name"),SA(t(a),"constraint"),a.code=l,a.extraCode=h,a.name=s,a.message=m,a.constraint=f,a.originMessage=c,a}return d(i,e),o(i,[{key:"getCode",value:function(){return this.code}},{key:"getExtraCode",value:function(){return this.extraCode}},{key:"toString",value:function(){return this.originMessage}}])}(I(Error)),FA=UA,BA=((new Date).getTime(),0),HA=function(){return(new Date).getTime()+BA},WA=function(){var e=new Date;return e.setTime(HA()),e.toLocaleString()},jA=function(e){var t=String(e.getMilliseconds());return"padStart"in String.prototype&&(t=t.toString().padStart(3,"0")),"".concat(e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(t)},GA={};EA(GA,{bytes2ms:function(){return Mw},calculateScaleResolutionDownNumber:function(){return wD},convertObjectNumberToInt:function(){return ID},copyProperties:function(){return Pw},deepClone:function(){return pD},deepMerge:function(){return fD},delay:function(){return bD},fibonacci:function(){return Ww},formatedTime:function(){return _D},getConstructorName:function(){return nD},getContainerFromElement:function(){return vD},getEnv:function(){return Rw},getInternalVersion:function(){return sD},getLoggerUrl:function(){return Cw},getMediaStreamTrackInfo:function(){return CD},getMuteStateFromFlag:function(){return lD},getNetworkType:function(){return Dw},getNumNetworkType:function(){return Ow},getReconnectionTimeout:function(){return jw},getStringByteLength:function(){return ED},getTurnServer:function(){return dD},getUint32Version:function(){return SD},getValueType:function(){return Gw},getViewListFromView:function(){return mD},glog:function(){return Fw},ipv4ToUint32:function(){return hD},isArray:function(){return Qw},isAudioWorkletSupported:function(){return rD},isBoolean:function(){return qw},isConstructor:function(){return tD},isEmpty:function(){return uD},isFunction:function(){return Jw},isLangChinese:function(){return Bw},isMediaStreamTrack:function(){return Zw},isNumber:function(){return zw},isObject:function(){return Xw},isOverseaSdkAppId:function(){return Aw},isPlainObject:function(){return Hw},isPortrait:function(){return kD},isPromise:function(){return eD},isRemoteTrack:function(){return $w},isRotate90Or270:function(){return DD},isString:function(){return Yw},isUndefined:function(){return Kw},loadImage:function(){return TD},ms2bytes:function(){return Vw},ms2samples:function(){return Uw},normalizeUrl:function(){return AD},performanceNow:function(){return aD},promiseAny:function(){return iD},samples2ms:function(){return Lw},setNetworkType:function(){return xw},stringify:function(){return gD},stringifyIncludeValue:function(){return yD},throttlePromise:function(){return RD}});var JA={};EA(JA,{AUDIO_MUTE_BIT:function(){return xC},AUDIO_STAT_BIT:function(){return NC},AUX_STAT_BIT:function(){return DC},AUX_STREAM_MSID:function(){return VC},BACKEND_ENV:function(){return RC},BASE_DOC_URL:function(){return oC},BASE_HOST:function(){return nC},CAPABILITIES_KEYS:function(){return Iw},CLASS_NAME:function(){return mw},CLOUD_CONSOLE_URL:function(){return aC},CROSS_ROOM_BIT:function(){return MC},DATA_FREEZE_TIMING:function(){return cw},DEFAULT_ASSETS_URL:function(){return sC},DOC_URL:function(){return cC},DTLS_STATE_UNKNOWN:function(){return YC},ENV_NAME:function(){return fC},EXCHANGE_SDP_TIMEOUT:function(){return rw},IS_WORKER:function(){return QA},IS_WORKLET:function(){return ZA},KIBANA_EVENT:function(){return ew},LOCAL_STREAM_PUBLISH_STATE:function(){return sw},LOGGER_CMD_TYPE:function(){return hC},LOGGER_DOMAIN:function(){return uC},LOGGER_DOMAIN_OVERSEA:function(){return lC},LOG_LEVEL:function(){return pC},LOG_LEVEL_NAME:function(){return Ew},MAIN_STREAM_MSID:function(){return LC},MAX_RTT:function(){return bw},MICROPHONE_COMMUNICATIONS:function(){return yw},MICROPHONE_DEFAULT:function(){return _w},MUTE_ALL_BIT:function(){return PC},NAME:function(){return IC},NETWORK_TYPE:function(){return _C},NOT_SUPPORTED_H264:function(){return ow},PAUSED_RETRY_COUNT:function(){return vw},PEERCONNECTION_CONNECTING_TIMEOUT:function(){return hw},PEER_CONNECTION_STATE:function(){return zC},PEER_LEAVE_REASON:function(){return kw},RECOVER_CAPTURE_INTERVAL:function(){return Sw},REMOTE_STREAM_TYPE_AUX:function(){return FC},REMOTE_STREAM_TYPE_MAIN:function(){return UC},RENDER_FREEZE_TIMING:function(){return uw},SCHEDULE_DOMAIN:function(){return fw},SCHEDULE_TIMEOUT:function(){return pw},SDP_SEMANTICS_PLAN_B:function(){return aw},SDP_SEMANTICS_UNIFIED_PLAN:function(){return iw},SECOND_HOST:function(){return rC},SIGNAL_PING_PONG_INTERVAL:function(){return vC},SIGNAL_PING_TIMEOUT:function(){return mC},SIGNAL_RECONNECTION_COUNT:function(){return $C},SMALL_STAT_BIT:function(){return wC},SPEAKER_DEFAULT:function(){return gw},STORAGE_EXPIRES_TIME:function(){return gC},STREAM_TYPE_BIG:function(){return lw},STREAM_TYPE_SMALL:function(){return dw},SUBSCRIBE_SMALL_RETRY_COUNT:function(){return Tw},SYNC_USER_LIST_INTERVAL:function(){return tw},Scene:function(){return AC},THIRD_HOST:function(){return iC},TRANSPORT_DIRECTION:function(){return bC},TRTC_ERROR_ASSISTANCE:function(){return dC},TRTC_QUALITY_BAD:function(){return GC},TRTC_QUALITY_DISCONNECTED:function(){return KC},TRTC_QUALITY_EXCELLENT:function(){return HC},TRTC_QUALITY_GOOD:function(){return WC},TRTC_QUALITY_POOR:function(){return jC},TRTC_QUALITY_UNKNOWN:function(){return BC},TRTC_QUALITY_VERY_BAD:function(){return JC},UPDATE_OFFER_TIMEOUT:function(){return nw},VIDEO_MUTE_BIT:function(){return OC},VIDEO_STAT_BIT:function(){return CC},audioProfileMap:function(){return yC},defaultBigVideoProfile:function(){return kC},defaultSmallVideoProfile:function(){return TC},getRetryCount:function(){return QC},getScriptDir:function(){return $A},innerVersion:function(){return KA},loggerProxy:function(){return eC},screenProfileMap:function(){return SC},setLoggerProxy:function(){return tC},setRetryCount:function(){return XC},setVersion:function(){return zA},version:function(){return YA},videoProfileMap:function(){return EC}});var KA="4.15.00.1600",YA="5.0.0";function zA(e){YA=e;var t=v(e.split(".").map((function(e){return parseInt(e,10)})),3),n=t[0],r=t[1],i=t[2];KA="".concat(n,".").concat(Math.min(15,r),".").concat(Math.min(15,i),".").concat(r.toString().padStart(2,"0")).concat(i.toString().padStart(2,"0"))}var qA,XA,QA="undefined"!=typeof importScripts,ZA="undefined"!=typeof registerProcessor,$A=function(){var e=QA?self.location.href:document.currentScript.src;return e.substring(0,e.lastIndexOf("/")+1)},eC="",tC=function(e){return eC=e},nC="web.sdk.qcloud.com",rC="web.sdk.tencent.cn",iC="web.sdk.cloud.tencent.cn",aC="https://console.cloud.tencent.com/trtc",oC="https://".concat(nC,"/trtc/webrtc/v5/doc"),sC="https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/",cC="".concat(oC,"/zh-cn/"),uC="https://yun.tim.qq.com",lC="https://apisgp.my-imcloud.com",dC="trtc_error_assistance",hC={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},fC={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},pC=((XA=pC||{})[XA.TRACE=0]="TRACE",XA[XA.DEBUG=1]="DEBUG",XA[XA.INFO=2]="INFO",XA[XA.WARN=3]="WARN",XA[XA.ERROR=4]="ERROR",XA[XA.NONE=5]="NONE",XA),mC=18e3,vC=2e3,_C={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},gC=6048e5,yC={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:128},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},EC={"120p":{width:160,height:120,frameRate:15,bitrate:200},"120p_2":{width:160,height:120,frameRate:15,bitrate:100},"180p":{width:320,height:180,frameRate:15,bitrate:350},"180p_2":{width:320,height:180,frameRate:15,bitrate:150},"240p":{width:320,height:240,frameRate:15,bitrate:400},"240p_2":{width:320,height:240,frameRate:15,bitrate:200},"360p":{width:640,height:360,frameRate:15,bitrate:800},"360p_2":{width:640,height:360,frameRate:15,bitrate:400},"480p":{width:640,height:480,frameRate:15,bitrate:900},"480p_2":{width:640,height:480,frameRate:15,bitrate:500},"720p":{width:1280,height:720,frameRate:15,bitrate:1500},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4860},"4K":{width:3840,height:2160,frameRate:30,bitrate:9e3}},kC=EC["480p_2"],TC=EC["120p_2"],SC={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},IC={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"},bC={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},RC={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},AC=((qA=AC||{}).LIVE="live",qA.RTC="rtc",qA),CC=1,wC=2,DC=4,NC=8,xC=64,OC=16,PC=112,MC=128,LC="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",VC="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",UC=IC.MAIN,FC=IC.AUXILIARY,BC=0,HC=1,WC=2,jC=3,GC=4,JC=5,KC=6,YC="unknown",zC={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},qC=1/0;function XC(e){qC=e}function QC(){return qC}var ZC,$C=30,ew={JOIN:"join",DELTA_JOIN:"delta-join",REJOIN:"rejoin",LEAVE:"leave",DELTA_LEAVE:"delta-leave",PUBLISH:"publish",DELTA_PUBLISH:"delta-publish",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",UPLINK_CONNECTION:"uplink-connection",UPLINK_RECONNECTION:"uplink-reconnection",DOWNLINK_CONNECTION:"downlink-connection",DOWNLINK_RECONNECTION:"downlink-reconnection",ON_TRACK:"ontrack",ICE_CONNECTION_STATE:"iceConnectionState",LOCAL_STREAM_INITIALIZE:"stream-initialize",SIGNAL_CONNECTION:"websocketConnectionState",SIGNAL_RECONNECTION:"websocketReconnectionState",UPDATE_STREAM:"update-stream",RECOVER_LOCAL_AUDIO_TRACK:"recover-local-audio-track",RECOVER_LOCAL_VIDEO_TRACK:"recover-local-video-track",RECOVER_SUBSCRIPTION:"recover-subscription",START_MIX_TRANSCODE:"start-mix-transcode",STOP_MIX_TRANSCODE:"stop-mix-transcode",PLAYER_ERROR:"player-error",SCHEDULE:"schedule",LOAD_WORKLET:"load-worklet",VIDEO_FROZEN_COUNT:"videoFrozenCount",GET_USER_MEDIA_RETRY:"getUserMedia-retry"},tw=1e4,nw=1e4,rw=1e4,iw="unified-plan",aw="plan-b",ow=1028,sw=((ZC=sw||{})[ZC.UNPUBLISH=-1]="UNPUBLISH",ZC[ZC.PUBLISHING=0]="PUBLISHING",ZC[ZC.PUBLISHED=1]="PUBLISHED",ZC),cw=500,uw=1e3,lw=IC.BIG,dw=IC.SMALL,hw=1e4,fw={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},pw=2e3,mw={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},vw=5,_w="default",gw=_w,yw="communications",Ew=Object.keys(pC),kw=["normal leave","timeout leave","kick","role change"],Tw=10,Sw=2e3,Iw=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],bw=1e4,Rw=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Aw=function(e){return Number(e)<14e8},Cw=function(e,t){var n;n=eC||(Aw(e)?lC:uC);var r=Math.floor(Math.random()*mA(2,31));return"".concat(n,"/v5/AVQualityReportSvc/C2S?random=").concat(r,"&sdkappid=").concat(e,"&cmdtype=").concat(t)},ww="unknown";function Dw(){if("unknown"!==ww)return ww;var e=navigator,t=e.userAgent,n=e.connection,r=(t.match(/NetType\/\S+/)||[])[0]||"";"3gnet"===(r=r.toLowerCase().replace("nettype/",""))&&(r="3g");var i=n&&n.type&&n.type.toLowerCase(),a=n&&n.effectiveType&&n.effectiveType.toLowerCase();return"slow-2"===a&&(a="2g"),i&&(ww=Nw(i,a)),ww}function Nw(e,t){if(_C[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function xw(e){ww=Nw(e)}function Ow(){return _C[Dw()]}function Pw(e,t){var n,r=s(Reflect.ownKeys(t));try{for(r.s();!(n=r.n()).done;){var i=n.value;if("constructor"!==i&&"prototype"!==i&&"name"!==i){var a=Object.getOwnPropertyDescriptor(t,i)||"";Object.defineProperty(e,i,a)}}}catch(o){r.e(o)}finally{r.f()}return e}function Mw(e){return Lw(e/4,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function Lw(e){return 1e3*e/(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function Vw(e){return 4*Uw(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)}function Uw(e){return e*(arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3)/1e3}var Fw="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:function(){},Bw=function(){var e=navigator.language;return"zh"===(e=e.substring(0,2))},Hw=function(e){if(!e||"object"!=T(e)||"[object Object]"!=Object.prototype.toString.call(e))return!1;var t=Object.getPrototypeOf(e);if(null===t)return!0;var n=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&Function.prototype.toString.call(n)===Function.prototype.toString.call(Object)};function Ww(e){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return e<=1?t:Ww(e-1,t,(arguments.length>1&&void 0!==arguments[1]?arguments[1]:1)+t)}function jw(e){return e>8?3e4:1e3*Ww(e)}function Gw(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var Jw=function(e){return"function"==typeof e},Kw=function(e){return void 0===e},Yw=function(e){return"string"==typeof e},zw=function(e){return"number"==typeof e},qw=function(e){return"boolean"==typeof e},Xw=function(e){return"object"===Gw(e)},Qw=function(e){return"array"===Gw(e)},Zw=function(e){return Gw(e)==="MediaStreamTrack".toLowerCase()},$w=function(e){return e.isRemote},eD=function(e){return"promise"===Gw(e)},tD=function(e){return Jw(e)&&e.prototype.constructor===e},nD=function(e){return tD(e)?e.prototype.constructor.name:""},rD="undefined"!=typeof AudioWorkletNode;function iD(e){return new Promise((function(t,n){var r=[];e.forEach((function(i){i.then(t).catch((function(t){r.push(t),r.length===e.length&&n(r)}))}))}))}function aD(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var oD=function(e){return+e<10?"0".concat(e):e},sD=function(e){var t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;var n=t.split("."),r=oD(n[1])+oD(n[2]);return n[1]-15>0&&(n[1]="15"),n[2]-15>0&&(n[2]="15"),"".concat(n.join("."),".").concat(r)},cD=Object.prototype.hasOwnProperty;function uD(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e||"function"==typeof e||Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(Hw(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return 0===e.size;case"[object Object]":for(var t in e)if(cD.call(e,t))return!1;return!0}return!1}function lD(e,t){return{userId:t,hasAudio:!!(e&NC),hasVideo:!!(e&CC),hasAuxiliary:!!(e&DC),hasSmall:!!(e&wC),audioMuted:!!(e&xC),videoMuted:!!(e&OC),audioAvailable:!(!(e&NC)||e&xC),videoAvailable:!(!(e&CC)||e&OC)}}function dD(e){var t={urls:e.url.startsWith("turn:")||e.url.startsWith("turns:")?e.url:"turn:".concat(e.url)};return!Kw(e.username)&&!Kw(e.credential)&&(t.username=e.username,t.credential=e.credential,t.credentialType="password",Kw(e.credentialType)||(t.credentialType=e.credentialType)),t}function hD(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!Yw(e))return 0;var n=e.split(".");return t?(Number(n[0])<<24|Number(n[1])<<16|Number(n[2])<<8|Number(n[3]))>>>0:(Number(n[3])<<24|Number(n[2])<<16|Number(n[1])<<8|Number(n[0]))>>>0}var fD=function(e,t,n,r){if(!Xw(e)||!Xw(t))return 0;for(var i,a=0,o=Object.keys(t),s=0,c=o.length;s<c;s++)if(i=o[s],!(Kw(t[i])||n&&n.includes(i)))if(Xw(e[i])&&Xw(t[i]))a+=fD(e[i],t[i],n,r);else{if(r&&r.includes(t[i]))continue;e[i]!==t[i]&&(e[i]=pD(t[i]),a+=1)}return a};function pD(e){if(Qw(e)){var t=[];return e.forEach((function(e,n){t[n]=pD(e)})),t}if(Xw(e)){var n={};return Object.keys(e).forEach((function(t){n[t]=pD(e[t])})),n}return e}var mD=function(e){var t=[];if(Qw(e))t=E(e);else if(Yw(e)){var n=document.getElementById(e);n&&t.push(n)}else e&&t.push(e);return t},vD=function(e){return Yw(e)?document.getElementById(e):e},_D=function(){return function(e){var t=function(e){return e<10?"0".concat(e):"".concat(e)},n=e.getFullYear(),r=e.getMonth()+1,i=e.getDate(),a=t(e.getHours()),o=t(e.getMinutes()),s=t(e.getSeconds());return"".concat(n,"/").concat(r,"/").concat(i," ").concat(a,":").concat(o,":").concat(s)}(new Date)};function gD(e,t){var n=t.keysToInclude,r=t.keysToExclude;try{if(Qw(e))return"[".concat(e.map((function(e){return gD(e,{keysToInclude:n,keysToExclude:r})})).join(","),"]");if(!Hw(e)||!Qw(n)&&!Qw(r))return JSON.stringify(e);var i={},a=new Set(n),o=new Set(r);return Object.keys(e).forEach((function(t){(0===o.size&&a.has(t)||0===a.size&&!o.has(t))&&(i[t]=Hw(e[t])||Qw(e[t])?JSON.parse(gD(e[t],{keysToExclude:r,keysToInclude:n})):e[t])})),JSON.stringify(i)}catch(ZC){return"{}"}}function yD(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=[];return Object.keys(e).forEach((function(r){t===e[r]&&n.push(r)})),gD(e,{keysToInclude:n})}function ED(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var kD=function(){var e,t,n,r;return null!=(e=window.screen)&&e.orientation?!(null==(r=null==(n=null==(t=window.screen)?void 0:t.orientation)?void 0:n.type)||!r.includes("portrait")):0===window.orientation||180===window.orientation},TD=function(e){return bA(void 0,null,f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.abrupt("return",new Promise((function(t,n){var r;if(Yw(e))(r=new Image).crossOrigin="anonymous",r.src=e;else if((r=e).complete)return void t(r);r.onload=function(){return t(r)},r.onerror=function(){n(new FA({code:VA.INVALID_PARAMETER,message:"load image failed, url: ".concat(e)}))}})));case 1:case"end":return t.stop()}}),t)})))},SD=function(e){var t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},ID=function(e){return Object.keys(e).forEach((function(t){zw(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(Hw(e[t])||Qw(e[t]))&&ID(e[t])})),e};function bD(e,t){return new Promise((function(n){var r=setTimeout(n,e);t&&t(r)}))}function RD(e,t){var n=null;return function(){for(var r=arguments.length,i=new Array(r),a=0;a<r;a++)i[a]=arguments[a];return n||((n=e.apply(t||this,i)).finally((function(){return n=null})),n)}}function AD(e){return e.replace(/(^|[^:])\/{2,}/g,"$1/")}function CD(e){var t;try{var n=null==(t=e.getSettings)?void 0:t.call(e),r=n.width,i=n.height,a=n.frameRate,o=n.sampleRate,s=n.sampleSize,c=n.channelCount,u=e.kind===IC.AUDIO?"".concat(o,"x").concat(s,"@").concat(c):"".concat(r,"x").concat(i,"@").concat(a),l=e.stats?" stats: ".concat(JSON.stringify(e.stats).replaceAll('"',"")):"";return"".concat(e.id," ").concat(e.readyState," muted:").concat(e.muted," ").concat(e.kind," ").concat(e.label," ").concat(u).concat(l)}catch(qA){return""}}function wD(e,t){return e.width*e.height==t.width*t.height?1:kD()&&t.width>t.height&&e.height>t.width?Math.max(e.width/t.height,e.height/t.width,1):Math.max(e.width/t.width,e.height/t.height,1)}function DD(e){return 90===e||270===e}function ND(e){var t=e.url,n=e.body,r=e.method,i=void 0===r?"POST":r,a=e.timeout,o=e.priority;return new Promise((function(e,r){if("fetch"in window)return fetch(t,{method:i,body:n,priority:o}).then((function(e){return e.text()})).then((function(t){try{e({data:JSON.parse(t)})}catch(Gx){e({data:t})}}),r);var s=new XMLHttpRequest;s.onreadystatechange=function(){if(4===s.readyState)if(s.status>=200&&s.status<300)try{var n=JSON.parse(s.response);e({data:n})}catch(t){e({data:s.response})}else r({status:s.status,statusText:s.statusText||"request failed!"})},s.timeout=a||5e3,s.open(i,t,!0),s.send(n)}))}function xD(e){return bA(this,null,f().mark((function t(){var n,r,i,a;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=aD(),r=JSON.stringify(e),t.prev=1,CompressionStream&&!(r.length<=2800)){t.next=4;break}return t.abrupt("return",r);case 4:return i=new Blob([r],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),t.next=7,new Response(i);case 7:return t.next=9,t.sent.blob();case 9:return t.next=11,t.sent.arrayBuffer();case 11:return a=t.sent,t.abrupt("return",(Ux.debug("compressJSON ".concat(r.length," -> ").concat(a.byteLength," ").concat(aD()-n,"ms")),a));case 15:return t.prev=15,t.t0=t.catch(1),t.abrupt("return",r);case 18:case"end":return t.stop()}}),t,null,[[1,15]])})))}var OD=Object.prototype.hasOwnProperty,PD=function(e){return"function"==typeof e},MD=function(e){return void 0===e},LD=function(e){return"boolean"==typeof e},VD=function(e){return e.isRemote},UD=function(e){if(!e||"object"!=T(e)||"[object Object]"!=Object.prototype.toString.call(e))return!1;var t=Object.getPrototypeOf(e);if(null===t)return!0;var n=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&Function.prototype.toString.call(n)===Function.prototype.toString.call(Object)},FD=function(e){var t=e.retryFunction,n=e.settings,r=e.onError,i=e.onRetrying,a=e.onRetryFailed,o=e.onRetrySuccess,s=e.context;return function(){for(var e=this,c=arguments.length,u=new Array(c),l=0;l<c;l++)u[l]=arguments[l];var d=n.retries,h=void 0===d?5:d,p=n.timeout,m=void 0===p?1e3:p,v=0,_=-1,g=0,y=function(n,c){return bA(e,null,f().mark((function e(){var l,d,p,E,k=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return l=s||this,e.prev=1,e.next=4,t.apply(l,u);case 4:d=e.sent,v>0&&o&&o.call(this,v),v=0,n(d),e.next=12;break;case 8:e.prev=8,e.t0=e.catch(1),p=function(){clearTimeout(_),v=0,g=2,c(e.t0)},E=function(){2!==g&&v<(PD(h)?h():h)?(v++,g=1,PD(i)&&i.call(k,v,p),_=window.setTimeout((function(){_=-1,y(n,c)}),PD(m)?m(v):m)):(p(),PD(a)&&a.call(k,e.t0))},PD(r)?r.call(this,{error:e.t0,retry:E,reject:c,retryFuncArgs:u,retriedCount:v}):E();case 12:case"end":return e.stop()}}),e,this,[[1,8]])})))};return new Promise(y)}},BD=function(){return o((function e(t){r(this,e),SA(this,"userId"),SA(this,"remoteUserId"),SA(this,"id"),SA(this,"sdkAppId"),SA(this,"type"),SA(this,"isLocal"),this.id=t.id,this.userId=t.userId,this.sdkAppId=t.sdkAppId,this.remoteUserId=t.remoteUserId,this.isLocal=!LD(t.isLocal)||t.isLocal,this.type=this.isLocal?"":t.type}),[{key:"createChild",value:function(e){return Object.setPrototypeOf(e,this)}},{key:"setUserId",value:function(e){this.userId=e}},{key:"setSdkAppId",value:function(e){this.sdkAppId=e}},{key:"log",value:function(e,t){var n=this.isLocal?this.userId:this.remoteUserId;t.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&"main"!==this.type?"*":"").concat(this.id).concat(n?"|".concat(n):"","]")),Ux.log(e,t,MD(this.userId)||function(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e||"function"==typeof e||Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(UD(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return 0===e.size;case"[object Object]":for(var t in e)if(OD.call(e,t))return!1;return!0}return!1}(this.userId),this.userId,this.sdkAppId)}},{key:"info",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.log(2,t)}},{key:"debug",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.log(1,t)}},{key:"warn",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.log(3,t)}},{key:"error",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.log(4,t)}}])}(),HD={};EA(HD,{ANDROID_VERSION:function(){return eN},CHROME_MAJOR_VERSION:function(){return ix},CHROME_VERSION:function(){return ax},EDGE_VERSION:function(){return sN},EDG_MAJOR_VERSION:function(){return lN},EDG_VERSION:function(){return uN},FIREFOX_MAJOR_VERSION:function(){return aN},FIREFOX_VERSION:function(){return iN},HUAWEI_VERSION:function(){return JN},IE_VERSION:function(){return kN},IOS_MAIN_VERSION:function(){return hx},IOS_VERSION:function(){return lx},IPADQQB_VERSION:function(){return xN},IS_ANDROID:function(){return $D},IS_ANDROID_WEBVIEW:function(){return ux},IS_ANY_SAFARI:function(){return sx},IS_CHROME:function(){return nx},IS_CHROME_OS:function(){return LN},IS_CHROMIUM_BASE:function(){return tx},IS_DESKTOP_IOS_CHROME:function(){return _x},IS_EDG:function(){return cN},IS_EDGE:function(){return oN},IS_ELECTRON:function(){return FN},IS_FIREFOX:function(){return rN},IS_HEADLESS_CHROME:function(){return rx},IS_HONOR:function(){return GN},IS_HUAWEI:function(){return jN},IS_HUAWEIBROWSER:function(){return WN},IS_IE:function(){return EN},IS_IE8:function(){return yN},IS_IOS:function(){return ZD},IS_IOS_13_OR_14:function(){return mx},IS_IOS_15_1:function(){return px},IS_IOS_CHROME:function(){return vx},IS_IPAD:function(){return zD},IS_IPADQQB:function(){return NN},IS_IPAD_PRO:function(){return qD},IS_IPHONE:function(){return XD},IS_IPOD:function(){return QD},IS_LINUX:function(){return MN},IS_LOCAL:function(){return gx},IS_MAC:function(){return PN},IS_MACQQB:function(){return wN},IS_MIBROWSER:function(){return BN},IS_MQQB:function(){return bN},IS_NATIVE_ANDROID:function(){return nN},IS_OLD_ANDROID:function(){return tN},IS_OPENHARMONY:function(){return ZN},IS_OPPOBROWSER:function(){return zN},IS_SAFARI:function(){return ox},IS_SAFARI_15_1:function(){return fx},IS_SAMSUNGBROWSER:function(){return KN},IS_SOGOU:function(){return fN},IS_SOGOUM:function(){return dN},IS_TBS:function(){return mN},IS_UCBROWSER:function(){return UN},IS_VIVOBROWSER:function(){return XN},IS_WECHAT:function(){return TN},IS_WIN:function(){return ON},IS_WQQB:function(){return AN},IS_WX:function(){return VN},IS_X5MQQB:function(){return IN},IS_XWEB:function(){return _N},MACQQB_VERSION:function(){return DN},MI_VERSION:function(){return HN},MQQB_VERSION:function(){return RN},OPENHARMONY_VERSION:function(){return $N},OPPO_VERSION:function(){return qN},SAFARI_VERSION:function(){return cx},SAMSUNG_VERSION:function(){return YN},SOGOUM_VERSION:function(){return hN},SOGOU_VERSION:function(){return pN},TBS_VERSION:function(){return vN},UA_DATA_STRING:function(){return Ix},USER_AGENT:function(){return WD},VIVO_VERSION:function(){return QN},WECHAT_VERSION:function(){return SN},WQQB_VERSION:function(){return CN},XWEB_VERSION:function(){return gN},browserInfo:function(){return Ex},getBrowserInfo:function(){return kx},getChromeMajorVersion:function(){return ex},getDeviceModel:function(){return Ax},getGPUInfo:function(){return Rx},getOSName:function(){return wx},getOSNumber:function(){return Dx},getOSString:function(){return Nx},getOSType:function(){return Ox},getTerminalType:function(){return xx},getUserAgentData:function(){return bx},isLocalStorageEnabled:function(){return yx},isMobile:function(){return Sx},isVersionSmallerThan:function(){return dx}});var WD="undefined"==typeof navigator?"":navigator.userAgent,jD=function(e){return new RegExp(e,"i").test(WD)},GD=function(e){if(jD(e)){var t=new RegExp("".concat(e,"\\/([\\d.]+)")),n=WD.match(t);if(n&&n[1])return n[1]}return""},JD=function(e){if(jD(e)){var t=new RegExp("".concat(e,"\\/(\\d+)")),n=WD.match(t);if(n&&n[1])return parseFloat(n[1])}return NaN},KD=/AppleWebKit\/([\d.]+)/i.exec(WD),YD=KD?parseFloat(KD[1]):NaN,zD=jD("iPad"),qD="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&jD("Macintosh"),XD=jD("iPhone")&&!zD,QD=jD("iPod"),ZD=XD||zD||QD||qD,$D=jD("Android"),eN=function(){if($D){var e=WD.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(e){var t=e[1]&&parseFloat(e[1]),n=e[2]&&parseFloat(e[2]);if(t&&n)return parseFloat("".concat(e[1],".").concat(e[2]));if(t)return t}}return NaN}(),tN=$D&&jD("webkit")&&eN<2.3,nN=$D&&eN<5&&YD<537,rN=jD("Firefox"),iN=GD("Firefox"),aN=JD("Firefox"),oN=jD("Edge"),sN=GD("Edge"),cN=jD("Edg"),uN=GD("Edg"),lN=JD("Edg"),dN=jD("SogouMobileBrowser"),hN=GD("SogouMobileBrowser"),fN=jD("MetaSr\\s"),pN=GD("MetaSr\\s"),mN=jD("TBS"),vN=GD("TBS"),_N=jD("XWEB"),gN=GD("XWEB"),yN=jD("MSIE\\s8\\.0"),EN=jD("MSIE\\/\\d+"),kN=function(){if(EN){var e=/MSIE\s(\d+)\.\d/.exec(WD),t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(WD)&&/rv:11.0/.test(WD)&&(t=11),t}return NaN}(),TN=jD("(micromessenger|webbrowser)"),SN=GD("MicroMessenger"),IN=!mN&&jD("MQQBrowser")&&jD("COVC"),bN=!mN&&jD("MQQBrowser")&&!jD("COVC"),RN=bN||IN?GD("MQQBrowser"):"",AN=!mN&&jD(" QQBrowser"),CN=GD(" QQBrowser"),wN=!mN&&jD("QQBrowserLite"),DN=GD("QQBrowserLite"),NN=!mN&&jD("MQBHD"),xN=GD("MQBHD"),ON=jD("Windows"),PN=!ZD&&jD("MAC OS X"),MN=!$D&&jD("Linux"),LN=jD("CrOS"),VN=jD("MicroMessenger"),UN=jD("UCBrowser"),FN=jD("Electron"),BN=jD("MiuiBrowser"),HN=GD("MiuiBrowser"),WN=jD("HuaweiBrowser"),jN=jD("Huawei")||jD("HUAWEI"),GN=jD("Honor")||jD("HONOR"),JN=GD("HuaweiBrowser"),KN=jD("SamsungBrowser"),YN=GD("SamsungBrowser"),zN=jD("HeyTapBrowser"),qN=GD("HeyTapBrowser"),XN=jD("VivoBrowser"),QN=GD("VivoBrowser"),ZN=jD("OpenHarmony"),$N=GD("OpenHarmony"),ex=function(){return JD("Chrome")},tx=jD("Chrome"),nx=!oN&&!fN&&!dN&&!mN&&!_N&&!cN&&!AN&&!BN&&!WN&&!KN&&!zN&&!XN&&tx,rx=jD("HeadlessChrome"),ix=ex(),ax=GD("Chrome"),ox=!tx&&!bN&&!IN&&!wN&&!NN&&jD("Safari"),sx=ox||ZD,cx=GD("Version"),ux=/Android.*(wv|.0.0.0)/.test(WD),lx=function(){if(qD)return cx;if(ZD){var e=WD.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){var t=e[1];return e[2]&&(t+=".".concat(e[2])),t}}return""}();function dx(e,t){for(var n=e.split(".").map((function(e){return Number(e)})),r=t.split(".").map((function(e){return Number(e)})),i=0;i<Math.max(n.length,r.length);i++){var a=n[i]||0,o=r[i]||0;if(a<o)return!0;if(a>o)return!1}return!1}var hx=Number(lx.split(".")[0]),fx="15.1"===cx,px="15.1"===lx,mx=function(){var e=Number(lx.split(".")[0]);return 14===e||13===e}(),vx=jD("CriOS"),_x=vx&&"11.1.1"===cx,gx="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),yx=function(){var e;return function(){if(void 0===e)try{e=!!window.localStorage}catch(Kx){e=!1}return e}}(),Ex=kx();function kx(){var e,t=new Map([[rN,["Firefox",iN]],[cN,["Edg",uN]],[nx,["Chrome",ax]],[ox,["Safari",cx]],[mN,["TBS",vN]],[_N,["XWEB",gN]],[TN&&XD,["WeChat",SN]],[AN,["QQ(Win)",CN]],[bN,["QQ(Mobile)",RN]],[IN,["QQ(Mobile X5)",RN]],[wN,["QQ(Mac)",DN]],[NN,["QQ(iPad)",xN]],[BN,["MI",HN]],[WN,["HW",JN]],[KN,["Samsung",YN]],[zN,["OPPO",qN]],[XN,["VIVO",QN]],[oN,["EDGE",sN]],[dN,["SogouMobile",hN]],[fN,["Sogou",pN]]]),n="unknown",r="unknown";return t.has(!0)&&(n=(e=v(t.get(!0),2))[0],r=e[1]),{name:n,version:r}}var Tx=null;function Sx(){return Tx&&"boolean"==typeof Tx.mobile?Tx.mobile:$D||ZD||XD||zD||ZN}var Ix="";function bx(){return bA(this,null,f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!Tx){e.next=2;break}return e.abrupt("return",Tx);case 2:if(navigator.userAgentData&&"function"==typeof navigator.userAgentData.getHighEntropyValues){e.next=4;break}return e.abrupt("return",null);case 4:return e.prev=4,e.next=7,navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]);case 7:if(e.t0=Tx=e.sent,!e.t0){e.next=10;break}e.t0=!Ix;case 10:if(e.t1=e.t0,!e.t1){e.next=13;break}Ix="UAData: ".concat(Tx.platform,"/").concat(Tx.platformVersion),Tx.architecture&&Tx.bitness&&(Ix+=" ".concat(Tx.architecture,"/").concat(Tx.bitness)),Tx.mobile&&(Ix+=" mobile"),Tx.model&&(Ix+=" model: ".concat(Tx.model.replace(/\s+/g,"/"))),Tx.fullVersionList&&(Ix+=" ".concat(Tx.fullVersionList.filter((function(e){return"Not/A)Brand"!==e.brand})).map((function(e){return"".concat(e.brand,"/").concat(e.version)})).join(",")));case 13:return e.abrupt("return",Tx);case 16:return e.prev=16,e.t2=e.catch(4),e.abrupt("return",null);case 19:case"end":return e.stop()}}),e,null,[[4,16]])})))}function Rx(){try{var e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return"";var n=t.getExtension("WEBGL_debug_renderer_info");if(n){var r=t.getParameter(n.UNMASKED_VENDOR_WEBGL),i=t.getParameter(n.UNMASKED_RENDERER_WEBGL);return"".concat(r," ").concat(i)}return""}catch(a){return""}}function Ax(){return(null==Tx?void 0:Tx.model)||""}var Cx=new Map([[$D,"Android"],[ZD,"iOS"],[ON,"Windows"],[PN,"MacOS"],[MN,"Linux"],[LN,"ChromeOS"]]),wx=function(){return Cx.get(!0)?Cx.get(!0):Tx?Tx.platform:"unknown"};function Dx(){return ON?1:$D?2:PN?3:ZD?4:MN?5:LN?6:0}var Nx=function(){var e=wx();return e+="/".concat(Ex.name,"/").concat(ox?Ex.version:Ex.version.split(".")[0]),null!=Tx&&Tx.platformVersion&&(e+="/".concat(Tx.platformVersion)),null!=Tx&&Tx.architecture&&(e+="/".concat(Tx.architecture)),e};function xx(){return $D?4:XD?2:zD?3:PN?12:ON?5:MN?13:ZN?22:1}function Ox(){return $D?"Android":XD?"iPhone":zD?"iPad":PN?"Mac":ON?"Windows":MN?"Linux":"unknown"}var Px=new(kA(RA(),1).default),Mx=function(e){return e.ROOM_DESTROY="1",e.JOIN_START="21",e.JOIN_SCHEDULE_SUCCESS="22",e.JOIN_SIGNAL_CONNECTION_START="23",e.JOIN_SIGNAL_CONNECTION_END="24",e.JOIN_SEND_CMD="25",e.JOIN_RECEIVED_CMD_RES="26",e.JOIN_SUCCESS="27",e.JOIN_FAILED="28",e.LEAVE_START="51",e.LEAVE_SEND_CMD="52",e.LEAVE_SUCCESS="53",e.PUBLISH_START="61",e.SEND_FIRST_VIDEO_FRAME="62",e.PUBLISH_FAILED="63",e.SUBSCRIBE_START="81",e.SUBSCRIBE_SUCCESS="82",e.SUBSCRIBE_FAILED="84",e.UNSUBSCRIBE_SUCCESS="83",e.LOCAL_TRACK_CAPTURE_START="101",e.LOCAL_TRACK_CAPTURE_SUCCESS="102",e.LOCAL_TRACK_CAPTURE_FAILED="103",e.LOCAL_TRACK_PUBLISHED="104",e.LOCAL_TRACK_UNPUBLISHED="105",e.LOCAL_TRACK_REPLACED="106",e.SWITCH_DEVICE_SUCCESS="107",e.TRACK_MUTED="108",e.TRACK_UNMUTED="109",e.REMOTE_TRACK_SUBSCRIBED="110",e.REMOTE_TRACK_UNSUBSCRIBED="111",e.LOCAL_TRACK_RECAPTURE="112",e.LOCAL_AUDIO_STARTED="113",e.LOCAL_AUDIO_STOPPED="114",e.REMOTE_AUDIO_STARTED="115",e.REMOTE_AUDIO_STOPPED="116",e.PLAY_TRACK_START="151",e.PLAYER_STATE_CHANGED="152",e.VIDEO_LOADED_DATA="153",e.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",e.SIGNAL_CONNECTION_STATE_CHANGED="201",e.PEER_CONNECTION_STATE_CHANGED="202",e.SINGLE_CONNECTION_STAT="203",e.SPC_RECONNECTED="204",e.HEARTBEAT_REPORT="251",e.RECEIVED_PUBLISHED_USER_LIST="252",e.REMOTE_PUBLISH_STATE_CHANGED="253",e.AUDIO_LEVEL_INTERVAL="260",e.NETWORK_QUALITY="261",e.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",e.QUALITY_LIMITATION_CHANGED="263",e.LOG="264",e.AUDIO_PROCESSOR_DEBUG="265",e.SWITCH_ROOM_START="401",e.SWITCH_ROOM_SUCCESS="407",e.SWITCH_ROOM_FAILED="408",e}(Mx||{}),Lx=Mx,Vx=function(){function e(){r(this,e),SA(this,"_isEnableUploadLog",!0),SA(this,"_localJoinedUser",new Map),SA(this,"_queue",[]),SA(this,"_timeoutId",-1),SA(this,"_logLevel",1),SA(this,"_logLevelToUpload",2),!QA&&!ZA&&(this.checkURLParam(),this.installEvents())}return o(e,[{key:"isAbleToUpload",get:function(){return this._isEnableUploadLog&&-1!==this._timeoutId}},{key:"installEvents",value:function(){var e=this;Px.on(Lx.JOIN_SCHEDULE_SUCCESS,(function(t){var n,r=t.schedule;null!=(n=null==r?void 0:r.config)&&n.logLevelToUpload&&pC[r.config.logLevelToUpload]&&(e._logLevelToUpload=r.config.logLevelToUpload)})),Px.on(Lx.JOIN_SUCCESS,(function(t){var n=t.room;e.addJoinedUser({userId:n.userId,sdkAppId:n.sdkAppId}),e.startUpload()})),Px.once(Lx.JOIN_FAILED,(function(){e.startUpload()})),Px.on(Lx.LEAVE_SUCCESS,(function(t){var n=t.room;e.deleteJoinedUser(n.userId)}))}},{key:"startUpload",value:function(){-1===this._timeoutId&&this.uploadInterval()}},{key:"addJoinedUser",value:function(e){this._localJoinedUser.set(e.userId,e),this.startUpload()}},{key:"deleteJoinedUser",value:function(e){this._localJoinedUser.delete(e)}},{key:"uploadInterval",value:function(){var e=this;this.upload().catch((function(){})),this._timeoutId=window.setTimeout((function(){return e.uploadInterval()}),5e3)}},{key:"getLogsToUpload",value:function(){var e=this,t={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&0===this._localJoinedUser.size)return t;for(var n=0,r=function(){var r=e._queue[n];if(r.forAllJoinedClients)e._localJoinedUser.forEach((function(e){var n=e.userId,i=e.sdkAppId;t.map.has(n)?t.map.get(n).logs.push(r):t.map.set(n,{userId:n,sdkAppId:i,logs:[r]})}));else if(Yw(r.userId)&&zw(r.sdkAppId)){var i=r.userId,a=r.sdkAppId;t.map.has(i)?t.map.get(i).logs.push(r):t.map.set(i,{userId:i,sdkAppId:a,logs:[r]})}};n<this._queue.length&&50!==n;n++)r();return t.map.size>0&&(t.splicedQueue=this._queue.splice(0,n)),t}},{key:"upload",value:function(){return bA(this,null,f().mark((function e(){var t,n,r,i,a,o,s,c,u,l;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(0!==this._queue.length&&this._isEnableUploadLog){e.next=2;break}return e.abrupt("return");case 2:if(t=this.getLogsToUpload(),n=t.map,r=t.splicedQueue,0!==n.size){e.next=5;break}return e.abrupt("return");case 5:e.prev=5,i=E(n.values()),a=0;case 8:if(!(a<i.length)){e.next=16;break}return o=i[a],s=o.userId,c=o.sdkAppId,u=o.logs,e.next=12,this.uploadLogWithRetry(JSON.stringify({timestamp:WA(),sdkAppId:String(c),userId:s,version:YA,log:u.map((function(e){return e.log})).join("\n")}),c);case 12:u.forEach((function(e){return e.uploaded=!0}));case 13:a++,e.next=8;break;case 16:e.next=20;break;case 18:e.prev=18,e.t0=e.catch(5);case 20:l=r.filter((function(e){return!e.uploaded})),l.length>0&&(this._queue=l.concat(this._queue));case 22:case"end":return e.stop()}}),e,this,[[5,18]])})))}},{key:"uploadLogWithRetry",value:function(e,t){return FD({retryFunction:function(){return ND({url:Cw(t,hC.LOG),body:e,timeout:5e3,priority:"low"})},settings:{retries:3,timeout:2e3},onError:function(e){(0,e.retry)()}})()}},{key:"getPrefix",value:function(e){var t=new Date;return t.setTime(HA()),"[".concat(jA(t),"] <").concat(pC[e],">")}},{key:"getLogLevel",value:function(){return this._logLevel}},{key:"setLogLevel",value:function(e){Kw(pC[e])||(this._logLevel!==e&&this.info("setLogLevel",e),this._logLevel=e)}},{key:"enableUploadLog",value:function(){this._isEnableUploadLog=!0}},{key:"disableUploadLog",value:function(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}},{key:"logChunkToString",value:function(e){if(Yw(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(qA){return""}}},{key:"log",value:function(t,n){var r,i,a,o=this,s=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],c=arguments.length>3?arguments[3]:void 0,u=arguments.length>4?arguments[4]:void 0;n.unshift(this.getPrefix(t));var l={log:n.reduce((function(e,t){return"".concat(e," ").concat(o.logChunkToString(t)).trim()}),""),level:t,userId:c,sdkAppId:u,forAllJoinedClients:s};if(Px.emit(Lx.LOG,{log:l}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(l),!(t<this._logLevel)){var d=(null==(a=pC[t])?void 0:a.toLowerCase())||"info";e.PRINT_LOG_TAG?(r=console)[d].apply(r,["%cTRTC%c%s","padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;","display: inline"].concat(E(n))):(i=console)[d].apply(i,E(n))}}},{key:"debug",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.log(1,t)}},{key:"info",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.log(2,t)}},{key:"warn",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.log(3,t)}},{key:"error",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.log(4,t)}},{key:"createLogger",value:function(e){return new BD(e)}},{key:"checkURLParam",value:function(){var e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;pC[t]&&(this._logLevelToUpload=t)}},{key:"getQueue",value:function(){return this._queue}}])}();SA(Vx,"PRINT_LOG_TAG",!(ZD||$D||rx));var Ux=new Vx,Fx=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))},Bx=new(function(){return o((function e(){r(this,e),SA(this,"_prefix","TRTC"),SA(this,"_queue",new Map)}),[{key:"getRealKey",value:function(e){return"".concat(this._prefix,"_").concat(e)}},{key:"checkStorage",value:function(){var e=this;yx()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter((function(t){if(t.startsWith(e._prefix))try{var n=localStorage.getItem(t);if(!n)return!1;var r=JSON.parse(n);if(r&&r.expiresIn<Date.now())return!0}catch(Yx){return!1}return!1})).forEach((function(e){return localStorage.removeItem(e)})))}},{key:"doFlush",value:function(){if(yx())try{var e,t=s(this._queue);try{for(t.s();!(e=t.n()).done;){var n=v(e.value,2),r=n[0],i=n[1];localStorage.setItem(r,JSON.stringify(i))}}catch(a){t.e(a)}finally{t.f()}}catch(Kx){Ux.warn(Kx)}}},{key:"getItem",value:function(e){if(!yx())return null;try{var t=localStorage.getItem(this.getRealKey(e));if(!t)return null;var n=JSON.parse(t);return n&&n.expiresIn>=Date.now()?n.value:null}catch(qA){Ux.warn(qA)}}},{key:"setItem",value:function(e,t){if(yx())try{var n={expiresIn:Date.now()+gC,value:t};this._queue.set(this.getRealKey(e),n)}catch(ZC){Ux.warn(ZC)}}},{key:"deleteItem",value:function(e){if(!yx())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(qA){return Ux.warn(qA),!1}}},{key:"clear",value:function(){if(yx())try{localStorage.clear()}catch(Kx){Ux.warn(Kx)}}}])}()),Hx={};EA(Hx,{HTTPS_API:function(){return yP},IS_GET_CAPABILITIES_SUPPORTED:function(){return BP},IS_GET_SETTINGS_SUPPORTED:function(){return FP},IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:function(){return UP},IS_INSERTABLE_STREAM_SUPPORTED:function(){return HP},IS_JITTER_BUFFER_TARGET_SUPPORTED:function(){return $P},IS_RTC_RTP_SENDER_SUPPORTED:function(){return MP},IS_SCRIPT_TRANSFORM_SUPPORTED:function(){return WP},IS_SEI_SUPPORTED:function(){return jP},IS_SPC_SUPPORTED:function(){return OP},basis:function(){return qP},capabilityCheck:function(){return QP},checkSystemRequirementsInternal:function(){return mP},decodeSupportStatus:function(){return pP},encodeSupportStatus:function(){return fP},getBrowserInfo:function(){return oP},getDisplayResolution:function(){return kP},isAddTransceiverSupported:function(){return xP},isBrowserSupported:function(){return sP},isCanvasCaptureStreamAPISupported:function(){return IP},isCanvasSmallStreamSupported:function(){return bP},isGetReceiversSupported:function(){return wP},isGetSendersSupported:function(){return DP},isGetTransceiversSupported:function(){return NP},isGetUserMediaSupported:function(){return TP},isMediaDevicesSupported:function(){return uP},isMediaSessionSupported:function(){return KP},isMediaStreamTrackProcessorSupported:function(){return hP},isReplaceTrackSupported:function(){return LP},isRequestVideoFrameCallbackSupported:function(){return ZP},isSIMDSupported:function(){return zP},isScaleResolutionDownBySupported:function(){return RP},isScreenCaptureApiAvailable:function(){return _P},isSelectedCandidatePair:function(){return EP},isSetParametersSupported:function(){return VP},isSmallStreamSupported:function(){return AP},isStopTransceiverSupported:function(){return PP},isTRTCSupported:function(){return vP},isUnifiedPlanDefault:function(){return CP},isUsedInHttpProtocol:function(){return dP},isWebAudioSupported:function(){return SP},isWebCodecSupported:function(){return JP},isWebCodecsSupported:function(){return cP},isWebRTCSupported:function(){return GP},isWebTransportSupported:function(){return YP}});var Wx={};EA(Wx,{AUDIO_LEVEL_SCALE:function(){return xO},AudioCodecPipelineType:function(){return VO},AudioDecoderDowngradeState:function(){return fO},AudioPlayerMode:function(){return wO},AudioType:function(){return yO},BASIC_TYPE:function(){return PO},BannedReason:function(){return DO},CONNECTION_CLOSED_REASON:function(){return eO},ClientEvent:function(){return tO},CodecType:function(){return UO},ConnectionEvent:function(){return $x},ConnectionState:function(){return hO},DECODE_FAILED_ERROR_CODE:function(){return FO},FacingMode:function(){return AO},LeaveReason:function(){return NO},LocalTrackEvent:function(){return rO},MULTI_VIDEO_DATA_TYPE:function(){return SO},MediaType:function(){return _O},MediaTypeLabel:function(){return gO},MonitorEventId:function(){return IO},MutedFlag:function(){return cO},NetworkQualityValue:function(){return bO},PlayerState:function(){return iO},ReceiveMode:function(){return RO},RemoteStreamType:function(){return TO},RemoteTrackEvent:function(){return sO},RoomEvent:function(){return aO},SMALL_MODE:function(){return WO},SceneNumber:function(){return uO},StreamEvent:function(){return nO},StreamType:function(){return kO},SubscribeMediaType:function(){return OO},TIMER_TYPE:function(){return HO},TRACK_ACTION:function(){return vO},TRACK_KIND:function(){return mO},TrackEvent:function(){return oO},UserRole:function(){return dO},UserRoleNumber:function(){return lO},VideoCodec:function(){return MO},VideoCodecPipelineType:function(){return LO},VideoContentHint:function(){return BO},VideoDecoderDowngradeState:function(){return pO},VideoPlayerMode:function(){return CO},VideoType:function(){return EO}});var jx,Gx,Jx,Kx,Yx,zx,qx,Xx,Qx,Zx,$x=((Zx=$x||{}).TRACK_ADDED="track-added",Zx.TRACK_UPDATED="track-updated",Zx.TRACK_SUBSCRIBED="track-subscribed",Zx.STREAM_ADDED="stream-added",Zx.STREAM_REMOVED="stream-removed",Zx.STREAM_UPDATED="stream-updated",Zx.STREAM_PUBLISHED="stream-published",Zx.STREAM_SUBSCRIBED="stream-subscribed",Zx.STREAM_UNSUBSCRIBED="stream-unsubscribed",Zx.STATE_CHANGED="state-changed",Zx.ERROR="error",Zx.CONNECTION_STATE_CHANGED="connection-state-changed",Zx.FIREWALL_RESTRICTION="firewall-restriction",Zx.SEI_MESSAGE="sei-message",Zx.CLOSED="closed",Zx),eO=function(e){return e.REMOTE_LEAVE="remote user exitRoom",e.REMOTE_UNPUBLISH="remote user unpublished",e.LOCAL_LEAVE="you exitRoom",e.LOCAL_UNPUBLISH="you unpublished",e.LOCAL_UNSUBSCRIBE="you unsubscribed",e.SWITCH_ROLE="you switch role to audience",e}(eO||{}),tO=((Qx=tO||{}).STREAM_ADDED="stream-added",Qx.STREAM_REMOVED="stream-removed",Qx.STREAM_UPDATED="stream-updated",Qx.STREAM_SUBSCRIBED="stream-subscribed",Qx.CONNECTION_STATE_CHANGED="connection-state-changed",Qx.PEER_JOIN="peer-join",Qx.PEER_LEAVE="peer-leave",Qx.MUTE_AUDIO="mute-audio",Qx.MUTE_VIDEO="mute-video",Qx.UNMUTE_AUDIO="unmute-audio",Qx.UNMUTE_VIDEO="unmute-video",Qx.CLIENT_BANNED="client-banned",Qx.NETWORK_QUALITY="network-quality",Qx.AUDIO_VOLUME="audio-volume",Qx.SEI_MESSAGE="sei-message",Qx.ERROR="error",Qx),nO=((Xx=nO||{}).PLAYER_STATE_CHANGED="player-state-changed",Xx.SCREEN_SHARING_STOPPED="screen-sharing-stopped",Xx.CONNECTION_STATE_CHANGED="connection-state-changed",Xx.DEVICE_AUTO_RECOVERED="device-auto-recovered",Xx.ERROR="error",Xx),rO=function(e){return e.DEVICE_AUTO_RECOVERED="1",e.DEVICE_RECOVER_FAILED="5",e.DEVICE_CHANGED="2",e.ERROR="3",e.PUBLISH_STATE_CHANGED="4",e.ENCODE_FAILED="6",e}(rO||{}),iO=function(e){return e.PAUSED="PAUSED",e.PLAYING="PLAYING",e.STOPPED="STOPPED",e}(iO||{}),aO=((qx=aO||{}).PEER_JOIN="peer-join",qx.PEER_LEAVE="peer-leave",qx.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",qx.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",qx.BANNED="banned",qx.NETWORK_QUALITY="network-quality",qx.AUDIO_VOLUME="audio-volume",qx.SEI_MESSAGE="sei-message",qx.ERROR="error",qx.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",qx.REMOTE_PUBLISHED="remote-published",qx.REMOTE_UNPUBLISHED="remote-unpublished",qx.FIREWALL_RESTRICTION="firewall-restriction",qx.HEARTBEAT_REPORT="heartbeat-report",qx.CUSTOM_MESSAGE="custom-message",qx.LAYER_DATA="layerData",qx.FIRST_VIDEO_FRAME="first-video-frame",qx.DUMP="dump",qx.AUDIO_FRAME="audio-frame",qx.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",qx),oO=((zx=oO||{}).PLAYER_STATE_CHANGED="player-state-changed",zx.MUTE="mute",zx.UNMUTE="unmute",zx.ERROR="error",zx.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",zx.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",zx.FIRST_VIDEO_FRAME="first-video-frame",zx),sO=function(e){return e.DECODE_FAILED="decode-failed",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e}(sO||{}),cO=function(e){return e[e.VIDEO=1]="VIDEO",e[e.SMALL=2]="SMALL",e[e.AUX=4]="AUX",e[e.AUDIO=8]="AUDIO",e[e.VIDEO_MUTE=16]="VIDEO_MUTE",e[e.AUX_MUTE=32]="AUX_MUTE",e[e.AUDIO_MUTE=64]="AUDIO_MUTE",e}(cO||{}),uO=function(e){return e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e}(uO||{}),lO=function(e){return e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e}(lO||{}),dO=function(e){return e.ANCHOR="anchor",e.AUDIENCE="audience",e}(dO||{}),hO=function(e){return e.CONNECTED="CONNECTED",e.DISCONNECTED="DISCONNECTED",e.CONNECTING="CONNECTING",e.RECONNECTED="RECONNECTED",e.RECONNECTING="RECONNECTING",e}(hO||{}),fO=((Yx=fO||{}).INITIALIZED="INITIALIZED",Yx.STARTING="STARTING",Yx.STARTED="STARTED",Yx.FAILED="FAILED",Yx),pO=function(e){return e.INITIALIZED="INITIALIZED",e.STARTING="STARTING",e.STARTED="STARTED",e.FAILED="FAILED",e}(pO||{}),mO=function(e){return e.AUDIO="audio",e.VIDEO="video",e.AUXILIARY="auxVideo",e}(mO||{}),vO=function(e){return e.ADD="add",e.REMOVE="remove",e}(vO||{}),_O=function(e){return e[e.NULL=0]="NULL",e[e.AUDIO=1]="AUDIO",e[e.AUX_VIDEO=2]="AUX_VIDEO",e[e.BIG_VIDEO=4]="BIG_VIDEO",e[e.SMALL_VIDEO=8]="SMALL_VIDEO",e}(_O||{}),gO={1:"audio",2:"auxVideo",4:"video"},yO=((Kx=yO||{})[Kx.opus=111]="opus",Kx),EO=function(e){return e[e.h264=100]="h264",e[e.vp8=101]="vp8",e}(EO||{}),kO=function(e){return e.Big="big",e.Small="small",e}(kO||{}),TO=function(e){return e.Main="main",e.Aux="auxiliary",e}(TO||{}),SO=function(e){return e[e.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",e[e.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",e[e.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",e[e.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",e[e.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",e}(SO||{}),IO=((Jx=IO||{})[Jx.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",Jx[Jx.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",Jx[Jx.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",Jx[Jx.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",Jx[Jx.MUTE_AUDIO=32772]="MUTE_AUDIO",Jx[Jx.MUTE_VIDEO=32773]="MUTE_VIDEO",Jx[Jx.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",Jx[Jx.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",Jx[Jx.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",Jx[Jx.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",Jx[Jx.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",Jx[Jx.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",Jx[Jx.SWITCH_CAMERA=32780]="SWITCH_CAMERA",Jx[Jx.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",Jx[Jx.REPLACE_VIDEO=32782]="REPLACE_VIDEO",Jx[Jx.REPLACE_AUDIO=32783]="REPLACE_AUDIO",Jx[Jx.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",Jx[Jx.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",Jx[Jx.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",Jx[Jx.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",Jx[Jx.JOIN=32788]="JOIN",Jx[Jx.LEAVE=32789]="LEAVE",Jx[Jx.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",Jx[Jx.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",Jx[Jx.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",Jx[Jx.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",Jx[Jx.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",Jx[Jx.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",Jx[Jx.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",Jx[Jx.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",Jx[Jx.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",Jx[Jx.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",Jx[Jx.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",Jx[Jx.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",Jx[Jx.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",Jx[Jx.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",Jx[Jx.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",Jx[Jx.PUBLISH_AUX=32805]="PUBLISH_AUX",Jx[Jx.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",Jx[Jx.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",Jx[Jx.VIDEO_ENCODER=4004]="VIDEO_ENCODER",Jx[Jx.VIDEO_DECODER=4005]="VIDEO_DECODER",Jx),bO=function(e){return e[e.UNKNOWN=0]="UNKNOWN",e[e.EXCELLENT=1]="EXCELLENT",e[e.GOOD=2]="GOOD",e[e.POOR=3]="POOR",e[e.BAD=4]="BAD",e[e.VERY_BAD=5]="VERY_BAD",e[e.DISCONNECTED=6]="DISCONNECTED",e}(bO||{}),RO=function(e){return e[e.MANUAL=0]="MANUAL",e[e.AUTO_AUDIO=1]="AUTO_AUDIO",e[e.AUTO_VIDEO=2]="AUTO_VIDEO",e[e.AUTO_ALL=3]="AUTO_ALL",e}(RO||{}),AO=function(e){return e.user="user",e.environment="environment",e}(AO||{}),CO=function(e){return e[e.ELEMENT=0]="ELEMENT",e[e.CANVAS_FROM_ELEMENT=1]="CANVAS_FROM_ELEMENT",e[e.CANVAS_WITHOUT_ELEMENT=2]="CANVAS_WITHOUT_ELEMENT",e}(CO||{}),wO=function(e){return e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e}(wO||{}),DO=function(e){return e.BANNED="banned",e.KICK="kick",e.USER_TIME_OUT="user_time_out",e.ROOM_DISBAND="room_disband",e}(DO||{}),NO=((Gx=NO||{})[Gx.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",Gx[Gx.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",Gx[Gx.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",Gx[Gx.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",Gx[Gx.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",Gx[Gx.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",Gx[Gx.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",Gx[Gx.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",Gx[Gx.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",Gx),xO=1e8,OO=function(){return o((function e(){r(this,e),SA(this,"mediaType",0)}),[{key:"audio",get:function(){return!!(1&this.mediaType)},set:function(e){e?this.mediaType|=1:this.mediaType&=-2}},{key:"video",get:function(){return!!(4&this.mediaType)},set:function(e){e?this.mediaType|=4:this.mediaType&=-5}},{key:"auxiliary",get:function(){return!!(2&this.mediaType)},set:function(e){e?this.mediaType|=2:this.mediaType&=-3}},{key:"smallVideo",get:function(){return!!(8&this.mediaType)},set:function(e){e?this.mediaType|=8:this.mediaType&=-9}}])}(),PO=function(e){return e.String="string",e.Number="number",e.Boolean="boolean",e.Array="array",e.Object="object",e}(PO||{}),MO=function(e){return e.H264="h264",e.H265="h265",e.VP8="vp8",e}(MO||{}),LO=function(e){return e[e.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",e[e.DUMP=1]="DUMP",e[e.SEI=2]="SEI",e[e.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",e}(LO||{}),VO=function(e){return e[e.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",e[e.NTP_TO_AUDIO_FRAME=1]="NTP_TO_AUDIO_FRAME",e[e.DUMP=2]="DUMP",e[e.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",e}(VO||{}),UO=function(e){return e.WebRTC="webrtc",e.WebCodecs="webcodecs",e.WebAssembly="webassembly",e}(UO||{}),FO=((jx=FO||{})[jx.SUCCESS=0]="SUCCESS",jx[jx.FAILED=1]="FAILED",jx[jx.WEBCODEC_INIT=2]="WEBCODEC_INIT",jx[jx.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",jx[jx.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",jx[jx.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",jx[jx.WASM_INIT=6]="WASM_INIT",jx[jx.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",jx[jx.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",jx[jx.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",jx[jx.TEST=10]="TEST",jx[jx.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",jx),BO=function(e){return e.NONE="",e.DETAIL="detail",e.MOTION="motion",e.TEXT="text",e}(BO||{}),HO=function(e){return e.INTERVAL="interval",e.TIMEOUT="timeout",e.RAF="raf",e.RIC="ric",e.INTERVAL_IN_WORKER="intervalInWorker",e}(HO||{}),WO=function(e){return e.CANVAS="canvas",e.API="api",e}(WO||{}),jO={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},GO={AVOID_REPEATED_CALL:function(e){return"previous ".concat(e.name,"() is ongoing, please avoid repeated calls.")},INVALID_PARAMETER_REQUIRED:function(e){var t=e.key,n=e.rule,r=e.fnName,i=e.value;return"'".concat(t||n.name,"' is a required param when calling ").concat(r,"(), received: ").concat(i,".")},INVALID_PARAMETER_TYPE:function(e){var t,n=e.key,r=e.rule,i=e.fnName,a=e.value,o="".concat(n||r.name);return t=Array.isArray(r.type)?r.type.join("|"):r.type,"'".concat(o,"' must be type of ").concat(t," when calling ").concat(i,"(), received type: ").concat(Gw(a),".")},INVALID_PARAMETER_EMPTY:function(e){var t=e.key,n=e.rule,r=e.fnName,i=e.value;return"'".concat(t||n.name,"' cannot be '").concat(i,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE:function(e){var t=e.key,n=e.rule,r=e.fnName,i=e.value,a="".concat(t||n.name),o="".concat(n.instanceOf.name||n.instanceOf);return"'".concat(a,"' must be instanceof ").concat(o," when calling ").concat(r,"(), received type: ").concat(Gw(i),".")},INVALID_PARAMETER_RANGE:function(e){var t=e.key,n=e.rule,r=e.fnName,i=e.value;return"'".concat(t||n.name,"' must be one of ").concat(n.values.join("|")," when calling ").concat(r,"(), received: ").concat(i,".")},INVALID_PARAMETER_MIN:function(e){var t=e.key,n=e.rule;e.fnName;var r=e.value;return"the min value of ".concat(t||n.name," is ").concat(n.min,", received: ").concat(r,".")},INVALID_PARAMETER_MAX:function(e){var t=e.key,n=e.rule;e.fnName;var r=e.value;return"the max value of ".concat(t||n.name," is ").concat(n.max,", received: ").concat(r,".")},API_CALL_TIMEOUT:function(e){return"".concat(e.commandDesc||e.command," timeout observed.")},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:function(e){return"SignalChannel setup failure: (errorCode: ".concat(e.errorCode,", errorMsg: ").concat(e.errorMsg," }).")},ERROR_MESSAGE:function(e){var t="".concat(e.type," failed");return e.message&&(t="".concat(t,": ").concat(e.message,".")),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:function(e){return"exchange sdp failed ".concat(e.errMsg,".")},UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:function(e){return"'".concat(e,"' must be validate string when useStringRoomId is true.")},INVALID_ROOMID_INTEGER:function(e){return"'".concat(e,"' must be an integer between [1, 4294967294] when useStringRoomId is false.")},INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED:function(e){var t=e.error,n=e.code;return"Failed to join room - ".concat(t," code: ").concat(n)},REJOIN_ROOM_FAILED:function(e){return"reJoin room: ".concat(e.roomId," failed, please check your network.")},INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:'no permission to publish() under live/audience, please call switchRole("anchor") firstly before publish().',INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:function(e){return"duplicate ".concat(e," stream publishing, please unpublish your prev ").concat(e," stream and then re-publish.")},INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED:function(e){var t=e.message,n=e.userId,r=e.streamType;return"failed to subscribe ".concat(n," ").concat(r," stream, reason: ").concat(t,".")},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as anchor or audience.",INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:function(e){return"switchRole failed, errCode: ".concat(e.code," errMsg: ").concat(e.message,".")},CLIENT_BANNED:function(e){return"client was banned because of ".concat(e.message,".")},INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:function(e){return"startPublishCDNStream failed, errMsg: ".concat(e.message,".")},STOP_PUBLISH_CDN_FAILED:function(e){return"stopPublishCDNStream failed, errMsg: ".concat(e.message,".")},INVALID_STREAM_ID:function(e){return"'".concat(e,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.")},START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK:function(e){return"cannot replace ".concat(e.kind," track because stream has not ").concat(e.kind," track")},NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED:function(e){return"startMixTranscode failed, errMsg: ".concat(e.message,".")},STOP_MIX_TRANSCODE_FAILED:function(e){return"stopMixTranscode failed, errMsg: ".concat(e.message,".")},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO:function(e){var t=e.key,n=e.rule,r=e.fnName;return e.value,"'".concat(t||n.name,"' cannot be less than 0 when calling ").concat(r,"().")},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER:function(e){return"'".concat(e,"' is required and must be between 1 and 15.")},MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:function(e){var t=e.key,n=e.fnName;return"'".concat(t,"' is not found in the document object when calling ").concat(n,"().")},INVALID_ELEMENT_ID_TYPE:function(e){var t=e.key,n=e.fnName,r=e.type;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(n,"(), received: ").concat(r,".")},PLAY_FAILED:function(e){return"".concat(e.media," play failed, browser exception: ").concat(e.error.toString())},INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK:function(e){return"".concat(e,"Track is not supported on your browser.")},NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED:function(e){return"".concat(e.signalResponse," failed, response code is ").concat(e.code," , errMsg: ").concat(e.message,".")},CATCH_HANDLER_ERROR:function(e){var t=e.name,n=e.event;return"an error was caught in ".concat(t,".on('").concat(n,"', handler), please check your code in 'handler'.")},API_NOT_EXIST:function(e){var t=e.name;return"experimental api ".concat(t," does not exist.")},REPEAT_JOIN:function(e){return"please avoid repeated join."},CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED:function(e){var t=e.funName;return"failed to call ".concat(t,"() because client was destroyed.")},SEI_NOT_SUPPORT:function(e){return"not support to sendSEIMessage".concat(!1===e?" without using h264 codec":"")},SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:function(e){var t=e.isSize,n=e.name,r=e.timesInSecond,i=e.maxSizeInSecond;return"api ".concat(n," call ").concat(t?"size":"times"," is over ").concat(t?"".concat(i," bytes"):r," in a second.")},CONNECTION_ABORTED:function(e){return"connection aborted due to: ".concat(e)},API_CALL_ABORTED:function(e){return e.message.includes("REMOTE_STREAM_NOT_EXIST")?"Subscribe ".concat(e.userId," ").concat(e.streamType," stream aborted, reason: remote user ").concat(e.userId," unpublished stream."):"API aborted, reason: ".concat(e.message)},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:function(e){return"'streamType' is required when 'userId' is not '*', calling ".concat(e,"()")}},JO=function(e,t){return t?"".concat(oC,"/").concat(e,"/").concat(t):"".concat(oC,"/").concat(e,"/index.html")},KO=function(){if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};var e=null==localStorage?void 0:localStorage.getItem(dC);if(e){e=JSON.parse(e);var t=document.createElement("script");t.type="text/javascript",t.text=e.message,document.body.appendChild(t);var n=window.TRTC_ERROR_INFO,r=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:n,TRTC_ERROR_LINK:r}}return{}};function YO(e){var t=e.key,n=e.data,r=e.link,i=e.addDocLink,a=void 0===i||i,o="",s="",c="";Jw(GO[t])?o=GO[t](n):Yw(GO[t])&&(o=GO[t]);var u=KO(),l=u.TRTC_ERROR_INFO,d=u.TRTC_ERROR_LINK;r?c="".concat(r.className,".html#").concat(r.fnName):d&&d[t]&&(Jw(d[t])?c=d[t](n):Yw(d[t])&&(c=d[t]));var h=o;return Bw()&&(l&&l[t]&&(Jw(l[t])?s=l[t](n):Yw(l[t])&&(s=l[t])),s&&(h=a?"".concat(s,"\n请查看文档: ").concat(JO("zh-cn",c),"\n\n"):"".concat(s,"\n\n"),h+=o)),a&&(h+=" \nRefer to: ".concat(JO("en",c),"\n")),h}var zO,qO=kA(DA(),1),XO=function(){return o((function e(){var t=this;r(this,e);var n=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];SA(this,"countMap",new Map),SA(this,"distributionMap",new Map),SA(this,"version"),SA(this,"log",Ux.createLogger({id:"kv"})),n&&(Px.on("102",(function(e){var n=e.track,r=e.cost;t.addSuccessEvent({key:n.kind===IC.AUDIO?501700:511700,cost:r})})),Px.on("103",(function(e){var n=e.track,r=e.error;t.addFailedEvent({key:n.kind===IC.AUDIO?501700:511700,error:r})})))}),[{key:"getReportData",value:function(){var e={msg_sdk_basic_info:{uint32_sdk_version:SD(this.version||YA),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:E(this.countMap.entries()).map((function(e){var t=v(e,2);return{uint32_key:t[0],uint32_count:t[1]}})),stats_distribution:E(this.distributionMap.entries()).map((function(e){var t=v(e,2);return{uint32_key:t[0],distribution_items:E(t[1].entries()).map((function(e){var t=v(e,2);return{uint32_item_key:t[0],uint32_item_value:t[1]}}))}}))};return this.countMap.clear(),this.distributionMap.clear(),e}},{key:"clear",value:function(){this.countMap.clear(),this.distributionMap.clear()}},{key:"isEnumKey",value:function(e){var t=+String(e).slice(-3);return t>=700&&t<799}},{key:"isErrorCodeKey",value:function(e){var t=+String(e).slice(-3);return t>=600&&t<699}},{key:"isCountKey",value:function(e){var t=+String(e).slice(-3);return t>=0&&t<599}},{key:"isNumberKey",value:function(e){var t=+String(e).slice(-3);return t>=800&&t<899}},{key:"addCount",value:function(e){var t=e.key,n=e.useUV,r=void 0!==n&&n;this.isCountKey(t)?r&&this.countMap.has(t)||this.countMap.set(t,(this.countMap.get(t)||0)+1):this.log.debug("".concat(t," is not count key, last 3 number should be 0~599"))}},{key:"addEnum",value:function(e){var t,n=e.key,r=e.value,i=e.useUV,a=void 0===i||i;if(!this.isEnumKey(n))return this.log.debug("".concat(n," is not enum key, last 3 number should be 700~799"));if(!a||!this.countMap.has(n)){this.countMap.set(n,(this.countMap.get(n)||0)+1);var o=(null==(t=this.distributionMap)?void 0:t.get(n))||new Map;o.set(r,(o.get(r)||0)+1),this.distributionMap.set(n,o)}}},{key:"addNumber",value:function(e){var t,n=e.key,r=e.value,i=e.split,a=void 0===i?100:i,o=e.useUV,s=void 0!==o&&o,c=e.max,u=void 0===c?5e3:c;if(!this.isNumberKey(n))return this.log.debug("".concat(n," is not number key, last 3 number should be 800~899"));if(!s||!this.countMap.has(n)){r>u&&(r=u),this.countMap.set(n,(this.countMap.get(n)||0)+1);var l=(null==(t=this.distributionMap)?void 0:t.get(n))||new Map,d=0;if(zw(a))d=Math.floor(r/a);else for(var h=a.length-1;h>0;h--)if(r>a[h]){d=h;break}l.set(d,(l.get(d)||0)+1),this.distributionMap.set(n,l)}}},{key:"addSuccessEvent",value:function(e){var t=e.key,n=e.cost,r=e.timeKey,i=e.split;if(t&&(this.addEnum({key:t,value:1,useUV:!1}),n)){var a=+String(t).slice(-3);a<800&&a>=700?this.addNumber({key:r||t+100,value:n,split:i}):r||this.log.debug("time stat ignored, ".concat(t))}}},{key:"addFailedEvent",value:function(e){var t=e.key,n=e.error;if(t){var r=VA.UNKNOWN;n&&(zw(n)?r=n:(!Kw(n.extraCode)||!Kw(n.code))&&(r=n.extraCode||n.code)),this.addEnum({key:t,value:0,useUV:!1}),this.addEnum({key:t,value:Math.abs(r),useUV:!1})}}}])}(),QO=((zO=QO||{})[zO.enterRoom=500700]="enterRoom",zO[zO.exitRoom=500701]="exitRoom",zO[zO.switchRole=500702]="switchRole",zO[zO.destroy=500703]="destroy",zO[zO.startLocalAudio=500704]="startLocalAudio",zO[zO.updateLocalAudio=500705]="updateLocalAudio",zO[zO.stopLocalAudio=500706]="stopLocalAudio",zO[zO.startLocalVideo=500707]="startLocalVideo",zO[zO.updateLocalVideo=500708]="updateLocalVideo",zO[zO.stopLocalVideo=500709]="stopLocalVideo",zO[zO.startScreenShare=500710]="startScreenShare",zO[zO.updateScreenShare=500711]="updateScreenShare",zO[zO.stopScreenShare=500712]="stopScreenShare",zO[zO.startRemoteVideo=500713]="startRemoteVideo",zO[zO.updateRemoteVideo=500714]="updateRemoteVideo",zO[zO.stopRemoteVideo=500715]="stopRemoteVideo",zO[zO.muteRemoteAudio=500716]="muteRemoteAudio",zO[zO.setRemoteAudioVolume=500717]="setRemoteAudioVolume",zO[zO.use=500718]="use",zO[zO.switchRoom=500719]="switchRoom",zO[zO.sendSEIMessage=5e5]="sendSEIMessage",zO[zO.sendCustomMessage=500001]="sendCustomMessage",zO),ZO=function(e){return e[e.AudioMixer=550700]="AudioMixer",e[e.AIDenoiser=551700]="AIDenoiser",e[e.VirtualBackground=570700]="VirtualBackground",e[e.Beauty=571700]="Beauty",e[e.Watermark=572700]="Watermark",e[e.BasicBeauty=574700]="BasicBeauty",e[e.CDNStreaming=590700]="CDNStreaming",e[e.DeviceDetector=591700]="DeviceDetector",e[e.Debug=592700]="Debug",e[e.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",e[e.VideoMixer=594700]="VideoMixer",e[e.AudioProcessor=595700]="AudioProcessor",e}(ZO||{}),$O=function(e){return e[e.AudioMixer=550701]="AudioMixer",e[e.AIDenoiser=551701]="AIDenoiser",e[e.VirtualBackground=570701]="VirtualBackground",e[e.Beauty=571701]="Beauty",e[e.Watermark=572701]="Watermark",e[e.BasicBeauty=574701]="BasicBeauty",e[e.CDNStreaming=590701]="CDNStreaming",e[e.DeviceDetector=591701]="DeviceDetector",e[e.Debug=592701]="Debug",e[e.SmallStreamAutoSwitcher=593701]="SmallStreamAutoSwitcher",e[e.VideoMixer=594701]="VideoMixer",e[e.AudioProcessor=595701]="AudioProcessor",e}($O||{}),eP=function(e){return e[e.AudioMixer=550702]="AudioMixer",e[e.AIDenoiser=551702]="AIDenoiser",e[e.VirtualBackground=570702]="VirtualBackground",e[e.Beauty=571702]="Beauty",e[e.Watermark=572702]="Watermark",e[e.BasicBeauty=574702]="BasicBeauty",e[e.CDNStreaming=590702]="CDNStreaming",e[e.DeviceDetector=591702]="DeviceDetector",e[e.Debug=592702]="Debug",e[e.SmallStreamAutoSwitcher=593702]="SmallStreamAutoSwitcher",e[e.VideoMixer=594702]="VideoMixer",e[e.AudioProcessor=595702]="AudioProcessor",e}(eP||{}),tP=new XO(!0),nP=new XO(!1),rP=tP,iP={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},aP=new Map([[rN,["Firefox",iN]],[cN,["Edg",uN]],[nx,["Chrome",ax]],[ox,["Safari",cx]],[mN,["TBS",vN]],[_N,["XWEB",gN]],[TN&&XD,["WeChat",SN]],[AN,["QQ(Win)",CN]],[bN,["QQ(Mobile)",RN]],[IN,["QQ(Mobile X5)",RN]],[wN,["QQ(Mac)",DN]],[NN,["QQ(iPad)",xN]],[BN,["MI",HN]],[WN,["HW",JN]],[KN,["Samsung",YN]],[zN,["OPPO",qN]],[XN,["VIVO",QN]],[oN,["EDGE",sN]],[dN,["SogouMobile",hN]],[fN,["Sogou",pN]]]);function oP(){var e=aP.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var sP=function(){return!(UN||oN||cN&&lN<80||rN&&aN<56)},cP=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every((function(e){return e in window}))},uP=function(){if(!navigator.mediaDevices)return dP()||Ux.error(GO.NOT_SUPPORTED_MEDIA),!1;var e=["getUserMedia","enumerateDevices"];return e.filter((function(e){return e in navigator.mediaDevices})).length===e.length},lP=!1;function dP(){return"http:"===location.protocol&&!gx&&(lP||Ux.error(YO({key:jO.NOT_SUPPORTED_HTTP})),lP=!0,!0)}var hP=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},fP=function(){return bA(this,null,f().mark((function e(){var t,n,r,i,a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!iP.detail.isH264EncodeSupported||!iP.detail.isVp8EncodeSupported){e.next=2;break}return e.abrupt("return",{isH264EncodeSupported:iP.detail.isH264EncodeSupported,isVp8EncodeSupported:iP.detail.isVp8EncodeSupported});case 2:return n=!1,r=!1,e.prev=3,i=new RTCPeerConnection,(a=document.createElement(IC.CANVAS)).getContext("2d"),o=a.captureStream(0),i.addTrack(o.getVideoTracks()[0],o),e.next=10,i.createOffer();case 10:return-1!==(t=e.sent).sdp.toLowerCase().indexOf("h264")&&(n=!0),-1!==t.sdp.toLowerCase().indexOf("vp8")&&(r=!0),i.close(),iP.detail.isH264EncodeSupported=n,iP.detail.isVp8EncodeSupported=r,e.abrupt("return",{isH264EncodeSupported:iP.detail.isH264EncodeSupported,isVp8EncodeSupported:iP.detail.isVp8EncodeSupported});case 19:return e.prev=19,e.t0=e.catch(3),e.abrupt("return",{isH264EncodeSupported:!1,isVp8EncodeSupported:!1});case 22:case"end":return e.stop()}}),e,null,[[3,19]])})))},pP=function(){return bA(this,null,f().mark((function e(){var t,n,r,i;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!iP.detail.isH264DecodeSupported||!iP.detail.isVp8DecodeSupported){e.next=2;break}return e.abrupt("return",{isH264DecodeSupported:iP.detail.isH264DecodeSupported,isVp8DecodeSupported:iP.detail.isVp8DecodeSupported});case 2:if(n=!1,r=!1,e.prev=3,i=new RTCPeerConnection,!xP()){e.next=12;break}return i.addTransceiver(IC.VIDEO,{direction:"recvonly"}),e.next=9,i.createOffer();case 9:t=e.sent,e.next=15;break;case 12:return e.next=14,i.createOffer({offerToReceiveVideo:!0});case 14:t=e.sent;case 15:return-1!==t.sdp.toLowerCase().indexOf("h264")&&(n=!0),-1!==t.sdp.toLowerCase().indexOf("vp8")&&(r=!0),i.close(),e.abrupt("return",{isH264DecodeSupported:n,isVp8DecodeSupported:r});case 21:return e.prev=21,e.t0=e.catch(3),e.abrupt("return",{isH264DecodeSupported:!1,isVp8DecodeSupported:!1});case 24:case"end":return e.stop()}}),e,null,[[3,21]])})))},mP=RD((function(){return bA(void 0,null,f().mark((function e(){var t,n,r,i,a,o,s,c,u,l,d,h,p,m,_,g,y;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(iP.result&&iP.detail.isH264EncodeSupported&&iP.detail.isVp8EncodeSupported&&iP.detail.isH264DecodeSupported&&iP.detail.isVp8DecodeSupported)){e.next=2;break}return e.abrupt("return",iP);case 2:return t=Date.now(),n=sP(),r=GP(),i=cP(),a=uP(),e.next=9,Promise.all([fP(),pP()]);case 9:if(o=e.sent,s=v(o,2),c=s[0],u=c.isH264EncodeSupported,l=c.isVp8EncodeSupported,d=s[1],h=d.isH264DecodeSupported,p=d.isVp8DecodeSupported,u&&l){e.next=22;break}return e.next=20,fP();case 20:m=e.sent,Ux.warn("detect encode again h264:".concat(u," vp8:").concat(l," result: ").concat(JSON.stringify(m))),u=m.isH264EncodeSupported,l=m.isVp8EncodeSupported;case 22:if(!(u&&h&&$D&&tx)||_N||mN){e.next=29;break}return e.next=25,function(){return bA(this,null,f().mark((function e(){var t=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",gP||(gP=new Promise((function(e){return bA(t,null,f().mark((function t(){var n,r,i,a,o,s,c,u,l,d,h,p,m,_,g=this;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n={encode:!1,decode:!1},r=function(){},t.prev=1,i=document.createElement("canvas"),a=i.getContext("2d"),i.width=320,i.height=240,o=setInterval((function(){a.fillText("test",Math.floor(320*Math.random()),Math.floor(240*Math.random()))}),66),s=-1,c=-1,r=function(){clearInterval(s),clearInterval(o),clearTimeout(c),l.close(),d.close(),u.getTracks().forEach((function(e){return e.stop()}))},c=setTimeout((function(){r(),e(n)}),2e3),u=i.captureStream(),l=new RTCPeerConnection({}),d=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),l.addEventListener("icecandidate",(function(e){return d.addIceCandidate(e.candidate)})),d.addEventListener("icecandidate",(function(e){return l.addIceCandidate(e.candidate)})),l.addTrack(u.getVideoTracks()[0],u),t.next=10,l.createOffer();case 10:return h=t.sent,t.next=13,l.setLocalDescription(h);case 13:return t.next=15,d.setRemoteDescription(h);case 15:return t.next=17,d.createAnswer();case 17:return p=t.sent,m=qO.default.parse(p.sdp),_=m.media[0].rtp.findIndex((function(e){return"H264"===e.codec})),m.media[0].rtp=[m.media[0].rtp[_]],m.media[0].fmtp=m.media[0].fmtp.filter((function(e){return e.payload===m.media[0].rtp[0].payload})),m.media[0].rtcpFb&&(m.media[0].rtcpFb=m.media[0].rtcpFb.filter((function(e){return e.payload===m.media[0].rtp[0].payload}))),p.sdp=qO.default.write(m),t.next=26,d.setLocalDescription(p);case 26:return t.next=28,l.setRemoteDescription(p);case 28:s=setInterval((function(){return bA(g,null,f().mark((function t(){var i,a,o,s;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n.encode&&n.decode&&(r(),e(n)),t.next=3,Promise.all([l.getSenders()[0].getStats(),d.getReceivers()[0].getStats()]);case 3:i=t.sent,a=v(i,2),o=a[0],s=a[1],n.encode||o.forEach((function(e){"outbound-rtp"===e.type&&e.mediaType===IC.VIDEO&&e.bytesSent>0&&(n.encode=!0)})),n.decode||s.forEach((function(e){"inbound-rtp"===e.type&&e.mediaType===IC.VIDEO&&e.bytesReceived>0&&(n.decode=!0)}));case 8:case"end":return t.stop()}}),t)})))}),100),t.next=34;break;case 31:t.prev=31,t.t0=t.catch(1),r(),Ux.warn("detectH264Supported failed",t.t0),e({encode:!0,decode:!0});case 34:case"end":return t.stop()}}),t,null,[[1,31]])})))})).then((function(e){return e.encode||(e.decode=!0),(!e.encode||!e.decode)&&Ux.warn("detectH264Supported encode: ".concat(e.encode," decode: ").concat(e.decode," ").concat(Ix)),e})),gP));case 1:case"end":return e.stop()}}),e)})))}();case 25:_=e.sent,g=_.encode,y=_.decode,u=g,h=y;case 29:return e.abrupt("return",(iP.result=n&&r&&a&&(u||l)&&(h||p),iP.detail.isBrowserSupported=n,iP.detail.isWebRTCSupported=r,iP.detail.isWebCodecsSupported=i,iP.detail.isMediaDevicesSupported=a,iP.detail.isScreenShareSupported=_P(),iP.detail.isSmallStreamSupported=AP(),iP.detail.isH264EncodeSupported=u,iP.detail.isVp8EncodeSupported=l,iP.detail.isH264DecodeSupported=h,iP.detail.isVp8DecodeSupported=p,iP.result||Ux.error("".concat(navigator.userAgent," ").concat(yD(iP.detail,!1))),Bx.setItem(XP,{ua:navigator.userAgent,checkResult:iP}),rP.addNumber({key:523800,value:Date.now()-t}),iP));case 30:case"end":return e.stop()}}),e)})))})),vP=function(){return iP.result},_P=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},gP=null,yP=function(e,t,n){"http:"===location.protocol&&!gx&&(e[t]=function(){throw new FA({code:VA.INVALID_OPERATION,message:GO.NOT_SUPPORTED_HTTP})})},EP=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state||qw(e.selected)&&!e.selected)};function kP(){var e="";if(screen.width){var t=screen.width?screen.width*window.devicePixelRatio:"",n=screen.height?screen.height*window.devicePixelRatio:"";e+="".concat(t," * ").concat(n)}return e}function TP(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function SP(){for(var e={isSupported:!1},t=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"],n=0;n<t.length;n++)if(t[n]in window){e.isSupported=!0;break}return e.isSupported}function IP(){return"captureStream"in HTMLCanvasElement.prototype}function bP(){return!(TN||ZD||ix&&ix<63||!sP()||!IP())}function RP(){return!(ix<74||oN||hx<11||aN<46)}function AP(){return bP()||RP()}var CP=function(){if(Kw(window.RTCRtpTransceiver)||!xP()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;var e=null,t=!1;try{(e=new RTCPeerConnection({sdpSemantics:iw})).addTransceiver(IC.AUDIO),t=!0}catch(qA){}return null==e||e.close(),t};function wP(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function DP(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function NP(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function xP(){return!(11===hx&&!_x)&&"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var OP=!(!xP()||tx&&ix<86);function PP(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var MP="RTCRtpSender"in window;function LP(){return MP&&"replaceTrack"in window.RTCRtpSender.prototype}function VP(){return MP&&"setParameters"in window.RTCRtpSender.prototype&&DP()}var UP="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,FP=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,BP=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,HP=MP&&"createEncodedStreams"in window.RTCRtpSender.prototype&&ex()>=86,WP="RTCRtpScriptTransform"in window,jP=MP&&(HP||WP),GP=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((function(e){return e in window})).length>0};function JP(){var e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return Kw(window.AudioDecoder)||(e.AudioDecoder=!0),Kw(window.AudioEncoder)||(e.AudioEncoder=!0),Kw(window.VideoDecoder)||(e.VideoDecoder=!0),Kw(window.VideoEncoder)||(e.VideoEncoder=!0),Kw(window.ImageDecoder)||(e.ImageDecoder=!0),e}function KP(){return"mediaSession"in navigator&&!Kw(navigator.mediaSession.setActionHandler)}function YP(){return!Kw(window.WebTransport)}function zP(){return"undefined"!=typeof WebAssembly&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}function qP(){var e={browser:"".concat(Ex.name,"/").concat(Ex.version),os:wx(),displayResolution:kP(),isScreenShareSupported:_P(),isWebRTCSupported:GP(),isGetUserMediaSupported:TP(),isWebAudioSupported:SP(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:JP(),isMediaSessionSupported:KP(),isWebTransportSupported:YP()};return navigator.userAgent.includes("miniProgram")&&(e.browser="mini/".concat(e.browser)),e}var XP="checkResult";function QP(){dP();var e=Bx.getItem(XP);e&&e.ua===navigator.userAgent&&(iP=e.checkResult),mP()}function ZP(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var $P="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype,eM=kA(RA(),1),tM=Symbol("instance"),nM=Symbol("cacheResult"),rM=function(){return o((function e(t,n,i){r(this,e),this.oldState=t,this.newState=n,this.action=i,this.aborted=!1}),[{key:"abort",value:function(e){this.aborted=!0,cM.call(e,this.oldState,new Error("action '".concat(this.action,"' aborted")))}},{key:"toString",value:function(){return"".concat(this.action,"ing")}}])}(),iM=function(e){function t(e,i,a){var o;return r(this,t),(o=n(this,t,[i])).state=e,o.message=i,o.cause=a,o}return d(t,e),o(t)}(I(Error)),aM=new Map;function oM(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function(r,i,a){var o=n.action||i;if(!n.context){var s=aM.get(r)||[];aM.has(r)||aM.set(r,s),s.push({from:e,to:t,action:o})}var c=a.value;a.value=function(){for(var r,i=this,a=this,s=arguments.length,u=new Array(s),l=0;l<s;l++)u[l]=arguments[l];if(n.context&&(a=uM.get("function"==typeof n.context?(r=n.context).call.apply(r,[this].concat(u)):n.context)),a.state===t)return n.sync?a[nM]:Promise.resolve(a[nM]);a.state instanceof rM&&a.state.action==n.abortAction&&a.state.abort(a);var d=null;Array.isArray(e)?0==e.length?a.state instanceof rM&&a.state.abort(a):("string"!=typeof a.state||!e.includes(a.state))&&(d=new iM(a._state,"".concat(a.name," ").concat(o," to ").concat(t," failed: current state ").concat(a._state," not from ").concat(e.join("|")))):e!==a.state&&(d=new iM(a._state,"".concat(a.name," ").concat(o," to ").concat(t," failed: current state ").concat(a._state," not from ").concat(e)));var h=function(e){if(n.fail&&n.fail.call(i,e),n.sync){if(n.ignoreError)return e;throw e}return n.ignoreError?Promise.resolve(e):Promise.reject(e)};if(d)return h(d);var f=a.state,p=new rM(f,t,o);cM.call(a,p);var m=function(e){var r;return a[nM]=e,p.aborted||(cM.call(a,t),null===(r=n.success)||void 0===r||r.call(i,a[nM])),e},v=function(e){return cM.call(a,f,e),h(e)};try{var _=c.apply(this,u);return function(e){return"object"==T(e)&&e&&"then"in e}(_)?_.then(m).catch(v):n.sync?m(_):Promise.resolve(m(_))}catch(Qx){return v(new iM(a._state,"".concat(a.name," ").concat(o," from ").concat(e," to ").concat(t," failed: ").concat(Qx),Qx instanceof Error?Qx:new Error(String(Qx))))}}}}var sM="undefined"!=typeof window&&window.__AFSM__?function(e,t){window.dispatchEvent(new CustomEvent(e,{detail:t}))}:"undefined"!=typeof importScripts?function(e,t){postMessage({type:e,payload:t})}:function(){};function cM(e,t){var n=this._state;this._state=e;var r=e.toString();e&&this.emit(r,n),this.emit(uM.STATECHANGED,e,n,t),this.updateDevTools({value:e,old:n,err:t instanceof Error?t.message:String(t)})}var uM=function(e){function i(e,a,o){var s;r(this,i),(s=n(this,i)).name=e,s.groupName=a,s._state=i.INIT,e||(e=Date.now().toString(36)),o?Object.setPrototypeOf(t(s),o):o=Object.getPrototypeOf(t(s)),a||(s.groupName=s.constructor.name);var c=o[tM];return c?s.name=c.name+"-"+c.count++:o[tM]={name:s.name,count:0},s.updateDevTools({diagram:s.stateDiagram}),s}return d(i,e),o(i,[{key:"stateDiagram",get:function(){var e=Object.getPrototypeOf(this),t=aM.get(e)||[],n=new Set,r=[],i=[],a=new Set,o=Object.getPrototypeOf(e);aM.has(o)&&(o.stateDiagram.forEach((function(e){return n.add(e)})),o.allStates.forEach((function(e){return a.add(e)}))),t.forEach((function(e){var t=e.from,n=e.to,a=e.action;"string"==typeof t?r.push({from:t,to:n,action:a}):t.length?t.forEach((function(e){r.push({from:e,to:n,action:a})})):i.push({to:n,action:a})})),r.forEach((function(e){var t=e.from,r=e.to,i=e.action;a.add(t),a.add(r),a.add(i+"ing"),n.add("".concat(t," --\x3e ").concat(i,"ing : ").concat(i)),n.add("".concat(i,"ing --\x3e ").concat(r," : ").concat(i," 🟢")),n.add("".concat(i,"ing --\x3e ").concat(t," : ").concat(i," 🔴"))})),i.forEach((function(e){var t=e.to,r=e.action;n.add("".concat(r,"ing --\x3e ").concat(t," : ").concat(r," 🟢")),a.forEach((function(e){e!==t&&n.add("".concat(e," --\x3e ").concat(r,"ing : ").concat(r))}))}));var s=E(n);return Object.defineProperties(e,{stateDiagram:{value:s},allStates:{value:a}}),s}},{key:"updateDevTools",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};sM(i.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}},{key:"state",get:function(){return this._state},set:function(e){cM.call(this,e)}}],[{key:"get",value:function(e){var t;return"string"==typeof e?(t=i.instances.get(e))||i.instances.set(e,t=new i(e,void 0,Object.create(i.prototype))):(t=i.instances2.get(e))||i.instances2.set(e,t=new i(e.constructor.name,void 0,Object.create(i.prototype))),t}},{key:"getState",value:function(e){var t;return null===(t=i.get(e))||void 0===t?void 0:t.state}}])}(eM.default);uM.STATECHANGED="stateChanged",uM.UPDATEAFSM="updateAFSM",uM.INIT="[*]",uM.ON="on",uM.OFF="off",uM.instances=new Map,uM.instances2=new WeakMap;var lM="undefined"!=typeof window,dM=lM&&window.requestIdleCallback||function(e){var t=Date.now();return setTimeout((function(){e({didTimeout:!1,timeRemaining:function(){return Math.max(0,50-(Date.now()-t))}})}),1e3)},hM=lM&&window.cancelIdleCallback||function(e){clearTimeout(e)},fM=lM&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),pM=function(){function e(){r(this,e)}return o(e,null,[{key:"generateTaskID",value:function(){return this.currentTaskID++}},{key:"run",value:function(e,t,n){null!=n&&n.fps&&(n.delay=n.delay||Number((1e3/n.fps).toFixed(2))),n=_A("interval"===e?{delay:2e3,count:0,backgroundTask:!0}:"ric"===e?{delay:1e4,count:0}:"raf"===e?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},n);var r=gA(_A({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:t},n),{delay:n.delay});return this.taskMap.set(r.taskID,r),this[e](r),r.taskID}},{key:"interval",value:function(t){return t.intervalID=setInterval((function(){t.callback(),t.loopCount+=1,e.isBreakLoop(t)}),t.delay)}},{key:"intervalInWorker",value:function(t){e.sharedWorker||(e.sharedWorker=new Worker(URL.createObjectURL(new Blob(["\n const timers = new Map();\n self.onmessage = function(e) {\n const { taskId, delay, type } = e.data;\n if (type === 'start') {\n timers.set(taskId, setInterval(() => {\n self.postMessage({ type: 'tick', taskId });\n }, delay));\n } else if (type === 'stop') {\n clearInterval(timers.get(taskId));\n timers.delete(taskId);\n }\n };\n "],{type:"application/javascript"}))),e.sharedWorker.onmessage=function(t){var n;if("tick"===t.data.type){var r=e.workerTasks.get(t.data.taskId);r&&(e.isBreakLoop(r)?(null==(n=e.sharedWorker)||n.postMessage({type:"stop",taskId:r.taskID}),e.workerTasks.delete(r.taskID)):(r.callback(),r.loopCount+=1))}}),e.workerTasks.set(t.taskID,t),e.sharedWorker.postMessage({taskId:t.taskID,delay:t.delay,type:"start"})}},{key:"timeout",value:function(t){var n=function(){if(t.callback(),t.loopCount+=1,!e.isBreakLoop(t))return t.timeoutID=setTimeout(n,t.delay)};return t.timeoutID=setTimeout(n,t.delay)}},{key:"ric",value:function(t){var n,r=aD(),i=function(){if((n=aD()-r)>=t.delay&&(r=aD()-Math.floor(n%t.delay),t.callback(),t.loopCount+=1),!e.isBreakLoop(t))return t.ricID=dM(i,{timeout:t.delay})};return t.ricID=dM(i,{timeout:t.delay})}},{key:"raf",value:function(t){var n,r=aD(),i=function(){return document.hidden&&t.backgroundTask?(n=aD()-r,r=aD(),t.callback(),t.loopCount+=1,e.isBreakLoop(t)?void 0:t.timeoutID=setTimeout(i,t.delay-Math.floor(n%t.delay))):((n=aD()-r)>=t.delay&&(r=aD()-Math.floor(n%t.delay),t.callback(),t.loopCount+=1),e.isBreakLoop(t)?void 0:t.rafID=requestAnimationFrame(i))};if(t.rafID=requestAnimationFrame(i),t.backgroundTask){var a=function(){if(document.hidden){var e=aD()-r;e>=t.delay?i():t.timeoutID=setTimeout(i,t.delay-e)}};document.addEventListener("visibilitychange",a),t.onVisibilitychange=a,document.hidden&&a()}return t.taskID}},{key:"hasTask",value:function(e){return this.taskMap.has(e)}},{key:"clearTask",value:function(e){if(!this.taskMap.has(e))return!0;var t=this.taskMap.get(e),n=t.intervalID,r=t.timeoutID,i=t.rafID,a=t.ricID,o=t.onVisibilitychange;return n&&clearInterval(n),r&&clearTimeout(r),i&&fM&&fM(i),a&&hM(a),o&&document.removeEventListener("visibilitychange",o),this.taskMap.delete(e),!0}},{key:"isBreakLoop",value:function(e){return!this.hasTask(e.taskID)||0!==e.count&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}}])}();SA(pM,"taskMap",new Map),SA(pM,"currentTaskID",1),SA(pM,"sharedWorker",null),SA(pM,"workerTasks",new Map);var mM=pM;IC.SEI_MESSAGE;var vM={LOADED_DATA:IC.LOADEDDATA,LOADED_META_DATA:IC.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"},_M={};EA(_M,{create:function(){return yM},remove:function(){return EM}});var gM=new WeakMap;function yM(e,t){gM.has(e)||gM.set(e,[]);var n=gM.get(e),r={add:function(e,i){return"addEventListener"in t?(n.push(t.removeEventListener.bind(t,e,i)),t.addEventListener(e,i)):(n.push(t.off.bind(t,e,i)),t.on(e,i)),r}};return r}function EM(e){var t=gM.get(e);t&&(t.forEach((function(e){return e()})),gM.delete(e))}var kM=new(function(){return o((function e(){r(this,e),SA(this,"_roomIdMap",new Map),SA(this,"_configs"),"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:YA,env:fC.QCLOUD,browserVersion:Ex.name+Ex.version,ua:navigator.userAgent})}),[{key:"setConfig",value:function(e){var t=e.sdkAppId,n=e.env,r=e.userId,i=e.roomId;t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=n,this._configs.userId=r,this._roomIdMap.set(r,String(i))}},{key:"logSuccessEvent",value:function(e){gx||!Ux.isAbleToUpload||this._configs.env===fC.QCLOUD&&this.uploadEventToKibana(gA(_A({},e),{result:"success"}))}},{key:"logFailedEvent",value:function(e){if(!gx&&Ux.isAbleToUpload){var t=e.eventType,n=e.code,r=e.error,i=e.userId,a={roomId:this._roomIdMap.get(i||this._configs.userId),userId:i,eventType:t,result:"failed",code:n||(null==r?void 0:r.extraCode)||(null==r?void 0:r.code)||VA.UNKNOWN};this._configs.env===fC.QCLOUD&&this.uploadEventToKibana(gA(_A({},a),{error:r}))}}},{key:"uploadEventToKibana",value:function(e){var t="stat-".concat(e.eventType,"-").concat(e.result);("delta-join"===e.eventType||"delta-leave"===e.eventType||"delta-publish"===e.eventType)&&(t="".concat(e.eventType,":").concat(e.delta)),this.uploadEvent({log:t,userId:e.userId}),"failed"===e.result&&(t="stat-".concat(e.eventType,"-").concat(e.result,"-").concat(e.code),this.uploadEvent({log:t,userId:e.userId,error:e.error}))}},{key:"uploadEvent",value:function(e){var t=e.log,n=e.userId,r=e.error,i={timestamp:WA(),sdkAppId:this._configs.sdkAppId,userId:n||this._configs.userId,version:YA,log:t};r&&(i.errorInfo=r.message,r.stack&&(i.errorInfo+="\n".concat(r.stack))),this.sendRequest(Cw(this._configs.sdkAppId,hC.LOG),i)}},{key:"sendRequest",value:function(e,t){setTimeout((function(){return ND({url:e,body:JSON.stringify(t),priority:"low"}).catch((function(){}))}),2e3)}}])}()),TM=new WeakMap;function SM(e){var t=e.settings,n=void 0===t?{retries:5,timeout:2e3}:t,r=e.onError,i=e.onRetrying,a=e.onRetryFailed;return function(e,t,o){var s=FD({retryFunction:o.value,settings:n,onError:function(n){var i,a=n.error,o=n.retry,s=n.reject,c=n.retryFuncArgs;r?r.call(this,a,(function(){var n;null!=(n=TM.get(e))&&n.has(t)?o():s(a)}),s,c):null!=(i=TM.get(e))&&i.has(t)?o():s(a)},onRetrying:function(n,r){var a;PD(i)&&i.call(this,n,r),null!=(a=TM.get(e))&&a.has(t)&&(TM.get(e).get(t).stopRetry=r)},onRetryFailed:a});return o.value=function(){for(var n=TM.get(e),r=arguments.length,i=new Array(r),a=0;a<r;a++)i[a]=arguments[a];return n?n.set(t,{args:i}):TM.set(e,new Map([[t,{args:i}]])),s.apply(this,i).finally((function(){var n;return null==(n=TM.get(e))?void 0:n.delete(t)}))},o}}function IM(e){var t=e.fnName,n=e.callback,r=e.validateArgs,i=void 0===r||r;return function(e,r,a){var o=a.value;return a.value=function(){for(var r,a,c=arguments.length,u=new Array(c),l=0;l<c;l++)u[l]=arguments[l];if(null!=(r=TM.get(e))&&r.has(t)){var d=TM.get(e).get(t),h=d.stopRetry,f=d.args,p=!0;if(i){var m,v=s(f);try{var _=function(){var e=m.value;if(!u.find((function(t){return t===e})))return p=!1,1};for(v.s();!(m=v.n()).done&&!_(););}catch(g){v.e(g)}finally{v.f()}}p&&(n&&n.apply(this,u),h&&h(),null==(a=TM.get(e))||a.delete(t))}return o.apply(this,u)},a}}var bM=function(e){function i(e,a){var o;return r(this,i),(o=n(this,i,[e.id,"".concat(a,"-player")])).kind=a,SA(t(o),"id"),SA(t(o),"element",null),SA(t(o),"track"),SA(t(o),"url"),SA(t(o),"attr"),SA(t(o),"mode"),SA(t(o),"muted"),SA(t(o),"_log"),SA(t(o),"_pausedRetryCount"),SA(t(o),"_isElementPlayingFired",!1),SA(t(o),"_interval"),SA(t(o),"_delayDestroyTimeoutId",0),SA(t(o),"_playSuccessResolve"),SA(t(o),"_isReplayByRecreateMediaStreamCalled",!1),SA(t(o),"isInAutoPlayFailedState",!1),o.id=e.id,o._log=e.log,o.track=e.track,o.muted=e.muted,o._pausedRetryCount=vw,o._state="STOPPED",o.bindTrackEvents(),o._log.info("create ".concat(a,"-player ").concat(o.id)),o}return d(i,e),o(i,[{key:"isPlaying",get:function(){var e;return"PLAYING"===this._state&&!1===(null==(e=this.element)?void 0:e.paused)}},{key:"isPaused",get:function(){var e;return"PAUSED"===this._state||!0===(null==(e=this.element)?void 0:e.paused)}},{key:"isStopped",get:function(){return"STOPPED"===this._state}},{key:"setAttr",value:function(e){this.attr=e}},{key:"setUrl",value:function(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,null!==e&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}},{key:"play",value:function(){return bA(this,null,f().mark((function e(){var t,n=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.isPlaying){e.next=13;break}return e.prev=1,this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),e.next=6,new Promise((function(e,t){n._playSuccessResolve=e,n.element.play().then(e,t)}));case 6:e.next=13;break;case 8:if(e.prev=8,e.t0=e.catch(1),t=YO({key:jO.PLAY_FAILED,data:{media:this.kind,error:e.t0}}),this._log.warn(e.t0),!t.includes("NotAllowedError")){e.next=13;break}throw this.isInAutoPlayFailedState=!0,new FA({code:VA.PLAY_NOT_ALLOWED,message:t});case 13:case"end":return e.stop()}}),e,this,[[1,8]])})))}},{key:"stop",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this._isElementPlayingFired=!1,this.unbindEvents(),t>0&&!sx?this._delayDestroyTimeoutId||(this._log.info("destroy element after 3 * ".concat(t)),this._delayDestroyTimeoutId=setTimeout((function(){return e.destroyElement()}),3*t)):this.destroyElement(),this.handleStopped(IC.ENDED),this._interval>0&&mM.clearTask(this._interval)}},{key:"destroyElement",value:function(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}},{key:"pause",value:function(){var e;this.isPlaying&&(null==(e=this.element)||e.pause())}},{key:"resume",value:function(){return this._log.info("resume"),this.isPlaying?Promise.resolve():px?this.replay():this.play().catch((function(){}))}},{key:"setMuted",value:function(e){this.element&&(this.element.muted=e),this.muted=e}},{key:"replay",value:function(){return this.stop(),this.play().catch((function(){}))}},{key:"bindElementEvents",value:function(){if(this.element){var e=this.handleElementEvent.bind(this);return yM(this.element,this.element).add(IC.PLAYING,e).add(IC.ENDED,e).add(IC.PAUSE,e).add(IC.ERROR,e).add(IC.LOADEDDATA,e).add(IC.LOADEDMETADATA,e)}}},{key:"bindTrackEvents",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.track;if(e){var t=this.handleTrackEvent.bind(this);null==_M||_M.create(e,e).add(IC.ENDED,t).add(IC.MUTE,t).add(IC.UNMUTE,t),e.readyState===IC.ENDED&&this.handleTrackEvent({type:IC.ENDED}),e.muted&&this.handleTrackEvent({type:IC.MUTE})}}},{key:"bindAutoPlayEvent",value:function(){Px.on(Lx.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}},{key:"unbindTrackEvents",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.track;e&&EM(e)}},{key:"unbindEvents",value:function(){this.element&&EM(this.element),this.unbindTrackEvents(),Px.off(Lx.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}},{key:"handleElementEvent",value:function(e){var t=this;switch(e.type){case IC.PLAYING:this.isInAutoPlayFailedState=!1,this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(IC.PLAYING),this._interval&&(mM.clearTask(this._interval),this._interval=-1);break;case IC.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(IC.ENDED);break;case IC.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(IC.PAUSE),ZD&&(this._interval=mM.run("timeout",(function(){t.element&&"PAUSED"===t._state&&t.resume()}),{delay:3e3}));break;case IC.ERROR:if(this.element&&this.element.error){this.handlePaused(IC.ERROR);var n=this.element.error,r=n.code,i=n.message;this._log.error("".concat(this.kind," ").concat(this._log.isLocal?"local":"remote"," MediaError code: ").concat(r," message: ").concat(i," userAgent: ").concat(navigator.userAgent)),kM.uploadEvent({log:"stat-".concat(this.kind,"-").concat(ew.PLAYER_ERROR,"-").concat(r,"-").concat(navigator.userAgent),error:this.element.error}),GN||jN?this.emit(vM.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case IC.LOADEDDATA:this.kind===IC.VIDEO&&this.emit(vM.LOADED_DATA);break;case IC.LOADEDMETADATA:this.kind===IC.VIDEO&&this.emit(vM.LOADED_META_DATA)}}},{key:"replayByRecreateMediaStream",value:function(e){var t=this;if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then((function(){t._log.warn("replayByRecreateMediaStream success"),kM.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),rP.addSuccessEvent({key:t.kind===IC.AUDIO?506700:516700})})).catch((function(){var n;t._log.error("replayByRecreateMediaStream failed"),kM.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),rP.addFailedEvent({key:t.kind===IC.AUDIO?506700:516700,error:null==(n=t.element)?void 0:n.error}),t.emit(vM.ERROR,e)}))}},{key:"doReplayByRecreateMediaStream",value:function(e){var t=this;return this._log.warn("delay ".concat(e,"ms to recreate mediaStream")),new Promise((function(n,r){bD(e).then((function(){t.element&&(t.element.srcObject=null,t.element.srcObject=new MediaStream([t.track]),t._log.warn("recreated mediaStream"),t.element.onerror=function(){var e,n,i;t._log.warn("element onerror ".concat(null==(n=null==(e=t.element)?void 0:e.error)?void 0:n.code," fired after recreated mediaStream")),r(null==(i=t.element)?void 0:i.error)}),bD(5e3).then((function(){var e,i;(!t.isPlaying||null!=(e=t.element)&&e.error)&&r(null==(i=t.element)?void 0:i.error),n()}))}))})).finally((function(){t.element&&(t.element.onerror=null)}))}},{key:"handleTrackEvent",value:function(e){return bA(this,null,f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:t.t0=e.type,t.next=t.t0===IC.ENDED?3:t.t0===IC.MUTE?5:t.t0===IC.UNMUTE?7:19;break;case 3:return this.handleStopped(IC.ENDED),t.abrupt("break",19);case 5:return this.handlePaused(IC.MUTE),t.abrupt("break",19);case 7:if(!(this.mode>0)){t.next=11;break}this.handlePlaying(this.mode.toString()),t.next=19;break;case 11:if(t.t1=this.element,!t.t1){t.next=19;break}if(t.t2=this.element.paused,!t.t2){t.next=18;break}return this._log.warn("track unmuted and element is paused, resume"),t.next=18,this.resume();case 18:!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(IC.UNMUTE);case 19:case"end":return t.stop()}}),t,this)})))}},{key:"handlePlaying",value:function(e){var t;this._log.debug("handlePlaying",e),null==(t=this._playSuccessResolve)||t.call(this,e),this.emit(vM.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}},{key:"handlePaused",value:function(e){this._log.debug("handlePaused",e),this.emit(vM.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}},{key:"handleStopped",value:function(e){this._log.debug("handleStopped",e),this.emit(vM.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}},{key:"getElement",value:function(){return this.element}}])}(uM);TA([SM({settings:{retries:2,timeout:0},onError:function(e,t,n,r){r[0]=(r[0]||1e3)+1e3,t()}})],bM.prototype,"doReplayByRecreateMediaStream",1),TA([oM([],"PLAYING",{sync:!0})],bM.prototype,"handlePlaying",1),TA([oM("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],bM.prototype,"handlePaused",1),TA([oM([],"STOPPED",{sync:!0})],bM.prototype,"handleStopped",1);var RM,AM="trtc_autoplay",CM="".concat(AM,"_mask"),wM="".concat(AM,"_wrapper"),DM="".concat(AM,"_header"),NM="".concat(AM,"_content"),xM="".concat(AM,"_action_wrapper"),OM="".concat(AM,"_question"),PM="".concat(AM,"_collapse"),MM="".concat(AM,"_action_confirm"),LM="".concat(AM,"_detail"),VM="#2473E8",UM="dialog",FM="".concat(UM,"-show"),BM="".concat(UM,"-1"),HM="".concat(UM,"-2"),WM=!1,jM=function(){return!!document.querySelector(".".concat(wM))},GM="".concat(oC,"/").concat(Bw()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),JM="<br><a href='".concat(GM,"' target='_blank'>").concat(Bw()?"其他方案?":"Any other solution?","</a>"),KM="".concat(Bw()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(JM):"Autoplay Policy: Before user interacts with the web page (clicking, touching), page will not be allowed to play media with sound. This Dialog is used to help users resume playback. ".concat(JM)),YM=function(){return o((function e(){if(r(this,e),SA(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),SA(this,"_dialogNode",null),SA(this,"_bodyPosition",""),SA(this,"_showDetail",!1),SA(this,"_isCollapseClicked",!1),SA(this,"_isQuestionClicked",!1),Bw()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!WM){var t=document.createElement("style");t.innerHTML=".".concat(CM,"{position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:rgba(0,0,0,0.5);z-index:1500;}.").concat(CM," div:not(.").concat(xM,"){display:block !important;}.").concat(wM,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(wM," a{color:").concat(VM,";}.").concat(DM,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(NM,"{margin:8px 0;}.").concat(xM,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(PM,"{margin-right:auto;cursor:pointer}.").concat(OM,"{height:100%;line-height:16px;cursor:pointer;}.").concat(MM,"{margin-left:8px;color:#fff;background:").concat(VM,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(MM,":hover{opacity:0.9;}.").concat(PM,",.").concat(MM,",.").concat(NM,",.").concat(OM,"{font-size:14px;}@media screen and (max-width:750px){.").concat(wM,"{width:80vw;}}"),document.head.appendChild(t),WM=!0}this.addDiaLog()}),[{key:"createDiaLog",value:function(){var e=document.createElement("template");e.innerHTML='<div class="'.concat(CM,"\"><div class='").concat(wM,"'><div class='").concat(DM,"'>").concat(location.host,"</div><div class='").concat(NM,"'>").concat(this.content,"</div><div class='").concat(LM,'\' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">').concat(KM,"</div><div class='").concat(xM,"'></div></div></div>").trim();var t=document.createElement("button");t.className=MM,t.innerText=Bw()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);var n=document.createElement("div");n.className=OM,n.innerHTML='<?xml version="1.0" encoding="UTF-8"?>\n <svg class="icon" width="18" height="18" p-id="2030" t="1639646523624" version="1.1" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">\n <path d="m464 784.35c0 26.51 21.49 48 48 48s48-21.49 48-48-21.49-48-48-48-48 21.49-48 48z" p-id="2031"/>\n <path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>\n <path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>\n </svg>\n ',n.onclick=this.onQuestionClick.bind(this);var r=document.createElement("div");r.className=PM,r.innerText="".concat(Bw()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);var i=e.content.firstChild,a=i.querySelector(".".concat(xM));return a.appendChild(r),a.appendChild(n),a.appendChild(t),i}},{key:"addDiaLog",value:function(){jM()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(wM)).onclick=function(e){return e.stopPropagation()},this._bodyPosition=document.body.style.position,document.body.style.position="fixed",Ux.info("show autoplay dialog"),kM.uploadEvent({log:FM}))}},{key:"deleteDiaLog",value:function(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}},{key:"onConfirm",value:function(){Ux.warn("confirm clicked, try resume stream"),Px.emit(Lx.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}},{key:"onCollapseClick",value:function(){var e=this._dialogNode.querySelector(".".concat(LM));e.style.visibility="".concat(this._showDetail?"hidden":"visible"),e.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||kM.uploadEvent({log:BM}),this._isCollapseClicked=!0}},{key:"onQuestionClick",value:function(){window.open(GM,"_blank"),this._isQuestionClicked||kM.uploadEvent({log:HM}),this._isQuestionClicked=!0}}])}(),zM=function(e){function i(e){var a;return r(this,i),a=n(this,i,[e,IC.VIDEO]),SA(t(a),"stat",{}),SA(t(a),"_calculateTimeout",-1),SA(t(a),"viewMirror",!1),SA(t(a),"objectFit"),SA(t(a),"container"),SA(t(a),"canvas"),a.mode=e.canvas?1:0,a.container=e.container,a.canvas=e.canvas,Kw(e.viewMirror)||(a.viewMirror=e.viewMirror),Kw(e.objectFit)||(a.objectFit=e.objectFit),a.initializeElement(),a}return d(i,e),o(i,[{key:"isPlaying",get:function(){var e;return!("PLAYING"!==this._state||this.element&&this.element.paused||"live"!==(null==(e=this.track)?void 0:e.readyState)||this.track.muted)}},{key:"initializeElement",value:function(){var e,t=document.createElement(IC.VIDEO);this.track&&2!==this.mode&&(t.srcObject=new MediaStream([this.track])),t.muted=!0,t.setAttribute("id","video_".concat(this.id)),t.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.element=t,null==(e=this.container)||e.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}},{key:"styleAttribute",get:function(){var e="width: 100%; height: 100%; object-fit: ".concat(this.objectFit,";background-color: black;");return this.viewMirror&&(e+="transform: scaleX(-1);"),e}},{key:"setContainer",value:function(e){var t;this.container=e,this.track&&this.elementToRender&&(null==(t=this.container)||t.appendChild(this.elementToRender))}},{key:"bindElementEvents",value:function(){var e=g(i,"bindElementEvents",this,3)([]);this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(IC.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(IC.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}},{key:"handleTrackEvent",value:function(e){var t;g(i,"handleTrackEvent",this,3)([e]),e.type===IC.MUTE&&null!=(t=this.stat)&&t.fps&&(this.stat.fps=0)}},{key:"handleElementEvent",value:function(e){var t,n;if(2!==this.mode){g(i,"handleElementEvent",this,3)([e]);var r=e.type;if(r===IC.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(null==(t=this.container)?void 0:t.id)),this.container&&this.container!==document.getElementById(this.container.id)&&(this._pausedRetryCount=vw,this._log.info("view container ".concat(null==(n=this.container)?void 0:n.id," is recreated"))),this._pausedRetryCount>0&&!jM()&&(this._log.info("[".concat(vw-this._pausedRetryCount+1,"/").concat(vw,"] ").concat(this.kind," player auto resume when paused")),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){var a=this.element.style.transform;r===IC.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=a.replace("scaleX(-1)",""):r===IC.LEAVE_PICTURE_IN_PICTURE&&!a.includes("scaleX")&&(this.element.style.transform="".concat(a," scaleX(-1)"))}}}},{key:"setCanvas",value:function(e){var t,n,r,i,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;this.canvas!==e&&(null==(t=this.canvas)||t.remove(),null==e||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?a:0,2===this.mode&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?(null==(n=this.element)||n.remove(),null==(r=this.container)||r.appendChild(e)):this.element&&(null==(i=this.container)||i.appendChild(this.element)))}},{key:"setAttr",value:function(e){var t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),g(i,"setAttr",this,3)([t])}},{key:"mirror",get:function(){return this.viewMirror}},{key:"setRect",value:function(e,t){this.elementToRender&&(this.elementToRender.style.width="".concat(e,"px"),this.elementToRender.style.height="".concat(t,"px"))}},{key:"setViewMirror",value:function(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}},{key:"setObjectFit",value:function(e){this.elementToRender&&(this.elementToRender.style.objectFit="".concat(e)),this.objectFit=e}},{key:"setPoster",value:function(e){this.element&&(this.element.poster=e)}},{key:"stop",value:function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;g(i,"stop",this,3)([t]),null==(e=this.canvas)||e.remove()}},{key:"play",value:function(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),2===this.mode?Promise.resolve():g(i,"play",this,3)([])}},{key:"elementToRender",get:function(){return this.canvas||this.element}},{key:"setTrack",value:function(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(vM.MEDIA_TRACK_CHANGED,e),null!==e&&(this.bindTrackEvents(),this.element&&2!==this.mode&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}},{key:"getVideoFrame",value:function(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";var e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}},{key:"getElement",value:function(){return this.element}},{key:"calculateStat",value:function(){var e=this;try{if(ZP()&&this.element&&this._calculateTimeout<0){var t=0,n=null,r=function(i,a){e.stat.width=a.width,e.stat.height=a.height,n&&(e.stat.fps=Math.round((a.presentedFrames-n.presentedFrames)/(i-t)*1e3)),t=i,n=a,e._calculateTimeout=-1,e.element&&(e._calculateTimeout=setTimeout((function(){var t;return null==(t=e.element)?void 0:t.requestVideoFrameCallback(r)}),2e3))};this.element.requestVideoFrameCallback(r)}}catch(qA){this._log.warn("init stat failed",qA)}}}])}(bM);function qM(e,t){return bA(this,null,f().mark((function n(){return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(e.audioWorklet){n.next=2;break}return n.abrupt("return",Promise.reject("audioWorklet is not supported"));case 2:return n.prev=2,n.next=5,e.audioWorklet.addModule(t);case 5:Ux.info("worklet addModule success"),n.next=11;break;case 8:throw n.prev=8,n.t0=n.catch(2),Ux.info("worklet addModule catch error. ".concat(n.t0.message)),n.t0;case 11:case"end":return n.stop()}}),n,null,[[2,8]])})))}"undefined"!=typeof AudioContext?RM=AudioContext:"undefined"!=typeof webkitAudioContext?RM=webkitAudioContext:"undefined"!=typeof mozAudioContext&&(RM=mozAudioContext);var XM,QM=-1;!function e(){try{if(XM)return;(XM=new RM({sampleRate:48e3})).onstatechange=function(){Ux.info("context state: ".concat(XM.state).concat("running"!==XM.state?" visibilityState: ".concat(document.visibilityState):"")),ZM()},clearTimeout(QM)}catch(t){Ux.error("initAudioContext failed: ".concat(t," typeof AudioContextClass: ").concat(T(RM))),QM=setTimeout(e,1e3)}}();var ZM=function(){"suspended"===XM.state?(tL(),document.addEventListener("click",ZM)):"interrupted"===XM.state?tL():(document.removeEventListener("visibilitychange",ZM),document.removeEventListener("click",ZM))},$M=0,eL=-1;function tL(){return new Promise((function(e,t){if("running"===XM.state)return e();Date.now()-$M<1e3?(clearTimeout(eL),eL=setTimeout((function(){$M=Date.now(),XM.resume().then(e,t)}),1e3)):(clearTimeout(eL),$M=Date.now(),XM.resume().then(e,t))})).catch((function(e){Ux.warn("context resume failed: ".concat(e)),document.addEventListener("visibilitychange",ZM)}))}document.addEventListener("click",ZM);var nL=function(e){return XM},rL=function(){return o((function e(t){r(this,e),this.name=t,SA(this,"node"),SA(this,"node2"),SA(this,"pre",new Set),SA(this,"next",new Set),SA(this,"context"),SA(this,"connectedNodes",new Set),SA(this,"nextInputChannelMap",new Map),SA(this,"_channelCount",1)}),[{key:"channelCount",get:function(){return this._channelCount},set:function(e){this._channelCount=e,this.setChannelCount(this.node,e),this.setChannelCount(this.node2,e),this.next.forEach((function(t){return t.channelCount=e}))}},{key:"setChannelCount",value:function(e,t){!e||e instanceof ScriptProcessorNode||(e.channelCountMode="explicit",e.channelCount=t||this.channelCount||1)}},{key:"setContext",value:function(e){this.context=e,this.node&&e.addMixWeight()}},{key:"removeContext",value:function(){var e;this.node&&(null==(e=this.context)||e.reduceMixWeight()),delete this.context}},{key:"replaceNode",value:function(e){var t;if(e!==this.node)try{this.node?this._disconnect():null==(t=this.context)||t.addMixWeight(),this.node=e,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(ZC){Ux.error(ZC)}}},{key:"setNode",value:function(e,t){var n;if(!this.node)try{null==(n=this.context)||n.addMixWeight(),this.node=e,this.setChannelCount(this.node),t&&(this.node2=t,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),rP.addSuccessEvent({key:502701})}catch(Yx){Ux.error(Yx),rP.addFailedEvent({key:502701,error:Yx})}}},{key:"deleteNode",value:function(){var e;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),rP.addSuccessEvent({key:502702})}catch(qA){Ux.error(qA),rP.addFailedEvent({key:502702,error:qA})}}},{key:"preNodeReconnect",value:function(){this.pre.forEach((function(e){e.node?e.reconnect():e.preNodeReconnect()}))}},{key:"connectNext",value:function(e){var t=this;this.next.forEach((function(n){var r=t.nextInputChannelMap.get(n);e._connect(n.node,r)||n.connectNext(e)}))}},{key:"_connect",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return!(!this.node||!e||((this.node2||this.node).connect(e,0,t),this.connectedNodes.add(e),0))}},{key:"_disconnect",value:function(){var e=this;this.connectedNodes.forEach((function(t){var n;return null==(n=e.node2||e.node)?void 0:n.disconnect(t)})),this.connectedNodes.clear()}},{key:"reconnect",value:function(){this._disconnect(),this.connectNext(this)}},{key:"pipeTo",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return this.next.add(e),e.pre.add(this),this.nextInputChannelMap.set(e,t),e}}])}(),iL=function(e){function i(){var e;r(this,i);var a=arguments.length>0&&void 0!==arguments[0]?arguments[0]:256;return(e=n(this,i)).fftSize=a,SA(t(e),"dataArray",new Uint8Array(0)),e}return d(i,e),o(i,[{key:"setNode",value:function(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),g(i,"setNode",this,3)([e])}},{key:"getByteTimeDomainData",value:function(){var e;return null==(e=this.node)||e.getByteTimeDomainData(this.dataArray),this.dataArray}},{key:"level",get:function(){var e;return null==(e=this.node)||e.getByteTimeDomainData(this.dataArray),Math.max.apply(Math,E(this.dataArray))/128-1}},{key:"timeDomainPathData",get:function(){for(var e=this.getByteTimeDomainData(),t=0,n=0,r="M".concat(t,",").concat(n),i=0;i<e.length;i++)n=e[i]/128*100/2,r+="L".concat(t,",").concat(n),t+=1;return r}}])}(rL),aL=function(){return o((function e(){r(this,e),SA(this,"source",new rL),SA(this,"gain",new rL),SA(this,"destination",new rL)}),[{key:"volume",get:function(){var e;return(null==(e=this.gain.node)?void 0:e.gain.value)||1}},{key:"setVolume",value:function(e){1!==e?(this.gain.node||this.gain.setNode(nL().createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}},{key:"replaceSource",value:function(e){this.source.replaceNode(uL(e))}},{key:"track",get:function(){var e;return null==(e=this.stream)?void 0:e.getAudioTracks()[0]}},{key:"stream",get:function(){var e;return null==(e=this.destination.node)?void 0:e.stream}}])}(),oL=function(e){function i(e){var a;return r(this,i),(a=n(this,i)).context=e,SA(t(a),"aec",new rL("aec")),SA(t(a),"mixNode",new rL("mixNode")),SA(t(a),"silentNode",new rL("silentNode")),SA(t(a),"denoiser",new rL("denoiser")),SA(t(a),"voiceChanger",new rL("voiceChanger")),a.source.pipeTo(a.aec).pipeTo(a.denoiser).pipeTo(a.voiceChanger).pipeTo(a.gain).pipeTo(a.destination),a.silentNode.pipeTo(a.mixNode).pipeTo(a.aec,1),a}return d(i,e),o(i,[{key:"connect",value:function(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.aec.setContext(this.context),this.silentNode.setContext(this.context),this.mixNode.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}},{key:"disconnect",value:function(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.aec.removeContext(),this.silentNode.removeContext(),this.mixNode.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}},{key:"remove",value:function(){this.gain.deleteNode(),this.aec.deleteNode(),this.silentNode.deleteNode(),this.mixNode.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}},{key:"setVolume",value:function(e){1!==e?(this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}}])}(aL),sL=function(){return o((function e(){r(this,e),SA(this,"audioContext",nL()),SA(this,"destination",this.audioContext.createMediaStreamDestination()),SA(this,"inputs",new Set),SA(this,"mixWeight",0),this.destination.channelCount=1}),[{key:"addMixWeight",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.mixWeight+=e,this.mixWeight-1==e+1>>1&&this.mixOnChange()}},{key:"reduceMixWeight",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;this.addMixWeight(-e)}},{key:"close",value:function(){this.inputs.forEach((function(e){return e.remove()}))}},{key:"mixTrack",get:function(){return this.destination.stream.getAudioTracks()[0]}}])}(),cL=new WeakMap;function uL(e){var t=cL.get(e);if(t)return t;var n=nL();if(e instanceof HTMLAudioElement)t=n.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=n.createMediaStreamSource(new MediaStream([e]))}return cL.set(e,t),t}var lL=function(){function e(t){r(this,e),SA(this,"_volume",0),SA(this,"_volumeDb",0),SA(this,"_log"),SA(this,"_scriptProcessorNode",null),SA(this,"_audioWorkletNode",null),SA(this,"_interval",200),SA(this,"ready",this.preload());var n=t.log;this._log=n,Px.on(Lx.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}return o(e,[{key:"node",get:function(){return this._audioWorkletNode||this._scriptProcessorNode}},{key:"preload",value:function(){var t=this;return e.workletReady||(e.workletReady=qM(e.audioContext,URL.createObjectURL(new Blob(['class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);'],{type:"application/javascript"})))),e.workletReady.then((function(){return t.initAudioWorklet()})).catch((function(e){return t._log.error("volumeMeter preload error: ".concat(e)),t.initScriptProcessor()}))}},{key:"initAudioWorklet",value:function(){var t=this;if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(e.audioContext,"volume-meter");var n=!1;this._audioWorkletNode.port.onmessage=function(r){e.lastMessageTime=Date.now(),t._volume=r.data.volume||0,t._volumeDb=r.data.volumeDb||0,!n&&r.data.cacheLen&&r.data.outputLen&&(t._log.warn("worklet play success"),n=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(Kx){this._log.error("volumeMeter init audio worklet error: ".concat(Kx)),kM.logFailedEvent({userId:this._log.userId,eventType:ew.LOAD_WORKLET,error:Kx}),this.initScriptProcessor()}}},{key:"initScriptProcessor",value:function(){var t=this;if(!this._scriptProcessorNode)try{this._scriptProcessorNode=nL().createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=function(n){e.lastMessageTime=Date.now();for(var r=n.inputBuffer.getChannelData(0),i=0,a=0;a<r.length;++a)i+=r[a]*r[a];t._volume=Math.sqrt(i/r.length)||0}}catch(Kx){this._log.error("volumeMeter init script processor error: ".concat(Kx))}}},{key:"destroy",value:function(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,Px.off(Lx.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}},{key:"getInternalAudioLevel",value:function(){return this._volume}},{key:"getCalculatedVolume",value:function(){return parseFloat(this._volume.toFixed(2))}},{key:"getVolumeDb",value:function(){return Math.floor(100*this._volumeDb)}},{key:"handleAudioLevelInterval",value:function(e){var t,n=e.interval;this._interval=n,null==(t=this._audioWorkletNode)||t.port.postMessage({name:"setIntervalTime",intervalTime:n})}}],[{key:"isRunning",get:function(){return Date.now()-e.lastMessageTime<2e3}}])}();SA(lL,"lastMessageTime",0),SA(lL,"audioContext",nL()),SA(lL,"workletReady");var dL=lL,hL=function(e){function i(e){var a;return r(this,i),a=n(this,i),SA(t(a),"_volumeMeter"),a._volumeMeter=new dL(e),a}return d(i,e),o(i,[{key:"deleteNode",value:function(){g(i,"deleteNode",this,3)([]),this._volumeMeter.destroy()}},{key:"init",value:function(){return bA(this,null,f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._volumeMeter.preload();case 2:this.setNode(this._volumeMeter.node);case 3:case"end":return e.stop()}}),e,this)})))}},{key:"getCalculatedVolume",value:function(){return this._volumeMeter.getCalculatedVolume()}},{key:"getInternalAudioLevel",value:function(){return this._volumeMeter.getInternalAudioLevel()}},{key:"getVolumeDb",value:function(){return this._volumeMeter.getVolumeDb()}},{key:"write",value:function(e){if(this.node){var t=e.allocationSize({planeIndex:0}),n=new Float32Array(t>>2);e.copyTo(n,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:n},[n.buffer]),e.close()}}}])}(rL),fL=dL,pL=kA(RA(),1),mL=function(e){return function(t){return t.deviceId===e}},vL=function(){return o((function e(t){r(this,e);var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Input";SA(this,"kind"),SA(this,"type"),SA(this,"devices",[]),this.kind=t,this.type=n}),[{key:"update",value:function(e,t){var n=this,r=e.filter((function(e){return e.kind==="".concat(n.kind).concat(n.type.toLocaleLowerCase())}));1===this.devices.length&&yL(this.devices[0])||t&&(r.forEach((function(e){if(e.deviceId&&!n.devices.find(mL(e.deviceId))){var r="".concat(n.kind).concat(n.type,"Added");Ux.warn("".concat(r,": ").concat(JSON.stringify(e))),t.emit(r,e)}})),this.devices.forEach((function(e){if(e.deviceId&&!r.find(mL(e.deviceId))){var i="".concat(n.kind).concat(n.type,"Removed");Ux.warn("".concat(i,": ").concat(JSON.stringify(e))),t.emit(i,e)}}))),this.devices=r}},{key:"hasDevice",value:function(e){return!!this.devices.find((function(t){return t.deviceId===e}))}}])}(),_L=function(e){function i(){var e;return r(this,i),e=n(this,i),SA(t(e),"audioInputs",new vL(IC.AUDIO)),SA(t(e),"videoInputs",new vL(IC.VIDEO)),SA(t(e),"audioOutputs",new vL(IC.AUDIO,"Output")),e.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(function(){return e.update()})),"ondevicechange"in navigator.mediaDevices||mM.run("interval",(function(){e.update()}),{delay:1e4})),e}return d(i,e),o(i,[{key:"init",value:function(){var e=this;EL().then((function(t){e.audioInputs.update(t),e.videoInputs.update(t),e.audioOutputs.update(t)}))}},{key:"update",value:function(){return bA(this,arguments,(function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return f().mark((function n(){var r;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.next=2,EL(t);case 2:return r=n.sent,n.abrupt("return",(e.audioInputs.update(r,e),e.videoInputs.update(r,e),e.audioOutputs.update(r,e),e));case 4:case"end":return n.stop()}}),n)}))()}))}}])}(pL.EventEmitter),gL=ZA||QA?null:new _L;function yL(e){return e.deviceId===e.groupId&&""===e.groupId}function EL(){return bA(this,arguments,(function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return f().mark((function t(){var n,r,i;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!dP()&&uP()){t.next=2;break}return t.abrupt("return",[]);case 2:return t.next=4,navigator.mediaDevices.enumerateDevices();case 4:if(n=t.sent,0===e){t.next=22;break}if(r={audio:!1,video:!1},n.forEach((function(e){yL(e)&&(e.kind===IC.AUDIO_INPUT?r.audio=!0:e.kind===IC.VIDEO_INPUT&&(r.video=!0))})),2===e&&(r.audio=!1),1===e&&(r.video=!1),!r.audio&&!r.video){t.next=22;break}return t.prev=8,t.next=11,navigator.mediaDevices.getUserMedia(r);case 11:i=t.sent,r.audio&&tL(),t.next=18;break;case 15:t.prev=15,t.t0=t.catch(8),Ux.debug("capture before getDevices failed: ",t.t0);case 18:return t.next=20,navigator.mediaDevices.enumerateDevices();case 20:n=t.sent,null==i||i.getTracks().forEach((function(e){return e.stop()}));case 22:return t.abrupt("return",n.map((function(e,t){var n={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||"".concat(e.kind,"_").concat(t)};return e.deviceId.length>0&&bL.add("".concat(e.deviceId,"_").concat(e.kind)),e.getCapabilities&&(n.getCapabilities=function(){return e.getCapabilities()}),n})));case 23:case"end":return t.stop()}}),t,null,[[8,15]])}))()}))}function kL(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return gL.update(e?1:0).then((function(e){return e.audioInputs.devices}))}function TL(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return gL.update(e?2:0).then((function(e){return e.videoInputs.devices}))}var SL=!1;function IL(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return bA(this,null,f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.abrupt("return",((ZD||ox)&&(e=!1),gL.update(e?1:0).then((function(e){return e.audioOutputs.devices}))));case 1:case"end":return t.stop()}}),t)})))}var bL=new Set;function RL(e,t){return bA(this,null,f().mark((function n(){var r;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.next=2,kL();case 2:return r=n.sent.find((function(e){return e.deviceId===_w})),n.abrupt("return",!t&&(null==r?void 0:r.groupId)===e||(null==r?void 0:r.groupId)===e&&r.label===t);case 4:case"end":return n.stop()}}),n)})))}var AL,CL=function(e){function i(e){var a;return r(this,i),(a=n(this,i)).log=e,SA(t(a),"volumeMeter"),SA(t(a),"volumeDestination"),SA(t(a),"analyser",new iL),a.volumeMeter=new hL({log:a.log}),a.volumeDestination=new rL,a.volumeMeter.pipeTo(a.volumeDestination),a}return d(i,e),o(i,[{key:"destroy",value:function(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}}])}(aL),wL=function(e){function i(e){var a;return r(this,i),a=n(this,i,[e,IC.AUDIO]),SA(t(a),"_outputDeviceId"),SA(t(a),"_volume",1),SA(t(a),"_destination",nL().createMediaStreamDestination()),SA(t(a),"pipeline"),SA(t(a),"volumeMeterMode","worklet"),a.mode=0,a.pipeline=new CL(a._log),a}return d(i,e),o(i,[{key:"getMediaStream",value:function(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}},{key:"initializeElement",value:function(e){if("15.2"!==lx&&"15.3"!==lx&&"15.4"!==lx||!this.muted){var t=AL||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.element=t,zw(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),t===AL&&(AL=void 0),this.bindElementEvents()}else this._log.info("audioElement is muted.")}},{key:"play",value:function(e){return bA(this,null,f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!this.track){t.next=10;break}if(this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(null==e?void 0:e.volume),t.t0=this._outputDeviceId,!t.t0){t.next=7;break}return t.next=7,this.setSinkId(this._outputDeviceId);case 7:return"worklet"===this.volumeMeterMode?this.pipeline.volumeMeter.init():"analyser"===this.volumeMeterMode&&this.pipeline.analyser.setNode(nL().createAnalyser()),function(){bA(this,null,f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,e.t0=SL,e.t0){e.next=11;break}return SL=!0,e.t1=Ux,e.t2="speakers:",e.next=8,IL();case 8:e.t3=e.sent.map((function(e){return" ".concat(e.deviceId.slice(0,8),": ").concat(e.label)})),e.t4=e.t2.concat.call(e.t2,e.t3),e.t1.info.call(e.t1,e.t4);case 11:e.next=15;break;case 13:e.prev=13,e.t5=e.catch(0);case 15:case"end":return e.stop()}}),e,null,[[0,13]])})))}(),t.abrupt("return",IA(i.prototype,this,"play").call(this));case 10:case"end":return t.stop()}}),t,this)})))}},{key:"stop",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destroy(),g(i,"stop",this,3)([e])}},{key:"setSinkId",value:function(e){return bA(this,null,f().mark((function t(){var n,r;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this._outputDeviceId!==e&&(this._outputDeviceId=e),t.t0=this.element&&this.element.sinkId!==e,!t.t0){t.next=5;break}return t.next=5,null==(r=(n=this.element).setSinkId)?void 0:r.call(n,e);case 5:case"end":return t.stop()}}),t,this)})))}},{key:"useDestination",get:function(){return!!this.pipeline.stream}},{key:"setLoop",value:function(e){this.element&&(this.element.loop=e)}},{key:"getAudioLevel",value:function(){return this.pipeline.volumeMeter.getCalculatedVolume()}},{key:"getInternalAudioLevel",value:function(){return this.pipeline.volumeMeter.getInternalAudioLevel()}}])}(bM),DL=function(e){function t(){return r(this,t),n(this,t,arguments)}return d(t,e),o(t,[{key:"setTrack",value:function(e){this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(vM.MEDIA_TRACK_CHANGED,e),e&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([e]))))}},{key:"setVolume",value:function(e){this._volume=e,this.element&&(this.element.volume=e)}}])}(wL),NL=function(e){function i(e){var a;return r(this,i),a=n(this,i,[e]),SA(t(a),"_sourceElement"),SA(t(a),"_output",new rL),a.pipeline.source.pipeTo(a.pipeline.gain),a.pipeline.gain.pipeTo(a.pipeline.volumeMeter).pipeTo(a._output),a.pipeline.gain.pipeTo(a.pipeline.destination),a}return d(i,e),o(i,[{key:"setOutput",value:function(){this.mode=1,this._output.setNode(nL().destination)}},{key:"write",value:function(e){this.pipeline.volumeMeter.write(e)}},{key:"setTrack",value:function(e){var t,n,r;(null==(n=null==(t=this.element)?void 0:t.error)?void 0:n.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(vM.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=(null==(r=e.getSettings())?void 0:r.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}},{key:"setVolume",value:function(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info("set pipeline volume: ".concat(e))):e<=1?this.element?(this._log.info("set element volume: ".concat(e)),this.element.volume=e):this._log.info("set element volume: no element"):ZD||(this._log.info("start set pipeline volume: ".concat(e)),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),EM(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}},{key:"stop",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.pipeline.destroy();var t=this._sourceElement||this.element;t&&sx&&(AL=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),g(i,"stop",this,3)([e])}}])}(wL),xL=function(e){function i(e){var a;r(this,i);var o,s=e.userId,c=e.sdkAppId,u=e.mediaType,l=e.room,d=e.PlayerClass,h=void 0===d?1===u?NL:zM:d;return a=n(this,i),SA(t(a),"id",Fx()),SA(t(a),"userId",""),SA(t(a),"isRemote"),SA(t(a),"mediaType"),SA(t(a),"room"),SA(t(a),"user"),SA(t(a),"_log"),SA(t(a),"_inputTrack"),SA(t(a),"_outputTrack"),SA(t(a),"isPlayCalled"),SA(t(a),"container",null),SA(t(a),"player"),SA(t(a),"subVideoPlayerMap"),SA(t(a),"muted",!1),SA(t(a),"abortCtrl"),SA(t(a),"objectFit","cover"),SA(t(a),"mirror"),SA(t(a),"rotation"),SA(t(a),"isScreen",!1),SA(t(a),"manager"),SA(t(a),"trackSettings"),SA(t(a),"isFirstVideoFrameEmitted",!1),a.userId=s||"",a.mediaType=u,a._log=Ux.createLogger({id:"".concat(a.kind[0],"t"),userId:null==(o=l||a.room)?void 0:o.userId,remoteUserId:t(a)instanceof eV?void 0:a.userId,sdkAppId:c,type:2===a.mediaType?"auxiliary":"main",isLocal:t(a)instanceof eV}),a.player=new h({id:a.userId||a.id,track:null,muted:!1,container:null,log:a._log}),a.player.on(vM.PLAYER_STATE_CHANGED,(function(e){Px.emit(Lx.PLAYER_STATE_CHANGED,_A({track:t(a)},e)),a.emit("player-state-changed",e)})),a.kind===IC.VIDEO&&(a.player.on(vM.LOADED_DATA,(function(){a.emitFirstVideoFrameEvent(vM.LOADED_DATA),Px.emit(Lx.VIDEO_LOADED_DATA,{track:t(a)})})),a.player.on(vM.LOADED_META_DATA,(function(){a.emitFirstVideoFrameEvent(vM.LOADED_META_DATA)})),a.player.on(vM.MEDIA_TRACK_CHANGED,(function(e){var t;null==(t=a.subVideoPlayerMap)||t.forEach((function(t){return t.setTrack(e)}))}))),a.onTrackMuted=a.onTrackMuted.bind(t(a)),a.onTrackUnmuted=a.onTrackUnmuted.bind(t(a)),a.onTrackEnded=a.onTrackEnded.bind(t(a)),a.onPlayerError&&a.player.on(vM.ERROR,a.onPlayerError.bind(t(a))),a}return d(i,e),o(i,[{key:"log",get:function(){return this._log||Ux}},{key:"kind",get:function(){return 1===this.mediaType?IC.AUDIO:IC.VIDEO}},{key:"strMediaType",get:function(){return 4===this.mediaType?IC.VIDEO:2===this.mediaType?IC.SCREEN:IC.AUDIO}},{key:"streamType",get:function(){return 2&this.mediaType?"auxiliary":"main"}},{key:"isMediaTrackActive",get:function(){return!!this.mediaTrack&&!this.mediaTrack.muted&&"live"===this.mediaTrack.readyState&&this.mediaTrack.enabled}},{key:"play",value:function(e,t){return bA(this,null,f().mark((function n(){var r;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(r=Qw(e)?e[0]:e,!this.isPlayCalled){n.next=16;break}if(this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!Kw(t.muted)&&this.setPlayerMute(t.muted),t&&!Kw(t.objectFit)&&(this.objectFit=t.objectFit),n.t0=this.player instanceof zM,!n.t0){n.next=15;break}if(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),n.t1=Qw(e)&&e.length>=1,!n.t1){n.next=14;break}return n.next=13,this.playSubContainer(e.slice(1),t);case 13:n.t1=n.sent;case 14:n.t0=n.t1;case 15:return n.abrupt("return",void n.t0);case 16:if(t&&!Kw(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===IC.VIDEO)&&this.setPlayerMute(!0),t&&!Kw(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof zM&&(this.player.setObjectFit(this.objectFit),t&&!Kw(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof zM&&this.player.setContainer(r)),Px.emit(Lx.PLAY_TRACK_START,{track:this}),!this._outputTrack){n.next=33;break}return this._log.info("play with options: ".concat(JSON.stringify(t))),n.prev=18,this.player.setTrack(this.playerMediaTrack),n.next=22,this.player.play(t);case 22:if(n.t2=Qw(e)&&e.length>1,!n.t2){n.next=26;break}return n.next=26,this.playSubContainer(e.slice(1),t);case 26:n.next=31;break;case 28:throw n.prev=28,n.t3=n.catch(18),this.handleAutoPlayFailed(n.t3),n.t3;case 31:n.next=34;break;case 33:this.log.info("play has not mediaTrack, abort");case 34:case"end":return n.stop()}}),n,this,[[18,28]])})))}},{key:"setMirror",value:function(e,t){if(!this.isScreen&&this.kind===IC.VIDEO&&!Kw(e)&&e!==this.mirror){this.mirror=e;var n=this.player;t&&(n=t);var r=this.manager;if(qw(this.mirror))return n.setViewMirror(this.mirror),void(r&&(r.mirror=!1));switch(this.mirror){case"view":r&&(r.mirror=!1),n.setViewMirror(!0);break;case"publish":r&&(r.mirror=!0),n.setViewMirror(!0);break;case"both":r&&(r.mirror=!0),n.setViewMirror(!1)}}}},{key:"playSubContainer",value:function(e,t){return bA(this,null,f().mark((function n(){var r,i,a,o,c,u,l,d,h,p,m=this;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(this._outputTrack&&this.kind!==IC.AUDIO){n.next=2;break}return n.abrupt("return");case 2:this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((function(t,n){var r;e.find((function(e){return n===e}))||(t.stop(),null==(r=m.subVideoPlayerMap)||r.delete(n))})),r=s(e.entries());try{for(r.s();!(i=r.n()).done;)a=v(i.value,2),o=a[0],c=a[1],(u=this.subVideoPlayerMap.get(c))?t&&(Kw(t.objectFit)||u.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(c,new zM({id:this.userId||this.id,track:this.playerMediaTrack,container:c,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:"vp-sub".concat(o+1)})}))}catch(f){r.e(f)}finally{r.f()}l=E(this.subVideoPlayerMap.values()),d=s(l),n.prev=7,d.s();case 9:if((h=d.n()).done){n.next=16;break}return(p=h.value).setViewMirror(this.player.mirror),n.next=14,p.play();case 14:n.next=9;break;case 16:n.next=21;break;case 18:n.prev=18,n.t0=n.catch(7),d.e(n.t0);case 21:return n.prev=21,d.f(),n.finish(21);case 24:case"end":return n.stop()}}),n,this,[[7,18,21,24]])})))}},{key:"setAudioOutput",value:function(e){return this.player.setSinkId(e)}},{key:"setAudioVolume",value:function(e){this.player.setVolume(e)}},{key:"getAudioLevel",value:function(){return this.player.getAudioLevel()||0}},{key:"getInternalAudioLevel",value:function(){var e;return(null==(e=this.player)?void 0:e.getInternalAudioLevel())||0}},{key:"stop",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.isPlayCalled&&(this.isPlayCalled=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(VD(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((function(e){e.stop()})),this.container=null)}},{key:"resume",value:function(){return bA(this,null,f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.t0=this.isPlayCalled,!e.t0){e.next=4;break}return e.next=4,null==(t=this.player)?void 0:t.resume();case 4:case"end":return e.stop()}}),e,this)})))}},{key:"close",value:function(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}},{key:"setMute",value:function(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),Px.emit(e?Lx.TRACK_MUTED:Lx.TRACK_UNMUTED,{track:this})}},{key:"setPlayerMute",value:function(e){this.player.setMuted(e)}},{key:"mediaTrack",get:function(){return this._inputTrack||null}},{key:"outMediaTrack",get:function(){return this._outputTrack||null}},{key:"playerMediaTrack",get:function(){return this.outMediaTrack}},{key:"installTrackEvent",value:function(e){yM(e,e).add(IC.MUTE,this.onTrackMuted).add(IC.UNMUTE,this.onTrackUnmuted).add(IC.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===IC.ENDED&&this.onTrackEnded()}},{key:"uninstallTrackEvent",value:function(e){EM(e)}},{key:"setInputMediaStreamTrack",value:function(e){var t,n=this._inputTrack;if(e!==n)return this._inputTrack=e,this.trackSettings=null==(t=e.getSettings)?void 0:t.call(e),e.enabled=!this.muted,n&&this.uninstallTrackEvent(n),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,n||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}},{key:"setOutputMediaStreamTrack",value:function(e){var t;e!==this._outputTrack&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",null==(t=e.getSettings)?void 0:t.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}},{key:"setMediaType",value:function(e){this.mediaType=e}},{key:"updatePlayingState",value:function(e){var t=this;if(this.isPlayCalled)if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch((function(e){return t.handleAutoPlayFailed(e)})),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return this.player.stop(VD(this)?this.jitterBufferDelay:0),void this.log.info("playing state updated, stop ".concat(this.kind));this.log.debug("updatePlayingState abort ".concat(this.isPlayCalled," ").concat(e," ").concat(this.player.isStopped))}},{key:"handleAutoPlayFailed",value:function(e){var t=this;if(this.room&&this.room.enableAutoPlayDialog)new YM;else{var n=function(){t.resume().then((function(){document.removeEventListener("click",n,!0)}))};document.addEventListener("click",n,!0)}this.emit("error",e)}},{key:"getVideoFrame",value:function(){return this.player instanceof zM?this.player.getVideoFrame():""}},{key:"emitFirstVideoFrameEvent",value:function(e){var t,n,r,i;if(!this.isFirstVideoFrameEmitted){var a=null==(n=this.mediaTrack)?void 0:n.getSettings(),o=(null==a?void 0:a.width)||(null==(r=this.player.element)?void 0:r.videoWidth)||0,s=(null==a?void 0:a.height)||(null==(i=this.player.element)?void 0:i.videoHeight)||0;e===vM.LOADED_META_DATA&&!o&&!s||(e===vM.LOADED_DATA&&!o&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,DD(this.rotation)&&(o=(t=[s,o])[0],s=t[1]),this.emit("first-video-frame",{width:o,height:s,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}}},{key:"onTrackMuted",value:function(){this._log.warn("".concat(this.kind," track is unable to provide media output"))}},{key:"onTrackUnmuted",value:function(){this._log.info("".concat(this.kind," track is able to provide media output"))}},{key:"onTrackEnded",value:function(){this._log.warn("".concat(this.kind," track ended"))}}])}(uM);TA([oM([],uM.INIT,{sync:!0})],xL.prototype,"close",1);var OL=Object.prototype.hasOwnProperty,PL=function(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e||"function"==typeof e||Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(Hw(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return 0===e.size;case"[object Object]":for(var t in e)if(OL.call(e,t))return!1;return!0}return!1},ML=FD({retryFunction:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a,o,s;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=function(e){return{audio:VL(e),video:UL(e)}}(e),Ux.info("getUserMedia with constraints: ".concat(JSON.stringify(n))),r=[],i=[],a=["label","deviceId","groupId"],t.t0=n.audio,!t.t0){t.next=9;break}return t.next=7,kL();case 7:r=t.sent,Ux.info("microphones: ".concat(gD(r.map((function(e){return gA(_A({},e),{groupId:e.groupId.substring(0,8)})})),{keysToInclude:a})));case 9:if(t.t1=n.video,!t.t1){t.next=15;break}return t.next=13,TL();case 13:i=t.sent,Ux.info("cameras: ".concat(gD(i,{keysToInclude:a})));case 15:return t.prev=15,t.next=18,navigator.mediaDevices.getUserMedia(n);case 18:return o=t.sent,t.abrupt("return",(BP&&o.getTracks().forEach((function(e){Ux.info("".concat(e.kind," capabilities: ").concat(gD(e.getCapabilities(),{keysToInclude:Iw})))})),n.audio&&tL(),o));case 22:throw t.prev=22,t.t2=t.catch(15),s=t.t2.message,"NotFoundError"===t.t2.name&&(e.video&&i&&0===i.length&&(s=YO({key:jO.CAMERA_NOT_FOUND})),e.audio&&r&&0===r.length&&(s=YO({key:jO.MICROPHONE_NOT_FOUND}))),new FA({code:VA.INITIALIZE_FAILED,name:t.t2.name,message:s,constraint:t.t2.constraint});case 26:case"end":return t.stop()}}),t,null,[[15,22]])})))},settings:{retries:3,timeout:500},onError:function(e){var t=e.error,n=e.retry,r=e.reject,i=e.retryFuncArgs,a=e.retriedCount+1;"NotReadableError"===t.name||"OverconstrainedError"===t.name?(1===a?(i[0].video&&(i[0].maxResolution=!1,(!ox||i[0].width*i[0].height<=2073600)&&i[0].frameRate&&(i[0].frameRate=i[0].frameRate>10?10:5)),i[0].retryWhenExactFailed&&i[0].useExactDeviceId&&(i[0].useExactDeviceId=!1)):2===a?i[0].useDeviceIdOnly=!0:3===a&&!i[0].useExactDeviceId&&(i[0].useTrueAsConstraint=!0),n()):r(t),i[0].microphoneId&&LL(i[0].microphoneId,!1),i[0].cameraId&&LL(i[0].cameraId,!0)},onRetrying:function(e){Ux.warn("getUserMedia NotReadableError observed, retrying [".concat(e,"/3]"))},onRetryFailed:function(e){kM.logFailedEvent({eventType:ew.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:function(e){kM.logSuccessEvent({eventType:ew.GET_USER_MEDIA_RETRY}),kM.uploadEvent({log:"stat-".concat(ew.GET_USER_MEDIA_RETRY,"-success-").concat(e)})}});function LL(e,t){return bA(this,null,f().mark((function n(){var r;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(!t){n.next=6;break}return n.next=3,TL();case 3:n.t0=n.sent,n.next=9;break;case 6:return n.next=8,kL();case 8:n.t0=n.sent;case 9:r=n.t0.find((function(t){return t.deviceId===e})),r&&Jw(r.getCapabilities)&&Ux.warn(gD(r.getCapabilities(),{keysToInclude:Iw}));case 11:case"end":return n.stop()}}),n)})))}function VL(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;var t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!PL(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(zw(e.channelCount)&&(t.channelCount=e.channelCount),qw(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),qw(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),qw(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!PL(t)||t)}function UL(e){if(!e.video)return!1;if(e.useTrueAsConstraint)return!0;var t=e.maxResolution,n=void 0===t||t,r={};return e.cameraId?r.deviceId=e.useExactDeviceId?{exact:e.cameraId}:e.cameraId:e.facingMode&&(r.facingMode=e.facingMode),e.useDeviceIdOnly&&!PL(r)?r:(e.width&&(r.width={ideal:e.width},n&&!rN&&(r.width.max=e.width)),e.height&&(r.height={ideal:e.height},n&&!rN&&(r.height.max=e.height)),rN&&PN&&e.width&&e.height&&e.width*e.height<101376&&(r.width=e.width,r.height=e.height),e.frameRate&&(r.frameRate=e.frameRate),!!PL(r)||r)}var FL=ML;function BL(e){return jL((function(t,n){return function(){for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return bA(this,null,f().mark((function n(){return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.next=2,e.apply(this,r);case 2:return n.abrupt("return",t.apply(this,r));case 3:case"end":return n.stop()}}),n,this)})))}}))}function HL(e){return jL((function(t,n){return function(){for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return bA(this,null,f().mark((function n(){var i;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.next=2,t.apply(this,r);case 2:return i=n.sent,n.next=5,e.call.apply(e,[this].concat(r));case 5:return n.abrupt("return",i);case 6:case"end":return n.stop()}}),n,this)})))}}))}function WL(e){return jL((function(t,n){return function(){for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return bA(this,null,f().mark((function n(){return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.prev=0,n.next=3,t.apply(this,r);case 3:return n.abrupt("return",n.sent);case 6:n.prev=6,n.t0=n.catch(0),e.call(this,n.t0);case 9:case"end":return n.stop()}}),n,this,[[0,6]])})))}}))}function jL(e){return function(t,n,r){return r.value=e(r.value,n),r}}var GL=function(){var e=!1,t=document.visibilityState;return function(){document.visibilityState!==t&&Ux.info("visibility change: ".concat(document.visibilityState)),!e&&(document.addEventListener("visibilitychange",(function(){Ux.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState})),e=!0)}}(),JL=0,KL=function(){return o((function e(){r(this,e),SA(this,"log",Ux.createLogger({id:"fq".concat(++JL)})),SA(this,"isRunning",!1),SA(this,"queue",[])}),[{key:"length",get:function(){return this.queue.length}},{key:"lastQueueItem",get:function(){return 0===this.length?null:this.queue[this.length-1]}},{key:"push",value:function(e){var t,n,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=_A({},e),a=new Promise((function(e,t){i.resolve=e,i.reject=t}));return i.promise=a,r?this.length<=1?this.queue.push(i):null==(n=null==(t=this.lastQueueItem)?void 0:t.promise)||n.then(i.resolve,i.reject):this.queue.push(i),this.log.debug("push ".concat(this.length)),this.isRunning||this.callNext(),a}},{key:"shift",value:function(){var e=this.queue.shift();return this.log.debug("shift ".concat(this.length)),e}},{key:"callNext",value:function(){var e=this;if(!this.isRunning&&0!==this.length){this.log.debug("callNext ",this.length);var t=this.queue[0],n=t.fn,r=t.args,i=t.context,a=t.resolve,o=t.reject;this.isRunning=!0,n.apply(i,r).then(a,o).finally((function(){e.isRunning=!1,e.shift(),e.callNext()}))}}}])}(),YL=new WeakMap,zL=new WeakMap;function qL(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return function(t,n,r){var i=r.value;return r.value=function(){for(var t=YL.get(this)||new KL,n=arguments.length,r=new Array(n),a=0;a<n;a++)r[a]=arguments[a];return YL.set(this,t),t.push({fn:i,args:r,context:this},e)},r}}function XL(e){return function(t,n,r){var i=r.value;return r.value=function(){for(var t,n,r,a=[],o=arguments.length,s=new Array(o),c=0;c<o;c++)s[c]=arguments[c];return null==(n=null==(t=YL.get(this))?void 0:t.queue)||n.forEach((function(e){return a.push(e)})),null==(r=zL.get(this))||r.forEach((function(e){return null==e?void 0:e.queue.forEach((function(e){return a.push(e)}))})),a.forEach((function(t){t.reject(new FA({code:VA.API_CALL_ABORTED,message:e}))})),YL.delete(this),zL.delete(this),i.apply(this,s)},r}}function QL(e){return function(t,n,r){var i=r.value,a=function(t){return e.apply(void 0,E(t))};return r.value=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=zL.get(this)||new Map,o=r.get(a(t))||new KL;return r.set(a(t),o),zL.set(this,r),o.push({fn:i,args:t,context:this})},r}}function ZL(e,t){return jL((function(n,r){return function(){var r=e;try{for(var i=arguments.length,a=new Array(i),o=0;o<i;o++)a[o]=arguments[o];var s=n.apply(this,a),c=aD();return eD(s)?s.then((function(e){return t?rP.addSuccessEvent({key:r,cost:aD()-c}):rP.addSuccessEvent({key:r}),e})).catch((function(e){throw rP.addFailedEvent({key:r,error:e}),e})):(rP.addSuccessEvent({key:r}),s)}catch(XA){throw rP.addFailedEvent({key:r,error:XA}),XA}}}))}var $L=function(e){function i(e,a){var o;return r(this,i),o=n(this,i,[{mediaType:e,PlayerClass:a}]),SA(t(o),"isRemote",!1),SA(t(o),"deviceId"),SA(t(o),"groupId",""),SA(t(o),"label",""),SA(t(o),"sourceTrack"),SA(t(o),"_isRecapturing",!1),SA(t(o),"_lastRecaptureTime",0),SA(t(o),"_onMuteTimeoutId",-1),SA(t(o),"_encodeCheckTimeoutId",-1),SA(t(o),"profile"),o}return d(i,e),o(i,[{key:"enableEncodeFrame",get:function(){return!1}},{key:"isPublishing",get:function(){return"publishing"===this.state.toString()}},{key:"isPublished",get:function(){return"publish"===this.state}},{key:"encodeFrame",value:function(e,t){throw new Error("Method not implemented.")}},{key:"installTrackEvent",value:function(e){yM(e,e).add(IC.MUTE,this.onTrackMuted).add(IC.UNMUTE,this.onTrackUnmuted).add(IC.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===IC.ENDED&&this.onTrackEnded()}},{key:"uninstallTrackEvent",value:function(e){EM(e)}},{key:"setStateToReady",value:function(){}},{key:"capture",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(t.prev=0,i=aD(),Px.emit(Lx.LOCAL_TRACK_CAPTURE_START,{track:this}),!e.customSource){t.next=7;break}(r=new MediaStream).addTrack(e.customSource),t.next=11;break;case 7:return null==(n=this.mediaTrack)||n.stop(),t.next=10,FL(e);case 10:r=t.sent;case 11:return a=r.getTracks()[0],this.sourceTrack=a,t.next=15,this.setInputMediaStreamTrack(a);case 15:return e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),Px.emit(Lx.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:aD()-i}),t.abrupt("return",r);case 20:throw t.prev=20,t.t0=t.catch(0),Px.emit(Lx.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:t.t0}),this.log.error("getUserMedia error observed ".concat(t.t0)),t.t0;case 23:case"end":return t.stop()}}),t,this,[[0,20]])})))}},{key:"setOutputMediaStreamTrack",value:function(e){var t;if(g(i,"setOutputMediaStreamTrack",this,3)([e]),this.setStateToReady(),this.isPublishing||this.isPublished)return null==(t=this.room)?void 0:t.replaceTrack(this)}},{key:"publish",value:function(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}},{key:"unpublish",value:function(){this.room&&this.room.localTracks.delete(this),Px.emit(Lx.LOCAL_TRACK_UNPUBLISHED,{track:this})}},{key:"updateDeviceIdInUse",value:function(){return bA(this,null,f().mark((function e(){var t,n,r,i,a=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.mediaTrack||!FP){e.next=7;break}return t=this.mediaTrack.getSettings(),n=t.deviceId,r=t.groupId,i=this.mediaTrack.label,e.next=4,function(e){return bA(this,arguments,(function(e){var t=e.newDeviceId,n=e.oldDeviceId,r=e.oldGroupId,i=e.oldLabel,a=e.kind;return f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.t0=t===n,!e.t0){e.next=8;break}if(e.t1=a!==IC.AUDIO||t!==_w,e.t1){e.next=7;break}return e.next=6,RL(r,i);case 6:e.t1=e.sent;case 7:e.t0=e.t1;case 8:return e.abrupt("return",e.t0);case 9:case"end":return e.stop()}}),e)}))()}))}({newDeviceId:n,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind});case 4:if(e.t0=e.sent,e.t0){e.next=7;break}this.deviceId=n,this.label=i,r&&(this.groupId=r),EL().then((function(e){var t=e.find((function(e){return e.deviceId===n}));t&&a.emit("2",t)}));case 7:case"end":return e.stop()}}),e,this)})))}},{key:"setProfile",value:function(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}},{key:"isNeedToRecapture",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return!(!this.deviceId||!this.mediaTrack||this.kind===IC.AUDIO&&!function(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;var t=e.label.toLocaleLowerCase();if(t.includes("mic")||t.includes("麦克风"))return!0;var n="".concat(((null==e?void 0:e.getSettings())||{}).deviceId,"_").concat(IC.AUDIO_INPUT);return!!bL.has(n)}(this.mediaTrack)||this.kind===IC.VIDEO&&!function(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;var t=e.label.toLocaleLowerCase();if(t.includes("camera")||t.includes("webcam"))return!0;var n="".concat(((null==e?void 0:e.getSettings())||{}).deviceId,"_").concat(IC.VIDEO_INPUT);return!!bL.has(n)}(this.mediaTrack)||this._isRecapturing||e&&PN&&ox)}},{key:"onTrackMuted",value:function(){var e=this;if(g(i,"onTrackMuted",this,3)([]),GL(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Sw)return void setTimeout((function(){return e.onTrackMuted()}),Sw);this._onMuteTimeoutId=setTimeout((function(){return bA(e,null,f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(null==(t=this.mediaTrack)||!t.muted){e.next=8;break}if(!ZD&&!$D||"visible"===document.visibilityState){e.next=3;break}return e.abrupt("return");case 3:return e.t0=this,e.next=6,this.getRecoverCaptureDeviceId();case 6:e.t1=e.sent,e.t0.recapture.call(e.t0,e.t1);case 8:case"end":return e.stop()}}),e,this)})))}),5e3)}}},{key:"onTrackUnmuted",value:function(){g(i,"onTrackUnmuted",this,3)([]),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}},{key:"onTrackEnded",value:function(){return bA(this,null,f().mark((function e(){var t=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(IA(i.prototype,this,"onTrackEnded").call(this),!this.isNeedToRecapture()){e.next=8;break}if(!(Date.now()-this._lastRecaptureTime<Sw)){e.next=3;break}return e.abrupt("return",void setTimeout((function(){return t.onTrackEnded()}),Sw));case 3:return e.t0=this,e.next=6,this.getRecoverCaptureDeviceId();case 6:e.t1=e.sent,e.t0.recapture.call(e.t0,e.t1);case 8:case"end":return e.stop()}}),e,this)})))}},{key:"recapture",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a=this;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!this._isRecapturing&&this._inputTrack){t.next=2;break}return t.abrupt("return");case 2:if(this.log.warn("recapture trying"),null==(n=this._inputTrack)||n.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now(),r={useExactDeviceId:!0},"user"!==e&&"environment"!==e){t.next=8;break}r.facingMode=e,t.next=21;break;case 8:if("audio"!==this.kind){t.next=14;break}return t.next=11,kL();case 11:t.t0=t.sent,t.next=17;break;case 14:return t.next=16,TL();case 16:t.t0=t.sent;case 17:if(t.t1=t.t0.find((function(t){return t.deviceId===e})),!t.t1){t.next=20;break}i=e;case 20:r.deviceId=i;case 21:return t.abrupt("return",this.capture(r).then((function(){a._isRecapturing=!1,a.log.warn("recapture success"),a.emit("1",{deviceId:a.deviceId}),Px.emit(Lx.LOCAL_TRACK_RECAPTURE,{track:a})})).catch((function(e){a._isRecapturing=!1,a.log.warn("recapture failed ".concat(e.message)),a.emit("5",e),Px.emit(Lx.LOCAL_TRACK_RECAPTURE,{track:a,error:e})})));case 22:case"end":return t.stop()}}),t,this)})))}},{key:"getRecoverCaptureDeviceId",value:function(){return bA(this,null,f().mark((function e(){var t,n,r,i;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(t=this instanceof oV)||!this.facingMode){e.next=3;break}return e.abrupt("return",this.facingMode);case 3:if(!(n=this.deviceId)){e.next=18;break}if(r=(tV.get(n)||0)+1,tV.set(n,r),!(r>=3)){e.next=18;break}if(!t){e.next=13;break}return e.next=10,TL();case 10:e.t0=e.sent.find((function(e){return!tV.has(e.deviceId)})),e.next=16;break;case 13:return e.next=15,kL();case 15:e.t0=e.sent.find((function(e){return!tV.has(e.deviceId)}));case 16:(i=e.t0)&&(this.log.warn("".concat(n," capture fail ").concat(r," times, change new ").concat(i.deviceId)),n=i.deviceId);case 18:return e.abrupt("return",n);case 19:case"end":return e.stop()}}),e,this)})))}},{key:"stopCapture",value:function(){var e;this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),null==(e=this.manager)||e.removeInput(this)}},{key:"close",value:function(){g(i,"close",this,3)([]),this.stopCapture()}}])}(xL);TA([oM(uM.INIT,"ready",{ignoreError:!0,sync:!0})],$L.prototype,"setStateToReady",1),TA([qL()],$L.prototype,"capture",1),TA([oM("ready","publish",{ignoreError:!0,success:function(){var e,t,n=this;this.room.localTracks.add(this),Px.emit(Lx.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout((function(){var e,t;if(!(((null==(t=null==(e=n.room)?void 0:e.networkQuality)?void 0:t.uplinkNetworkQuality)||0)>3)&&n.isPublished&&n.isMediaTrackActive){var r=n.kind===IC.AUDIO,i=n.stat.bytesSent>0;rP[i?"addSuccessEvent":"addFailedEvent"]({key:r?503700:513702}),i||(rP.addEnum({key:r?503701:513703,value:Dx()}),kM.uploadEvent({log:"stat-encode-failed-".concat(n.kind,"-").concat(Ax()||Nx()),userId:n.userId}),n.log.warn("encode failed"),n.emit("6",n))}}),5e3))},fail:function(e){var t="error";if(e.cause instanceof RTCError){var n=e.cause;n.message.includes("timeout")?t="timeout":n.code===VA.API_CALL_ABORTED&&(t="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:e.cause||e})}}),ZL(521714,!1)],$L.prototype,"publish",1),TA([jL((function(e){return function(){return bA(this,null,f().mark((function t(){var n;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:n="publish"===this.state?"started":"starting",e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:n,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId);case 2:case"end":return t.stop()}}),t,this)})))}})),oM([],"ready",{sync:!0})],$L.prototype,"unpublish",1);var eV=$L,tV=new Map;Px.on(Lx.SWITCH_DEVICE_SUCCESS,(function(e){e.track.deviceId&&tV.delete(e.track.deviceId)}));var nV=function(e){function i(e){var a;return r(this,i),a=n(this,i,[1,DL]),SA(t(a),"mediaType",1),SA(t(a),"volume",0),SA(t(a),"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),SA(t(a),"playerMuted",!0),SA(t(a),"pipeline"),SA(t(a),"earMonitorGainNode",new rL),SA(t(a),"_output",new rL),SA(t(a),"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),SA(t(a),"mixedAudioReferenceMap",new Map),a.manager=e,a.pipeline=new oL(e),a.pipeline.gain.pipeTo(a.earMonitorGainNode).pipeTo(a._output),a.pipeline.gain.pipeTo(a.player.pipeline.volumeMeter),a.handleMicrophoneAdded=a.handleMicrophoneAdded.bind(t(a)),a.handleMicrophoneRemoved=a.handleMicrophoneRemoved.bind(t(a)),a}return d(i,e),o(i,[{key:"dbVolume",get:function(){return fL.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}},{key:"getAudioLevel",value:function(){var e=(this.volume||g(i,"getAudioLevel",this,3)([]))*this.captureVolume;return e>1?1:e}},{key:"setInputMediaStreamTrack",value:function(e){return bA(this,null,f().mark((function t(){var n,r,a;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n=this.trackSettings||{},rP.addEnum({key:501701,value:n.channelCount||0,useUV:!1}),rP.addEnum({key:501702,value:n.sampleRate||0,useUV:!1}),rP.addEnum({key:502700,value:0}),r=n.sampleRate,a=n.channelCount,this._log.info("local audio track input ".concat(JSON.stringify({sampleRate:r,channelCount:a}))),this.pipeline.source.channelCount=a||1,this.pipeline.replaceSource(e),t.next=8,IA(i.prototype,this,"setInputMediaStreamTrack").call(this,e);case 8:this.updatePlayingState(!!e);case 9:case"end":return t.stop()}}),t,this)})))}},{key:"capture",value:function(e){var t=e.deviceId,n=e.customSource,r=e.useExactDeviceId,a=void 0===r||r,o=e.retryWhenExactFailed,s=void 0===o||o;return g(i,"capture",this,3)([{video:!1,audio:!0,microphoneId:t,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:a,retryWhenExactFailed:s,customSource:n}])}},{key:"switchDevice",value:function(e){return bA(this,null,f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!this.mediaTrack){t.next=20;break}if(this.deviceId!==e){t.next=8;break}if(e===_w){t.next=4;break}return t.abrupt("return");case 4:return t.next=6,RL(this.groupId,this.label);case 6:if(!t.sent){t.next=8;break}return t.abrupt("return");case 8:return t.prev=8,this.log.info("switchDevice audio to: ".concat(e)),this.mediaTrack&&this.mediaTrack.stop(),t.next=13,this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1});case 13:Px.emit(Lx.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success"),t.next=20;break;case 17:throw t.prev=17,t.t0=t.catch(8),this.log.error("switch microphone failed ".concat(t.t0)),this.deviceId&&this.recapture(this.deviceId),t.t0;case 20:case"end":return t.stop()}}),t,this,[[8,17]])})))}},{key:"listenDeviceChange",value:function(){gL&&!gL.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&gL.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}},{key:"handleMicrophoneRemoved",value:function(e){return bA(this,null,f().mark((function t(){var n;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(e.deviceId!==this.deviceId){t.next=6;break}return this.log.warn("current microphone is lost: ".concat(JSON.stringify(e))),QF(this.userId,{eventId:2003,param1:6,streamType:1}),t.next=4,kL();case 4:(n=t.sent)[0]?this.recapture(n[0].deviceId):gL.on("audioInputAdded",this.handleMicrophoneAdded,this);case 6:case"end":return t.stop()}}),t,this)})))}},{key:"handleMicrophoneAdded",value:function(e){this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId)}},{key:"update3A",value:function(e){return bA(this,arguments,(function(e){var t=this,n=e.echoCancellation,r=e.noiseSuppression,i=e.autoGainControl;return f().mark((function e(){var a,o,s;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(a=t.sourceTrack||t.mediaTrack){e.next=3;break}return e.abrupt("return");case 3:if(o=a.getConstraints(),s=!1,!Kw(n)&&n!==t.profile.echoCancellation&&(t.profile.echoCancellation=n,o.echoCancellation=n,s=!0),!Kw(r)&&r!==t.profile.noiseSuppression&&(t.profile.noiseSuppression=r,o.noiseSuppression=r,s=!0),!Kw(i)&&i!==t.profile.autoGainControl&&(t.profile.autoGainControl=i,o.autoGainControl=i,s=!0),e.t0=s,!e.t0){e.next=18;break}if(!rN&&!ox){e.next=14;break}return e.next=12,a.applyConstraints(o).catch((function(e){return t._log.warn("update3A failed: ",e)}));case 12:e.next=18;break;case 14:if(e.t1=t.deviceId,!e.t1){e.next=18;break}return e.next=18,t.recapture(t.deviceId);case 18:case"end":return e.stop()}}),e)}))()}))}},{key:"captureVolume",get:function(){return this.pipeline.volume}},{key:"setCaptureVolume",value:function(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&rP.addEnum({key:502700,value:2})}},{key:"setAudioVolume",value:function(e){g(i,"setAudioVolume",this,3)([0]),ZD&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(nL().createGain()),this._output.setNode(nL().destination)),this.earMonitorGainNode.node.gain.value=e}},{key:"enableTrackANS",value:function(e){return this.update3A({noiseSuppression:e})}},{key:"enableTrackAEC",value:function(e){if(this.sourceTrack&&!ox&&!ZD)return this.update3A({echoCancellation:e})}},{key:"addDenoiser",value:function(e){var t;ix<=92&&48e3!==(null==(t=this.trackSettings)?void 0:t.sampleRate)?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(rP.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1))}},{key:"mixAudioReference",value:function(e,t){if(!this.mixedAudioReferenceMap.has(t)){this.log.info("mixAudioReference() => ".concat(t));var n=uL(e),r=new rL,i=nL().createGain();i.gain.value=1;var a=new rL;r.pipeTo(a).pipeTo(this.pipeline.mixNode),r.setNode(n),a.setNode(i),this.mixedAudioReferenceMap.set(t,[r,a])}}},{key:"unMixAudioReference",value:function(e){var t=v(this.mixedAudioReferenceMap.get(e)||[],2),n=t[0],r=t[1];n&&(this.log.info("unMixAudioReference() => ".concat(e)),n.deleteNode(),null==r||r.deleteNode(),this.mixedAudioReferenceMap.delete(e))}},{key:"setAudioReferenceVolume",value:function(e,t){var n=v(this.mixedAudioReferenceMap.get(e)||[],2);n[0];var r=n[1];null!=r&&r.node&&(r.node.gain.value=t/100,this.log.info("setAudioReferenceVolume() => ".concat(e," ").concat(r.node.gain.value)))}},{key:"addAudioProcessor",value:function(e,t,n,r){this.pipeline.silentNode.setNode(n),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e),this.enableTrackAEC(!1)}},{key:"removeDenoiser",value:function(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0))}},{key:"removeAudioProcessor",value:function(e,t,n,r){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}},{key:"close",value:function(){this.mixedAudioReferenceMap.forEach((function(e){var t=v(e,2),n=t[0],r=t[1];n.deleteNode(),r.deleteNode()})),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),gL.off("audioInputAdded",this.handleMicrophoneAdded,this),gL.off("audioInputRemoved",this.handleMicrophoneRemoved,this),g(i,"close",this,3)([])}},{key:"recapture",value:function(e){return bA(this,null,f().mark((function t(){var n;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,IA(i.prototype,this,"recapture").call(this,e);case 3:t.next=14;break;case 5:return t.prev=5,t.t0=t.catch(0),t.next=9,kL();case 9:if(n=t.sent.find((function(t){return t.deviceId!==e})),n){t.next=12;break}throw t.t0;case 12:return t.next=14,IA(i.prototype,this,"recapture").call(this,n.deviceId);case 14:case"end":return t.stop()}}),t,this,[[0,5]])})))}},{key:"encodeFrame",value:function(e){return this.manager?this.manager.encodePipeline.reduceRight((function(e,t){return t?t({frame:e}):e}),e):e}},{key:"enableEncodeFrame",get:function(){return!!this.manager&&this.manager.encodePipeline.some((function(e){return e}))}}])}(eV),rV=function(){return o((function e(t){r(this,e);var n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.dataView=t,this.isSEI&&(n?this.addPreventionByte():this.removePreventionByte())}),[{key:"addPreventionByte",value:function(){for(var e=this.seiPayloadStartIndex,t=this.dataView.byteLength-2,n=[],r=0,i=e;i<=t;i++){var a=this.dataView.getInt8(i);switch(a){case 0:case 1:case 2:case 3:2===r&&(n.push(3),r=0),0==a?r++:r=0,n.push(a);break;default:r=0,n.push(a)}}n.push(this.dataView.getInt8(this.dataView.byteLength-1));var o=new DataView(new Uint8Array([].concat(E(new Uint8Array(this.dataView.buffer).slice(0,e)),n)).buffer);this.dataView=o}},{key:"removePreventionByte",value:function(){for(var e=this.seiPayloadStartIndex,t=this.dataView.byteLength-1,n=[],r=0,i=e;i<=t;i++)switch(this.dataView.getInt8(i)){case 0:r++,n.push(this.dataView.getInt8(i));break;case 3:2!==r&&n.push(this.dataView.getInt8(i)),r=0;break;default:n.push(this.dataView.getInt8(i)),r=0}var a=new DataView(new Uint8Array([].concat(E(new Uint8Array(this.dataView.buffer).slice(0,e)),n)).buffer);this.dataView=a}},{key:"isSEI",get:function(){return 6===this.dataView.getUint8(4)}},{key:"seiPayloadStartIndex",get:function(){for(var e=6,t=6;t<this.dataView.buffer.byteLength&&(e++,255===this.dataView.getUint8(t));t++);return e}},{key:"seiPayloadType",get:function(){return this.isSEI?this.dataView.getUint8(5):null}},{key:"seiPayload",get:function(){if(!this.isSEI)return null;for(var e=0,t=6,n=6;n<this.dataView.buffer.byteLength;n++){var r=this.dataView.getUint8(n);if(t++,255!==r){e+=r;break}e+=255}for(var i=new ArrayBuffer(e),a=new DataView(i),o=0;o<i.byteLength;o++,t++)a.setInt8(o,this.dataView.getInt8(t));return a}}])}(),iV=function(){return o((function e(){r(this,e),SA(this,"_seiMessageList",[]),SA(this,"_smallSeiMessageList",[]),SA(this,"_seiPayloadType",243)}),[{key:"encodeSEINalu",value:function(e){var t=e.byteLength,n=parseInt(String(t/255),10),r=t%255,i=[];i.push(0,0,0,1,6,this._seiPayloadType);for(var a=0;a<n;a++)i.push(255);i.push(r);var o=new DataView(e);return i.push.apply(i,E(new Uint8Array(o.buffer))),i.push(128),new rV(new DataView(new Uint8Array(i).buffer),!0)}},{key:"sendSEI",value:function(e,t){null!=t&&t.seiPayloadType&&(this._seiPayloadType=t.seiPayloadType),this._seiMessageList.push(e),null!=t&&t.small&&this._smallSeiMessageList.push(e)}},{key:"isEmpty",value:function(){return!this._seiMessageList.length}},{key:"getNaluCount",value:function(e){for(var t=0,n=0,r=new DataView(e),i=0;i<e.byteLength;i++)switch(r.getUint8(i)){case 0:t++;break;case 1:(2===t||3===t)&&n++,t=0;break;default:t=0}return n}},{key:"encode",value:function(e,t){var n=t?this._smallSeiMessageList:this._seiMessageList;if(n.length>0&&e.data.byteLength>0){var r=9-this.getNaluCount(e.data);if(r<=0)return 0;for(var i=n.splice(0,r).reverse().map(this.encodeSEINalu.bind(this)),a=i.reduce((function(e,t){return e+t.dataView.byteLength}),0),o=new ArrayBuffer(a+e.data.byteLength),s=new DataView(o),c=new DataView(e.data),u=0,l=0;l<i.length;l++)for(var d=0;d<i[l].dataView.byteLength;d++)s.setInt8(u++,i[l].dataView.getInt8(d));for(var h=0;h<e.data.byteLength;h++)s.setInt8(u++,c.getInt8(h));return e.data=o,i.length}return 0}}])}(),aV=function(e){function i(e){var a;r(this,i),a=n(this,i,[arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,zM]),SA(t(a),"profile",_A({},kC)),SA(t(a),"avoidCropping",!1),SA(t(a),"_scaleResolutionDownBy"),SA(t(a),"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0}),SA(t(a),"small"),SA(t(a),"isNeedToSetBandwidth"),SA(t(a),"muteImage"),SA(t(a),"manager"),SA(t(a),"_seiCodec",new iV),a.manager=e;var o=function(){a.isAllowed2k4k(a.profile)?a.room&&a.settings.height>=1440&&"publish"===a.state&&a.room.sendAbilityStatus({"2k4k":1}):(a.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),a.setProfile(gA(_A({},a.profile),{width:1920,height:1080})),a.applyProfile())};return a.on("input-media-track-changed",o),a.on("publish",o),a.handleCameraAdded=a.handleCameraAdded.bind(a),a.handleCameraRemoved=a.handleCameraRemoved.bind(a),a}return d(i,e),o(i,[{key:"facingMode",get:function(){if(FP&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}},{key:"contentHint",get:function(){var e;return(null==(e=this._inputTrack)?void 0:e.contentHint)||""}},{key:"isQosClearFirst",get:function(){var e;return"detail"===(null==(e=this._inputTrack)?void 0:e.contentHint)}},{key:"setMute",value:function(e){return bA(this,null,f().mark((function t(){var n,r,a;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!Yw(e)){t.next=11;break}if(this.muteImage!==e){t.next=3;break}return t.abrupt("return");case 3:return t.next=5,null==(n=this.manager)?void 0:n.deleteWatermark("mute");case 5:return t.next=7,null==(r=this.manager)?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e});case 7:this.muteImage=e,IA(i.prototype,this,"setMute").call(this,!1),t.next=17;break;case 11:if(t.t0=this.muteImage,!t.t0){t.next=16;break}return t.next=15,null==(a=this.manager)?void 0:a.deleteWatermark("mute");case 15:this.muteImage=void 0;case 16:IA(i.prototype,this,"setMute").call(this,e);case 17:case"end":return t.stop()}}),t,this)})))}},{key:"capture",value:function(e){var t=e.deviceId,n=e.facingMode,r=e.useExactDeviceId,a=void 0===r||r,o=e.customSource,s=e.retryWhenExactFailed,c=void 0===s||s;return g(i,"capture",this,3)([{audio:!1,video:!0,facingMode:n||this.facingMode,cameraId:t,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:a,retryWhenExactFailed:c,customSource:o}])}},{key:"setProfile",value:function(e){var t=this.fallbackProfile(e);t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?g(i,"setProfile",this,3)([t]):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),g(i,"setProfile",this,3)([gA(_A({},this.profile),{width:1920,height:1080})]))}},{key:"applyProfile",value:function(){return bA(this,null,f().mark((function e(){var t,n,r,i,a,o,s,c,u,l,d,h,p;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.mediaTrack){e.next=2;break}return e.abrupt("return");case 2:if(n=(this.sourceTrack||this.mediaTrack).getSettings(),r=n.width,i=void 0===r?0:r,a=n.height,o=i*(void 0===a?0:a),s=this.settings,c=s.height!==this.profile.height||s.width!==this.profile.width||s.frameRate!==this.profile.frameRate,e.t0=c,!e.t0){e.next=14;break}if(16!==hx||!this.deviceId){e.next=10;break}return e.next=8,this.recapture(this.deviceId);case 8:e.next=13;break;case 10:return e.next=12,null==(t=this.sourceTrack||this.mediaTrack)?void 0:t.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate});case 12:this.manager&&this.manager.changeInput(this);case 13:this.room&&this.settings.height>=1440&&"publish"===this.state&&this.room.sendAbilityStatus({"2k4k":1});case 14:if(!(this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)){e.next=18;break}return this.isNeedToSetBandwidth=!1,u=(this.sourceTrack||this.mediaTrack).getSettings(),l=u.width,d=void 0===l?0:l,h=u.height,p=d*(void 0===h?0:h),e.abrupt("return",c&&p&&o&&p===o?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:IC.VIDEO,videoType:IC.BIG}));case 18:case"end":return e.stop()}}),e,this)})))}},{key:"settings",get:function(){var e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return FP&&t&&Object.assign(e,t.getSettings()),e}},{key:"scaleResolutionDownBy",get:function(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:wD(this.settings,this.profile)}},{key:"isAllowed2k4k",value:function(e){var t;return!(this.room&&this.room.scheduleResult&&!this.isScreen&&!(e.height*e.width<3686400))||1===(null==(t=this.room.scheduleResult.trtcAutoConf)?void 0:t["2k4k"])}},{key:"isNeedToSwitchDevice",value:function(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}},{key:"switchDevice",value:function(e){return bA(this,null,f().mark((function t(){var n;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(t.prev=0,this.isNeedToSwitchDevice(e)){t.next=3;break}return t.abrupt("return");case 3:return n={useExactDeviceId:!0,retryWhenExactFailed:!1},"user"===e||"environment"===e?n.facingMode=e:n.deviceId=e,this.mediaTrack.stop(),t.next=8,this.capture(n);case 8:Px.emit(Lx.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success"),t.next=15;break;case 12:throw t.prev=12,t.t0=t.catch(0),this.log.error("switch camera failed ".concat(t.t0)),this.deviceId&&this.recapture(this.deviceId),t.t0;case 15:case"end":return t.stop()}}),t,this,[[0,12]])})))}},{key:"updateSmallConfig",value:function(e){var t,n;this._log.info("update small stream config: ".concat(JSON.stringify(e)));var r=!this.small;this.small=this.fallbackProfile(e,!0),null==(t=this.manager)||t.update(),r&&(null==(n=this.room)||n.enableSmall(!0)),this.log.info("update small stream config success")}},{key:"fallbackProfile",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=e.width>e.height,r=_A({},e);return e.width*e.height<=19200&&$D&&tx&&(this.log.warn("".concat(t?"small ":"","resolution is ").concat(e.width,"*").concat(e.height,", fallback to 240*180 for android chrome")),r.width=n?240:180,r.height=n?180:240,r.bitrate=Math.max(e.bitrate,150)),e.width*e.height>921600&&mx&&(r.width=n?1280:720,r.height=n?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),!t&&this.avoidCropping&&(tx||rN)&&!Sx()&&e.width*e.height<=230400&&e.width/e.height==16/9&&(this._scaleResolutionDownBy=1280/e.width,e.width=1280,e.height=720,this.log.warn("capture 720p, scale: ".concat(this._scaleResolutionDownBy))),r}},{key:"stopSmall",value:function(){var e,t;this.small&&(delete this.small,null==(e=this.manager)||e.update(),null==(t=this.room)||t.enableSmall(!1))}},{key:"listenDeviceChange",value:function(){gL&&!gL.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&gL.on("videoInputRemoved",this.handleCameraRemoved,this)}},{key:"handleCameraRemoved",value:function(e){return bA(this,null,f().mark((function t(){var n;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(e.deviceId!==this.deviceId){t.next=6;break}return this.log.warn("current camera is lost: ".concat(JSON.stringify(e))),QF(this.userId,{eventId:2003,param1:7,streamType:2}),t.next=4,TL();case 4:(n=t.sent)[0]?this.recapture(n[0].deviceId):gL.on("videoInputAdded",this.handleCameraAdded,this);case 6:case"end":return t.stop()}}),t,this)})))}},{key:"handleCameraAdded",value:function(e){return bA(this,null,f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId);case 1:case"end":return t.stop()}}),t,this)})))}},{key:"encodeFrame",value:function(e,t){if(!this.manager)return e;var n=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight((function(e,t){return t?t({frame:e,mediaType:n}):e}),e)}},{key:"enableEncodeFrame",get:function(){return!!this.manager&&this.manager.encodePipeline.some((function(e){return e}))}},{key:"play",value:function(e,t){return Kw(this.mirror)&&!this.isScreen&&this.setMirror("view"),g(i,"play",this,3)([e,t])}},{key:"close",value:function(){gL.off("videoInputAdded",this.handleCameraAdded,this),gL.off("videoInputRemoved",this.handleCameraRemoved,this),g(i,"close",this,3)([])}},{key:"recapture",value:function(e){return bA(this,null,f().mark((function t(){var n;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,IA(i.prototype,this,"recapture").call(this,e);case 3:t.next=14;break;case 5:return t.prev=5,t.t0=t.catch(0),t.next=9,TL();case 9:if(n=t.sent.find((function(t){return t.deviceId!==e})),n){t.next=12;break}throw t.t0;case 12:return t.next=14,IA(i.prototype,this,"recapture").call(this,n.deviceId);case 14:case"end":return t.stop()}}),t,this,[[0,5]])})))}},{key:"setContentHint",value:function(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info("setContentHint ".concat(e)),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}},{key:"setRotation",value:function(e){this.manager&&(this.isScreen||Kw(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}}])}(eV);TA([HL((function(e){this.setContentHint(e.contentHint||"motion")}))],aV.prototype,"capture",1);var oV=aV,sV=Fx();if("undefined"!=typeof navigator&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:sV,exposeOrigin:!0,permittedOrigins:["*"]})}catch(Vj){}var cV=function(e){return bA(this,null,f().mark((function t(){var n,r,i,a;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n=null,r=function(e){var t={preferCurrentTab:"current-tab"===e.preferDisplaySurface||!!e.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},n={width:ox?{max:e.width}:{ideal:e.width,max:e.width},height:ox?{max:e.height}:{ideal:e.height,max:e.height},frameRate:e.frameRate,displaySurface:e.preferDisplaySurface||"monitor"};if(t.video=n,e.systemAudio){var r=e.echoCancellation,i=void 0===r||r,a=e.noiseSuppression,o=void 0!==a&&a,s=e.autoGainControl,c=void 0!==s&&s;t.audio={echoCancellation:i,noiseSuppression:o,autoGainControl:c,sampleRate:48e3}}return t}(e),Ux.info("getDisplayMedia with constraints: ".concat(JSON.stringify(r))),t.next=4,navigator.mediaDevices.getDisplayMedia(r);case 4:if(i=t.sent,e.systemAudio&&0===i.getAudioTracks().length&&(nx&&ix<74||ox||rN)&&Ux.warn("Your browser not support capture system audio"),!(a=i.getVideoTracks()[0])){t.next=21;break}if(!e.frameRate){t.next=17;break}return t.prev=9,t.next=12,a.applyConstraints({frameRate:{min:e.frameRate,ideal:e.frameRate},width:e.width,height:e.height});case 12:t.next=17;break;case 14:t.prev=14,t.t0=t.catch(9),Ux.warn("screen applyConstraints failed: ".concat(t.t0));case 17:if(t.t1=e.captureElement,!t.t1){t.next=21;break}return t.next=21,function(e,t){return bA(this,null,f().mark((function n(){var r,i;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(!("CropTarget"in window&&"fromElement"in CropTarget&&Jw(e.cropTo))){n.next=14;break}if(n.prev=1,(null==(r=e.getCaptureHandle())?void 0:r.handle)===sV){n.next=4;break}return n.abrupt("return");case 4:return n.next=6,CropTarget.fromElement(t);case 6:return i=n.sent,n.next=9,e.cropTo(i);case 9:n.next=14;break;case 11:n.prev=11,n.t0=n.catch(1),Ux.warn("cropTo target failed ".concat(n.t0));case 14:case"end":return n.stop()}}),n,null,[[1,11]])})))}(a,e.captureElement);case 21:if(!e.audio){t.next=28;break}return r=function(e){var t={echoCancellation:e.echoCancellation,autoGainControl:e.autoGainControl,noiseSuppression:e.noiseSuppression,sampleRate:e.sampleRate,channelCount:e.channelCount};return Kw(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}(e),Ux.info("getUserMedia with constraints: ".concat(JSON.stringify(r))),t.next=26,navigator.mediaDevices.getUserMedia(r);case 26:n=t.sent,i.addTrack(n.getAudioTracks()[0]);case 28:return t.abrupt("return",i);case 29:case"end":return t.stop()}}),t,null,[[9,14]])})))},uV=function(e){function i(e){var a;return r(this,i),a=n(this,i,[e,2]),SA(t(a),"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),SA(t(a),"objectFit","contain"),SA(t(a),"isScreen",!0),a._log.id="s-".concat(a._log.id),a}return d(i,e),o(i,[{key:"isShareCurrentTab",get:function(){var e,t;try{return sV===(null==(t=null==(e=this.mediaTrack)?void 0:e.getCaptureHandle())?void 0:t.handle)}catch(Yx){return}}},{key:"capture",value:function(e){return bA(this,arguments,(function(e){var t=this,n=e.systemAudio,r=void 0!==n&&n,i=e.autoGainControl,a=e.echoCancellation,o=e.noiseSuppression,s=e.audioTrack,c=e.videoTrack,u=e.captureElement,l=e.preferDisplaySurface;return f().mark((function e(){var n;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,!c&&!s){e.next=5;break}n=new MediaStream,c&&n.addTrack(c),s&&n.addTrack(s),e.next=8;break;case 5:return e.next=7,cV({audio:!1,systemAudio:r,width:t.profile.width,height:t.profile.height,frameRate:t.profile.frameRate,autoGainControl:i,echoCancellation:a,noiseSuppression:o,captureElement:u,preferDisplaySurface:l});case 7:n=e.sent;case 8:return e.next=10,t.setInputMediaStreamTrack(n.getVideoTracks()[0]);case 10:return e.abrupt("return",n);case 13:throw e.prev=13,e.t0=e.catch(0),t.log.error("getDisplayMedia error observed ".concat(e.t0)),e.t0 instanceof FA?e.t0:new FA({code:VA.INITIALIZE_FAILED,name:e.t0.name,message:e.t0.message});case 16:case"end":return e.stop()}}),e,null,[[0,13]])}))()}))}},{key:"switchDevice",value:function(e){return bA(this,null,f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:throw new Error("Method not implemented.");case 1:case"end":return e.stop()}}),e)})))}}])}(oV);TA([HL((function(e){this.setContentHint(e.contentHint||"detail")}))],uV.prototype,"capture",1);var lV,dV=function(e){function t(e){var i;return r(this,t),(i=n(this,t,[e]))._log.id="s-".concat(i._log.id),i}return d(t,e),o(t,[{key:"addAudioProcessor",value:function(e,t,n,r){this.pipeline.silentNode.setNode(n),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(r),this.enableTrackAEC(!1)}},{key:"removeAudioProcessor",value:function(e,t,n,r){this.pipeline.aec.node===r&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}}])}(nV);function hV(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:48e3,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,r=arguments.length>3?arguments[3]:void 0;return bA(this,null,f().mark((function i(){var a,o,s;return f().wrap((function(i){for(;;)switch(i.prev=i.next){case 0:return a=nL(),lV||(lV=qM(a,URL.createObjectURL(new Blob(['registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;t<r.length;t++){o[t]=[];for(let e=0;e<r[t].length;e++)o[t][e]=this.resample(r[t][e],s,a)}return o}resample(t,e,r){if(e===r)return t;var s=Math.round(t.length*(this.targetSampleRate/this.sourceSampleRate)),a=new Float32Array(s),o=(t.length-1)/(s-1);a[0]=t[0];for(let e=1;e<s-1;e++){var l=e*o,p=Math.floor(l),h=Math.ceil(l);a[e]=t[p]+(t[h]-t[p])*(l-p)}return a[s-1]=t[t.length-1],a}});'],{type:"application/javascript"})))),i.next=4,lV;case 4:return o=a.sampleRate,s=new AudioWorkletNode(a,"dumper",{numberOfInputs:e.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:o,targetSampleRate:t}}),i.abrupt("return",(s.channelCountMode="explicit",s.channelCount=n,r&&s.port.postMessage({port:r},[r]),e.forEach((function(e,t){return e.connect(s,0,t)})),new ReadableStream({start:function(e){s.port.onmessage=function(t){e.enqueue(t.data)}},cancel:function(){e.forEach((function(e){return e.disconnect(s)})),s.port.close()}})));case 6:case"end":return i.stop()}}),i)})))}var fV=function(e){function i(e){var a;return r(this,i),(a=n(this,i)).room=e,SA(t(a),"_localAudioTrack"),SA(t(a),"_localScreenAudioTrack"),SA(t(a),"log",Ux.createLogger({id:"am"})),SA(t(a),"denoiser"),SA(t(a),"voiceChanger"),SA(t(a),"mixChangedDebounce"),SA(t(a),"audioProcessor"),SA(t(a),"encodePipeline",[]),SA(t(a),"decodePipeline",[]),SA(t(a),"getPCMAbortCtrlMap",new Map),SA(t(a),"audioFrameEventConfigMap",new Map),SA(t(a),"audioReferenceMap",new Map),SA(t(a),"isLocalAudioNeedAudioProcess",!1),SA(t(a),"isScreenAudioNeedAudioProcess",!1),e&&(a.log.setUserId(e.userId),a.log.setSdkAppId(e.sdkAppId)),a.installEvent(),a}return d(i,e),o(i,[{key:"_localAudioPipline",get:function(){var e;return null==(e=this._localAudioTrack)?void 0:e.pipeline}},{key:"_localScreenAudioPipeline",get:function(){var e;return null==(e=this._localScreenAudioTrack)?void 0:e.pipeline}},{key:"dump",value:function(e){var t,n,r=this;if(this._localAudioTrack){var i=[],a=[];null!=(t=this._localAudioPipline)&&t.source.node&&(i.push(this._localAudioPipline.source.node),a.push("mic")),null!=(n=this._localAudioPipline)&&n.denoiser.node&&(i.push(this._localAudioPipline.denoiser.node),a.push("mic-processed")),this.mixWeight>1&&(i.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),a.push("mix")),this.log.info("dump audio track ".concat(a,", duration: ").concat(e));var o=new AbortController,s=[],c=setTimeout((function(){r.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")}),1e3*e),u=function(){for(var e=0;e<a.length;e++){var t=URL.createObjectURL(new Blob(s[e])),n=document.createElement("a");n.href=t,n.download="".concat(a[e],".pcm"),n.style.display="none",document.body.appendChild(n),n.click(),URL.revokeObjectURL(t),n.remove()}clearTimeout(c),o.abort("download")},l=hV(i).then((function(e){return e.pipeTo(new WritableStream({write:function(e){e.forEach((function(e,t){return s[t]=s[t]?s[t].concat(e[0]):[e[0]]}))}}),o).catch((function(e){return u}))}));return{then:l.then.bind(l),download:u}}}},{key:"getPCM",value:function(e,t){var n,r,i,a=this;if(Kw(WritableStream))this.log.warn("getPCM failed: browser not support WritableStream");else{var o=(""===t?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{},s=o.enable,c=o.sampleRate,u=void 0===c?48e3:c,l=o.channelCount,d=void 0===l?1:l,h=o.port;if(s){this.log.info("getPCM ".concat(t||"local"));var f,p,m=Math.floor(.04*u),v=new Float32Array(m),_=new Float32Array(m),g=0,y=new AbortController,E=""===t?null==(n=this._localAudioTrack)?void 0:n.mediaTrack:null==(i=null==(r=this.room)?void 0:r.remotePublishedUserMap.get(t))?void 0:i.remoteAudioTrack.mediaTrack;if(E)return hV([nL().createMediaStreamSource(new MediaStream([E]))],u,d,h).then((function(n){return n.pipeTo(new WritableStream({write:function(n){n[0][0]&&(g+n[0][0].length>m?(v.set(n[0][0].subarray(0,m-g),g),f=n[0][0].subarray(m-g),n[0][1]&&(_.set(n[0][1].subarray(0,m-g),g),p=n[0][1].subarray(m-g)),g+=m-g):(f&&(v.set(f,g),g+=f.length,f=void 0),p&&(_.set(p,g),p=void 0),v.set(n[0][0],g),n[0][1]&&_.set(n[0][1],g),g+=n[0][0].length),g>=m&&(g=0,e({userId:t,sampleRate:u,channelCount:d,data:1===d?v:[v,_]}),v=new Float32Array(m),_=new Float32Array(m)))}}),y).catch((function(e){return a.log.warn("stop getPCM reason:".concat(e))}))})),y;this.log.info("getPCM failed: ".concat(t||"local"," has no audio track"))}}}},{key:"hasScreenAudioTrack",get:function(){return!Kw(this._localScreenAudioTrack)}},{key:"hasAudioTrack",get:function(){return!Kw(this._localAudioTrack)}},{key:"changeInput",value:function(e){return e instanceof dV?(this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&this.audioProcessor&&(e.addAudioProcessor.apply(e,E(this.audioProcessor)),this.audioReferenceMap.forEach((function(t,n){e.mixAudioReference(t,n)}))),e.pipeline.connect(),this.mixOnChange()):e instanceof nV?(this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&this.audioProcessor&&(e.addAudioProcessor.apply(e,E(this.audioProcessor)),this.audioReferenceMap.forEach((function(t,n){e.mixAudioReference(t,n)}))),e.pipeline.connect(),this.mixOnChange()):e instanceof DF?e.setOutputMediaStreamTrack(e.mediaTrack):void 0}},{key:"mixAudioReference",value:function(e,t){var n;null==(n=this._localAudioTrack)||n.mixAudioReference(e,t)}},{key:"unMixAudioReference",value:function(e){var t;null==(t=this._localAudioTrack)||t.unMixAudioReference(e)}},{key:"setAudioReferenceVolume",value:function(e,t){var n;null==(n=this._localAudioTrack)||n.setAudioReferenceVolume(e,t)}},{key:"mixOnChange",value:function(){var e=this;return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then((function(){var t,n;return delete e.mixChangedDebounce,Promise.all([null==(t=e._localAudioTrack)?void 0:t.setOutputMediaStreamTrack(e.mixWeight>1?e.mixTrack:e._localAudioTrack.mediaTrack),null==(n=e._localScreenAudioTrack)?void 0:n.setOutputMediaStreamTrack(e.mixWeight>1?e.mixTrack:e._localScreenAudioTrack.mediaTrack)])}))),this.mixChangedDebounce}},{key:"removeInput",value:function(e){e instanceof dV?delete this._localScreenAudioTrack:e instanceof nV&&delete this._localAudioTrack}},{key:"addDenoiser",value:function(e){var t;this.denoiser=e,null==(t=this._localAudioTrack)||t.addDenoiser(e)}},{key:"addAudioProcessor",value:function(e,t,n,r){var i,a,o,s=this;this.audioProcessor=[e,t,n,r],this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&((i=this._localAudioTrack).addAudioProcessor.apply(i,E(this.audioProcessor)),this.audioReferenceMap.forEach((function(e,t){var n;null==(n=s._localAudioTrack)||n.mixAudioReference(e,t)}))),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&(null==(o=this._localScreenAudioTrack)||(a=o).addAudioProcessor.apply(a,E(this.audioProcessor)),this.audioReferenceMap.forEach((function(e,t){var n;null==(n=s._localScreenAudioTrack)||n.mixAudioReference(e,t)})))}},{key:"removeDenoiser",value:function(e){var t;delete this.denoiser,null==(t=this._localAudioTrack)||t.removeDenoiser(e)}},{key:"addVoiceChanger",value:function(e,t){var n;this.voiceChanger=[e,t],null==(n=this._localAudioTrack)||n.pipeline.voiceChanger.setNode(e,t)}},{key:"removeVoiceChanger",value:function(){var e;delete this.voiceChanger,null==(e=this._localAudioTrack)||e.pipeline.voiceChanger.deleteNode()}},{key:"removeAudioProcessor",value:function(e,t,n,r){var i;delete this.audioProcessor,null==(i=this._localAudioTrack)||i.removeAudioProcessor(e,t,n,r)}},{key:"destroy",value:function(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach((function(e){return null==e?void 0:e.abort("destroy")})),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}},{key:"addEncodeProcessor",value:function(e){var t,n=e.processor,r=e.type;this.encodePipeline.includes(n)||(this.encodePipeline[r]=n,null==(t=this.room)||t.enableInsertableStreams())}},{key:"addDecodeProcessor",value:function(e){var t,n=e.processor,r=e.type;this.decodePipeline.includes(n)||(this.decodePipeline[r]=n,null==(t=this.room)||t.enableInsertableStreams())}},{key:"removeEncodeProcessor",value:function(e){var t=e.type;this.encodePipeline[t]=void 0}},{key:"removeDecodeProcessor",value:function(e){var t=e.type;this.decodePipeline[t]=void 0}},{key:"handleLocalTrackStarted",value:function(e){var t,n=this,r=e.room,i=e.userId;if(r===this.room&&!this.getPCMAbortCtrlMap.get(i)){var a=this.getPCM((function(e){var t;null==(t=n.room)||t.emit("audio-frame",e)}),"");this.getPCMAbortCtrlMap.set(i,a),this.getPCMAbortCtrlMap.get(i)&&(null==(t=this._localAudioTrack)||t.on("input-media-track-changed",(function(){var e=n.getPCMAbortCtrlMap.get(i);e&&(e.abort("inputMediaTrackChanged"),e=n.getPCM((function(e){var t;null==(t=n.room)||t.emit("audio-frame",e)}),""),n.getPCMAbortCtrlMap.set(i,e))})))}}},{key:"handleLocalTrackStopped",value:function(e){var t=e.room,n=e.userId;if(t===this.room){var r=this.getPCMAbortCtrlMap.get(n);r&&(r.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(n))}}},{key:"handleRemoteTrackStarted",value:function(e){var t=this,n=e.room,r=e.userId;if(n===this.room&&!this.getPCMAbortCtrlMap.get(r)){var i=this.room.audioManager.getPCM((function(e){var n;null==(n=t.room)||n.emit("audio-frame",e)}),r);this.getPCMAbortCtrlMap.set(r,i)}}},{key:"handleRemoteTrackStopped",value:function(e){var t=e.room,n=e.userId;if(t===this.room){var r=this.getPCMAbortCtrlMap.get(n);r&&(r.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(n))}}},{key:"installEvent",value:function(){Px.on("113",this.handleLocalTrackStarted,this),Px.on("114",this.handleLocalTrackStopped,this),Px.on("115",this.handleRemoteTrackStarted,this),Px.on("116",this.handleRemoteTrackStopped,this)}},{key:"uninstallEvent",value:function(){Px.off("113",this.handleLocalTrackStarted),Px.off("114",this.handleLocalTrackStopped),Px.off("115",this.handleRemoteTrackStarted),Px.off("116",this.handleRemoteTrackStopped)}},{key:"updateAudioReference",value:function(e){var t=e.type,n=e.audioReference,r=e.refId,i=e.volume;if("add"===t){if(this.audioReferenceMap.get(r)||!n||(this.audioReferenceMap.set(r,n),!this.audioProcessor))return;this.mixAudioReference(n,r)}else if("remove"===t)this.audioReferenceMap.get(r)&&(this.audioReferenceMap.delete(r),this.unMixAudioReference(r));else if("updateVolume"===t){if(!this.audioProcessor||Kw(i))return;this.setAudioReferenceVolume(r,i)}}}])}(sL);function pV(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2;return jL((function(n,r){return function(){for(var i=this,a=arguments.length,o=new Array(a),s=0;s<a;s++)o[s]=arguments[s];return new Promise((function(a,s){var c=setTimeout((function(){var n=new FA({code:VA.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(r,"() timeout ").concat(e,"s")});Ux.warn(n),2===t?s(n):1===t&&a()}),1e3*e);n.apply(i,o).then(a,s).finally((function(){clearTimeout(c)}))}))}}))}var mV={};function vV(){}EA(mV,{Events:function(){return NV},Inspect:function(){return TV},LastSink:function(){return SV},Sink:function(){return IV},Subscribe:function(){return bV},TimeoutError:function(){return xV},audit:function(){return LU},bindCallback:function(){return dU},bindNodeCallback:function(){return hU},buffer:function(){return JV},bufferCount:function(){return GV},bufferTime:function(){return yF},call:function(){return _V},catchError:function(){return kF},combineLatest:function(){return BV},concat:function(){return VV},concatMap:function(){return sF},concatMapTo:function(){return cF},count:function(){return gU},create:function(){return AV},debounce:function(){return FU},debounceTime:function(){return BU},defer:function(){return zV},delay:function(){return EF},deliver:function(){return CV},dispose:function(){return yV},elementAt:function(){return HU},empty:function(){return mU},every:function(){return KU},exhaustMap:function(){return mF},exhaustMapTo:function(){return vF},filter:function(){return TU},find:function(){return WU},findIndex:function(){return jU},first:function(){return GU},fromAnimationFrame:function(){return uU},fromArray:function(){return ZV},fromEvent:function(){return rU},fromEventPattern:function(){return nU},fromFetch:function(){return aU},fromIterable:function(){return oU},fromPromise:function(){return iU},fromReadableStream:function(){return cU},fromReader:function(){return sU},groupBy:function(){return _F},identity:function(){return gV},ignoreElements:function(){return SU},iif:function(){return FV},inspect:function(){return EV},interval:function(){return $V},last:function(){return JU},map:function(){return XU},mapTo:function(){return QU},max:function(){return yU},merge:function(){return MV},mergeMap:function(){return dF},mergeMapTo:function(){return hF},min:function(){return EU},never:function(){return fU},nothing:function(){return vV},of:function(){return QV},pairwise:function(){return zU},pipe:function(){return RV},race:function(){return LV},range:function(){return lU},reduce:function(){return _U},retry:function(){return AF},scan:function(){return YU},share:function(){return PV},shareReplay:function(){return UV},skip:function(){return CU},skipUntil:function(){return wU},skipWhile:function(){return DU},startWith:function(){return WV},subject:function(){return YV},subscribe:function(){return IF},sum:function(){return kU},switchMap:function(){return nF},switchMapTo:function(){return iF},take:function(){return IU},takeLast:function(){return AU},takeUntil:function(){return bU},takeWhile:function(){return RU},tap:function(){return bF},throttle:function(){return PU},throwError:function(){return pU},timeInterval:function(){return gF},timeout:function(){return RF},timer:function(){return eU},toPromise:function(){return TF},toReadableStream:function(){return SF},withLatestFrom:function(){return jV},zip:function(){return HV}});var _V=function(e){return e()},gV=function(e){return e};function yV(){this.dispose()}var EV=function(){return"undefined"!=typeof __FASTRX_DEVTOOLS__},kV=1,TV=function(e){function t(){return r(this,t),n(this,t,arguments)}return d(t,e),o(t,[{key:"toString",value:function(){return"".concat(this.name,"(").concat(this.args.length?E(this.args).join(", "):"",")")}},{key:"subscribe",value:function(e){var t=new DV(e,this,this.streamId++);return NV.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}}])}(I(Function)),SV=function(){return o((function e(){r(this,e),this.defers=new Set,this.disposed=!1}),[{key:"next",value:function(e){}},{key:"complete",value:function(){this.dispose()}},{key:"error",value:function(e){this.dispose()}},{key:"bindDispose",get:function(){var e=this;return function(){return e.dispose()}}},{key:"dispose",value:function(){this.disposed=!0,this.complete=vV,this.error=vV,this.next=vV,this.dispose=vV,this.subscribe=vV,this.doDefer()}},{key:"subscribe",value:function(e){return e instanceof TV?e.subscribe(this):e(this),this}},{key:"bindSubscribe",get:function(){var e=this;return function(t){return e.subscribe(t)}}},{key:"doDefer",value:function(){this.defers.forEach(_V),this.defers.clear()}},{key:"defer",value:function(e){this.defers.add(e)}},{key:"removeDefer",value:function(e){this.defers.delete(e)}},{key:"reset",value:function(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}},{key:"resetNext",value:function(){delete this.next}},{key:"resetComplete",value:function(){delete this.complete}},{key:"resetError",value:function(){delete this.error}}])}(),IV=function(e){function t(e){var i;return r(this,t),(i=n(this,t)).sink=e,e.defer(i.bindDispose),i}return d(t,e),o(t,[{key:"next",value:function(e){this.sink.next(e)}},{key:"complete",value:function(){this.sink.complete()}},{key:"error",value:function(e){this.sink.error(e)}}])}(SV),bV=function(e){function t(e){var i;r(this,t);var a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:vV,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:vV,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:vV;if((i=n(this,t))._next=a,i._error=o,i._complete=s,i.then=vV,e instanceof TV){var c={toString:function(){return"subscribe"},id:0,source:e};i.defer((function(){NV.defer(c,0)})),NV.create(c),NV.pipe(c),i.sourceId=c.id,i.subscribe(e),NV.subscribe({id:c.id,end:!0}),a==vV?i._next=function(e){return NV.next(c,0,e)}:i.next=function(e){NV.next(c,0,e),a(e)},s==vV?i._complete=function(){return NV.complete(c,0)}:i.complete=function(){i.dispose(),NV.complete(c,0),s()},o==vV?i._error=function(e){return NV.complete(c,0,e)}:i.error=function(e){i.dispose(),NV.complete(c,0,e),o()}}else i.subscribe(e);return i}return d(t,e),o(t,[{key:"next",value:function(e){this._next(e)}},{key:"complete",value:function(){this.dispose(),this._complete()}},{key:"error",value:function(e){this.dispose(),this._error(e)}}])}(SV);function RV(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return n.reduce((function(e,t){return t(e)}),e)}function AV(e,t,n){if(EV()){var r=Object.defineProperties(Object.setPrototypeOf(e,TV.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:t,writable:!0,configurable:!0},args:{value:n,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});NV.create(r);for(var i=0;i<n.length;i++){var a=n[i];"function"==typeof a&&a instanceof TV&&NV.addSource(r,a)}return r}return e}function CV(e,t){return function(){for(var n=arguments,r=arguments.length,a=new Array(r),o=0;o<r;o++)a[o]=arguments[o];return function(r){if(r instanceof TV){var o=AV((function(t){var n=i(e,[t].concat(a));n.sourceId=o.id,n.subscribe(r)}),t,n);return o.source=r,NV.pipe(o),o}return function(t){return r(i(e,[t].concat(a)))}}}}function wV(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var DV=function(e){function t(e,i,a){var o;return r(this,t),(o=n(this,t,[e])).source=i,o.id=a,o.sourceId=e.sourceId,o.defer((function(){NV.defer(o.source,o.id)})),o}return d(t,e),o(t,[{key:"next",value:function(e){NV.next(this.source,this.id,e),this.sink.next(e)}},{key:"complete",value:function(){NV.complete(this.source,this.id),this.sink.complete()}},{key:"error",value:function(e){NV.complete(this.source,this.id,e),this.sink.error(e)}}])}(IV),NV={addSource:function(e,t){wV("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next:function(e,t,n){wV("next",{id:e.id,streamId:t,data:n&&n.toString()})},subscribe:function(e,t){wV("subscribe",{id:e.id,end:e.end,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete:function(e,t,n){wV("complete",{id:e.id,streamId:t,err:n?n.toString():null})},defer:function(e,t){wV("defer",{id:e.id,streamId:t})},pipe:function(e){wV("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update:function(e){wV("update",{id:e.id,name:e.toString()})},create:function(e){e.id||(e.id=kV++),wV("create",{name:e.toString(),id:e.id})}},xV=function(e){function t(e){var i;return r(this,t),(i=n(this,t,["timeout after ".concat(e,"ms")])).timeout=e,i}return d(t,e),o(t)}(I(Error)),OV=function(e){function t(e){var i;return r(this,t),(i=n(this,t)).source=e,i.sinks=new Set,i}return d(t,e),o(t,[{key:"add",value:function(e){var t=this;e.defer((function(){return t.remove(e)})),1===this.sinks.add(e).size&&(this.reset(),this.subscribe(this.source))}},{key:"remove",value:function(e){this.sinks.delete(e),0===this.sinks.size&&this.dispose()}},{key:"next",value:function(e){this.sinks.forEach((function(t){return t.next(e)}))}},{key:"complete",value:function(){this.sinks.forEach((function(e){return e.complete()})),this.sinks.clear()}},{key:"error",value:function(e){this.sinks.forEach((function(t){return t.error(e)})),this.sinks.clear()}}])}(SV);function PV(){var e=arguments;return function(t){var n=new OV(t);if(t instanceof TV){var r=AV((function(e){n.add(e)}),"share",e);return n.sourceId=r.id,r.source=t,NV.pipe(r),r}return AV(n.add.bind(n),"share",e)}}function MV(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return AV((function(e){var n=new IV(e),r=t.length;n.complete=function(){0==--r&&e.complete()},t.forEach(n.bindSubscribe)}),"merge",arguments)}function LV(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return AV((function(e){var n=new Map;t.forEach((function(t){var r=new IV(e);n.set(t,r),r.complete=function(){n.delete(t),0===n.size?e.complete():r.dispose()},r.next=function(e){n.delete(t),n.forEach((function(e){return e.dispose()})),r.resetNext(),r.resetComplete(),r.next(e)}})),t.forEach((function(e){return n.get(e).subscribe(e)}))}),"race",arguments)}function VV(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return AV((function(e){var n=0,r=t.length,i=new IV(e);i.complete=function(){n<r&&!i.disposed?(i.doDefer(),i.subscribe(t[n++])):e.complete()},i.complete()}),"concat",arguments)}function UV(e){var t=arguments;return function(n){var r=new OV(n),i=[];return r.next=function(t){i.push(t),i.length>e&&i.shift(),this.sinks.forEach((function(e){return e.next(t)}))},AV((function(e){e.defer((function(){return r.remove(e)})),i.forEach((function(t){return e.next(t)})),r.add(e)}),"shareReplay",t)}}function FV(e,t,n){return AV((function(r){return e()?t(r):n(r)}),"iif",arguments)}function BV(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return AV((function(e){var n=t.length,r=n,i=n,a=new Array(n),o=function(){0==--i&&e.complete()};t.forEach((function(t,n){var i=new IV(e);i.next=function(t){0==--r?(i.next=function(t){a[n]=t,e.next(a)},i.next(t)):a[n]=t},i.complete=o,i.subscribe(t)}))}),"combineLatest",arguments)}function HV(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return AV((function(e){var n=t.length,r=n,i=new Array(n),a=function(){0==--r&&e.complete()};t.forEach((function(t,n){var r=new IV(e),o=[];i[n]=o,r.next=function(t){o.push(t),i.every((function(e){return e.length}))&&e.next(i.map((function(e){return e.shift()})))},r.complete=a,r.subscribe(t)}))}),"zip",arguments)}function WV(){for(var e=arguments,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return function(t){return AV((function(e){for(var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:n.length;r<i&&!e.disposed;)e.next(n[r++]);e.disposed||e.subscribe(t)}),"startWith",e)}}var jV=CV(function(e){function t(e){var i;r(this,t),i=n(this,t,[e]);for(var a=new IV(i.sink),o=arguments.length,s=new Array(o>1?o-1:0),c=1;c<o;c++)s[c-1]=arguments[c];return a.next=function(e){return i.buffer=e},a.complete=vV,a.subscribe(BV.apply(void 0,s)),i}return d(t,e),o(t,[{key:"next",value:function(e){this.buffer&&this.sink.next([e].concat(E(this.buffer)))}}])}(IV),"withLatestFrom"),GV=CV(function(e){function t(e,i,a){var o;return r(this,t),(o=n(this,t,[e])).bufferSize=i,o.startBufferEvery=a,o.buffer=[],o.count=0,o.startBufferEvery&&(o.buffers=[[]]),o}return d(t,e),o(t,[{key:"next",value:function(e){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach((function(t){t.push(e)})),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(e),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}},{key:"complete",value:function(){var e=this;this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach((function(t){return e.sink.next(t)})),g(t,"complete",this,3)([])}}])}(IV),"bufferCount"),JV=CV(function(e){function t(e,i){var a;r(this,t),(a=n(this,t,[e])).buffer=[];var o=new IV(e);return o.next=function(t){e.next(a.buffer),a.buffer=[]},o.complete=vV,o.subscribe(i),a}return d(t,e),o(t,[{key:"next",value:function(e){this.buffer.push(e)}},{key:"complete",value:function(){this.buffer.length&&this.sink.next(this.buffer),g(t,"complete",this,3)([])}}])}(IV),"buffer"),KV=function(e,t,n,r){return new(n||(n=Promise))((function(i,a){function o(e){try{c(r.next(e))}catch(t){a(t)}}function s(e){try{c(r.throw(e))}catch(t){a(t)}}function c(e){e.done?i(e.value):function(e){return e instanceof n?e:new n((function(t){t(e)}))}(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())}))};function YV(e){var t=arguments,n=PV()(AV((function(t){n.next=function(e){return t.next(e)},n.complete=function(){return t.complete()},n.error=function(e){return t.error(e)},e&&t.subscribe(e)}),"subject",t));return n.next=vV,n.complete=vV,n.error=vV,n}function zV(e){return AV((function(t){return t.subscribe(e())}),"defer",arguments)}var qV=function(e){return function(t){setTimeout((function(){return e(t)}))}},XV=function(e){return qV((function(t){for(var n=0;!t.disposed&&n<e.length;n++)t.next(e[n]);t.complete()}))};function QV(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return AV(XV(t),"of",arguments)}function ZV(e){return AV(XV(e),"fromArray",arguments)}function $V(e){return AV((function(t){var n=0,r=setInterval((function(){return t.next(n++)}),e);return t.defer((function(){clearInterval(r)})),"interval"}),"interval",arguments)}function eU(e,t){return AV((function(n){var r=0,i=setTimeout((function(){if(n.removeDefer(a),n.next(r++),t){var e=setInterval((function(){return n.next(r++)}),t);n.defer((function(){clearInterval(e)}))}else n.complete()}),e),a=function(){clearTimeout(i)};n.defer(a)}),"timer",arguments)}function tU(e,t){return function(n){var r=function(e){return n.next(e)};n.defer((function(){return t(r)})),e(r)}}function nU(e,t){return AV(tU(e,t),"fromEventPattern",arguments)}function rU(e,t){if("on"in e&&"off"in e)return AV(tU((function(n){return e.on(t,n)}),(function(n){return e.off(t,n)})),"fromEvent",arguments);if("addListener"in e&&"removeListener"in e)return AV(tU((function(n){return e.addListener(t,n)}),(function(n){return e.removeListener(t,n)})),"fromEvent",arguments);if("addEventListener"in e)return AV(tU((function(n){return e.addEventListener(t,n)}),(function(n){return e.removeEventListener(t,n)})),"fromEvent",arguments);throw"target is not a EventDispachter"}function iU(e){return AV((function(t){e.then(t.next.bind(t),t.error.bind(t))}),"fromPromise",arguments)}function aU(e,t){return AV(zV((function(){return iU(fetch(e,t))})),"fromFetch",arguments)}function oU(e){return AV(qV((function(t){try{var n,r=s(e);try{for(r.s();!(n=r.n()).done;){var i=n.value;if(t.disposed)return;t.next(i)}}catch(a){r.e(a)}finally{r.f()}t.complete()}catch(qA){t.error(qA)}})),"fromIterable",arguments)}function sU(e){var t=this,n=function(r){return KV(t,void 0,void 0,f().mark((function t(){var i,a,o;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!r.disposed){t.next=2;break}return t.abrupt("return");case 2:return t.next=4,e.read();case 4:i=t.sent,a=i.done,o=i.value,a?r.complete():(r.next(o),n(r));case 8:case"end":return t.stop()}}),t)})))};return AV((function(e){n(e)}),"fromReader",arguments)}function cU(e){return AV((function(t){var n=new AbortController,r=n.signal;t.defer((function(){return n.abort("cancelled")})),e.pipeTo(new WritableStream({write:function(e){t.next(e)},close:function(){t.complete()},abort:function(e){t.error(e)}}),{signal:r}).then((function(){return t.complete()}),(function(e){return t.error(e)}))}),"fromReadableStream",arguments)}function uU(){return AV((function(e){var t=requestAnimationFrame((function n(r){e.disposed||(e.next(r),t=requestAnimationFrame(n))}));e.defer((function(){return cancelAnimationFrame(t)}))}),"fromAnimationFrame",arguments)}function lU(e,t){return AV((function(n){for(var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t+e;r<i&&!n.disposed;)n.next(r++);return n.complete(),"range"}),"range",arguments)}function dU(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i<n;i++)r[i-2]=arguments[i];return AV((function(n){var i=r.concat((function(e){return n.next(e),n.complete()}));e.apply(t,i)}),"bindCallback",arguments)}function hU(e,t){for(var n=arguments.length,r=new Array(n>2?n-2:0),i=2;i<n;i++)r[i-2]=arguments[i];return AV((function(n){var i=r.concat((function(e,t){return e?n.error(e):(n.next(t),n.complete())}));e.apply(t,i)}),"bindNodeCallback",arguments)}function fU(){return AV((function(){}),"never",arguments)}function pU(e){return AV((function(t){return t.error(e)}),"throwError",arguments)}function mU(){return AV((function(e){return e.complete()}),"empty",arguments)}var vU=function(e){function t(e,i,a){var o;r(this,t),(o=n(this,t,[e])).f=i;var s=function(){o.sink.next(o.acc),o.sink.complete()};return void 0===a?o.next=function(e){o.acc=e,o.complete=s,o.resetNext()}:(o.acc=a,o.complete=s),o}return d(t,e),o(t,[{key:"next",value:function(e){this.acc=this.f(this.acc,e)}}])}(IV),_U=CV(vU,"reduce"),gU=function(e){return CV(vU,"count")((function(t,n){return e(n)?t+1:t}),0)},yU=function(){return CV(vU,"max")(Math.max)},EU=function(){return CV(vU,"min")(Math.min)},kU=function(){return CV(vU,"sum")((function(e,t){return e+t}),0)},TU=CV(function(e){function t(e,i,a){var o;return r(this,t),(o=n(this,t,[e])).filter=i,o.thisArg=a,o}return d(t,e),o(t,[{key:"next",value:function(e){this.filter.call(this.thisArg,e)&&this.sink.next(e)}}])}(IV),"filter"),SU=CV(function(e){function t(){return r(this,t),n(this,t,arguments)}return d(t,e),o(t,[{key:"next",value:function(e){}}])}(IV),"ignoreElements"),IU=CV(function(e){function t(e,i){var a;return r(this,t),(a=n(this,t,[e])).count=i,a}return d(t,e),o(t,[{key:"next",value:function(e){this.sink.next(e),0==--this.count&&this.complete()}}])}(IV),"take"),bU=CV(function(e){function t(e,i){var a;r(this,t),a=n(this,t,[e]);var o=new IV(e);return o.next=function(){return e.complete()},o.complete=yV,o.subscribe(i),a}return d(t,e),o(t)}(IV),"takeUntil"),RU=CV(function(e){function t(e,i){var a;return r(this,t),(a=n(this,t,[e])).f=i,a}return d(t,e),o(t,[{key:"next",value:function(e){this.f(e)?this.sink.next(e):this.complete()}}])}(IV),"takeWhile"),AU=function(e){return _U((function(t,n){return t.push(n),t.length>e&&t.shift(),t}),[])},CU=CV(function(e){function t(e,i){var a;return r(this,t),(a=n(this,t,[e])).count=i,a}return d(t,e),o(t,[{key:"next",value:function(e){0==--this.count&&(this.next=g(t,"next",this,1))}}])}(IV),"skip"),wU=CV(function(e){function t(e,i){var a;r(this,t),a=n(this,t,[e]),e.next=vV;var o=new IV(e);return o.next=function(){o.dispose(),e.resetNext()},o.complete=yV,o.subscribe(i),a}return d(t,e),o(t)}(IV),"skipUntil"),DU=CV(function(e){function t(e,i){var a;return r(this,t),(a=n(this,t,[e])).f=i,a}return d(t,e),o(t,[{key:"next",value:function(e){this.f(e)||(this.next=g(t,"next",this,1),this.next(e))}}])}(IV),"skipWhile"),NU={leading:!0,trailing:!1},xU=function(e){function t(e,i,a){var o;return r(this,t),(o=n(this,t,[e])).durationSelector=i,o.trailing=a,o}return d(t,e),o(t,[{key:"cacheValue",value:function(e){this.last=e,this.disposed&&this.throttle(e)}},{key:"send",value:function(e){this.sink.next(e),this.throttle(e)}},{key:"throttle",value:function(e){this.reset(),this.subscribe(this.durationSelector(e))}},{key:"next",value:function(){this.complete()}},{key:"complete",value:function(){this.dispose(),this.trailing&&this.send(this.last)}}])}(IV),OU=function(e){function t(e,i){var a;r(this,t);var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:NU;return(a=n(this,t,[e])).durationSelector=i,a.config=o,a._throttle=new xU(a.sink,a.durationSelector,a.config.trailing),a._throttle.dispose(),a}return d(t,e),o(t,[{key:"next",value:function(e){this._throttle.disposed&&this.config.leading?this._throttle.send(e):this._throttle.cacheValue(e)}},{key:"complete",value:function(){this._throttle.throttle=vV,this._throttle.complete(),g(t,"complete",this,3)([])}}])}(IV),PU=CV(OU,"throttle"),MU={leading:!1,trailing:!0},LU=function(e){return CV(OU,"audit")(e,MU)},VU=function(e){function t(){return r(this,t),n(this,t,arguments)}return d(t,e),o(t,[{key:"next",value:function(){this.complete()}},{key:"complete",value:function(){this.dispose(),this.sink.next(this.last)}}])}(IV),UU=function(e){function t(e,i){var a;return r(this,t),(a=n(this,t,[e])).durationSelector=i,a._debounce=new VU(a.sink),a._debounce.dispose(),a}return d(t,e),o(t,[{key:"next",value:function(e){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=e,this._debounce.subscribe(this.durationSelector(e))}},{key:"complete",value:function(){this._debounce.complete(),g(t,"complete",this,3)([])}}])}(IV),FU=CV(UU,"debounce"),BU=function(e){return CV(UU,"debounceTime")((function(t){return eU(e)}))},HU=CV(function(e){function t(e,i,a){var o;return r(this,t),(o=n(this,t,[e])).count=i,o.defaultValue=a,o}return d(t,e),o(t,[{key:"next",value:function(e){0==this.count--&&(this.defaultValue=e,this.complete())}},{key:"complete",value:function(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),g(t,"complete",this,3)([])):this.error(new Error("not enough elements in sequence"))}}])}(IV),"elementAt"),WU=function(e){return function(t){return IU(1)(DU((function(t){return!e(t)}))(t))}},jU=CV(function(e){function t(e,i){var a;return r(this,t),(a=n(this,t,[e])).f=i,a.i=0,a}return d(t,e),o(t,[{key:"next",value:function(e){this.f(e)?(this.sink.next(this.i++),this.complete()):++this.i}}])}(IV),"findIndex"),GU=CV(function(e){function t(e,i,a){var o;return r(this,t),(o=n(this,t,[e])).f=i,o.defaultValue=a,o.index=0,o}return d(t,e),o(t,[{key:"next",value:function(e){(!this.f||this.f(e,this.index++))&&(this.defaultValue=e,this.complete())}},{key:"complete",value:function(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),g(t,"complete",this,3)([])):this.error(new Error("no elements in sequence"))}}])}(IV),"first"),JU=CV(function(e){function t(e,i,a){var o;return r(this,t),(o=n(this,t,[e])).f=i,o.defaultValue=a,o.index=0,o}return d(t,e),o(t,[{key:"next",value:function(e){(!this.f||this.f(e,this.index++))&&(this.defaultValue=e)}},{key:"complete",value:function(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),g(t,"complete",this,3)([])):this.error(new Error("no elements in sequence"))}}])}(IV),"last"),KU=CV(function(e){function t(e,i){var a;return r(this,t),(a=n(this,t,[e])).predicate=i,a.index=0,a}return d(t,e),o(t,[{key:"next",value:function(e){this.predicate(e,this.index++)?this.result=!0:(this.result=!1,this.complete())}},{key:"complete",value:function(){void 0!==this.result?(this.sink.next(this.result),g(t,"complete",this,3)([])):this.error(new Error("no elements in sequence"))}}])}(IV),"every"),YU=CV(function(e){function t(e,i,a){var o;return r(this,t),(o=n(this,t,[e])).f=i,void 0===a?o.next=function(e){o.acc=e,o.resetNext(),o.sink.next(o.acc)}:o.acc=a,o}return d(t,e),o(t,[{key:"next",value:function(e){this.sink.next(this.acc=this.f(this.acc,e))}}])}(IV),"scan"),zU=CV(function(e){function t(){var e;return r(this,t),(e=n(this,t,arguments)).hasLast=!1,e}return d(t,e),o(t,[{key:"next",value:function(e){this.hasLast?this.sink.next([this.last,e]):this.hasLast=!0,this.last=e}}])}(IV),"pairwise"),qU=function(e){function t(e,i,a){var o;return r(this,t),(o=n(this,t,[e])).mapper=i,o.thisArg=a,o}return d(t,e),o(t,[{key:"next",value:function(e){g(t,"next",this,3)([this.mapper.call(this.thisArg,e)])}}])}(IV),XU=CV(qU,"map"),QU=function(e){return CV(qU,"mapTo")((function(t){return e}))},ZU=function(e){function t(e,i,a){var o;return r(this,t),(o=n(this,t,[e])).data=i,o.context=a,o}return d(t,e),o(t,[{key:"next",value:function(e){var t=this.context.combineResults;t?this.sink.next(t(this.data,e)):this.sink.next(e)}},{key:"tryComplete",value:function(){this.context.resetComplete(),this.dispose()}}])}(IV),$U=function(e){function t(e,i,a){var o;return r(this,t),(o=n(this,t,[e])).makeSource=i,o.combineResults=a,o.index=0,o}return d(t,e),o(t,[{key:"subInner",value:function(e,t){var n=this.currentSink=new t(this.sink,e,this);this.complete=this.tryComplete,n.complete=n.tryComplete,n.subscribe(this.makeSource(e,this.index++))}},{key:"tryComplete",value:function(){this.currentSink.resetComplete(),this.dispose()}}])}(IV),eF=function(e){function t(){return r(this,t),n(this,t,arguments)}return d(t,e),o(t)}(ZU),tF=function(e){function t(){return r(this,t),n(this,t,arguments)}return d(t,e),o(t,[{key:"next",value:function(e){var t=this;this.subInner(e,eF),this.next=function(e){t.currentSink.dispose(),t.subInner(e,eF)}}}])}($U),nF=CV(tF,"switchMap");function rF(e){return function(t,n){return e((function(){return t}),n)}}var iF=rF(CV(tF,"switchMapTo")),aF=function(e){function t(){return r(this,t),n(this,t,arguments)}return d(t,e),o(t,[{key:"tryComplete",value:function(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}}])}(ZU),oF=function(e){function t(){var e;return r(this,t),(e=n(this,t,arguments)).sources=[],e.next2=e.sources.push.bind(e.sources),e}return d(t,e),o(t,[{key:"next",value:function(e){this.next2(e),this.subNext()}},{key:"subNext",value:function(){this.next=this.next2,this.subInner(this.sources.shift(),aF),this.disposed&&0===this.sources.length&&this.currentSink.resetComplete()}},{key:"tryComplete",value:function(){0===this.sources.length&&this.currentSink.resetComplete(),this.dispose()}}])}($U),sF=CV(oF,"concatMap"),cF=rF(CV(oF,"concatMapTo")),uF=function(e){function t(){return r(this,t),n(this,t,arguments)}return d(t,e),o(t,[{key:"tryComplete",value:function(){this.context.inners.delete(this),g(t,"dispose",this,3)([]),0===this.context.inners.size&&this.context.resetComplete()}}])}(ZU),lF=function(e){function t(){var e;return r(this,t),(e=n(this,t,arguments)).inners=new Set,e}return d(t,e),o(t,[{key:"next",value:function(e){this.subInner(e,uF),this.inners.add(this.currentSink)}},{key:"tryComplete",value:function(){1===this.inners.size?this.inners.forEach((function(e){return e.resetComplete()})):this.dispose()}}])}($U),dF=CV(lF,"mergeMap"),hF=rF(CV(lF,"mergeMapTo")),fF=function(e){function t(){return r(this,t),n(this,t,arguments)}return d(t,e),o(t,[{key:"dispose",value:function(){this.context.resetNext(),g(t,"dispose",this,3)([])}}])}(ZU),pF=function(e){function t(){return r(this,t),n(this,t,arguments)}return d(t,e),o(t,[{key:"next",value:function(e){this.next=vV,this.subInner(e,fF)}}])}($U),mF=CV(pF,"exhaustMap"),vF=rF(CV(pF,"exhaustMapTo")),_F=CV(function(e){function t(e,i){var a;return r(this,t),(a=n(this,t,[e])).f=i,a.groups=new Map,a}return d(t,e),o(t,[{key:"next",value:function(e){var n=this.f(e),r=this.groups.get(n);void 0===r&&((r=YV()).key=n,this.groups.set(n,r),g(t,"next",this,3)([r])),r.next(e)}},{key:"complete",value:function(){this.groups.forEach((function(e){return e.complete()})),g(t,"complete",this,3)([])}},{key:"error",value:function(e){this.groups.forEach((function(t){return t.error(e)})),g(t,"error",this,3)([e])}}])}(IV),"groupBy"),gF=CV(function(e){function t(){var e;return r(this,t),(e=n(this,t,arguments)).start=new Date,e}return d(t,e),o(t,[{key:"next",value:function(e){this.sink.next({value:e,interval:Number(new Date)-Number(this.start)}),this.start=new Date}}])}(IV),"timeInterval"),yF=CV(function(e){function t(e,i){var a;return r(this,t),(a=n(this,t,[e])).miniseconds=i,a.buffer=[],a.id=setInterval((function(){a.sink.next(a.buffer.concat()),a.buffer.length=0}),a.miniseconds),a}return d(t,e),o(t,[{key:"next",value:function(e){this.buffer.push(e)}},{key:"complete",value:function(){this.sink.next(this.buffer),g(t,"complete",this,3)([])}},{key:"dispose",value:function(){clearInterval(this.id),g(t,"dispose",this,3)([])}}])}(IV),"bufferTime"),EF=CV(function(e){function t(e,i){var a;return r(this,t),(a=n(this,t,[e])).buffer=[],a.delayTime=i,a}return d(t,e),o(t,[{key:"dispose",value:function(){clearTimeout(this.timeoutId),g(t,"dispose",this,3)([])}},{key:"delay",value:function(e){var n=this;this.timeoutId=setTimeout((function(){var e=n.buffer.shift();if(e){var r=e.time,i=e.data;g(t,"next",n,3)([i]),n.buffer.length&&n.delay(Number(n.buffer[0].time)-Number(r))}}),e)}},{key:"next",value:function(e){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:e})}},{key:"complete",value:function(){var e=this;this.timeoutId=setTimeout((function(){return g(t,"complete",e,3)([])}),this.delayTime)}}])}(IV),"delay"),kF=CV(function(e){function t(e,i){var a;return r(this,t),(a=n(this,t,[e])).selector=i,a}return d(t,e),o(t,[{key:"error",value:function(e){this.dispose(),this.selector(e)(this.sink)}}])}(IV),"catchError"),TF=function(){return function(e){return new Promise((function(t,n){var r;new bV(e,(function(e){return r=e}),n,(function(){return t(r)}))}))}},SF=function(){return function(e){var t;return new ReadableStream({start:function(n){t=new bV(e,n.enqueue.bind(n),n.error.bind(n),n.close.bind(n))},cancel:function(){t.dispose()}})}},IF=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:vV,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:vV,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:vV;return function(r){return new bV(r,e,t,n)}},bF=CV(function(e){function t(e,i){var a;return r(this,t),a=n(this,t,[e]),i instanceof Function?a.next=function(t){i(t),e.next(t)}:(i.next&&(a.next=function(t){i.next(t),e.next(t)}),i.complete&&(a.complete=function(){i.complete(),e.complete()}),i.error&&(a.error=function(t){i.error(t),e.error(t)})),a}return d(t,e),o(t)}(IV),"tap"),RF=CV(function(e){function t(e,i){var a;return r(this,t),(a=n(this,t,[e])).timeout=i,a.id=setTimeout((function(){return a.error(new xV(a.timeout))}),a.timeout),a}return d(t,e),o(t,[{key:"next",value:function(e){g(t,"next",this,3)([e]),clearTimeout(this.id),this.next=g(t,"next",this,1)}},{key:"dispose",value:function(){clearTimeout(this.id),g(t,"dispose",this,3)([])}}])}(IV),"timeout"),AF=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1/0;return function(t){if(t instanceof TV){var n=AV((function(r){var i=e,a=new IV(r);a.error=function(e){i-- >0?a.subscribe(t):r.error(e)},a.sourceId=n.id,a.subscribe(t)}),"retry",[e]);return n.source=t,NV.pipe(n),n}return function(n){var r=e,i=new IV(n);i.error=function(e){r-- >0?t(i):n.error(e)},t(i)}}},CF=function(e){function i(e,a,o){var s;r(this,i),(s=n(this,i,[{userId:a.userId,sdkAppId:e.sdkAppId,mediaType:o,room:e}])).room=e,s.user=a,SA(t(s),"tinyId"),SA(t(s),"isRemote",!0),SA(t(s),"jitterBufferDelay",0),SA(t(s),"availableState"),SA(t(s),"remotePublishState"),SA(t(s),"_triggerCheckDecodeSubject",YV(rU(t(s),i.STATE_SUBSCRIBE))),s.tinyId=a.tinyId,s.availableState=new uM("".concat(a.userId,"-").concat(s.mediaType,"-available"),"remote-track-available"),s.remotePublishState=new uM("".concat(a.userId,"-").concat(s.mediaType,"-remote-publish"),"remote-track-publish"),RV(MV(rU(t(s),uM.STATECHANGED),rU(s.remotePublishState,uM.STATECHANGED)),XU((function(){return s.isRemotePublished&&(s.isSubscribed||s.isSubscribing)})),IF((function(e){s.availableState.state!==(e?uM.ON:uM.OFF)&&(s.availableState.state=e?uM.ON:uM.OFF),s.updatePlayingState(e)})));var c=RV(rU(s.player,vM.ERROR),TU((function(e){return e.code===MediaError.MEDIA_ERR_DECODE}))),u=RV(eU(5e3),TU((function(){return!(s.ignoreDecodeError||!s.isSubscribed||!s.isPlayCalled||!s.stat.bytesReceived||(s.player.isPlaying||(s.kind===IC.AUDIO?s.getAudioLevel()>0:s.stat.framesDecoded>0))&&(s.reportDecodeResult(!0),1))}))),l=RV(LV(c,u),bU(rU(s,uM.INIT)));return RV(s._triggerCheckDecodeSubject,TU((function(){return!s.ignoreDecodeError})),iF(l),IF((function(e){s.reportDecodeResult(!1,e)}))),s}return d(i,e),o(i,[{key:"setMute",value:function(e){this.isRemotePublished&&g(i,"setMute",this,3)([e])}},{key:"setInputMediaStreamTrack",value:function(e){g(i,"setInputMediaStreamTrack",this,3)([e]),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}},{key:"checkDecodeResult",value:function(){this._triggerCheckDecodeSubject.next(!0)}},{key:"waitHasMediaTrack",value:function(){var e=this;return new Promise((function(t){e.mediaTrack?t():e.once("input-media-track-changed",t)}))}},{key:"ignoreDecodeError",get:function(){var e,t;return((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}},{key:"isSubscribing",get:function(){return"subscribeing"===this.state.toString()}},{key:"isSubscribed",get:function(){return this.state===i.STATE_SUBSCRIBE}},{key:"isAvailable",get:function(){return this.availableState.state===uM.ON}},{key:"isNeedPlay",get:function(){return this.isAvailable&&this.isPlayCalled}},{key:"subscribe",value:function(e){return e}},{key:"unsubscribe",value:function(){this.player.setTrack(null),"main"===this.streamType&&"video"===this.kind&&this.room.changeType(!1,this.user)}},{key:"reportDecodeResult",value:function(e,t){var n=this.kind===IC.AUDIO;rP[e?"addSuccessEvent":"addFailedEvent"]({key:n?504700:514702}),e||(rP.addEnum({key:n?504701:514703,value:Dx()}),kM.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(Ax()||Nx()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===IC.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0))),this.emit("decode-failed",{error:t}))}},{key:"updatePlayingState",value:function(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack))return void this.log.info("abort play, isSubscribed: ".concat(this.isSubscribed," isAvailable: ").concat(this.isRemotePublished," hasTrack: ").concat(!!this.outMediaTrack," "));g(i,"updatePlayingState",this,3)([e])}}},{key:"close",value:function(){g(i,"close",this,3)([]),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}},{key:"onFlagChanged",value:function(){this.remotePublishState.state=this.isRemotePublished?uM.ON:uM.OFF}},{key:"onTrackMuted",value:function(){this.isNeedPlay&&g(i,"onTrackMuted",this,3)([])}},{key:"onTrackUnmuted",value:function(){this.isNeedPlay&&g(i,"onTrackUnmuted",this,3)([])}},{key:"onTrackEnded",value:function(){this.isNeedPlay&&g(i,"onTrackEnded",this,3)([])}}])}(xL);SA(CF,"STATE_SUBSCRIBE","subscribe"),TA([pV(5,1)],CF.prototype,"waitHasMediaTrack",1),TA([oM(uM.INIT,CF.STATE_SUBSCRIBE,{success:function(){this.log.info("subscribed"),Px.emit(Lx.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),ZL(521716,!1)],CF.prototype,"subscribe",1),TA([oM(CF.STATE_SUBSCRIBE,uM.INIT,{sync:!0,success:function(){this.log.info("unsubscribed"),Px.emit(Lx.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],CF.prototype,"unsubscribe",1);var wF=CF,DF=function(e){function i(e,a){var o;return r(this,i),o=n(this,i,[e,a,1]),SA(t(o),"volume",0),SA(t(o),"mediaType",1),SA(t(o),"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),o.manager=e.audioManager,o}return d(i,e),o(i,[{key:"dbVolume",get:function(){return fL.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}},{key:"decodeFrame",value:function(e){if(!this.manager)return e;var t,n=e,r=s(this.manager.decodePipeline);try{for(r.s();!(t=r.n()).done;){var i=t.value;if(i&&!(n=i({frame:n,track:this})))return}}catch(a){r.e(a)}finally{r.f()}return n}},{key:"getAudioLevel",value:function(){var e=this.volume||g(i,"getAudioLevel",this,3)([]);return e>1?1:e}},{key:"isRemotePublished",get:function(){return this.user.muteState.audioAvailable}}])}(wF),NF=[-1,-1,1,-1,-1,1,1,1],xF=[0,0,1,0,0,1,1,1],OF=function(e){function i(e,a){var o;if(r(this,i),(o=n(this,i)).context=e,SA(t(o),"name"),SA(t(o),"input"),SA(t(o),"output"),SA(t(o),"texture"),SA(t(o),"ctx2d",null),SA(t(o),"fbo"),SA(t(o),"width",0),SA(t(o),"height",0),SA(t(o),"x",0),SA(t(o),"y",0),SA(t(o),"program"),SA(t(o),"vertexShader"),SA(t(o),"fragmentShader"),SA(t(o),"totalFrames",0),SA(t(o),"dropFrames",0),SA(t(o),"matchInputSize",!0),SA(t(o),"texCoordBuffer"),SA(t(o),"positionBuffer"),SA(t(o),"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),SA(t(o),"cost",0),SA(t(o),"_canvas",null),SA(t(o),"_image"),SA(t(o),"log"),o.context.on("disconnect",o.close,t(o)),o.name=a.name,o.log=a.logger,o.matchInputSize=!1!==a.matchInputSize,o.width=a.width||e.width,o.height=a.height||e.height,o._image=a.image,e instanceof YF)e.ctx&&a.create2d&&("function"==typeof OffscreenCanvas&&16!==hx?o._canvas=new OffscreenCanvas(o.width,o.height):(o._canvas=document.createElement("canvas"),o._canvas.width=o.width,o._canvas.height=o.height),o.ctx2d=o._canvas.getContext("2d"),o._image=o._canvas);else try{var s=e.ctx;o.texCoordBuffer=o.createBuffer(xF),o.positionBuffer=o.createBuffer(NF),!1!==a.createTexture&&(o.texture=s.createTexture(),o.useTexture(),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.pixelStorei(s.PACK_ALIGNMENT,1),s.pixelStorei(s.UNPACK_ALIGNMENT,1)),a.useFbo&&(o.fbo=s.createFramebuffer(),o.useBufferFrame(),o.useTexture(),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,o.width,o.height,0,s.RGBA,s.UNSIGNED_BYTE,null),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,o.texture,0)),a.useDefaultProgram?o.program=e.defaultProgam:(a.vertexShaderSource||a.fragmentShaderSource)&&(o.vertexShader=a.vertexShaderSource?e.createShader(s.VERTEX_SHADER,a.vertexShaderSource):e.defaultVShader,o.fragmentShader=a.fragmentShaderSource?e.createShader(s.FRAGMENT_SHADER,a.fragmentShaderSource):e.defaultFShader,o.program=e.createProgram(o.vertexShader,o.fragmentShader))}catch(Yx){o.context.destroy(new FA({code:VA.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(o.name," error ").concat(Yx.message||Yx)}))}return o}return d(i,e),o(i,[{key:"image",get:function(){return this._image},set:function(e){this._image=e}},{key:"createFramebuffer",value:function(e){var t=this.context.ctx,n=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,n),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),n}},{key:"connect",value:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return e.addInput.apply(e,[this].concat(n)),this.output=e,e}},{key:"addInput",value:function(e){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}},{key:"requestFrame",value:function(e){var t=Date.now();return!!(this.context instanceof KF&&this.render(e)||this.context instanceof YF&&this.render2d(e))&&(this.totalFrames++,this.cost=Date.now()-t,!0)}},{key:"render2d",value:function(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))&&this.draw2d(this.input.image,0,0,this.width,this.height)}},{key:"update",value:function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;null==(e=this.output)||e.update(t)}},{key:"disconnect",value:function(){for(var e,t,n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];null==(t=this.output)||(e=t).removeInput.apply(e,[this].concat(r)),delete this.output}},{key:"removeInput",value:function(e){delete this.input}},{key:"close",value:function(){var e,t;if(this.context.off("disconnect",this.close,this),null==(e=this.output)||e.removeInput(this),delete this.output,null==(t=this.input)||t.disconnect(),this.context instanceof KF){var n=this.context.ctx;n.deleteBuffer(this.texCoordBuffer),n.deleteBuffer(this.positionBuffer),this.fbo&&n.deleteFramebuffer(this.fbo),this.texture&&n.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&n.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&n.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&n.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}},{key:"useTexture",value:function(){this.useTextures(this.texture)}},{key:"useInputTexture",value:function(){var e;this.useTextures(null==(e=this.input)?void 0:e.texture)}},{key:"useTextures",value:function(){for(var e=this.context.ctx,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];n.forEach((function(t,n){t&&(e.activeTexture(e.TEXTURE0+n),e.bindTexture(e.TEXTURE_2D,t))}))}},{key:"useProgram",value:function(){this.context.ctx.useProgram(this.program)}},{key:"useBufferFrame",value:function(){var e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}},{key:"createBuffer",value:function(e){var t=this.context.ctx,n=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,n),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),n}},{key:"setTexBuffer",value:function(e){var t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}},{key:"setPosBuffer",value:function(e){var t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}},{key:"changeBufferData",value:function(e,t){var n=this.context.ctx;n.bindBuffer(n.ARRAY_BUFFER,e),n.bufferData(n.ARRAY_BUFFER,new Float32Array(t),n.STATIC_DRAW)}},{key:"setAttributes",value:function(){for(var e=this.context.ctx,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];n.forEach((function(t,n){e.enableVertexAttribArray(n),e.bindBuffer(e.ARRAY_BUFFER,t),e.vertexAttribPointer(n,2,e.FLOAT,!1,0,0)}))}},{key:"getVertexPoint",value:function(e,t){return[e/this.width*2-1,t/this.height*2-1]}},{key:"layout2texCoords",value:function(e){return[].concat(E(this.getVertexPoint(e.x,e.y)),E(this.getVertexPoint(e.x+e.width,e.y)),E(this.getVertexPoint(e.x,e.y+e.height)),E(this.getVertexPoint(e.x+e.width,e.y+e.height)))}},{key:"resize",value:function(e,t){if(this.width!==e||this.height!==t){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();var n=this.context.ctx;n.texImage2D(n.TEXTURE_2D,0,n.RGBA,e,t,0,n.RGBA,n.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}},{key:"draw",value:function(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);var n=this.context.ctx;n.drawArrays(n.TRIANGLE_STRIP,0,4)}},{key:"draw2d",value:function(e,t,n,r,i){return!(!this.ctx2d||!e||(e instanceof ImageData?this.ctx2d.putImageData(e,t,n):(this.ctx2d.drawImage(e,t,n,r,i),"undefined"!=typeof VideoFrame&&e instanceof VideoFrame&&e.close()),0))}},{key:"getInfo",value:function(){var e,t=this.totalFrames,n=this.x,r=this.y,i=this.width,a=this.height,o=this.name,s=this.cost,c=Date.now(),u=(t-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:t,x:n,y:r,width:i,height:a,timestamp:c,fps:u,name:o,cost:s},_A({parent:null==(e=this.input)?void 0:e.getInfo()},this.lastInfo)}},{key:"createTexture",value:function(e){var t=this.context.ctx,n=t.createTexture();return this.useTextures(n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),n}}])}(uM);TA([oM(uM.INIT,"connected",{sync:!0})],OF.prototype,"connect",1),TA([oM("connected",uM.INIT,{ignoreError:!0,sync:!0})],OF.prototype,"disconnect",1),TA([oM([],"closed",{sync:!0})],OF.prototype,"close",1);var PF=RV($V(250),XU((function(){return performance.now()})),PV()),MF=[0,1,1,1,0,0,1,0],LF=function(e){function i(e,a){var o;return r(this,i),o=n(this,i,[e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},a)]),SA(t(o),"_intervalId",0),SA(t(o),"_sequence",0),SA(t(o),"checkGLError",!1),SA(t(o),"checkVisibilityChange"),e instanceof YF?o.ctx2d=e.ctx||null:e.available&&null!=a&&a.mirrorUpAndDown&&o.setTexBuffer(MF),o}return d(i,e),o(i,[{key:"start",value:function(e){var t=this;this.log.info("".concat(this.name," start render ").concat(e," fps")),mM.clearTask(this._intervalId),this._intervalId=mM.run("intervalInWorker",(function(){if(e!==t.context.frameRate&&(mM.clearTask(t._intervalId),t.start(t.context.frameRate)),t.requestFrame(t._sequence++),t.checkGLError&&t.context instanceof KF){var n=t.context.ctx.getError();n&&t.context.destroy(new FA({code:VA.VIDEO_MANAGER_ERROR,extraCode:5,message:"".concat(t.name," req ").concat(t._sequence," render ").concat(t.totalFrames," faild ").concat(n)}))}}),{fps:this.context.frameRate})}},{key:"render",value:function(e){var t;return!(null==(t=this.input)||!t.requestFrame(e)||(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),0))}},{key:"addInput",value:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];g(i,"addInput",this,3)([e].concat(n)),this.start(this.context.frameRate)}},{key:"update",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if(this._intervalId&&(mM.clearTask(this._intervalId),this._intervalId=0,1===t)){this.log.info("".concat(this.name," use requestVideoFrameCallback"));var n=function(){document.hidden&&(e.start(e.context.frameRate),e.log.info("".concat(e.name," use timer")),document.removeEventListener("visibilitychange",n))};document.addEventListener("visibilitychange",n)}this.requestFrame(this._sequence++)}},{key:"removeInput",value:function(e){g(i,"removeInput",this,3)([e]),mM.clearTask(this._intervalId)}},{key:"resize",value:function(e,t){g(i,"resize",this,3)([e,t]),this.context.setSize(e,t)}},{key:"close",value:function(){g(i,"close",this,3)([]),mM.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}}])}(OF),VF=function(e){function i(e,a){var o,s;return r(this,i),s=n(this,i,[e,a]),SA(t(s),"_videoTrack"),SA(t(s),"_muteOb"),SA(t(s),"_closedOb",rU(t(s),"closed")),SA(t(s),"_subscription"),SA(t(s),"_canvasContainer"),Number(cx)<17&&(s._canvasContainer=document.createElement("div"),s._canvasContainer.style.display="none"),o=v(e._canvas.captureStream().getVideoTracks(),1),s._videoTrack=o[0],s._muteOb=rU(s._videoTrack,"mute"),RV(rU(s._videoTrack,"ended"),bU(s._closedOb),IF((function(){s.context.destroy(new FA({code:VA.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))),s}return d(i,e),o(i,[{key:"enableCheckMute",value:function(){var e=this;this._subscription=RV(this._muteOb,bU(this._closedOb),iF((function(e){var t=performance.now();RV(PF,DU((function(e){return e-t<5e3})),IU(1))(e)})),TU((function(){var t;return!(null==(t=e._videoTrack)||!t.muted||document.hidden)})),IF((function(){e.context.destroy(new FA({code:VA.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))})))}},{key:"disableCheckMute",value:function(){var e;null==(e=this._subscription)||e.dispose()}},{key:"videoTrack",get:function(){return this._videoTrack}},{key:"putCanvasIntoDom",value:function(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info("".concat(this.name," put canvas to body")),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}},{key:"render",value:function(e){return this.putCanvasIntoDom(),g(i,"render",this,3)([e])}},{key:"render2d",value:function(e){return this.putCanvasIntoDom(),g(i,"render2d",this,3)([e])}},{key:"close",value:function(){var e,t;g(i,"close",this,3)([]),null==(e=this._videoTrack)||e.stop(),delete this._videoTrack,null==(t=this._canvasContainer)||t.remove()}}])}(LF),UF=function(e){function t(){return r(this,t),n(this,t,arguments)}return d(t,e),o(t,[{key:"render",value:function(e){var t;return!(null==(t=this.input)||!t.requestFrame(e))}}])}(VF),FF=function(e){function t(e,i,a){var o;return r(this,t),(o=n(this,t,[e,{name:"smallDestination",logger:a}])).resolution=i,o}return d(t,e),o(t,[{key:"resize",value:function(e,n){var r,i=e*n,a=this.resolution.width*this.resolution.height;this.log.info("big res: ".concat(e,"*").concat(n," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),i>a?r=i/a:(this.log.warn("Small stream resolution is not smaller than big stream, which is invalid. big: ".concat(e," * ").concat(n," small: ").concat(this.resolution.width," * ").concat(this.resolution.height)),r=i/19200),g(t,"resize",this,3)([e/Math.sqrt(r),n/Math.sqrt(r)])}}])}(VF),BF=function(e){function i(e,a){var o;return r(this,i),o=n(this,i,[e,_A({name:"imageSource"},a)]),SA(t(o),"_lastImage"),SA(t(o),"_totalFrames",0),SA(t(o),"_autoResize",!1),SA(t(o),"_canvasRendered"),SA(t(o),"_videoCallbackId",0),SA(t(o),"waitingFirstFrame",!0),SA(t(o),"shouldUpdate",!0),o._autoResize=!1!==(null==a?void 0:a.autoResize),16===hx&&(o._canvasRendered=YV(),RV(o._canvasRendered,WV(o._image),nF((function(e){return e instanceof HTMLCanvasElement?rU(e,"rendered"):mU()})),bU(rU(t(o),"closed")),IF((function(){o.update()})))),o}return d(i,e),o(i,[{key:"onFirstFrame",value:function(){this.waitingFirstFrame=!1}},{key:"tryVideoFrameCallback",value:function(){var e=this;if(this.shouldUpdate){var t=this.image;this._videoCallbackId&&t.cancelVideoFrameCallback(this._videoCallbackId),ZP()&&!document.hidden&&(this._videoCallbackId=t.requestVideoFrameCallback((function(t,n){e.waitingFirstFrame&&e.onFirstFrame(),document.hidden||(e._totalFrames=n.presentedFrames,e.update(1))})))}}},{key:"_render",value:function(e,t){var n,r=this.width,i=this.height,a=this.image;if(a instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),r=a.videoWidth,i=a.videoHeight,!r||!i)return!1;a.width=r,a.height=i}else if(a instanceof HTMLImageElement||a instanceof ImageData||a instanceof ImageBitmap){if(r=a.width,i=a.height,a!==this._lastImage)this._lastImage=a;else if(r===this.width&&i===this.height)return!1}else a instanceof HTMLCanvasElement||a instanceof OffscreenCanvas?(r=a.width,i=a.height,this._lastImage=a):"undefined"!=typeof VideoFrame&&a instanceof VideoFrame&&(r=a.displayWidth,i=a.displayHeight,null==(n=this._lastImage)||n.close(),this._lastImage=a);if(!this._autoResize)return!0;if(this.width===r&&this.height===i&&this.totalFrames){if(t){this.useTexture();var o=this.context.ctx;o.texSubImage2D(o.TEXTURE_2D,0,0,0,o.RGBA,o.UNSIGNED_BYTE,a)}}else{if(t){this.useTexture();var s=this.context.ctx;s.texImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,a)}this.resize(r,i)}return!0}},{key:"image",get:function(){return this._image},set:function(e){var t;null==(t=this._canvasRendered)||t.next(e),this._image=e}},{key:"render",value:function(e){return this._render(e,!0)}},{key:"render2d",value:function(e){return this._render(e,!1)}}])}(OF),HF=function(e){function i(e,a,o){var s;return r(this,i),(s=n(this,i,[e,o]))._player=a,s.name="videoPlayerSource",RV(rU(s._player,vM.PLAYER_STATE_CHANGED),bU(rU(t(s),"closed")),TU((function(e){return"PLAYING"===e.state})),IF((function(){s.tryVideoFrameCallback()}))),s}return d(i,e),o(i,[{key:"image",get:function(){return this._player.element}}])}(BF),WF=function(e){function t(e,i,a){var o;return r(this,t),(o=n(this,t,[e,new zM({id:a.name,track:i,muted:!0,container:null,objectFit:"contain",log:a.logger}),a])).name="videoTrackSource",o._player.play(),o}return d(t,e),o(t,[{key:"available",get:function(){return this._player.isPlaying&&!this.waitingFirstFrame}},{key:"replaceTrack",value:function(e){this.waitingFirstFrame=!0,this._player.setTrack(e),this._player.play()}},{key:"close",value:function(){g(t,"close",this,3)([]),this._player.stop()}}])}(HF),jF=function(e){function i(e){var a;return r(this,i),a=n(this,i),SA(t(a),"frameRate"),SA(t(a),"_canvas"),SA(t(a),"log"),SA(t(a),"hasAlpha",!1),SA(t(a),"name"),SA(t(a),"error"),a.name=e.name,a.log=e.logger.createChild({id:"vc-".concat(a.name)}),a.frameRate=e.frameRate,a}return d(i,e),o(i,[{key:"width",get:function(){var e;return(null==(e=this._canvas)?void 0:e.width)||0},set:function(e){this._canvas&&(this._canvas.width=e)}},{key:"height",get:function(){var e;return(null==(e=this._canvas)?void 0:e.height)||0},set:function(e){this._canvas&&(this._canvas.height=e)}},{key:"setSize",value:function(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}},{key:"createVideoTrackSource",value:function(e,t){return new WF(this,e,{logger:this.log,name:t})}},{key:"createVideoTrackDestination",value:function(e){return new VF(this,e)}},{key:"createVideoImageSource",value:function(e,t){return new BF(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}},{key:"createVideoPlayerSource",value:function(e,t){return new HF(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}},{key:"available",get:function(){return"created"===this.state}},{key:"disconnect",value:function(){this.emit("disconnect")}}])}(uM);SA(jF,"_ids",0);var GF={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},JF=function(e){function i(){var e;return r(this,i),e=n(this,i,arguments),SA(t(e),"defaultProgam"),SA(t(e),"defaultVShader"),SA(t(e),"defaultFShader"),SA(t(e),"ctx"),e}return d(i,e),o(i,[{key:"create",value:function(){var e=this;if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(jF._ids++)),this.ctx=this._canvas.getContext("webgl2",GF),!this.ctx)throw new FA({code:VA.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,"\n// 顶点着色器\nattribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\n\nvoid main() {\n gl_Position = a_position;\n v_texCoord = a_texCoord;\n}\n"),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,"\n// 片元着色器\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_texture;\n\nvoid main() {\n gl_FragColor = texture2D(u_texture, v_texCoord);\n} "),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",(function(){e.destroy(new FA({code:VA.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))}))}},{key:"destroy",value:function(e){var t="";return e&&(t=e.message,this.error=e,rP.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info("video context destroy".concat(t)?": ".concat(t):""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}},{key:"width",set:function(e){var t;null==(t=this.ctx)||t.viewport(0,0,e,this.height),y(i,"width",e,this,1,1)}},{key:"height",set:function(e){var t;null==(t=this.ctx)||t.viewport(0,0,this.width,e),y(i,"height",e,this,1,1)}},{key:"setSize",value:function(e,t){var n;null==(n=this.ctx)||n.viewport(0,0,e,t),g(i,"setSize",this,3)([e,t])}},{key:"createShader",value:function(e,t){var n=this.ctx,r=n.createShader(e);return n.shaderSource(r,t),n.compileShader(r),r}},{key:"createProgram",value:function(e,t){var n=this.ctx,r=n.createProgram();return n.attachShader(r,e),n.attachShader(r,t),n.linkProgram(r),n.getProgramParameter(r,n.LINK_STATUS)||this.log.error(n.getProgramInfoLog(r)),r}}])}(jF);SA(JF,"UNAVAILABLE","unavailable"),TA([oM(uM.INIT,"created",{sync:!0,fail:function(e){this.log.error("video gl context create failed",e.cause),rP.addFailedEvent({key:512700,error:e.cause||e})},success:function(){this.log.info("video context created use webgl"),rP.addSuccessEvent({key:512700})}})],JF.prototype,"create",1),TA([oM("created",uM.INIT,{ignoreError:!0,sync:!0,success:function(e){e&&this.emit(JF.UNAVAILABLE,e),this.removeAllListeners()}})],JF.prototype,"destroy",1);var KF=JF,YF=function(e){function i(){var e;return r(this,i),e=n(this,i,arguments),SA(t(e),"ctx"),e}return d(i,e),o(i,[{key:"create",value:function(e){var t=this;if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(jF._ids++),this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new FA({code:VA.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",(function(){t.log.error("2d context lost")})),this._canvas.addEventListener("contextrestored",(function(){t.log.warn("2d context restored")}))}},{key:"destroy",value:function(e){var t="";e&&(t=e.message,this.error=e,rP.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info("video context destroy ".concat(t?": ".concat(t):"")),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),rP.addSuccessEvent({key:512703})}}])}(jF);TA([oM(uM.INIT,"created",{sync:!0,fail:function(e){this.log.error("video 2d context create failed",e.cause),rP.addFailedEvent({key:512701,error:e.cause||e})},success:function(){this.log.info("video context created use 2d"),rP.addSuccessEvent({key:512701})}})],YF.prototype,"create",1),TA([oM("created",uM.INIT,{ignoreError:!0,sync:!0})],YF.prototype,"destroy",1);var zF=function(e){function i(e,a){var o;return r(this,i),o=n(this,i,[e,a,arguments.length>2&&void 0!==arguments[2]?arguments[2]:4]),SA(t(o),"mediaType",4),SA(t(o),"source"),SA(t(o),"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0}),o.manager=e.videoManager,o.once("first-video-frame",(function(e){o.room.emit("first-video-frame",e)})),o}return d(i,e),o(i,[{key:"play",value:function(e,t){var n=this;return(qw(null==t?void 0:t.canvasRender)?t.canvasRender:17===hx)&&!this.source&&this.useCanvasPlayer(),g(i,"play",this,3)([e,t]).then((function(){n.player.calculateStat()}))}},{key:"useCanvasPlayer",value:function(){if(this.log.info("useCanvasPlayer(), has element:".concat(!!this.player.element)),this.player.element){var e=new YF({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});var t=new LF(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),ZP()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}}},{key:"updateCanvasPlayerFPS",value:function(e){var t,n=this.decodeFPS,r=(t=n,[15,30,45,60].reduce((function(e,n){return Math.abs(n-t)<Math.abs(e-t)?n:e})));!zw(n)||n<=0?this.log.debug("updateCanvasPlayerFPS() ignore decoder: ".concat(n," ")):r!==e.frameRate?(this.log.info("updateCanvasPlayerFPS() decoder: ".concat(n,", closest: ").concat(r,", current: ").concat(e.frameRate)),e.frameRate=r):this.log.debug("updateCanvasPlayerFPS() ignore ClosestFPS ".concat(r," == ").concat(e.frameRate))}},{key:"decodeFPS",get:function(){var e,t=this,n=((null==(e=this.room.heartbeatReport)?void 0:e.msg_down_stream_info.find((function(e){return e.msg_user_info.str_identifier===t.userId})))||{}).msg_video_status,r=2===this.mediaType?7:this.isSmall?3:2;if(!n||0===n.length)return 0;var i=n.find((function(e){return e.uint32_video_stream_type===r}));return(null==i?void 0:i.uint32_video_dec_fps)||0}},{key:"stop",value:function(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),g(i,"stop",this,3)([])}},{key:"decodeFrame",value:function(e){if(!this.manager)return e;var t,n=s(this.manager.decodePipeline);try{for(n.s();!(t=n.n()).done;){var r=t.value;if(r&&!(e=r({frame:e,track:this})))return}}catch(i){n.e(i)}finally{n.f()}return e}},{key:"isBig",get:function(){return 4===this.mediaType}},{key:"isSmall",get:function(){return 8===this.mediaType}},{key:"changeType",value:function(e){this.room.changeType(e,this.user)}},{key:"isRemotePublished",get:function(){return this.user.muteState.videoAvailable}},{key:"setMirror",value:function(e){"publish"===e||"both"===e||g(i,"setMirror",this,3)([e])}},{key:"onDecodeDowngradeStateChanged",value:function(e){this.emit("decode-downgrade-state-changed",e)}}])}(wF),qF=function(e){function i(e,a){var o;return r(this,i),o=n(this,i,[e,a,2]),SA(t(o),"mediaType",2),SA(t(o),"objectFit","contain"),o}return d(i,e),o(i,[{key:"isRemotePublished",get:function(){return this.user.muteState.hasAuxiliary}}])}(zF),XF=new Map;function QF(e,t){var n=gA(_A({},t),{timestamp:HA()});XF.has(e)?XF.get(e).push(n):XF.set(e,[n])}function ZF(e,t,n,r){try{if(Qw(e))for(var i=0;i<e.length;i++)$F.call(this,{rule:e[i],value:t[i],key:e[i].name,fnName:n,className:r});else $F.call(this,{rule:e,value:t[0],key:e.name,fnName:n,className:r})}catch(Yx){throw Ux.error(Yx),Yx}}function $F(e){var t=this,n=e.rule,r=e.value,i=e.key,a=e.fnName,o=e.className;if(Kw(r)){if(n.required)throw new FA({code:VA.INVALID_PARAMETER,message:YO({key:jO.INVALID_PARAMETER_REQUIRED,data:{key:i,rule:n,fnName:a,value:r},link:{className:o,fnName:a}})});if(Kw(n.defaultValue))return;r=n.defaultValue}if(Array.isArray(n.type)){for(var s=!1,c=0;c<n.type.length;c++)null===n.type[c]&&null===r&&(s=!0),Jw(n.type[c])&&r instanceof n.type[c]&&(s=!0),Yw(n.type[c])&&Gw(r)===n.type[c].toLowerCase()&&(s=!0);if(!s)throw new FA({code:VA.INVALID_PARAMETER,message:YO({key:jO.INVALID_PARAMETER_TYPE,data:{key:i,rule:{type:n.type.map((function(e){return tD(e)?nD(e):Yw(e)?e:Gw(e)}))},fnName:a,value:r},link:{className:o,fnName:a}})})}else if(!Kw(n.type)&&Gw(r)!==n.type)throw new FA({code:VA.INVALID_PARAMETER,message:YO({key:jO.INVALID_PARAMETER_TYPE,data:{key:i,rule:n,fnName:a,value:r},link:{className:o,fnName:a}})});if(!1===n.allowEmpty){var u=zw(r)&&(0===r||Number.isNaN(r)),l=Yw(r)&&""===r.trim();if(u||l)throw new FA({code:VA.INVALID_PARAMETER,message:YO({key:jO.INVALID_PARAMETER_EMPTY,data:{key:i,rule:n,fnName:a,value:r},link:{className:o,fnName:a}})})}if(n.notLessThanZero&&zw(r)&&r<0)throw new FA({code:VA.INVALID_PARAMETER,message:YO({key:jO.CANNOT_LESS_THAN_ZERO,data:{key:i,rule:n,fnName:a,value:r},link:{className:o,fnName:a}})});if(!Kw(n.min)&&zw(r)&&r<n.min)throw new FA({code:VA.INVALID_PARAMETER,message:YO({key:jO.INVALID_PARAMETER_MIN,data:{key:i,rule:n,fnName:a,value:r},link:{className:o,fnName:a}})});if(!Kw(n.max)&&zw(r)&&r>n.max)throw new FA({code:VA.INVALID_PARAMETER,message:YO({key:jO.INVALID_PARAMETER_MAX,data:{key:i,rule:n,fnName:a,value:r},link:{className:o,fnName:a}})});if(Yw(n.instanceOf)){if(!r||r._name!==n.instanceOf)throw new FA({code:VA.INVALID_PARAMETER,message:YO({key:jO.INVALID_PARAMETER_INSTANCE,data:{key:i,rule:n,fnName:a,value:r},link:{className:o,fnName:a}})})}else if(Jw(n.instanceOf)&&!(r instanceof n.instanceOf))throw new FA({code:VA.INVALID_PARAMETER,message:YO({key:jO.INVALID_PARAMETER_INSTANCE,data:{key:i,rule:n,fnName:a,value:r},link:{className:o,fnName:a}})});if(n.values&&!n.values.includes(r))throw new FA({code:VA.INVALID_PARAMETER,message:YO({key:jO.INVALID_PARAMETER_RANGE,data:{key:i,rule:n,fnName:a,value:r},link:{className:o,fnName:a}})});var d=n.properties;Hw(d)&&Xw(r)&&Object.keys(d).forEach((function(e){$F.call(t,{rule:d[e],value:r&&r[e],key:"".concat(i,".").concat(e),fnName:a,className:o})}));var h=n.arrayItem;Hw(h)&&Qw(r)&&r.forEach((function(e,n){$F.call(t,{rule:h,value:e,key:"".concat(i,"[").concat(n,"]"),fnName:a,className:o})})),Jw(n.validate)&&n.validate.call(this,r,i,a,o,this)}Px.on(Lx.JOIN_SUCCESS,(function(e){QF(e.room.userId,{eventId:32788})})),Px.on(Lx.LEAVE_START,(function(e){QF(e.room.userId,{eventId:32789})})),Px.on(Lx.LOCAL_TRACK_PUBLISHED,(function(e){var t=e.track;if(t.room){var n=32769;4===t.mediaType?n=32768:2===t.mediaType&&(n=32805),QF(t.room.userId,{eventId:n})}})),Px.on(Lx.LOCAL_TRACK_UNPUBLISHED,(function(e){var t=e.track;if(t.room){var n=32771;4===t.mediaType?n=32770:2===t.mediaType&&(n=32806),QF(t.room.userId,{eventId:n})}})),Px.on(Lx.TRACK_MUTED,(function(e){var t=e.track;t.room&&(t.kind===IC.AUDIO?QF(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):QF(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))})),Px.on(Lx.TRACK_UNMUTED,(function(e){var t=e.track;t.room&&(t.kind===IC.AUDIO?QF(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):QF(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))})),Px.on(Lx.REMOTE_TRACK_SUBSCRIBED,(function(e){var t=e.track;t.room&&(1===t.mediaType&&QF(t.room.userId,{eventId:32777,remoteUserId:t.userId}),4===t.mediaType&&QF(t.room.userId,{eventId:32776,remoteUserId:t.userId}),8===t.mediaType&&QF(t.room.userId,{eventId:32803,remoteUserId:t.userId}))})),Px.on(Lx.REMOTE_TRACK_UNSUBSCRIBED,(function(e){var t=e.track;t.room&&(1===t.mediaType&&QF(t.room.userId,{eventId:32779,remoteUserId:t.userId}),4===t.mediaType&&QF(t.room.userId,{eventId:32778,remoteUserId:t.userId}),8===t.mediaType&&QF(t.room.userId,{eventId:32804,remoteUserId:t.userId}))})),Px.on(Lx.SWITCH_DEVICE_SUCCESS,(function(e){var t=e.track;t.room&&QF(t.room.userId,{eventId:t.kind===IC.VIDEO?32780:32781})})),Px.on(Lx.LOCAL_TRACK_REPLACED,(function(e){var t=e.track;t.room&&QF(t.room.userId,{eventId:t.kind===IC.VIDEO?32782:32783})})),Px.on(Lx.SIGNAL_CONNECTION_STATE_CHANGED,(function(e){var t,n=e.room,r=e.prevState;switch(e.state){case"CONNECTED":t="RECONNECTING"===r?32795:32791;break;case"DISCONNECTED":t="RECONNECTING"===r?32796:32790;break;case"RECONNECTING":t=32794}t&&QF(n.userId,{eventId:t})})),Px.on(Lx.PEER_CONNECTION_STATE_CHANGED,(function(e){var t,n=e.room,r=e.prevState,i=e.state,a=e.remoteUserId,o=!!a;switch(i){case"CONNECTED":t="RECONNECTING"===r?o?32801:32798:o?32793:32792;break;case"DISCONNECTED":"RECONNECTING"===r&&(t=o?32802:32799);break;case"RECONNECTING":t=o?32800:32797}t&&QF(n.userId,{eventId:t,remoteUserId:a})})),Px.on(Lx.VIDEO_CODEC_IMPLEMENTATION_CHANGED,(function(e){e.implementation;var t=e.userId,n=e.remoteUserId,r=e.codec,i=e.isHWCodec,a=i?1:0;e.prevImplementation||(a=i?3:2);var o="h264"===r?0:2,s={eventId:4004,param1:a,param2:o,streamType:e.streamType||2};n&&(s.remoteUserId=n,s.eventId=4005),QF(t,s),rP.addEnum({key:n?514701:513701,value:a}),rP.addEnum({key:n?514700:513700,value:o})})),Px.on(Lx.LOCAL_TRACK_RECAPTURE,(function(e){var t=e.track,n=e.error;if(t.userId){var r={eventId:2003,param1:0};t.kind===IC.AUDIO?(r.streamType=1,n&&(r.param1=2)):(r.streamType="auxiliary"===t.streamType?7:2,n&&(r.param1=8)),QF(t.userId,r)}}));var eB=function(e){function i(e,a){var o;r(this,i);var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"userId";return(o=n(this,i)).mySelfId=e,o._log=a,o.key=s,SA(t(o),"userMap",new Map),SA(t(o),"remotePublishedUserMap",new Map),o}return d(i,e),o(i,[{key:"hasRobotUser",get:function(){return!!E(this.remotePublishedUserMap.values()).find((function(e){return e.isRobot}))}},{key:"getPublishedUser",value:function(e){return this.remotePublishedUserMap.get(e)}},{key:"addUser",value:function(e){var t=e[this.key],n=e.userId,r=e.tinyId,i=e.role;if(!this.userMap.has(t)){var a={userId:n,tinyId:r,role:20===i?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}}},{key:"deleteUser",value:function(e,t){var n=this.userMap.get(e);if(n){var r="peer leave [".concat(e,"]");Kw(t)||(r+=":".concat(kw[t])),this._log.info(r);var i=this.remotePublishedUserMap.get(e);if(i){var a=i.muteState;i.flag=0,this.emit("5",i.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:i.muteState,flag:0})}this.userMap.delete(e),this.emit("2",n.userId)}}},{key:"setUserList",value:function(e){var t=this;this.userMap.forEach((function(n){e.findIndex((function(e){return e[t.key]===n[t.key]}))<0&&t.deleteUser(n[t.key],0)})),e.forEach((function(e){!t.userMap.has(e[t.key])&&e[t.key]!==t.mySelfId&&t.addUser(e)}))}},{key:"addRemotePublishedUser",value:function(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}},{key:"deleteRemotePublishedUser",value:function(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}},{key:"setRemotePublishedUserList",value:function(e){var t=this;this.remotePublishedUserMap.forEach((function(n){var r=n[t.key];if(e.findIndex((function(e){return e[t.key]===n[t.key]}))<0){t._log.info("remote [".concat(r,"] unpublish"));var i=n.muteState;n.flag=0,t.emit("5",n.userId),t.deleteRemotePublishedUser(r),t.emit("6",{prevMuteState:i,muteState:n.muteState,flag:0})}})),e.forEach((function(e){var n,r=e[t.key];if(r!==t.mySelfId){var i=e.flag,a=e.userId,o=e.tinyId,s=lD(i,a),c=null==(n=t.remotePublishedUserMap.get(r))?void 0:n.muteState;if(c){var u=t.remotePublishedUserMap.get(r);u&&u.flag!==i&&(u.flag=i,t._log.info("remote publish updated: ".concat(JSON.stringify(u.muteState))),t.emit("6",{prevMuteState:c,muteState:s,flag:i}))}else t._log.info("remote publish. state: ".concat(JSON.stringify(s))),t.addUser({userId:a,tinyId:o,role:20}),t.emit("3",e),t.emit("6",{prevMuteState:lD(0,a),muteState:s,flag:i})}}))}},{key:"clear",value:function(){this.userMap.clear(),this.remotePublishedUserMap.clear()}}])}(kA(RA(),1).EventEmitter);function tB(e){var t=e.timesInSecond,n=e.maxSizeInSecond,r=e.getSize;return jL((function(e,i){var a=new WeakMap;return Px.on(Lx.ROOM_DESTROY,(function(e){var t=e.room;return a.delete(t)})),function(){for(var o=a.get(this),s=arguments.length,c=new Array(s),u=0;u<s;u++)c[u]=arguments[u];if(o||(o={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},a.set(this,o)),0===o.timestamp?o.timestamp=Date.now():Date.now()-o.timestamp>1e3&&(o.timestamp=Date.now(),o.callCountInSecond=0,o.totalSizeInSecond=0),r&&(o.totalSizeInSecond+=r.apply(void 0,c)),0!==o.timestamp&&Date.now()-o.timestamp<1e3&&(o.callCountInSecond>=t||o.totalSizeInSecond>n))throw new FA({code:VA.INVALID_OPERATION,message:YO({key:jO.CALL_FREQUENCY_LIMIT,data:{isTimes:o.callCountInSecond>=t,isSize:o.totalSizeInSecond>n,name:i,timesInSecond:t,maxSizeInSecond:n}})});o.callCountInSecond++,e.call.apply(e,[this].concat(c))}}))}var nB,rB=!0,iB={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"},aB={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},oB=((nB=oB||{})[nB.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",nB[nB.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",nB[nB.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",nB[nB.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",nB[nB.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",nB[nB.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",nB[nB.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",nB[nB.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",nB[nB.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",nB[nB.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",nB[nB.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",nB[nB.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",nB[nB.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",nB[nB.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",nB[nB.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",nB[nB.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",nB[nB.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",nB[nB.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",nB[nB.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",nB[nB.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",nB[nB.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",nB[nB.INVALID_OPERATION=5100]="INVALID_OPERATION",nB[nB.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",nB[nB.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",nB[nB.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",nB[nB.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",nB[nB.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",nB[nB.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",nB[nB.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",nB[nB.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",nB[nB.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",nB[nB.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",nB[nB.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",nB[nB.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",nB[nB.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",nB[nB.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",nB[nB.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",nB[nB.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",nB[nB.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",nB[nB.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",nB[nB.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",nB[nB.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",nB[nB.DEVICE_ERROR=5300]="DEVICE_ERROR",nB[nB.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",nB[nB.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",nB[nB.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",nB[nB.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",nB[nB.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",nB[nB.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",nB[nB.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",nB[nB.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",nB[nB.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",nB[nB.SERVER_ERROR=5400]="SERVER_ERROR",nB[nB.NEED_TO_BUY=5401]="NEED_TO_BUY",nB[nB.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",nB[nB.OPERATION_FAILED=5500]="OPERATION_FAILED",nB[nB.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",nB[nB.REJOIN_FAILED=5502]="REJOIN_FAILED",nB[nB.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",nB[nB.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",nB[nB.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",nB[nB.OPERATION_ABORT=5998]="OPERATION_ABORT",nB[nB.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",nB),sB=gA(_A({},GO),{INVALID_PARAMETER:function(e){var t=e.fnName;return"the parameters of the '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_PARAMETER_REQUIRED:function(e){var t=e.key,n=e.rule,r=e.fnName,i=e.value;return"'".concat(t||n.name,"' is a required param when calling ").concat(r,"(), received: ").concat(i,".")},INVALID_PARAMETER_TYPE:function(e){var t,n=e.key,r=e.rule,i=e.fnName,a=e.value,o="".concat(n||r.name);return t=Array.isArray(r.type)?r.type.join("|"):r.type,"'".concat(o,"' must be type of ").concat(t," when calling ").concat(i,"(), received type: ").concat(Gw(a),".")},INVALID_PARAMETER_EMPTY:function(e){var t=e.key,n=e.rule,r=e.fnName,i=e.value;return"'".concat(t||n.name,"' cannot be '").concat(i,"' when calling ").concat(r,"().")},INVALID_PARAMETER_INSTANCE:function(e){var t=e.key,n=e.rule,r=e.fnName,i=e.value,a="".concat(t||n.name),o="".concat(n.instanceOf.name||n.instanceOf);return"'".concat(a,"' must be instanceof ").concat(o," when calling ").concat(r,"(), received type: ").concat(Gw(i),".")},INVALID_PARAMETER_RANGE:function(e){var t=e.key,n=e.rule,r=e.fnName,i=e.value;return"'".concat(t||n.name,"' must be one of ").concat(n.values.join("|")," when calling ").concat(r,"(), received: ").concat(i,".")},INVALID_PARAMETER_LESS_THAN_ZERO:function(e){var t=e.key,n=e.rule,r=e.fnName;return"'".concat(t||n.name,"' cannot be less than 0 when calling ").concat(r,"().")},INVALID_PARAMETER_MIN:function(e){var t=e.key,n=e.rule,r=e.value;return"the min value of ".concat(t||n.name," is ").concat(n.min,", received: ").concat(r,".")},INVALID_PARAMETER_MAX:function(e){var t=e.key,n=e.rule,r=e.value;return"the max value of ".concat(t||n.name," is ").concat(n.max,", received: ").concat(r,".")},INVALID_ELEMENT_ID:function(e){var t=e.key,n=e.fnName;return"'".concat(t,"' is not found in the document object when calling ").concat(n,"().")},INVALID_ELEMENT_ID_TYPE:function(e){var t=e.key,n=e.fnName,r=e.type;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(n,"(), received: ").concat(r,".")},INVALID_STREAM_ID:function(e){var t=e.key;return"'".concat(t,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.")},INVALID_ROOM_ID_STRING:function(e){var t=e.key;return"'".concat(t,"' must be a valid string.")},INVALID_ROOM_ID_INTEGER:function(e){var t=e.key;return"'".concat(t,"' must be an integer between [1, 4294967294].")},INVALID_ROOM_ID_INTEGER_STRING:function(e){var t=e.key;return"'".concat(t,"' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.")},INVALID_ROOM_ID_REQUIRED:function(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_ROOM_ID_TYPE_MISMATCH:function(e){var t=e.key;return"The type of target roomId must match the current roomId. Current room is using '".concat(t,"', but received '").concat("strRoomId"===t?"roomId":"strRoomId","'.")},INVALID_ROOM_ID_DUPLICATE:function(e){var t=e.key;return"the target '".concat(t,"' must not be the same as the current '").concat(t,"'.")},INVALID_STREAM_TYPE:function(e){var t=e.fnName;return"'streamType' is required when 'userId' is not '*', calling ".concat(t,"()")},INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION:function(e){var t=e.fnName;return"the API '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_OPERATION_NOT_JOINED:function(e){var t=e.fnName;return"cannot ".concat(t," because you are not enter room yet.")},INVALID_OPERATION_REMOTE_USER_NOT_EXIST:function(e){var t=e.fnName,n=e.value;return"cannot ".concat(t," because remote user(userId: ").concat(n.userId,") does not publishing stream.")},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST:function(e){var t=e.fnName,n=e.value;return"cannot ".concat(t," because remote user(userId: ").concat(n.userId,") does not publishing ").concat(n.streamType," video.")},INVALID_OPERATION_REPEAT_CALL:function(e){var t=e.fnName;return"you are already ".concat(t,"(), cannot repeated call '").concat(t,"'.")},INVALID_OPERATION_NEED_VIDEO:function(e){var t=e.fnName;return"cannot call '".concat(t,"' because the camera is not turned on.")},INVALID_OPERATION_NEED_AUDIO:function(e){var t=e.fnName;return"cannot call '".concat(t,"' because the microphone or screen share is not turned on.")},INVALID_BUFFER_EMPTY:function(e){var t=e.key;return"the buffer size of paramerter '".concat(t,"' cannot be empty")},INVALID_BUFFER_OVERSIZE:function(){return"buffer size is over 1000 Bytes"},INVALID_ROLE_AUDIENCE:function(){return"role: 'audience' cannot call this api."},INVALID_NOT_ENABLE_SEI:function(){return"you need to enable SEI in TRTC.create({ enableSEI: true })"},INVALID_NEED_CALL_PUBLISHED:function(e){var t=e.fnName;return"you need to call ".concat(t,"() after publish stream.")},ENV_NOT_SUPPORTED:function(e){var t=e.fnName;return"the current browser does not support the capability of the function '".concat(t,"' you are calling, please check the API documentation.")},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION:function(e){var t=e.fnName;return"cannot call ".concat(t," because the browser version is too low, please upgrade to the latest version")},DEVICE_ERROR:function(e){var t=e.fnName,n=e.error;return"'".concat(t,"' got device exception").concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_NOT_FOUND_ERROR:function(e){var t=e.fnName,n=e.deviceType,r=void 0===n?cB(t):n,i=e.error;return"NotFoundError, no ".concat(r," detected, please check your device and the configuration on '").concat(t,"'").concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_NOT_ALLOWED_ERROR:function(e){var t=e.fnName,n=e.deviceType,r=void 0===n?cB(t):n,i=e.error;return"NotAllowedError, you have disabled ".concat(r," access, please allow the current application to use the ").concat(r).concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_NOT_READABLE_ERROR:function(e){var t=e.fnName,n=e.deviceType,r=void 0===n?cB(t):n;return e.error,"NotReadableError, the ".concat(r," maybe in use by another APP, please check if the device is pre-occupied by another APP.")},DEVICE_OVERCONSTRAINED_ERROR:function(e){var t=e.fnName,n=e.deviceType;void 0===n&&cB(t);var r=e.error;return"OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct".concat(r?", error: ".concat(r.toString(),"."):".")},DEVICE_INVALID_STATE_ERROR:function(e){var t=e.fnName,n=e.deviceType,r=void 0===n?cB(t):n,i=e.error;return"InvalidStateError, after the user clicks and interacts with the page, turn on the ".concat(r).concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_SECURITY_ERROR:function(e){var t=e.fnName,n=e.deviceType,r=void 0===n?cB(t):n,i=e.error;return"SecurityError, check whether the system security policy restricts the use of the ".concat(r,", and it is recommended to turn on the ").concat(r," after the user interacts with the page").concat(i?", error: ".concat(i.toString(),"."):".")},DEVICE_ABORT_ERROR:function(e){var t=e.fnName,n=e.deviceType;void 0===n&&cB(t);var r=e.error;return"AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal".concat(r?" error: ".concat(r.toString(),"."):".")},CAMERA_RECOVER_FAILED:function(e){var t=e.error;return"camera recover capture failed ".concat((null==t?void 0:t.name)||"",": ").concat((null==t?void 0:t.originMessage)||(null==t?void 0:t.message))},MICROPHONE_RECOVER_FAILED:function(e){var t=e.error;return"microphone recover capture failed ".concat((null==t?void 0:t.name)||"",": ").concat((null==t?void 0:t.originMessage)||(null==t?void 0:t.message))},OPERATION_FAILED:function(e){var t=e.fnName,n=e.error;return"'".concat(t,"' failed, reason: ").concat(null==n?void 0:n.toString())},FIREWALL_RESTRICTION:function(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR:function(e){var t=e.eventName;return"an error was caught on trtc.on('".concat(t,"', handler), please check your code on 'handler'.")},VIDEO_CONTEXT_ERROR:function(e){var t=e.reason,n=e.error;return"video context error ".concat(t," ").concat((null==n?void 0:n.name)||""," ").concat((null==n?void 0:n.message)||"")},SERVER_ERROR:function(e){var t=e.fnName,n=e.error;return"'".concat(t,"' got server error: ").concat(null==n?void 0:n.toString(),", please check the SDK documentation.")},NEED_TO_BUY:function(e){var t=e.value,n=e.url;return"You need to buy packages for ".concat(t,". Refer to: ").concat(n)},ACCOUNT_NO_MONEY:function(e){var t=e.fnParams;return"your TRTC account run out of credit, please recharge.".concat(t.sdkAppId?" SDKAppId: ".concat(t.sdkAppId):"")},OPERATION_ABORT:function(e){var t=e.fnName;return"'".concat(t,"' abort")},UNKNOWN_ERROR:function(e){var t=e.fnName,n=e.error;return"'".concat(t,"' throw unknown exception").concat(n?", error: ".concat(n.toString(),"."):".")}});function cB(e){if(!e)return"camera";var t=e.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var uB=function(e){function i(e){var a;r(this,i);var o,s,c=e.code,u=e.extraCode,l=e.message,d=void 0===l?"":l,h=e.messageParams,f=e.fnName,p=void 0===f?"":f,m=e.originError;return s=d||function(e){var t,n=e.params,r=e.enableDocLink,i=void 0!==r&&r,a="",o=oB[e.code];try{t=sB[o]}catch(p){t=sB.UNKNOWN_ERROR}return Jw(t)?a=t(n):Yw(t)&&(a=t),n.fnName&&!a.includes(n.fnName)&&("."!==a[a.length-1]&&(a+="."),a+=" thrown from ".concat(n.fnName,"()")),i&&(a+=" doc:"),a}({code:c===aB.SERVER_ERROR?c:u||c,params:_A({fnName:p,error:m},h)}),a=n(this,i,[s]),SA(t(a),"name","RtcError"),SA(t(a),"code"),SA(t(a),"extraCode"),SA(t(a),"functionName"),SA(t(a),"message"),SA(t(a),"handler"),SA(t(a),"originError"),a.name=oB[c],a.code=c,a.extraCode=u,a.functionName=p,a.originError=m,a.message=s,5302===a.extraCode&&null!=(o=a.originError)&&o.message.includes("system")&&(a.handler=function(){var e=document.createElement("a");ON?e.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[a.functionName]):PN&&(e.href="x-apple.systempreferences:com.apple.preference.security?Privacy_".concat({startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"}[a.functionName])),e.href.length>0&&e.click()}),a}return d(i,e),o(i,null,[{key:"convertFrom",value:function(e,t,n){var r=e;if(e instanceof FA){var a=e.stack,o={code:aB.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case VA.INVALID_PARAMETER:o.code=aB.INVALID_PARAMETER,o.message=e.message;break;case VA.INVALID_OPERATION:o.code=aB.INVALID_OPERATION;break;case VA.NOT_SUPPORTED:case VA.NOT_SUPPORTED_H264:o.code=aB.ENV_NOT_SUPPORTED,e.getCode()===VA.NOT_SUPPORTED_H264&&(o.extraCode=e.message.includes(GO.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case VA.JOIN_ROOM_FAILED:o.messageParams={fnParams:n};case VA.SERVER_TIMEOUT:case VA.SWITCH_ROLE_FAILED:case VA.SWITCH_ROOM_FAILED:o.code=aB.SERVER_ERROR,o.extraCode=e.getExtraCode();break;case VA.API_CALL_ABORTED:o.code=aB.OPERATION_ABORT;break;case VA.DEVICE_NOT_FOUND:case VA.DEVICE_AUTO_RECOVER_FAILED:case VA.INITIALIZE_FAILED:o.code=5300,e.name&&(o.extraCode=function(e){var t;switch(e){case"NotFoundError":t=5301;break;case"NotAllowedError":t=5302;break;case"NotReadableError":t=5303;break;case"OverconstrainedError":t=5304;break;case"InvalidStateError":t=5305;break;case"SecurityError":t=5306;break;case"AbortError":t=5307;break;default:t=5300}return t}(e.name));break;case VA.UNKNOWN:break;default:o.code=aB.OPERATION_FAILED}r=new i(o),a&&(r.stack+=a.substr(a.indexOf("\n")))}else{if(e instanceof i)return e;r=new i({code:aB.UNKNOWN_ERROR,fnName:t,originError:e})}return r}}])}(I(Error)),lB=uB;function dB(e){return"sub"===e?"auxiliary":"auxiliary"===e?"sub":"main"}function hB(e){return e===iB.QOS_PREFERENCE_CLEAR?"detail":e===iB.QOS_PREFERENCE_SMOOTH?"motion":""}function fB(e,t){var n=t?TC:kC;return UD(e)?_A(_A({},n),e):EC[e]?EC[e]:n}var pB={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{type:["string","object","boolean"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},mB={type:"object",properties:{systemAudio:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},profile:{type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack},audioTrack:{instanceOf:MediaStreamTrack}}},vB={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate:function(e,t,n){if(Yw(e)&&!document.getElementById(e))throw new lB({code:aB.INVALID_PARAMETER,extraCode:5009,fnName:n,messageParams:{key:t}})}},_B={name:"userId",required:!0,type:"string"},gB={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[iB.AUDIO_PROFILE_STANDARD,iB.AUDIO_PROFILE_STANDARD_STEREO,iB.AUDIO_PROFILE_HIGH,iB.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function yB(e,t){if(!e)throw new lB({code:aB.INVALID_OPERATION,extraCode:5101,fnName:t})}function EB(e,t,n){if(!e)throw new lB({code:aB.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:n}})}function kB(e,t,n){if(!(/^[1-9]\d*$/.test(String(e))&&e<4294967295))throw new lB({code:aB.INVALID_PARAMETER,extraCode:5013,fnName:t,messageParams:{key:n}})}function TB(e,t,n){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(e))throw new lB({code:aB.INVALID_PARAMETER,extraCode:5012,fnName:t,messageParams:{key:n}})}function SB(e){var t;if(null!=(t=null==e?void 0:e.option)&&t.small){if(!AP())return Ux.warn("small stream is not supported"),void delete e.option.small;var n=fB(e.option.profile),r=fB(e.option.small,!0);return function(e,t){return e.width*e.height>=t.width*t.height&&e.frameRate>=t.frameRate&&e.bitrate>=t.bitrate}(n,r)?void 0:(Ux.warn("small stream profile must be less than big stream profile. Big: ".concat(JSON.stringify(n),", Small: ").concat(JSON.stringify(r))),void delete e.option.small)}}var IB={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate:function(e,t,n){if(this._room.isJoined)throw new lB({code:aB.INVALID_OPERATION,extraCode:5104,fnName:n});if(e.roomId){if(Yw(e.roomId))throw new lB({code:aB.INVALID_PARAMETER,extraCode:5016,fnName:n,messageParams:{key:t}});kB(e.roomId,n,t)}else{if(!e.strRoomId)throw new lB({code:aB.INVALID_PARAMETER,extraCode:5015,fnName:n});TB(e.strRoomId,n,t)}},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:vB,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:pB},validate:function(e){var t,n;if((null==(t=null==e?void 0:e.option)||!t.videoTrack)&&dP())throw new lB({code:aB.ENV_NOT_SUPPORTED,extraCode:5201});null!=(n=null==e?void 0:e.option)&&n.small&&SB(e)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:gA(_A({},vB),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:pB},validate:function(e){var t;null!=(t=null==e?void 0:e.option)&&t.small&&SB(e)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:gB},validate:function(e){var t;if((null==(t=null==e?void 0:e.option)||!t.audioTrack)&&dP())throw new lB({code:aB.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:gB}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:vB,publish:{type:"boolean"},option:mB},validate:function(e,t,n,r,i){var a;if(null==(a=null==e?void 0:e.option)||!a.videoTrack){if(dP())throw new lB({code:aB.ENV_NOT_SUPPORTED,extraCode:5201});if(!_P())throw new lB({code:aB.ENV_NOT_SUPPORTED,fnName:n,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:vB,publish:{type:"boolean"},option:mB}},muteRemoteAudio:[_B,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[_B,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:vB,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate:function(e,t,n){yB(this._room.isJoined,n);var r=this._room.remotePublishedUserMap.get(e.userId);if(EB(!!r,n,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new lB({code:aB.INVALID_OPERATION,extraCode:5103,fnName:n,messageParams:{value:e}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:gA(_A({},vB),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate:function(e,t,n){yB(this._room.isJoined,n);var r=this._room.remotePublishedUserMap.get(e.userId);if(EB(!!r,n,e),r&&("main"===e.streamType&&!r.muteState.videoAvailable||"sub"===e.streamType&&!r.muteState.hasAuxiliary))throw new lB({code:aB.INVALID_OPERATION,extraCode:5103,fnName:n,messageParams:{value:e}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate:function(e,t,n){if("*"!==e.userId&&Kw(e.streamType))throw new lB({code:aB.INVALID_PARAMETER,extraCode:5014,fnName:n})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate:function(e,t,n){yB(this._room.isJoining||this._room.isJoined,n)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate:function(e,t,n,r){if(!jP)throw new lB({code:aB.ENV_NOT_SUPPORTED,fnName:n,extraCode:5207});if(!this._room.enableSEI)throw new lB({code:aB.INVALID_OPERATION,fnName:n,extraCode:5108});if(e.byteLength>1e3)throw new lB({code:aB.INVALID_PARAMETER,extraCode:5018,fnName:n});if(0===e.byteLength)throw new lB({code:aB.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:n});yB(this._room.isJoined,n)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate:function(e,t,n){if(!e&&!this._room.isMainStreamPublished||e&&!this._room.isAuxStreamPublished)throw new lB({code:aB.INVALID_OPERATION,extraCode:5109,messageParams:{key:t},fnName:n})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate:function(e,t,n,r){if(e.byteLength>1e3)throw new lB({code:aB.INVALID_PARAMETER,extraCode:5018,fnName:n});if(0===e.byteLength)throw new lB({code:aB.INVALID_PARAMETER,extraCode:5017,fnName:n,messageParams:{key:t}})}}},validate:function(e,t,n){if(yB(this._room.isJoined,n),"live"===this._room.scene&&"audience"===this._room.role)throw new lB({code:aB.INVALID_OPERATION,extraCode:5107,fnName:n,messageParams:{key:t}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate:function(e,t,n){if(yB(this._room.isJoined,n),this._room.useStringRoomId&&e.strRoomId===this._room.roomId||!this._room.useStringRoomId&&e.roomId===Number(this._room.roomId))throw new lB({code:aB.INVALID_PARAMETER,extraCode:5020,fnName:n,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(e.roomId&&this._room.useStringRoomId||!e.roomId&&e.strRoomId&&!this._room.useStringRoomId)throw new lB({code:aB.INVALID_PARAMETER,extraCode:5019,fnName:n,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(e.roomId)kB(e.roomId,n,t);else{if(!e.strRoomId)throw new lB({code:aB.INVALID_PARAMETER,extraCode:5015,fnName:n});TB(e.strRoomId,n,t)}},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},bB={TRTC:IB},RB=function(e){function t(){return r(this,t),n(this,t,arguments)}return d(t,e),o(t)}(I(Error));function AB(e,t){for(var n=pD(e),r=0;r<t.length;r++)fD(n[r],t[r]);return n}function CB(e){this._resolve=Promise.resolve(e)}function wB(e){this._reject=Promise.reject(e)}var DB=function(){function e(t,n){r(this,e),this.instance=t,this.group=n,SA(this,"started",!1),SA(this,"ops",[]),SA(this,"startSame",(function(){return!0})),SA(this,"mergeUpdate",AB);var i=e.instances.get(t);i?i.set(n,this):e.instances.set(t,new Map([[n,this]]))}return o(e,[{key:"action",value:function(e,t,n){var r=this,i=function(t){var n;return 0===e?r.started=!0:3===e&&(r.started=!1),r.ops.shift(),null==(n=r.currentOp)||n.action(),t},a=function(t){var n,i;throw r.ops.shift(),0===e&&2===(null==(n=r.currentOp)?void 0:n.type)&&r.ops.shift().reject(new RB("start failed")),null==(i=r.currentOp)||i.action(),t},o={type:e,action:function(){return t.apply(void 0,E(o.args)).then(i,a)},args:n,resolve:CB,reject:wB};try{switch(this.state){case 1:if(0===e)throw new RB("already started");break;case 4:if(2===e)throw new RB("not started");break;default:return this.cacheOp(o)}}catch(zx){return Promise.reject(zx)}return this.ops.push(o),o.promise=t.apply(void 0,E(o.args)).then(i,a)}},{key:"cacheOp",value:function(e){if(1===this.ops.length)switch(this.state){case 0:case 2:if(0===e.type)throw new RB("already start");break;case 3:switch(e.type){case 2:throw new RB("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new RB("unknown state")}else switch(e.type){case 3:if(3===this.lastOpType)return this.lastOp.promise;var t=new RB("keep stop");if(this.ops.slice(1).forEach((function(e){return e.reject(t)})),this.ops=this.ops.slice(0,1),3===this.state)return this.currentOp.promise;break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,e.args),this.lastOp.promise;case 3:throw new RB("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new RB("start not allowed after update");case 0:throw new RB("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new RB("keep start")),new RB("already start")}}e.promise=new Promise((function(t,n){e._resolve?e._resolve.then(t):e.resolve=t,e._reject?e._reject.catch(n):e.reject=n}));var n=e.action;return e.action=function(){return n().then(e.resolve,e.reject)},this.ops.push(e),e.promise}},{key:"lastOp",get:function(){return this.ops[this.ops.length-1]}},{key:"lastOpType",get:function(){return this.lastOp.type}},{key:"currentOp",get:function(){return this.ops[0]}},{key:"state",get:function(){return this.currentOp?this.currentOp.type:this.started?1:4}}],[{key:"get",value:function(t,n){if(n){var r=e.instances.get(t);return r&&r.get(n)||new e(t,n)}}},{key:"gets",value:function(t,n){var r=e.instances.get(t),i=[];return r&&r.forEach((function(e,t){n.test(t)&&i.push(e)})),i}}])}();SA(DB,"instances",new WeakMap);var NB=DB,xB=new WeakMap,OB=function(e,t){if(t instanceof RB){var n=t.stack;t=new lB({code:aB.OPERATION_ABORT,message:"".concat(e," abort: ").concat(t.message),fnName:e}),n&&(t.stack+=n.substr(n.indexOf("\n")))}throw t};function PB(e,t){return jL((function(n,r){return function(){for(var i=arguments.length,a=new Array(i),o=0;o<i;o++)a[o]=arguments[o];var s=NB.get(this,"string"==typeof e?e:e.call.apply(e,[this].concat(a)));return s?(t&&(s.startSame=t.bind(this)),s.action(0,n.bind(this),a).catch(OB.bind(null,r))):n.apply(this,a)}}))}function MB(e,t){var n=t||{},r=n.merge,i=n.debounce;return jL((function(t,n){return function(){for(var a=this,o=arguments.length,s=new Array(o),c=0;c<o;c++)s[c]=arguments[c];var u=NB.get(this,"string"==typeof e?e:e.call.apply(e,[this].concat(s)));if(!u)return t.apply(this,s);if(r&&(u.mergeUpdate=r.bind(this)),i&&i.isNeedToDebounce.apply(this,s)){var l=i.delay,d=i.getKey;return new Promise((function(e,r){var i,o,c=null==(i=xB.get(a))?void 0:i.get(d.apply(void 0,s));if(c){var h=c.timeoutId,f=c.resolve;clearTimeout(h),f()}var p=setTimeout((function(){if(3===u.state||4===u.state)return e();u.action(2,t.bind(a),s).catch(OB.bind(null,n)).then(e,r)}),l);xB.has(a)?null==(o=xB.get(a))||o.set(d.apply(void 0,s),{timeoutId:p,resolve:e}):xB.set(a,new Map([[d.apply(void 0,s),{timeoutId:p,resolve:e}]]))}))}return u.action(2,t.bind(this),s).catch(OB.bind(null,n))}}))}function LB(e){return jL((function(t,n){return function(){for(var r=this,i=arguments.length,a=new Array(i),o=0;o<i;o++)a[o]=arguments[o];var s="function"==typeof e?e.call.apply(e,[this].concat(a)):e;if(s instanceof RegExp)return Promise.all(NB.gets(this,s).map((function(e){return e.action(3,(function(){return Promise.resolve()}),a)}))).then((function(){return t.call.apply(t,[r].concat(a))}));var c=NB.get(this,s);return c?c.action(3,t.bind(this),a).catch(OB.bind(null,n)):t.apply(this,a)}}))}var VB={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame"},UB=new Set([VB.ERROR,VB.AUTOPLAY_FAILED,VB.KICKED_OUT,VB.REMOTE_USER_ENTER,VB.REMOTE_USER_EXIT,VB.REMOTE_AUDIO_AVAILABLE,VB.REMOTE_AUDIO_UNAVAILABLE,VB.REMOTE_VIDEO_AVAILABLE,VB.REMOTE_VIDEO_UNAVAILABLE,VB.CONNECTION_STATE_CHANGED,VB.PUBLISH_STATE_CHANGED,VB.SCREEN_SHARE_STOPPED,VB.DEVICE_CHANGED,VB.FIRST_VIDEO_FRAME]),FB={};EA(FB,{bytes2ms:function(){return Mw},calculateScaleResolutionDownNumber:function(){return wD},convertObjectNumberToInt:function(){return ID},copyProperties:function(){return Pw},deepClone:function(){return pD},deepMerge:function(){return fD},delay:function(){return bD},fibonacci:function(){return Ww},formatedTime:function(){return _D},getConstructorName:function(){return nD},getContainerFromElement:function(){return vD},getEnv:function(){return Rw},getInternalVersion:function(){return sD},getLoggerUrl:function(){return Cw},getMediaStreamTrackInfo:function(){return CD},getMuteStateFromFlag:function(){return lD},getNetworkType:function(){return Dw},getNumNetworkType:function(){return Ow},getReconnectionTimeout:function(){return jw},getStringByteLength:function(){return ED},getTurnServer:function(){return dD},getUint32Version:function(){return SD},getValueType:function(){return Gw},getViewListFromView:function(){return mD},glog:function(){return Fw},ipv4ToUint32:function(){return hD},isArray:function(){return Qw},isAudioWorkletSupported:function(){return rD},isBoolean:function(){return qw},isConstructor:function(){return tD},isEmpty:function(){return uD},isFunction:function(){return Jw},isLangChinese:function(){return Bw},isMediaStreamTrack:function(){return Zw},isNumber:function(){return zw},isObject:function(){return Xw},isOverseaSdkAppId:function(){return Aw},isPlainObject:function(){return Hw},isPortrait:function(){return kD},isPromise:function(){return eD},isRemoteTrack:function(){return $w},isRotate90Or270:function(){return DD},isString:function(){return Yw},isUndefined:function(){return Kw},loadImage:function(){return TD},ms2bytes:function(){return Vw},ms2samples:function(){return Uw},normalizeUrl:function(){return AD},performanceNow:function(){return aD},promiseAny:function(){return iD},samples2ms:function(){return Lw},setNetworkType:function(){return xw},stringify:function(){return gD},stringifyIncludeValue:function(){return yD},throttlePromise:function(){return RD}});var BB={};EA(BB,{ScheduleRequestType:function(){return YB},getAbilityConfig:function(){return qB},getScheduleDomain:function(){return XB},isNeedToSchedule:function(){return WB},scheduleProxy:function(){return JB},sendScheduleRequest:function(){return GB},setIsNeedToSchedule:function(){return jB},setScheduleProxy:function(){return KB}});var HB=null,WB=!0;function jB(e){qw(e)&&e!==WB&&(WB=e,Ux.info("setIsNeedToSchedule ".concat(e)))}function GB(e){return bA(this,arguments,(function(e){var t=e.userId,n=e.sdkAppId,r=e.useStringRoomId,i=e.roomId,a=e.userSig,o=e.version,c=e.frameWorkType,u=e.role,l=e.latencyLevel;return f().mark((function e(){var d,h,p,m,v,_,g,y,E,k;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(WB||!HB){e.next=2;break}return e.abrupt("return",{isCached:!0,result:HB});case 2:return d={delta:0,count:[1,1],msg:[],detail:[]},e.prev=3,(h=new FormData).append("userId",String(t)),h.append("sdkAppId",String(n)),h.append("isStrGroupId",String(r)),h.append("groupId",String(i)),h.append("sdkVersion",o),h.append("userSig",String(a)),e.next=8,bx();case 8:return null!=(p=e.sent)&&p.model&&h.append("model",String(null==p?void 0:p.model)),u&&h.append("role",String(u)),l&&h.append("latencyLevel",String(l)),c&&h.append("frameWorkType",String(c)),m=aD(),e.next=13,function(e,t,n){return new Promise((function(r,i){var a=null;iD([ZB((function(e){return t.count[0]=e+1}),(function(e){var r=e.error,i=e.retry,o=e.retriedCount,s=e.retryFuncArgs;t.msg[0]=r.message,a||(o>=1&&(s[0]=zB(n,"config",IC.MAIN,!0)),i())}))(zB(n,"config",IC.MAIN),e,{get timeout(){return 1e3*Ww(2+t.count[0])}}),ZB((function(e){return t.count[1]=e+1}),(function(e){var r=e.error,i=e.retry,o=e.retriedCount,s=e.retryFuncArgs;t.msg[1]=r.message,a||(o>=2&&(s[0]=zB(n,"config",IC.BACKUP,!0)),i())}))(zB(n,"config",IC.BACKUP),e,{get timeout(){return 1e3*Ww(2+t.count[1])}})]).then((function(e){r(a=e)})).catch(i)}))}(h,d,n);case 13:return(v=e.sent).config&&(v.config.loggerDomain&&tC(v.config.loggerDomain),qw(v.config.scheduleCache)&&jB(!v.config.scheduleCache)),d.delta=aD()-m,_=function(e,t,n){var r={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{var i,o=performance.getEntriesByType("resource"),c=zB(e,"config",IC.MAIN),u=zB(e,"config",IC.BACKUP),l=s(o);try{for(l.s();!(i=l.n()).done;){var d=i.value;if(d.startTime>=n&&(d.name===c||d.name===u)&&d.transferSize>0){var h=d.name===c?IC.MAIN:IC.BACKUP,f=Math.round(d.duration),p=Math.round(d.domainLookupStart-d.startTime),m=d.redirectStart>0?Math.round(d.redirectEnd-d.redirectStart):0,v=d.fetchStart>0?Math.round(d.domainLookupStart-d.fetchStart):0,_=Math.round(d.domainLookupEnd-d.domainLookupStart),g=Math.round(d.requestStart-d.secureConnectionStart),y=Math.round(d.secureConnectionStart-d.connectStart),E=Math.round(d.responseStart-d.requestStart),k=Math.round(d.responseEnd-d.responseStart),T=[_,g,y,E,k];kM.uploadEvent({log:"stat-schedule-net:".concat(f,"(").concat(p,"(").concat(m,"->").concat(v,")->").concat(T.join("->"),") ").concat(h),userId:t}),r=gA(_A({},r),{totalCost:f,local:p,dns:_,tcp:y,tls:g,request:E,response:k});break}}}catch(S){l.e(S)}finally{l.f()}}catch(a){Ux.error("getScheduleDetailCost error",a)}return r}(Number(n),t,m),e.abrupt("return",(HB=v,{isCached:!1,result:v,detailCost:_}));case 19:throw e.prev=19,e.t0=e.catch(3),g=Qw(e.t0)?e.t0[0]:e.t0,y=zw(g.code)?g.code:0,E="schedule failed".concat(g.message?": ".concat(g.message):""),k=new FA({code:VA.SCHEDULE_FAILED,extraCode:y,message:YO({key:jO.JOIN_ROOM_FAILED,data:{error:E,code:y}})}),Ux.error(E,y),k;case 23:case"end":return e.stop()}}),e,null,[[3,19]])}))()}))}"undefined"!=typeof document&&document.head.insertAdjacentHTML("beforeend",Object.values(fw).map((function(e){return'<link rel="dns-prefetch" href="https://'.concat(e,'">')})).join("\r\n")),Px.on("28",(function(){return jB(!0)})),Px.on("63",(function(){return jB(!0)})),Px.on("84",(function(){return jB(!0)})),Px.on("201",(function(e){"RECONNECTING"===e.state&&jB(!0)})),Px.on("202",(function(e){"RECONNECTING"===e.state&&jB(!0)}));var JB={main:"",backup:""};function KB(e){Qw(e)?(JB.main=e[0],JB.backup=e[1]):JB.main=e}var YB=function(e){return e.CONFIG="config",e.TRTC_AUTO_CONF="trtcAutoConf",e.AUDIO_AI_AUTH="audioAiAuth",e}(YB||{});function zB(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:IC.MAIN,r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];return"https://".concat(JB[n]||XB(e,n,r),"/api/v1/").concat(t)}function qB(e,t,n){var r=zB(e,t),i=zB(e,t,IC.BACKUP),a=new URLSearchParams(n).toString();return iD([fetch("".concat(r,"?").concat(a)).then((function(e){return e.json()})),fetch("".concat(i,"?").concat(a)).then((function(e){return e.json()}))])}function XB(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:IC.MAIN,n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return Aw(e)?n?t===IC.MAIN?fw.MAIN_OVERSEA_BACKUP:fw.BACKUP_OVERSEA:t===IC.MAIN?fw.MAIN_OVERSEA:fw.BACKUP_OVERSEA:t===IC.MAIN?fw.MAIN:fw.BACKUP}function QB(e,t,n){return new Promise((function(r,i){ND({url:e,body:t,timeout:n.timeout,priority:"high"}).then((function(e){0===e.data.code?r(e.data.data):i({code:e.data.code,message:e.data.msg})})).catch(i)}))}var ZB=function(e,t){return FD({retryFunction:QB,settings:{retries:3,timeout:0},onError:t,onRetrying:e})},$B=function(){return o((function e(){r(this,e),SA(this,"_log"),this._log=Ux.createLogger({id:"fd"})}),[{key:"download",value:function(e,t){return bA(this,null,f().mark((function n(){var r,i,a,o,s;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(r=(t||{}).type,i=void 0===r?"blob":r,e=AD(e),n.prev=2,o=aD(),!Jw(fetch)){n.next=10;break}return n.next=7,this.downloadWithFetch(e,i);case 7:n.t0=n.sent,n.next=13;break;case 10:return n.next=12,this.downloadWithXHR(e,i);case 12:n.t0=n.sent;case 13:if((a=n.t0)&&a.data){n.next=16;break}throw new Error("data is empty");case 16:return s=aD()-o,n.abrupt("return",(this._log.info("downloaded: ".concat(e,", return type: ").concat(i,", cost: ").concat(s,"ms")),rP.addSuccessEvent({key:522700,cost:aD()-o}),a.data));case 20:throw n.prev=20,n.t1=n.catch(2),this._log.error("failed to download: ".concat(e,", error: ").concat(n.t1)),rP.addFailedEvent({key:522700,error:n.t1}),n.t1;case 23:case"end":return n.stop()}}),n,this,[[2,20]])})))}},{key:"downloadWithFetch",value:function(e,t){return bA(this,null,f().mark((function n(){var r,i,a;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return this._log.info("download with fetch: ".concat(e,", return type: ").concat(t)),n.prev=1,n.next=4,fetch(e);case 4:if((i=n.sent).ok){n.next=8;break}throw(a=new Error("network response was not ok: ".concat(i.status))).status=i.status,a;case 8:if("arraybuffer"!==t){n.next=14;break}return n.next=11,i.arrayBuffer();case 11:n.t0=n.sent,n.next=17;break;case 14:return n.next=16,i.blob();case 16:n.t0=n.sent;case 17:return r=n.t0,n.abrupt("return",{data:r});case 21:throw n.prev=21,n.t1=n.catch(1),n.t1;case 24:case"end":return n.stop()}}),n,this,[[1,21]])})))}},{key:"downloadWithXHR",value:function(e,t){return this._log.info("download with xhr: ".concat(e,", return type: ").concat(t)),new Promise((function(n,r){var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType=t,i.onload=function(){if(200===i.status||0===i.status&&i.response)n({data:i.response});else{var e=new Error("XHR failed, status: ".concat(i.status));e.status=i.status,r(e)}},i.onerror=r,i.send(null)}))}},{key:"loadWasm",value:function(e,t){return bA(this,null,f().mark((function n(){var r,i,a,o,s,c;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(this._log.info("loadWasm ".concat(e,", importObject: ").concat(JSON.stringify(t))),r=aD(),i=null,a=null,!Jw(WebAssembly.instantiateStreaming)||e.startsWith("data:application/octet-stream;base64,")||function(e){return e.startsWith("file://")}(e)||!Jw(fetch)){n.next=13;break}return n.prev=3,o=fetch(e),n.next=7,WebAssembly.instantiateStreaming(o,t);case 7:i=n.sent.instance,n.next=13;break;case 10:n.prev=10,n.t0=n.catch(3),a=n.t0;case 13:if(i){n.next=26;break}return n.prev=14,n.next=17,this.download(e,{type:"arraybuffer"});case 17:return s=n.sent,n.next=20,WebAssembly.instantiate(s,t);case 20:i=n.sent.instance,n.next=26;break;case 23:n.prev=23,n.t1=n.catch(14),a=n.t1;case 26:if(!i){n.next=29;break}return c=aD()-r,n.abrupt("return",(this._log.info("loadedWasm ".concat(e,", cost: ").concat(c,"ms")),rP.addSuccessEvent({key:522701,cost:c}),i));case 29:throw this._log.error("failed to loadWasm ".concat(e,", error: ").concat(a)),rP.addFailedEvent({key:522701,error:a}),a;case 30:case"end":return n.stop()}}),n,this,[[3,10],[14,23]])})))}},{key:"loadScript",value:function(e){var t=this;this._log.info("loadScript ".concat(e));var n=aD();return new Promise((function(r,i){var a=document.createElement("script");a.type="text/javascript",a.onload=function(){t._log.info("loadedScript ".concat(e,", cost: ").concat(aD()-n,"ms")),rP.addSuccessEvent({key:522702,cost:aD()-n,split:1e3}),r(a)},a.onerror=function(n){t._log.error("failed to loadScript ".concat(e,", error: ").concat(n)),rP.addFailedEvent({key:522702}),i(n)},a.crossOrigin="anonymous",a.src=e,document.head.append?document.head.append(a):document.getElementsByTagName("head")[0].appendChild(a)}))}}])}();TA([SM({settings:{timeout:0,retries:3},onError:function(e,t,n){var r;404===(null==e?void 0:e.status)||null!=(r=null==e?void 0:e.message)&&r.includes("404")?(this._log.warn("download 404, stop retry"),n(e)):t()},onRetrying:function(e){this._log.warn("download retrying: ".concat(e))}})],$B.prototype,"download",1),TA([SM({settings:{timeout:3e3,retries:3},onRetrying:function(e){this._log.warn("loadScript retrying: ".concat(e))}})],$B.prototype,"loadScript",1);var eH=new $B;function tH(e){var t=this,n=e.TRTC,r=e.room,i=e.errorModule;return{TRTC:n,room:r,assetsPath:e.assetsPath,fileDownloader:eH,innerEmitter:Px,constants:JA,environment:HD,utils:FB,eventLogger:kM,log:this.room.getLogger(),loggerManager:Ux,errorModule:i,kvStatManager:rP,rtcDectection:Hx,trtc:this,rx:mV,enums:Wx,schedule:BB,clearStarted:function(e,n){var r=e.getAlias(),i=NB.instances.get(t);if(i)if(n){var a=i.get(r+n);if(!a)return;a.started=!1}else i.forEach((function(e,t){t.startsWith(r)&&(e.started=!1)}))},startGetPCM:hV,createAudioNode:uL}}var nH=new WeakMap;function rH(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return jL((function(e,n){return function(){for(var r=arguments.length,i=new Array(r),a=0;a<r;a++)i[a]=arguments[a];try{aH.call(this,t,i,n,this._name)}catch(Yx){return Promise.reject(Yx)}return e.apply(this,i)}}))}function iH(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return jL((function(e,n){return function(){for(var r=arguments.length,i=new Array(r),a=0;a<r;a++)i[a]=arguments[a];try{aH.call(this,t,i,n,this._name)}catch(Yx){throw Yx}return e.apply(this,i)}}))}function aH(e,t,n,r){if(Qw(e))for(var i=0;i<e.length;i++)oH.call(this,{rule:e[i],value:t[i],key:e[i].name,fnName:n,className:r});else oH.call(this,{rule:e,value:t[0],key:e.name,fnName:n,className:r})}function oH(e){var t=this,n=e.rule,r=e.value,i=e.key,a=e.fnName,o=e.className;function s(e){return{code:aB.INVALID_PARAMETER,extraCode:e,fnName:a,messageParams:{key:i,rule:n,value:r}}}if(Kw(r)){if(n.required)throw new lB(s(5001));if(Kw(n.defaultValue))return void(Jw(n.validate)&&n.validate.call(this,r,i,a,o,this));r=n.defaultValue}if(Array.isArray(n.type)){for(var c=!1,u=0;u<n.type.length;u++)null===n.type[u]&&null===r&&(c=!0),Jw(n.type[u])&&r instanceof n.type[u]&&(c=!0),Yw(n.type[u])&&Gw(r)===n.type[u].toLowerCase()&&(c=!0);if(!c)throw new lB({code:aB.INVALID_PARAMETER,extraCode:5002,fnName:a,messageParams:{key:i,rule:{type:n.type.map((function(e){return tD(e)?nD(e):Yw(e)?e:Gw(e)}))},value:r}})}else if(!Kw(n.type)&&Gw(r)!==n.type)throw new lB(s(5002));if(!1===n.allowEmpty){var l=zw(r)&&(0===r||Number.isNaN(r)),d=Yw(r)&&""===r.trim();if(l||d)throw new lB(s(5003))}if(n.notLessThanZero&&zw(r)&&r<0)throw new lB(s(5006));if(!Kw(n.min)&&zw(r)&&r<n.min)throw new lB(s(5007));if(!Kw(n.max)&&zw(r)&&r>n.max)throw new lB(s(5008));if(Yw(n.instanceOf)){if(!r||r._name!==n.instanceOf)throw new lB(s(5004))}else if(Jw(n.instanceOf)&&!(r instanceof n.instanceOf))throw new lB(s(5004));if(Array.isArray(n.values)&&!n.values.includes(r))throw new lB(s(5005));var h=n.properties;Hw(h)&&Xw(r)&&Object.keys(h).forEach((function(e){oH.call(t,{rule:h[e],value:r&&r[e],key:"".concat(e),fnName:a,className:o})}));var f=n.arrayItem;Hw(f)&&Qw(r)&&r.forEach((function(e,n){oH.call(t,{rule:f,value:e,key:"".concat(i,"[").concat(n,"]"),fnName:a,className:o})})),Jw(n.validate)&&n.validate.call(this,r,i,a,o,this)}function sH(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.getRemoteId,n=void 0===t?function(){return""}:t,r=e.replaceArg,i=e.getKVReportKey,a=e.ignoreLog,o=e.ignoreErrorLog;return jL((function(e,t){return function(){for(var s,c,u,l=this,d=arguments.length,h=new Array(d),f=0;f<d;f++)h[f]=arguments[f];function p(e,t,n){if(n&&n.includes(e))return"hided";if(r){var i=r.apply(void 0,h);if(h[i.argIndex]===t)return i.value}if(t===h||e in h)return t;try{return t instanceof HTMLElement?"id: ".concat(t.id," type:").concat(Gw(t)):t instanceof MediaStreamTrack?CD(t):(JSON.stringify(t),t)}catch(a){return"type:".concat(Gw(t))}}var m=this._log||Ux;if(null!=a&&a.apply(void 0,h))return e.apply(this,h);h.length>0?m.info("".concat(t,"() ").concat(JSON.stringify(h,(function(e,t){return p(e,t,["userSig","privateMapKey"])})))):m.info("".concat(t,"()"));var v=i?i.apply(void 0,h):QO[t],_=(null==o?void 0:o.apply(void 0,h))||!1;try{var g=e.apply(this,h),y=aD();if(eD(g)){var E="".concat(t.includes("Plugin")?"".concat((null==(c=(s=h[0]).getName)?void 0:c.call(s))||""," "):" ");return g.then((function(e){return m.info("".concat(t,"() success ").concat(E).concat(n.call.apply(n,[l].concat(h)))),rP.addSuccessEvent({key:v,cost:aD()-y}),e})).catch((function(e){var r,i=(e=lB.convertFrom.call(l,e,t,1===h.length?h[0]:h)).extraCode||e.code,a=null!=(r=e.message)&&r.includes(i)?"":" code:".concat(i);throw _||m.error("".concat(t,"() failed ").concat(E).concat(n.call.apply(n,[l].concat(h))," ").concat(e).concat(a," params: ").concat(JSON.stringify(h,p))),rP.addFailedEvent({key:v,error:e}),e}))}return rP.addSuccessEvent({key:v}),g}catch(Qx){var k=(Qx=lB.convertFrom.call(this,Qx,t)).extraCode||Qx.code,T=null!=(u=Qx.message)&&u.includes(k)?"":" code:".concat(k);throw _||m.error("".concat(t,"() failed ").concat(Qx).concat(T," params: ").concat(JSON.stringify(h,p))),rP.addFailedEvent({key:v,error:Qx}),Qx}}}))}var cH,uH=function(e){return jL((function(t,n){return function(r,i){return bA(this,null,f().mark((function a(){var o;return f().wrap((function(a){for(;;)switch(a.prev=a.next){case 0:if(o=this._plugins.get(r)){a.next=3;break}throw this._log.error("plugin ".concat(String(r)," is not found")),new lB({code:aB.OPERATION_ABORT,message:"plugin ".concat(String(r)," is not found"),fnName:n});case 3:if(!Jw(o.constructor.isSupported)||o.constructor.isSupported()){a.next=5;break}throw this._log.error("plugin ".concat(String(r)," is not supported")),new lB({code:aB.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(r)," is not supported"),extraCode:5210,fnName:n});case 5:return a.abrupt("return",(aH.call(this,o.getValidateRule(e),[i],n,"TRTC"),t.call(this,o,i)));case 6:case"end":return a.stop()}}),a,this)})))}}))},lH=0,dH=function(){function e(t){r(this,e),this.core=t,SA(this,"log"),SA(this,"customAudioReferenceMap",new Map),SA(this,"audioRefId",0),SA(this,"audioContext",nL()),SA(this,"localAudioWorkletNode"),SA(this,"screenAudioWorkletNode"),SA(this,"mixNode"),SA(this,"silentNode"),lH+=1,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(lH)}),this.log.info("created id=".concat(this.getAlias()).concat(lH))}return o(e,[{key:"preload",value:function(e){return cH||(cH=this.doPreload(e)),cH}},{key:"doPreload",value:function(e){return bA(this,null,f().mark((function t(){var n,r;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.core.fileDownloader.download(e,{type:"blob"});case 2:return n=t.sent,r=URL.createObjectURL(n),t.prev=4,t.next=7,qM(this.audioContext,r);case 7:t.next=12;break;case 9:t.prev=9,t.t0=t.catch(4),this.log.error("preload audioProcessor failed. ".concat(t.t0));case 12:return t.prev=12,URL.revokeObjectURL(r),t.finish(12);case 15:case"end":return t.stop()}}),t,this,[[4,9,12,15]])})))}},{key:"getName",value:function(){return e.Name}},{key:"getAlias",value:function(){return"ap"}},{key:"getGroup",value:function(){return"ap"}},{key:"getValidateRule",value:function(t){switch(t){case"start":return e.getStartValidateRule(this.core);case"update":return e.updateValidateRule;case"stop":return e.stopValidateRule}}},{key:"start",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a,o,s,c,u,l,d,h,p,m,v,_,g,y,E,k=this;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=this.core.room,r=e.sdkAppId,i=e.userId,a=e.assetsPath,o=void 0===a?this.core.assetsPath:a,s=e.audioReference,c=e.processLevel,u=e.enableDump,l=e.isLocalAudioNeedAudioProcess,d=void 0===l||l,h=e.isScreenAudioNeedAudioProcess,p=void 0===h||h,this.core.room.audioManager.isLocalAudioNeedAudioProcess=d,this.core.room.audioManager.isScreenAudioNeedAudioProcess=p,o){t.next=3;break}throw new lB({code:aB.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});case 3:return t.next=5,this.preload("".concat(o,"/audioProcessor-wasm.js"));case 5:if(this.localAudioWorkletNode&&this.screenAudioWorkletNode){t.next=17;break}return m=String(Date.now()).slice(0,-3),t.next=9,function(e){return bA(this,arguments,(function(e){var t=e.sdkAppId,n=e.userId,r=e.userSig,i=e.timestamp;return f().mark((function e(){var a,o,s,c,u,l,d,h,p,m,v;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return a="".concat(function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:IC.MAIN;return"https://".concat(JB[t]||XB(e,t),"/api/v1/audioAiAuth")}(t),"?sdkAppId=").concat(t,"&userId=").concat(n,"&userSig=").concat(r,"×tamp=").concat(i),e.next=3,fetch(a);case 3:return o=e.sent,e.next=6,o.json();case 6:if(s=e.sent,c=s.data,u=c.errCode,l=c.errMsg,d=c.sign,"1"!==(h=c.status)){e.next=14;break}return e.abrupt("return",{auth:!0,sign:d,status:h,message:l});case 14:p=Aw(t)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",m="Init RTCAudioProcessor failed.",v="",e.t0=u,e.next=1===e.t0?18:2===e.t0?20:3===e.t0?22:4===e.t0?24:5===e.t0?26:6===e.t0?28:29;break;case 18:return v="Please check your params.",e.abrupt("break",29);case 20:return v="You need to buy packages. Refer to: ".concat(p),e.abrupt("break",29);case 22:return v="Server is invalid. Please contact our engineer. ",e.abrupt("break",29);case 24:return v="Your packages is not active. Refer to: ".concat(p),e.abrupt("break",29);case 26:return v="Your packages is expired. Refer to: ".concat(p),e.abrupt("break",29);case 28:v="Your version is not supported.";case 29:return e.abrupt("return",{auth:!1,status:h,message:l?"".concat(m," Reason: ").concat(l,". ").concat(v):"".concat(m,", ").concat(v)});case 30:case"end":return e.stop()}}),e)}))()}))}(gA(_A({},e),{timestamp:m}));case 9:if(v=t.sent,_=v.auth,g=v.sign,y=v.status,E=v.message,_){t.next=16;break}throw this.log.info("audioProcessor: ".concat(i," auth result: ").concat(_,". Message: ").concat(E)),new lB({code:aB.INVALID_PARAMETER,message:E});case 16:this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",r,i,m,g,y,n),this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",r,i,m,g,y,n);case 17:this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),this.localAudioWorkletNode.port.postMessage({type:"enable"}),this.screenAudioWorkletNode.port.postMessage({type:"enable"}),n.audioManager.addAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode),Kw(s)||s.forEach((function(e){k.customAudioReferenceMap.set(e,"o-".concat(k.audioRefId++)),k.core.room.audioManager.updateAudioReference({type:"add",audioReference:e,refId:"o-".concat(k.audioRefId++)})})),Kw(c)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:c}}),Kw(u)||this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:u}});case 18:case"end":return t.stop()}}),t,this)})))}},{key:"update",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a=this;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this.localAudioWorkletNode&&this.screenAudioWorkletNode){t.next=2;break}return t.abrupt("return");case 2:n=e.audioReference,r=e.enableDump,i=e.processLevel,Kw(n)||(this.customAudioReferenceMap.forEach((function(e,t){a.customAudioReferenceMap.delete(t),a.core.room.audioManager.updateAudioReference({type:"remove",refId:e})})),n.forEach((function(e){a.customAudioReferenceMap.set(e,"o-".concat(a.audioRefId++)),a.core.room.audioManager.updateAudioReference({type:"add",audioReference:e,refId:"o-".concat(a.audioRefId++)})}))),Kw(i)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:i}}),Kw(r)||(this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:r}}),this.screenAudioWorkletNode.port.postMessage({type:"dump",data:{enable:r}}));case 4:case"end":return t.stop()}}),t,this)})))}},{key:"stop",value:function(){return bA(this,null,f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.localAudioWorkletNode&&this.mixNode&&this.silentNode&&this.screenAudioWorkletNode){e.next=2;break}return e.abrupt("return");case 2:return t=this.core.room,this.localAudioWorkletNode.port.postMessage({type:"disable"}),this.screenAudioWorkletNode.port.postMessage({type:"disable"}),e.next=7,t.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode);case 7:case"end":return e.stop()}}),e,this)})))}},{key:"destroy",value:function(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null)}},{key:"initWorkletNode",value:function(e,t,n,r,i,a,o,s){var c=this;e.port.postMessage({type:"init",data:{sdkAppId:String(n),userId:r,timestamp:i,sign:a,status:o}}),e.port.onmessage=function(e){var n,r=e.data;switch(r.type){case"cost":var i=(null==r?void 0:r.value)>10?"info":"debug";return void c.log[i]("[".concat(t,"] avg cost: ").concat(r.value," max: ").concat(null==r?void 0:r.max,"(").concat(jA(new Date(null==r?void 0:r.maxCostTimestamp)),") hist: ").concat(null==(n=null==r?void 0:r.hist)?void 0:n.join(" ")));case"log":return void c.log[r.logLevel]("[".concat(t,"] ").concat(r.value));case"dump":return void Px.emit("265",{room:s,data:r.value,type:"localAudio"===t?"dump":"dump-screen-audio"})}}}}],[{key:"getStartValidateRule",value:function(e){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate:function(t,n,r,i){if(!e.room.audioManager.hasAudioTrack&&!e.room.audioManager.hasScreenAudioTrack)throw new lB({code:aB.INVALID_OPERATION,extraCode:5106,fnName:r})}}}}])}();SA(dH,"updateValidateRule",{type:"object"}),SA(dH,"stopValidateRule",{type:"object"}),SA(dH,"Name","AudioProcessor");var hH=dH,fH=0,pH=function(){return o((function e(t,n){r(this,e),SA(this,"player"),SA(this,"publisher"),SA(this,"mixInput"),this.mixInput=new oL(n),t.url?(this.player=new Audio(t.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(t.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(t.track),this.mixInput.connect()}),[{key:"updateSettings",value:function(e){this.player&&(Kw(e.volume)||(this.volume=e.volume),Kw(e.loop)||(this.loop=e.loop),Kw(e.playbackRate)||(this.playbackRate=e.playbackRate))}},{key:"updateListener",value:function(e){if(this.player){if(e.onDurationChange){var t=e.onDurationChange;this.player.ondurationchange=function(e){t(e.target.duration)}}if(e.onTimeUpdate){var n=e.onTimeUpdate,r=this.player;r.ontimeupdate=function(){n(r.currentTime,r.duration)}}e.onEnded&&(this.player.onended=e.onEnded)}}},{key:"reset",value:function(){this.seek(0),this.mixInput.connect()}},{key:"seek",value:function(e){this.player&&(e<0&&e>this.player.duration||(this.player.currentTime=e,this.publisher.currentTime=e))}},{key:"play",value:function(){var e,t;return null==(e=this.publisher)||e.play(),null==(t=this.player)?void 0:t.play()}},{key:"pause",value:function(){var e,t;null==(e=this.player)||e.pause(),null==(t=this.publisher)||t.pause()}},{key:"stop",value:function(){var e;null==(e=this.player)||e.pause(),this.mixInput.disconnect()}},{key:"setOperation",value:function(e){"pause"===e&&this.pause(),"resume"===e&&(this.pause(),this.play()),"stop"===e&&(this.pause(),this.seek(0))}},{key:"volume",set:function(e){!this.player||!this.publisher||(this.player.volume=e,this.publisher.volume=e)}},{key:"loop",set:function(e){!this.player||!this.publisher||(this.player.loop=e,this.publisher.loop=e)}},{key:"playbackRate",set:function(e){!this.player||!this.publisher||(this.player.playbackRate=e,this.publisher.playbackRate=e)}}])}();function mH(e,t){if(t&&"function"!=typeof t)throw new lB({code:aB.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(e," should be a function.")})}var vH=function(){function e(t){r(this,e),this.core=t,SA(this,"log"),SA(this,"mixedMusicMap",new Map),SA(this,"cacheMusicMap",new Map),fH+=1,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(fH)}),this.log.info("created id=".concat(this.getAlias()).concat(fH))}return o(e,[{key:"getName",value:function(){return e.Name}},{key:"getAlias",value:function(){return"ax"}},{key:"getGroup",value:function(e){return null==e?void 0:e.id}},{key:"getValidateRule",value:function(t){switch(t){case"start":return e.startValidateRule;case"update":return e.updateValidateRule;case"stop":return e.stopValidateRule}}},{key:"start",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=this.core.room,this.log.info("add music source, id: ".concat(e.id," url: ").concat(e.url,", track: ").concat(e.track)),r=e.id,e.url,!this.mixedMusicMap.has(r)){t.next=5;break}return t.abrupt("return");case 5:return(i=this.cacheMusicMap.get(r))?e.url?i.reset():(i.mixInput.replaceSource(e.track),i.mixInput.connect()):(i=new pH(e,n.audioManager),this.cacheMusicMap.set(r,i)),i.updateListener(e),i.updateSettings(e),t.next=11,i.play();case 11:this.mixedMusicMap.set(r,i),i.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:i.mixInput.source.node,refId:"ax-".concat(r)}),this.log.info("start mix audio track ".concat(r," success.")),rP.addEnum({key:502700,value:3}),this.kvUpload(e);case 16:case"end":return t.stop()}}),t,this)})))}},{key:"update",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:n=e.id,r=e.operation,i=e.seekFrom,e.playbackRate,this.log.info("update music source, ".concat(JSON.stringify(e))),(a=this.mixedMusicMap.get(n))?(a.updateSettings(e),a.updateListener(e),Kw(r)||a.setOperation(r),Kw(i)||a.seek(i),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(n," not found."));case 4:case"end":return t.stop()}}),t,this)})))}},{key:"stop",value:function(e){return bA(this,arguments,(function(e){var t=this,n=e.id;return f().mark((function e(){var r;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t.mixedMusicMap.has(n)&&(t.log.info("remove music source, music id: ".concat(n)),null!=(r=t.mixedMusicMap.get(n))&&r.mixInput.source.node&&t.core.room.audioManager.updateAudioReference({type:"remove",audioReference:r.mixInput.source.node,refId:"ax-".concat(n)}),null==r||r.stop(),t.mixedMusicMap.delete(n)),"*"===n&&t.destroyAllMusic();case 2:case"end":return e.stop()}}),e)}))()}))}},{key:"kvUpload",value:function(e){var t=e.track,n=e.loop,r=e.volume,i=e.playbackRate,a=e.operation,o=e.seekFrom,s=e.onTimeUpdate,c=e.onDurationChange,u=e.onEnded;t&&rP.addCount({key:502711}),n&&rP.addCount({key:502703}),r&&rP.addCount({key:502704}),i&&rP.addCount({key:502705}),a&&rP.addCount({key:502706}),o&&rP.addCount({key:502707}),"function"!=typeof s&&rP.addCount({key:502709}),"function"!=typeof u&&rP.addCount({key:502710}),"function"!=typeof c&&rP.addCount({key:502708})}},{key:"destroyAllMusic",value:function(){var e=this;this.log.info("destroy all music source."),this.mixedMusicMap.forEach((function(t,n){null!=t&&t.mixInput.track&&e.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.track,refId:n}),e.stop({id:n})}))}},{key:"destroyAllCache",value:function(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}},{key:"destroy",value:function(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}}])}();SA(vH,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate:function(e,t,n){if(e.url&&"*"!==e.url){var r=e.url.split("?")[0],i=r.split(".").pop(),a=["mp3","ogg","wav","flac"].indexOf(i)>=0,o=r.startsWith("blob"),s=r.startsWith("data");if(!(a||o||s))throw new lB({code:aB.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:n})}if(!e.url&&!e.track)throw new lB({code:aB.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:n});mH("onTimeUpdate",e.onTimeUpdate),mH("onEnded",e.onEnded),mH("onDurationChange",e.onDurationChange)}}),SA(vH,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate:function(e,t,n){mH("onTimeUpdate",e.onTimeUpdate),mH("onEnded",e.onEnded),mH("onDurationChange",e.onDurationChange)}}),SA(vH,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),SA(vH,"Name","AudioMixer");var _H,gH=vH,yH=0,EH=function(){function e(t){r(this,e),this.core=t,SA(this,"log"),SA(this,"audioContext",nL()),SA(this,"workletNode"),yH+=1,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(yH)}),this.log.info("created id=".concat(this.getAlias()).concat(yH))}return o(e,[{key:"preload",value:function(e){return _H||(_H=this.doPreload(e)),_H}},{key:"doPreload",value:function(e){return bA(this,null,f().mark((function t(){var n,r;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.core.fileDownloader.download(e,{type:"blob"});case 2:return n=t.sent,r=URL.createObjectURL(n),t.prev=4,t.next=7,qM(this.audioContext,r);case 7:t.next=12;break;case 9:throw t.prev=9,t.t0=t.catch(4),this.log.error("load worklet failed",t.t0),t.t0;case 12:return t.prev=12,URL.revokeObjectURL(r),t.finish(12);case 15:case"end":return t.stop()}}),t,this,[[4,9,12,15]])})))}},{key:"getName",value:function(){return e.Name}},{key:"getAlias",value:function(){return"ad"}},{key:"getGroup",value:function(){return"AIDenoiser_".concat(Date.now())}},{key:"getValidateRule",value:function(t){switch(t){case"start":return e.startValidateRule(this.core);case"update":return e.updateValidateRule;case"stop":return e.stopValidateRule}}},{key:"start",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a,o,s,c,u,l,d,h,p=this;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=this.core,r=n.room,i=n.schedule,a=e.assetsPath,o=void 0===a?this.core.assetsPath:a){t.next=3;break}throw new lB({code:aB.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});case 3:return t.next=5,this.preload("".concat(o,"/denoiser-wasm.js"));case 5:if(this.workletNode){t.next=17;break}return s=String(Date.now()).slice(0,-3),t.next=9,function(e,t){return bA(this,arguments,(function(e,t){var n=t.sdkAppId,r=t.userId,i=t.userSig,a=t.timestamp;return f().mark((function t(){var o,s,c,u,l,d,h,p,m;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,e.getAbilityConfig(n,e.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:n,userId:r,userSig:i,timestamp:a});case 3:if(o=t.sent,s=o.data,c=s.errCode,u=s.errMsg,l=s.sign,"1"!==(d=s.status)){t.next=11;break}return t.abrupt("return",{auth:!0,sign:l,status:d,message:u});case 11:h=Aw(n)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",p="Init RTCAIDenoiser failed.",m="",t.t0=c,t.next=1===t.t0?15:2===t.t0?17:3===t.t0?19:4===t.t0?21:5===t.t0?23:6===t.t0?25:26;break;case 15:return m="Please check your params.",t.abrupt("break",26);case 17:return m="You need to buy packages. Refer to: ".concat(h),t.abrupt("break",26);case 19:return m="Server is invalid. Please contact our engineer. ",t.abrupt("break",26);case 21:return m="Your packages is not active. Refer to: ".concat(h),t.abrupt("break",26);case 23:return m="Your packages is expired. Refer to: ".concat(h),t.abrupt("break",26);case 25:m="Your version is not supported.";case 26:return t.abrupt("return",{auth:!1,status:d,message:u?"".concat(p," Reason: ").concat(u,". ").concat(m):"".concat(p,", ").concat(m)});case 29:return t.prev=29,t.t1=t.catch(0),t.abrupt("return",{auth:!1,status:"0",message:"Init RTCAIDenoiser failed. All requests failed. ".concat(t.t1)});case 32:case"end":return t.stop()}}),t,null,[[0,29]])}))()}))}(i,gA(_A({},e),{timestamp:s}));case 9:if(c=t.sent,u=c.auth,l=c.sign,d=c.status,h=c.message,u){t.next=16;break}throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(u,". Message: ").concat(h)),new lB({code:aB.INVALID_PARAMETER,message:h});case 16:this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(e.sdkAppId),userId:e.userId,timestamp:s,sign:l,status:d}}),this.workletNode.port.onmessage=function(e){var t,n=e.data;if("cost"===n.type){var r=(null==n?void 0:n.max)>20?"warn":(null==n?void 0:n.max)>10?"info":"debug";p.log[r]("avg cost: ".concat(n.value," max: ").concat(null==n?void 0:n.max,"(").concat(jA(new Date(null==n?void 0:n.maxCostTimestamp)),") hist: ").concat(null==(t=null==n?void 0:n.hist)?void 0:t.join(" ")))}else"log"===n.type&&p.log[n.logLevel]("".concat(n.value))};case 17:this.workletNode.port.postMessage({type:"enable"}),r.audioManager.addDenoiser(this.workletNode),r.sendAbilityStatus({ai_denoise:1});case 18:case"end":return t.stop()}}),t,this)})))}},{key:"update",value:function(){return bA(this,null,f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:case"end":return e.stop()}}),e)})))}},{key:"stop",value:function(){return bA(this,null,f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.workletNode){e.next=2;break}return e.abrupt("return");case 2:return t=this.core.room,this.workletNode.port.postMessage({type:"disable"}),e.next=6,t.audioManager.removeDenoiser(this.workletNode);case 6:case"end":return e.stop()}}),e,this)})))}},{key:"destroy",value:function(){this.workletNode&&(this.workletNode.port.onmessage=null)}}],[{key:"startValidateRule",value:function(e){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate:function(t,n,r,i){if(!e.room.audioManager.hasAudioTrack)throw new lB({code:aB.INVALID_OPERATION,extraCode:5106,fnName:r})}}}}])}();SA(EH,"updateValidateRule",{type:"object"}),SA(EH,"stopValidateRule",{type:"object"}),SA(EH,"Name","AIDenoiser");var kH=EH,TH=function(e){function i(){var e;return r(this,i),e=n(this,i),SA(t(e),"observer"),SA(t(e),"state","nominal"),e.onPressureChange=e.onPressureChange.bind(t(e)),e}return d(i,e),o(i,[{key:"stateNum",get:function(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}},{key:"start",value:function(){return bA(this,null,f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.observer){e.next=12;break}if(e.prev=1,e.t0="PressureObserver"in window&&!$D,!e.t0){e.next=7;break}return this.observer=new PressureObserver(this.onPressureChange),e.next=7,this.observer.observe("cpu",{sampleInterval:2e3});case 7:e.next=12;break;case 9:e.prev=9,e.t1=e.catch(1),kM.uploadEvent({log:"stat-pressure-detector-start-failed",error:e.t1});case 12:case"end":return e.stop()}}),e,this,[[1,9]])})))}},{key:"onPressureChange",value:function(e){var t=this.stateNum,n=e[e.length-1];this.state=n.state,(this.stateNum>3||t>3)&&Ux.info("".concat(n.source,": ").concat(n.state)),this.emit("state-changed",{type:n.source,state:this.state})}},{key:"destroy",value:function(){var e;try{null==(e=this.observer)||e.disconnect(),this.observer=null}catch(ZC){kM.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:ZC})}}}])}(kA(RA(),1).EventEmitter),SH=new TH;function IH(e){var t=v(e,2),n=t[0],r=t[1],i=r.byteLength,a=parseInt(String(i/255),10),o=i%255,s=[];s.push(0,0,0,1,6,n);for(var c=0;c<a;c++)s.push(255);s.push(o);var u=new DataView(r);return s.push.apply(s,E(new Uint8Array(u.buffer))),s.push(128),new rV(new DataView(new Uint8Array(s).buffer),!0)}function bH(e){return"empty"===e.type||0===e.data.byteLength}function RH(e){return 1===e.getInt32(0)&&6===e.getInt8(4)}function AH(e){for(var t=0,n=0,r=new DataView(e),i=0;i<e.byteLength;i++)switch(r.getUint8(i)){case 0:t++;break;case 1:(2===t||3===t)&&n++,t=0;break;default:t=0}return n}function CH(e){var t=e.frame,n=e.seiMessageList;if(!n||0===n.length||0===t.data.byteLength)return t;var r=9-AH(t.data);if(r<=0)return t;for(var i=n.splice(0,r).reverse().map(IH),a=i.reduce((function(e,t){return e+t.dataView.byteLength}),0),o=new ArrayBuffer(a+t.data.byteLength),s=new DataView(o),c=new DataView(t.data),u=0,l=0;l<i.length;l++)for(var d=0;d<i[l].dataView.byteLength;d++)s.setInt8(u++,i[l].dataView.getInt8(d));for(var h=0;h<t.data.byteLength;h++)s.setInt8(u++,c.getInt8(h));return t.data=o,t}function wH(e){var t=e.frame,n=e.onSEI;try{var r=new DataView(t.data);if(bH(t)||!RH(r))return t;for(var i=[],a=0,o=-1,s=-1,c=0;c<t.data.byteLength;c++){var u=r.getUint8(c);if(0===u)a++;else if(1===u){if(2===a||3===a){var l=c-a;if(-1===o?o=l:-1===s&&(s=l,i.push(new rV(new DataView(r.buffer.slice(o,s)))),o=l,s=-1),6!==r.getUint8(c+1)){t.data=r.buffer.slice(l);break}}a=0}else a=0}null==n||n(i.reverse())}catch(qA){}return t}var DH=0,NH=function(){function e(t){r(this,e),this.core=t,SA(this,"log"),SA(this,"_seiMessageList",[]),SA(this,"_smallSeiMessageList",[]),SA(this,"_subStreamSeiMessageList",[]),DH++,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(DH)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(DH)),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}return o(e,[{key:"encode",value:function(e){var t=e.frame,n=e.mediaType;try{return CH({frame:t,seiMessageList:8===n?this._smallSeiMessageList:2===n?this._subStreamSeiMessageList:this._seiMessageList})}catch(ZC){this.log.warn(ZC)}return t}},{key:"decode",value:function(e){var t=this,n=e.frame,r=e.track;return wH({frame:n,onSEI:function(e){e.forEach((function(e){t.core.trtc.emit(VB.SEI_MESSAGE,{seiPayloadType:e.seiPayloadType,data:e.seiPayload.buffer,userId:r.userId,streamType:2===r.mediaType?"sub":"main"})}))}})}},{key:"destroy",value:function(){this.log.debug("destory"),this.stop(),delete this.core}},{key:"getValidateRule",value:function(e){switch(e){case"start":case"update":case"stop":return{type:"object"}}}},{key:"start",value:function(){this.core.room.videoManager.addEncodeProcessor({processor:HP?this.encode:CH,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:HP?this.decode:wH,type:2})}},{key:"stop",value:function(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}},{key:"update",value:function(e){var t,n=e.buffer,r=e.options,i=[r.seiPayloadType,n],a=!!r.small;r.toSubStream?this._subStreamSeiMessageList.push(i):(this._seiMessageList.push(i),a&&this._smallSeiMessageList.push(i)),null==(t=this.core.room.scriptTransformWorker)||t.postMessage({type:"sei",data:i,isMain:!r.toSubStream,small:a})}},{key:"getName",value:function(){return e.Name}},{key:"getAlias",value:function(){return"sei"}},{key:"getGroup",value:function(){return"sei"}}])}();SA(NH,"autoStart",!0),SA(NH,"Name","SEI");var xH=NH;function OH(e){var t=e.frame,n=e.onDump;return null==n||n(),t}function PH(e){var t=e.frame,n=e.onDump;return null==n||n(),t}var MH,LH=0,VH=function(){function e(t){r(this,e),this.core=t,SA(this,"_core"),SA(this,"log"),SA(this,"dumpLocalVideoMap",{}),SA(this,"dumpRemoteVideoMap",{}),SA(this,"dialog"),this._core=t,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(++LH)}),this.log.info("created")}return o(e,[{key:"getName",value:function(){return e.Name}},{key:"getAlias",value:function(){return"dm"}},{key:"getGroup",value:function(){return"dm"}},{key:"getValidateRule",value:function(e){switch(e){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}},{key:"start",value:function(){return bA(this,null,f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.t0=!new URLSearchParams(location.search).has("trtcDebug")&&"true"!==(null==(t=window.sessionStorage)?void 0:t.getItem("TRTC_ENABLE_DEBUG_PLUGIN")),e.t0){e.next=5;break}return e.next=4,this.openDebugDiaLog();case 4:this.addVideoProcessor();case 5:case"end":return e.stop()}}),e,this)})))}},{key:"update",value:function(e){return bA(this,arguments,(function(e){var t=this,n=e.forceOpen;return f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.t0=Kw(n),!e.t0){e.next=9;break}if(!n){e.next=8;break}return e.next=5,t.openDebugDiaLog();case 5:t.addVideoProcessor(),e.next=9;break;case 8:t.closeDebugDiaLog(),t.removeVideoProcessor();case 9:case"end":return e.stop()}}),e)}))()}))}},{key:"stop",value:function(){this.closeDebugDiaLog(),this.removeVideoProcessor()}},{key:"destroy",value:function(){this.stop()}},{key:"openDebugDiaLog",value:function(){return bA(this,null,f().mark((function e(){var t,n;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.dialog){e.next=17;break}if(e.prev=1,!MH){e.next=7;break}return e.next=5,MH;case 5:e.next=11;break;case 7:return n=new URLSearchParams(location.search).get("trtcDebugDialogPath")||(null==(t=window.sessionStorage)?void 0:t.getItem("TRTC_DEBUG_DIALOG_PATH"))||"https://unpkg.com/".concat("trtc-sdk-v5","@").concat(YA,"/assets/debug-dialog.js"),MH=this._core.fileDownloader.loadScript(n),e.next=11,MH;case 11:this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705}),e.next=17;break;case 14:e.prev=14,e.t0=e.catch(1),this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e.t0));case 17:case"end":return e.stop()}}),e,this,[[1,14]])})))}},{key:"closeDebugDiaLog",value:function(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}},{key:"addVideoProcessor",value:function(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):OH,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):PH,type:1})}},{key:"removeVideoProcessor",value:function(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}},{key:"encodeVideo",value:function(e){var t=this,n=e.frame,r=e.mediaType;return OH({frame:n,onDump:function(){if(r){var e=2===r?"sub":"main",i=t.dumpLocalVideoMap[e];i&&(i.data.push(n.data.slice(0)),i.duration>0&&Date.now()-i.startTimestamp>1e3*i.duration&&i.onDumpEnd())}}})}},{key:"decodeVideo",value:function(e){var t=this,n=e.frame,r=e.track;return PH({frame:n,onDump:function(){if(r){var e=t.dumpRemoteVideoMap["".concat(r.userId,"-").concat(r.streamType)];e&&(e.data.push(n.data.slice(0)),e.duration>0&&Date.now()-e.startTimestamp>1e3*e.duration&&e.onDumpEnd())}}})}}])}();SA(VH,"Name","Debug"),SA(VH,"autoStart",!0);var UH=VH,FH=function(e){switch(e){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},BH=function(){return o((function e(t,n,i){var a=this;r(this,e),SA(this,"trackDoneOB"),SA(this,"startOB"),SA(this,"stopOB"),SA(this,"inputFrameCount",0),SA(this,"decodedFrameCount",0),SA(this,"type","auto"),SA(this,"config"),SA(this,"decoder"),SA(this,"_decodeSink");var o=t.kvStatManager;t.trtc,this.config=i.config,this.trackDoneOB=rU(n,uM.INIT),this.stopOB=YV(),this.startOB=YV(),"auto"===i.type?this.type="webCodecs":this.type=i.type;var s=YV();RV(this.startOB,WV(0),nF((function(e){var t=a.pipe(n);return s.next("STARTING"),n.log.info("decoder type: ".concat(a.type)),RV(t,bU(a.stopOB),IF((function(){}),(function(t){n.log.error(t),o.addFailedEvent({key:FH(a.type),error:t}),e>4?a.startOB.error(t):a.startOB.next(e+1)}))),RV(t,IU(1),kF(mU))})),bU(this.stopOB),IF((function(){n.player.setOutput(),s.next("STARTED")}),(function(e){s.next("FAILED")}),(function(){o.addSuccessEvent({key:FH(a.type)}),o.addSuccessEvent({key:504702})})))}),[{key:"mock",value:function(e){this._decodeSink?this._decodeSink.error(e):this.startOB.next(0)}},{key:"close",value:function(e){this.stopOB.next(e)}},{key:"pipe",value:function(e){var t=this;return PV()((function(n){return bA(t,null,f().mark((function t(){var r,i=this;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:this._decodeSink=n,n.defer((function(){var e;null==(e=i.decoder)||e.close()})),r=this.type;try{"webCodecs"===r&&(this.decoder=new AudioDecoder({error:function(t){e.log.error(t),n.error(4)},output:function(t){i.decodedFrameCount++,n.next(t),e.player.write(t)}})),this.decoder.configure(this.config)}catch(Yx){e.log.error(Yx),n.error("webCodecs"===r?2:6)}case 3:case"end":return t.stop()}}),t,this)})))}))}},{key:"decodeFrame",value:function(e){var t;this.inputFrameCount++,"configured"===(null==(t=this.decoder)?void 0:t.state)&&this.decoder.decode(new EncodedAudioChunk({data:e.data,timestamp:e.timestamp,type:"key"}))}}])}(),HH={type:"object"},WH=function(){function e(t){r(this,e),this.core=t,SA(this,"log"),SA(this,"contextMap",new Map),SA(this,"decodeProcessorMap",new WeakMap),this.log=t.log.createChild({id:"".concat(this.getAlias())})}return o(e,[{key:"getAlias",value:function(){return e.Name}},{key:"getGroup",value:function(e){return e.track.userId+e.track.streamType}},{key:"getName",value:function(){return e.Name}},{key:"getValidateRule",value:function(e){return HH}},{key:"start",value:function(e){var t=this,n=e.track;this.decodeProcessorMap.set(n,this.decode(e)),this.core.room.audioManager.addDecodeProcessor({processor:function(e){var n=e.frame,r=e.track;return t.decodeProcessorMap.has(r)?t.decodeProcessorMap.get(r)({frame:n,track:r}):n},type:3})}},{key:"decode",value:function(e){var t=this;return function(n){var r=n.frame,i=n.track;if(i!==e.track)return r;if(t.contextMap.has(i))return t.contextMap.get(i).decodeFrame(r);var a=new BH(t.core,i,e);return RV(a.trackDoneOB,IU(1),IF((function(){t.core.clearStarted(t,t.getGroup(e)),t.stop({track:i})}))),t.contextMap.set(i,a),a.decodeFrame(r)}}},{key:"stop",value:function(e){var t=e.track,n=this.contextMap.get(t);n&&(n.close("stop"),this.contextMap.delete(t),0===this.contextMap.size&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}},{key:"update",value:function(e){var t=this.contextMap.get(e.track);if(t){if("mock"===e.type)return void t.mock(10);t.close("update"),this.contextMap.set(e.track,new BH(this.core,e.track,e))}}}])}();SA(WH,"Name","TRTCAudioDecoder");var jH=WH,GH=function(){return o((function e(){r(this,e),SA(this,"log"),this.log=Ux.createLogger({id:"exp"})}),[{key:"call",value:function(e,t){return bA(this,null,f().mark((function n(){return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.abrupt("return",Jw(this[e])?this[e](t):Promise.reject(new FA({code:VA.INVALID_PARAMETER,message:YO({key:jO.API_NOT_EXIST,data:{name:e}})})));case 1:case"end":return n.stop()}}),n,this)})))}},{key:"enableAudioFrameEvent",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a,o,s,c,u,l,d,h,p;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=e.trtcInstance,r=e.enable,i=e.userId,a=e.sampleRate,o=void 0===a?48e3:a,s=e.channelCount,c=void 0===s?1:s,u=e.port,l=n.room.audioManager,d=l.getPCMAbortCtrlMap,l.audioFrameEventConfigMap.set(i,{enable:r,sampleRate:o,channelCount:c,port:u}),!r){t.next=12;break}if("*"!==i){t.next=6;break}n.room.remotePublishedUserMap.forEach((function(e){if(e.remoteAudioTrack.isAvailable){if(d.get(e.userId))return;var t=l.getPCM((function(e){n.emit(VB.AUDIO_FRAME,e)}),e.userId);d.set(e.userId,t)}})),t.next=10;break;case 6:if(!d.get(i)){t.next=8;break}return t.abrupt("return");case 8:h=l.getPCM((function(e){n.emit(VB.AUDIO_FRAME,e)}),i),d.set(i,h);case 10:t.next=13;break;case 12:"*"===i?n.room.remotePublishedUserMap.forEach((function(e){if(e.remoteAudioTrack.isSubscribed){var t=e.userId,n=d.get(t);null==n||n.abort("disable"),d.delete(t)}})):(null==(p=d.get(i))||p.abort("disable"),d.delete(i));case 13:case"end":return t.stop()}}),t)})))}}])}();TA([function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return jL((function(e,n){return function(){for(var r=arguments.length,i=new Array(r),a=0;a<r;a++)i[a]=arguments[a];return ZF.call(this,t,i,n,this._name),e.apply(this,i)}}))}({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],GH.prototype,"enableAudioFrameEvent",1);var JH=new GH,KH=0,YH=new Set,zH=null;zA("5.11.1-beta.6"),Bx.checkStorage(),QP();var qH={RtcError:lB,ErrorCode:aB,ErrorCodeDictionary:oB},XH=function(e){function i(e,a){var o;return r(this,i),o=n(this,i),SA(t(o),"_room"),SA(t(o),"_eventListened",new Set),SA(t(o),"_localVideoTrack",null),SA(t(o),"_localAudioTrack",null),SA(t(o),"_localScreenTrack",null),SA(t(o),"_localScreenAudioTrack",null),SA(t(o),"_localVideoConfig",null),SA(t(o),"_localScreenConfig",null),SA(t(o),"_localAudioConfig",null),SA(t(o),"_remoteVideoConfigMap",new Map),SA(t(o),"_remoteAudioConfigMap",new Map),SA(t(o),"_remoteAudioVolumeMap",new Map),SA(t(o),"_remoteAudioMuteMap",new Map),SA(t(o),"_mediaTrackMap",new WeakMap),SA(t(o),"_log",Ux.createLogger({id:"t".concat(++KH)})),SA(t(o),"_plugins",new Map),SA(t(o),"_networkQuality",null),SA(t(o),"_speakerId"),SA(t(o),"enterRoomParams"),o._room=new e(_A({logger:o._log,frameWorkType:i.frameWorkType},a)),o._room.videoDecodeFallbackType=a.videoDecodeFallback,o._log.info("create() ".concat(JSON.stringify(a,(function(e,t){return"plugins"===e?t.map((function(e){return e.Name})):t})))),Object.defineProperties(t(o),{dumpAudio:{enumerable:!1,value:function(e){return this._room.audioManager.dump(e)}}}),a.plugins&&a.plugins.forEach((function(e){o._use(e,a.assetsPath)})),o._use(gH,a.assetsPath),o._use(hH,a.assetsPath),o._use(kH,a.assetsPath),o._use(jH,a.assetsPath||sC),o._use(UH),a.enableSEI&&jP&&o._use(xH),o._room.on("audio-volume",(function(e){!e.find((function(e){return""===e.userId}))&&o._localAudioTrack&&e.push({userId:"",volume:Math.floor(100*o._localAudioTrack.getAudioLevel())}),1===a.volumeType&&e.forEach((function(e){var t,n=""===e.userId?o._localAudioTrack:null==(t=o.room.remotePublishedUserMap.get(e.userId))?void 0:t.remoteAudioTrack;n&&(e.volume=n.dbVolume)})),o.emit(VB.AUDIO_VOLUME,{result:e.sort((function(e,t){return t.volume-e.volume}))})})),o._room.videoManager.on("error",(function(e){o._log.error(new lB({code:aB.OPERATION_FAILED,extraCode:5504,message:e.message,originError:e}))})),o._listenEvents(),o._initActiveSpeaker(),function(e){var t=e.emit;e.emit=function(){for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];try{return t.apply(e,r)}catch(Yx){var a=YO({key:jO.CATCH_HANDLER_ERROR,data:{name:"trtc",event:r[0]},addDocLink:!1});return Ux.warn("".concat(a,"\n\n").concat(Yx.stack)),!1}}}(t(o)),o}return d(i,e),o(i,[{key:"room",get:function(){return this._room}},{key:"_listenEvents",value:function(){var e=this;yM(this,this._room).add("peer-join",(function(t){var n=t.userId;e.emit(VB.REMOTE_USER_ENTER,{userId:n})})).add("peer-leave",(function(t){e.emit(VB.REMOTE_USER_EXIT,{userId:t}),e._remoteAudioVolumeMap.delete(t)})).add("banned",(function(t){e._exitRoom().finally((function(){e.emit(VB.KICKED_OUT,{reason:t.reason})}))})).add("error",(function(t){e._exitRoom().finally((function(){e.emit(VB.ERROR,lB.convertFrom(t))}))})).add("signal-connection-state-changed",(function(t){e.emit(VB.CONNECTION_STATE_CHANGED,t)})).add("network-quality",(function(t){e._networkQuality=t;var n=gA(_A({},t),{uplinkRTT:Math.min(t.uplinkRTT,bw),downlinkRTT:Math.min(t.downlinkRTT,bw)});e.emit(VB.NETWORK_QUALITY,n)})).add("remote-published",(function(t){[t.remoteAudioTrack,t.remoteVideoTrack,t.remoteAuxiliaryTrack].forEach((function(n){yM(n,n).add("player-state-changed",(function(r){var i=gA(_A({},r),{userId:t.userId});n.kind===IC.VIDEO&&(i.streamType=dB(n.streamType)),e.emit(n.kind===IC.AUDIO?VB.AUDIO_PLAY_STATE_CHANGED:VB.VIDEO_PLAY_STATE_CHANGED,i)})).add("error",(function(t){t.getCode()===VA.PLAY_NOT_ALLOWED&&e.emit(VB.AUTOPLAY_FAILED,{userId:n.userId,mediaType:n.strMediaType,resume:function(){return n.player.resume()}})}))}))})).add("remote-unpublished",(function(e){[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach((function(e){EM(e)}))})).add("remote-publish-state-changed",(function(t){var n=t.prevMuteState,r=t.muteState,i=r.userId,a=n.audioAvailable,o=n.videoAvailable,s=r.audioAvailable,c=r.videoAvailable;s||e._remoteAudioConfigMap.delete(i),c||e._removeRemoteVideoConfig(i,"main"),r.hasAuxiliary||e._removeRemoteVideoConfig(i,"sub"),o!==c&&(c?e._onVideoAvailable({userId:i,streamType:"main"}):e._onVideoUnavailable({userId:i,streamType:"main"}),e.emit(c?VB.REMOTE_VIDEO_AVAILABLE:VB.REMOTE_VIDEO_UNAVAILABLE,{userId:i,streamType:"main"})),a!==s&&(s?e._onAudioAvailable({userId:i}):e._onAudioUnavailable({userId:i,muteState:r}),e.emit(s?VB.REMOTE_AUDIO_AVAILABLE:VB.REMOTE_AUDIO_UNAVAILABLE,{userId:i})),n.hasAuxiliary!==r.hasAuxiliary&&(r.hasAuxiliary?e._onVideoAvailable({userId:i,streamType:"sub"}):e._onVideoUnavailable({userId:i,streamType:"sub"}),e.emit(r.hasAuxiliary?VB.REMOTE_VIDEO_AVAILABLE:VB.REMOTE_VIDEO_UNAVAILABLE,{userId:i,streamType:"sub"}))})).add("sei-message",(function(t){e.emit(VB.SEI_MESSAGE,gA(_A({},t),{streamType:dB(t.streamType)}))})).add("firewall-restriction",(function(){e.emit(VB.ERROR,new lB({code:aB.OPERATION_FAILED,extraCode:5501}))})).add("heartbeat-report",(function(t){var n,r,i,a,o,s,c,u={2:"big",3:"small",7:"sub"},l={rtt:Math.min(t.msg_up_stream_info.msg_network_status.uint32_rtt||(null==(n=t.msg_down_stream_info[0])?void 0:n.msg_network_status.uint32_rtt)||(null==(r=e._networkQuality)?void 0:r.uplinkRTT)||(null==(i=e._networkQuality)?void 0:i.downlinkRTT)||0,bw),upLoss:(null==(a=e._networkQuality)?void 0:a.uplinkLoss)||0,downLoss:(null==(o=e._networkQuality)?void 0:o.downlinkLoss)||0,bytesSent:t.bytes_sent||0,bytesReceived:t.bytes_received||0,localStatistics:{audio:{bitrate:((null==(s=t.msg_up_stream_info.msg_audio_status)?void 0:s.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:((null==(c=t.msg_up_stream_info.msg_audio_status)?void 0:c.uint32_audio_level)||0)/xO},video:t.msg_up_stream_info.msg_video_status.filter((function(e){return u[e.uint32_video_stream_type]})).map((function(e){return{bitrate:(e.uint32_video_codec_bitrate||0)/1e3,width:e.uint32_video_width,height:e.uint32_video_height,frameRate:e.uint32_video_enc_fps,videoType:u[e.uint32_video_stream_type]}}))},remoteStatistics:t.msg_down_stream_info.map((function(e){return{userId:e.msg_user_info.str_identifier,audio:{bitrate:(e.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(e.msg_audio_status.uint32_audio_level||0)/xO,point2pointDelay:(e.msg_audio_status.uint32_audio_p2p_delay||0)+(e.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:e.msg_audio_status.uint32_audio_cache_ms||0},video:e.msg_video_status.map((function(e){return{bitrate:(e.uint32_video_codec_bitrate||0)/1e3,width:e.uint32_video_width,height:e.uint32_video_height,frameRate:e.uint32_video_dec_fps,videoType:u[e.uint32_video_stream_type],point2pointDelay:(e.uint32_video_p2p_delay||0)+(e.uint32_video_cache_ms||0),jitterBufferDelay:e.uint32_video_cache_ms||0}}))}}))};e.emit(VB.STATISTICS,l)})).add("custom-message",(function(t){e.emit(VB.CUSTOM_MESSAGE,t)})).add("layerData",(function(t){return e.emit(VB.LAYER_DATA,t)})).add("first-video-frame",(function(t){e.emit(VB.FIRST_VIDEO_FRAME,gA(_A({},t),{streamType:dB(t.streamType)}))})).add("audio-frame",(function(t){e.emit(VB.AUDIO_FRAME,t)})),yM(this,gL).add("audioInputAdded",(function(t){e.emit(VB.DEVICE_CHANGED,{type:"microphone",action:"add",device:t})})).add("audioInputRemoved",(function(t){e.emit(VB.DEVICE_CHANGED,{type:"microphone",action:"remove",device:t})})).add("videoInputAdded",(function(t){e.emit(VB.DEVICE_CHANGED,{type:"camera",action:"add",device:t})})).add("videoInputRemoved",(function(t){e.emit(VB.DEVICE_CHANGED,{type:"camera",action:"remove",device:t})})).add("audioOutputAdded",(function(t){return bA(e,null,f().mark((function e(){var n;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.emit(VB.DEVICE_CHANGED,{type:"speaker",action:"add",device:t}),!zH||zH.deviceId!==gw){e.next=5;break}return e.next=3,IL();case 3:n=e.sent.find((function(e){return e.deviceId===gw})),n&&zH.groupId!==n.groupId&&(zH=n,this.emit(VB.DEVICE_CHANGED,{type:"speaker",action:"active",device:n}));case 5:case"end":return e.stop()}}),e,this)})))})).add("audioOutputRemoved",(function(t){return bA(e,null,f().mark((function e(){var n,r,i;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.emit(VB.DEVICE_CHANGED,{type:"speaker",action:"remove",device:t}),e.next=3,IL();case 3:if((n=e.sent[0])&&zH&&zH.groupId!==n.groupId){e.next=6;break}return e.abrupt("return");case 6:r=zH.deviceId===t.deviceId,i=zH.deviceId===gw&&zH.deviceId===n.deviceId,(r||i)&&(zH=n,this.emit(VB.DEVICE_CHANGED,{type:"speaker",action:"active",device:n}));case 8:case"end":return e.stop()}}),e,this)})))}))}},{key:"use",value:function(e){var t,n;"plugin"in e?(t=e.plugin,n=e.assetsPath):t=e,this._use(t,n||sC)}},{key:"_use",value:function(e,t){if(this._plugins.get(e.Name))this._log.warn("duplicate install plugin",e.Name);else{var n=new e(tH.call(this,{TRTC:i,room:this._room,errorModule:qH,assetsPath:t}));this._plugins.set(e.Name,n),e.autoStart&&this.startPlugin(e.Name)}}},{key:"enterRoom",value:function(e){return bA(this,null,f().mark((function t(){var n,r,a,o,s,c,u,l,d,h,p;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return this.enterRoomParams=e,a=e.scene,o=void 0===a?"rtc":a,s=e.enableAutoPlayDialog,c=void 0===s||s,u=e.autoReceiveAudio,l=void 0===u||u,d=e.autoReceiveVideo,h=void 0!==d&&d,e.proxy&&(this._room.setProxyServer(e.proxy),!Yw(e.proxy)&&e.proxy.turnServer&&(null==(r=(n=this._room).setTurnServer)||r.call(n,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=c,this._room.autoReceiveAudio=l,this._room.autoReceiveVideo=h,qw(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay),p={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:"audience"===e.role?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,keepAlive:e.keepAlive},e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,t.next=7,this._room.join(p,o,i.frameWorkType);case 7:this._checkTrackToPublish(),SH.start();case 9:case"end":return t.stop()}}),t,this)})))}},{key:"exitRoom",value:function(){return bA(this,null,f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._exitRoom();case 2:return e.abrupt("return",e.sent);case 3:case"end":return e.stop()}}),e,this)})))}},{key:"switchRoom",value:function(e){return bA(this,null,f().mark((function t(){var n;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!this.room.isSwitchRoomSupported()){t.next=5;break}return t.next=3,this._room.switchRoom(e);case 3:t.next=10;break;case 5:return t.next=7,this.exitRoom();case 7:return n=_A(_A({},this.enterRoomParams),e),t.next=10,this.enterRoom(n);case 10:case"end":return t.stop()}}),t,this)})))}},{key:"switchRole",value:function(e,t){return bA(this,null,f().mark((function n(){return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return null!=t&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),null!=t&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),n.next=4,this._room.switchRole(e);case 4:"anchor"===e&&this._checkTrackToPublish();case 5:case"end":return n.stop()}}),n,this)})))}},{key:"destroy",value:function(){EM(this),this.removeAllListeners(),this._room.destroy(),YH.delete(this),0===YH.size&&SH.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach((function(e){var t;return null==(t=e.destroy)?void 0:t.call(e)})),this._plugins.clear(),Px.off("102",this._onLocalTrackCaptured,this)}},{key:"startLocalAudio",value:function(){return bA(this,arguments,(function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0};return f().mark((function n(){var r,i,a,o,s,c,u;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(!e._localAudioTrack){n.next=2;break}return n.abrupt("return",void e._log.warn("local audio is already started"));case 2:return r=t.publish,i=void 0===r||r,a=t.mute,o=t.option,s=new nV(e._room.audioManager),c={},u={muted:!0},o&&(Kw(o.microphoneId)?Kw(o.audioTrack)||(c.customSource=o.audioTrack):c.deviceId=o.microphoneId,o&&zw(o.captureVolume)&&s.setCaptureVolume(o.captureVolume),Kw(o.profile)||(Yw(o.profile)?yC[o.profile]&&s.setProfile(yC[o.profile]):s.setProfile(o.profile)),zw(o.earMonitorVolume)&&(u.muted=!(o.earMonitorVolume>0),u.volume=o.earMonitorVolume),Kw(o.echoCancellation)||(s.profile.echoCancellation=o.echoCancellation),Kw(o.noiseSuppression)||(s.profile.noiseSuppression=o.noiseSuppression),Kw(o.autoGainControl)||(s.profile.autoGainControl=o.autoGainControl)),s.on("5",(function(t){e.emit(VB.ERROR,new lB({code:aB.DEVICE_ERROR,extraCode:5309,messageParams:{error:t}}))})),s.on("2",(function(t){e.emit(VB.DEVICE_CHANGED,{type:"microphone",action:"active",device:t})})),s.on("4",(function(t){var n;t.error&&(n=lB.convertFrom(t.error)),e.emit(VB.PUBLISH_STATE_CHANGED,gA(_A({},t),{error:n}))})),e._listenOutputTrackChanged(s),e._speakerId&&s.setAudioOutput(e._speakerId),n.next=11,s.capture(c);case 11:return Kw(a)||s.setMute(a),yM(s,s).add("player-state-changed",(function(t){e.emit(VB.AUDIO_PLAY_STATE_CHANGED,gA(_A({},t),{userId:""}))})),i&&e._room.isJoined&&e._room.publish(s).catch((function(){})),e._localAudioTrack=s,e._localAudioConfig=gA(_A({},t),{publish:i}),n.next=18,e._updateAudioPlayOption({playOption:u,track:s});case 18:Px.emit("113",{userId:"",room:e.room});case 19:case"end":return n.stop()}}),n)}))()}))}},{key:"updateLocalAudio",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this._localAudioTrack&&this._localAudioConfig){t.next=2;break}return t.abrupt("return");case 2:if(n=e.publish,r=e.mute,i=e.option,a={},t.t0=i,!t.t0){t.next=18;break}if(!i.microphoneId){t.next=10;break}return t.next=8,this._localAudioTrack.switchDevice(i.microphoneId);case 8:t.next=14;break;case 10:if(t.t1=Kw(i.audioTrack),t.t1){t.next=14;break}return t.next=14,this._localAudioTrack.setInputMediaStreamTrack(i.audioTrack);case 14:return Kw(i.captureVolume)||this._localAudioTrack.setCaptureVolume(i.captureVolume),Kw(i.earMonitorVolume)||(a.muted=!(i.earMonitorVolume>0),a.volume=i.earMonitorVolume),t.next=18,this._localAudioTrack.update3A(i);case 18:return this._room.isJoined&&!Kw(n)&&(n&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch((function(){})),this._localAudioConfig.publish&&!n&&this._room.unpublish(this._localAudioTrack).catch((function(){}))),Kw(r)||this._localAudioTrack.setMute(r),t.next=22,this._updateAudioPlayOption({playOption:a,track:this._localAudioTrack,prevConfig:this._localAudioConfig});case 22:fD(this._localAudioConfig,e);case 23:case"end":return t.stop()}}),t,this)})))}},{key:"stopLocalAudio",value:function(){return bA(this,null,f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.t0=this._localAudioTrack,!e.t0){e.next=13;break}if(e.t1=this._room.isJoined,!e.t1){e.next=6;break}return e.next=6,this._room.unpublish(this._localAudioTrack).catch((function(){}));case 6:Px.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),EM(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null;case 13:case"end":return e.stop()}}),e,this)})))}},{key:"startLocalVideo",value:function(){return bA(this,arguments,(function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null,capture:!0};return f().mark((function n(){var r,i,a,o,s,c,u,l,d,h,p;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(!e._localVideoTrack){n.next=2;break}return n.abrupt("return",void e._log.warn("local video is already started"));case 2:if(i=t.view,a=t.publish,o=void 0===a||a,s=t.capture,c=void 0===s||s,u=t.mute,l=t.option,d=new oV(e._room.videoManager),h={},p={},qw(null==l?void 0:l.avoidCropping)&&(d.avoidCropping=l.avoidCropping),l&&(l.cameraId?h.deviceId=l.cameraId:Kw(l.useFrontCamera)?Kw(l.videoTrack)||(h.customSource=l.videoTrack):h.facingMode=l.useFrontCamera?IC.FACING_MODE_USER:IC.FACING_MODE_ENVIRONMENT,Kw(l.retryWhenExactFailed)||(h.retryWhenExactFailed=l.retryWhenExactFailed),l.qosPreference&&(h.contentHint=hB(l.qosPreference)),Kw(l.profile)||(Yw(l.profile)?EC[l.profile]&&d.setProfile(EC[l.profile]):d.setProfile(l.profile)),Kw(l.fillMode)||(p.objectFit=l.fillMode),Kw(l.mirror)||(p.mirror=l.mirror),Kw(l.small)||(Kw(l.smallMode)||(e._room.smallMode=l.smallMode),qw(l.small)&&!1===l.small?d.stopSmall():d.updateSmallConfig(fB(l.small,!0))),Kw(l.rotation)||d.setRotation(l.rotation)),d.once("first-video-frame",(function(t){e.emit(VB.FIRST_VIDEO_FRAME,gA(_A({},t),{streamType:dB(t.streamType)}))})),d.on("5",(function(t){e.emit(VB.ERROR,new lB({code:aB.DEVICE_ERROR,extraCode:5308,messageParams:{error:t}}))})),d.on("2",(function(t){e.emit(VB.DEVICE_CHANGED,{type:"camera",action:"active",device:t})})),d.on("4",(function(t){var n;t.error&&(n=lB.convertFrom(t.error)),e.emit(VB.PUBLISH_STATE_CHANGED,gA(_A({},t),{error:n}))})),e._listenOutputTrackChanged(d),!c){n.next=15;break}return n.next=13,d.capture(h);case 13:n.next=16;break;case 15:null==(r=d.manager)||r.changeInput(d);case 16:if(n.t0=Kw(u),n.t0){n.next=20;break}return n.next=20,d.setMute(u);case 20:return yM(d,d).add("player-state-changed",(function(t){e.emit(VB.VIDEO_PLAY_STATE_CHANGED,gA(_A({},t),{userId:"",streamType:"main"}))})),o&&e._room.isJoined&&e._room.publish(d).catch((function(){})),e._localVideoTrack=d,e._localVideoConfig=gA(_A({},t),{view:i,publish:o,capture:c}),n.next=26,e._updateVideoPlayOption({view:i,playOption:p,track:d});case 26:case"end":return n.stop()}}),n)}))()}))}},{key:"updateLocalVideo",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a,o,s,c,u,l,d;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this._localVideoTrack&&this._localVideoConfig){t.next=2;break}return t.abrupt("return");case 2:if(a=e.view,o=e.publish,s=e.mute,c=e.capture,u=e.option,l={},!this._localVideoConfig.capture){t.next=24;break}if(!1===c){t.next=21;break}if(null==u||!u.cameraId){t.next=10;break}return t.next=8,this._localVideoTrack.switchDevice(null==u?void 0:u.cameraId);case 8:t.next=19;break;case 10:if(!Kw(null==u?void 0:u.useFrontCamera)){t.next=17;break}if(t.t0=Kw(null==u?void 0:u.videoTrack),t.t0){t.next=15;break}return t.next=15,this._localVideoTrack.setInputMediaStreamTrack(null==u?void 0:u.videoTrack);case 15:t.next=19;break;case 17:return t.next=19,this._localVideoTrack.switchDevice(null!=u&&u.useFrontCamera?IC.FACING_MODE_USER:IC.FACING_MODE_ENVIRONMENT);case 19:t.next=22;break;case 21:this._localVideoTrack.stopCapture();case 22:t.next=31;break;case 24:if(!c){t.next=31;break}return(d={}).deviceId=(null==u?void 0:u.cameraId)||(null==(n=this._localVideoConfig.option)?void 0:n.cameraId),d.facingMode=null!=u&&u.useFrontCamera||null!=(r=this._localVideoConfig.option)&&r.useFrontCamera?IC.FACING_MODE_USER:IC.FACING_MODE_ENVIRONMENT,d.customSource=(null==u?void 0:u.videoTrack)||(null==(i=this._localVideoConfig.option)?void 0:i.videoTrack),t.next=31,this._localVideoTrack.capture(d);case 31:if(t.t1=u,!t.t1){t.next=45;break}if(t.t2=Kw(u.profile),t.t2){t.next=40;break}if(Yw(u.profile)?EC[u.profile]&&this._localVideoTrack.setProfile(EC[u.profile]):this._localVideoTrack.setProfile(u.profile),t.t3=(!u.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(u.cameraId))&&Kw(u.useFrontCamera),!t.t3){t.next=40;break}return t.next=40,this._localVideoTrack.applyProfile();case 40:Kw(u.fillMode)||(l.objectFit=u.fillMode),Kw(u.mirror)||(l.mirror=u.mirror),Kw(u.rotation)||this._localVideoTrack.setRotation(u.rotation),u.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(hB(u.qosPreference)),Kw(u.small)||(qw(u.small)&&!u.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(fB(u.small,!0)));case 45:if(this._room.isJoined&&Kw(o)&&this._localVideoConfig.publish&&c&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch((function(){})),this._room.isJoined&&((null!=o?o:this._localVideoConfig.publish)?this._room.publish(this._localVideoTrack).catch((function(){})):this._room.unpublish(this._localVideoTrack).catch((function(){}))),t.t4=Kw(s),t.t4){t.next=51;break}return t.next=51,this._localVideoTrack.setMute(s);case 51:return t.next=53,this._updateVideoPlayOption({view:a,playOption:l,track:this._localVideoTrack,prevConfig:this._localVideoConfig});case 53:fD(this._localVideoConfig,e);case 54:case"end":return t.stop()}}),t,this)})))}},{key:"stopLocalVideo",value:function(){return bA(this,null,f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.t0=this._localVideoTrack,!e.t0){e.next=11;break}if(e.t1=this._room.isJoined,!e.t1){e.next=6;break}return e.next=6,this._room.unpublish(this._localVideoTrack).catch((function(){}));case 6:this._localVideoTrack.stop(),this._localVideoTrack.close(),EM(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null;case 11:case"end":return e.stop()}}),e,this)})))}},{key:"startScreenShare",value:function(){return bA(this,arguments,(function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{publish:!0,view:null};return f().mark((function n(){var r,i,a,o,s,c,u,l,d,h,p,m;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(!e._localScreenTrack){n.next=2;break}return n.abrupt("return",void e._log.warn("screen share is already started"));case 2:return r=t.view,i=void 0===r?null:r,a=t.publish,o=void 0===a||a,s=t.option,(c=new uV(e._room.videoManager)).on("4",(function(t){var n;t.error&&(n=lB.convertFrom(t.error)),e.emit(VB.PUBLISH_STATE_CHANGED,gA(_A({},t),{error:n}))})),c.once("first-video-frame",(function(t){e.emit(VB.FIRST_VIDEO_FRAME,gA(_A({},t),{streamType:dB(t.streamType)}))})),e._listenOutputTrackChanged(c),"main"===t.streamType&&(c.mediaType=4),u=null,l={},d={},s&&(Kw(s.profile)||(Yw(s.profile)?SC[s.profile]&&c.setProfile(SC[s.profile]):c.setProfile(s.profile)),s.systemAudio&&(l.systemAudio=!0,l.echoCancellation=s.echoCancellation,l.noiseSuppression=s.noiseSuppression,l.autoGainControl=s.autoGainControl),Kw(s.fillMode)||(d.objectFit=s.fillMode),s.videoTrack&&(l.videoTrack=s.videoTrack),s.audioTrack&&(l.audioTrack=s.audioTrack),s.captureElement&&(l.captureElement=s.captureElement),s.preferDisplaySurface&&(l.preferDisplaySurface=s.preferDisplaySurface),s.qosPreference&&(l.contentHint=hB(s.qosPreference))),n.next=8,c.capture(l);case 8:if(h=n.sent,c.mediaTrack.addEventListener(IC.ENDED,(function(){e._stopScreenShare(),e.emit(VB.SCREEN_SHARE_STOPPED)})),n.t0=h.getAudioTracks()[0],!n.t0){n.next=16;break}return u=new dV(e._room.audioManager),n.next=15,u.setInputMediaStreamTrack(h.getAudioTracks()[0]);case 15:e._speakerId&&u.setAudioOutput(e._speakerId);case 16:if(yM(c,c).add("player-state-changed",(function(t){e.emit(VB.VIDEO_PLAY_STATE_CHANGED,gA(_A({},t),{userId:"",streamType:"sub"}))})),!o||!e._room.isJoined){n.next=20;break}m=[c],u&&(m.push(u),e._checkScreenAudioEchoCancellation(c,u)),(p=e._room).publish.apply(p,m).catch((function(){}));case 20:return e._localScreenTrack=c,e._localScreenAudioTrack=u,e._localScreenConfig=gA(_A({},t),{view:i,publish:o}),n.next=25,e._updateVideoPlayOption({view:i,playOption:d,track:c});case 25:case"end":return n.stop()}}),n)}))()}))}},{key:"updateScreenShare",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a,o;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this._localScreenTrack&&this._localScreenConfig){t.next=2;break}return t.abrupt("return");case 2:return n=e.view,r=e.publish,i=e.option,a={},i&&(Kw(i.fillMode)||(a.objectFit=i.fillMode),i.qosPreference)&&(o=hB(i.qosPreference),this._localScreenTrack.setContentHint(o)),this._room.isJoined&&!Kw(r)&&(r&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch((function(){})),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch((function(){}))),this._localScreenConfig.publish&&!r&&(this._room.unpublish(this._localScreenTrack).catch((function(){})),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch((function(){})))),t.next=7,this._updateVideoPlayOption({view:n,playOption:a,track:this._localScreenTrack,prevConfig:this._localScreenConfig});case 7:fD(this._localScreenConfig,e);case 8:case"end":return t.stop()}}),t,this)})))}},{key:"stopScreenShare",value:function(){return bA(this,null,f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._stopScreenShare();case 2:return e.abrupt("return",e.sent);case 3:case"end":return e.stop()}}),e,this)})))}},{key:"startRemoteVideo",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a,o,s,c,u;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=e.view,r=e.userId,i=e.streamType,a=e.option,o="".concat(r,"_").concat(i),!this._remoteVideoConfigMap.has(o)){t.next=3;break}return t.abrupt("return",void this._log.warn("remote video has already started. userId:".concat(r,", streamType:").concat(i)));case 3:if(s=this._room.remotePublishedUserMap.get(r)){t.next=6;break}return t.abrupt("return");case 6:return c={},u="main"===i?s.remoteVideoTrack:s.remoteAuxiliaryTrack,this._listenOutputTrackChanged(u),a&&(Kw(a.fillMode)||(c.objectFit=a.fillMode),Kw(a.mirror)||(c.mirror=a.mirror),Kw(a.poster)||(c.poster=a.poster),c.canvasRender=a.canvasRender,"main"===i&&!Kw(a.small)&&(!s.remoteVideoTrack.isSubscribing&&!s.remoteVideoTrack.isSubscribed&&s.remoteVideoTrack.setMediaType(a.small?8:4),this._room.changeType(a.small,u.user))),t.next=11,this._room.subscribe(u);case 11:return t.next=13,this._enableVideoDecodeFallback(u,i);case 13:return t.next=15,this._updateVideoPlayOption({view:n,playOption:c,track:u});case 15:this._emitTrackEvent(u),this._remoteVideoConfigMap.set(o,{config:e}),a&&!Kw(a.receiveWhenViewVisible)&&this._observeView({remoteTrack:u,view:n,receiveWhenViewVisible:a.receiveWhenViewVisible,viewRoot:null==a?void 0:a.viewRoot});case 18:case"end":return t.stop()}}),t,this)})))}},{key:"updateRemoteVideo",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a,o,s,c,u,l,d,h,p,m,v,_;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(i=e.view,a=e.userId,o=e.streamType,s=e.option,c="".concat(a,"_").concat(o),(u=this._remoteVideoConfigMap.get(c))&&this._room.remotePublishedUserMap.has(a)){t.next=3;break}return t.abrupt("return");case 3:if(l={},s&&(Kw(s.fillMode)||(l.objectFit=s.fillMode),Kw(s.mirror)||(l.mirror=s.mirror)),d=null,h=this._room.remotePublishedUserMap.get(a),"main"===o&&null!=h&&h.muteState.hasVideo&&(d=h.remoteVideoTrack),"sub"===o&&null!=h&&h.muteState.hasAuxiliary&&(d=h.remoteAuxiliaryTrack),d){t.next=8;break}return t.abrupt("return");case 8:return p=u.config,"main"===o&&s&&!Kw(s.small)&&this._room.changeType(s.small,d.user),t.next=12,this._updateVideoPlayOption({view:i,playOption:l,track:d,prevConfig:p});case 12:fD(p,e),m=Kw(null==s?void 0:s.receiveWhenViewVisible)?null==(n=p.option)?void 0:n.receiveWhenViewVisible:s.receiveWhenViewVisible,v=Kw(i)?p.view:i,_=Kw(null==s?void 0:s.viewRoot)?null==(r=p.option)?void 0:r.viewRoot:s.viewRoot,this._observeView({remoteTrack:d,view:v,receiveWhenViewVisible:m,viewRoot:_});case 15:case"end":return t.stop()}}),t,this)})))}},{key:"stopRemoteVideo",value:function(e){return bA(this,null,f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.abrupt("return",this._stopRemoteVideo(e));case 1:case"end":return t.stop()}}),t,this)})))}},{key:"_stopRemoteVideo",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return bA(this,null,f().mark((function n(){var r,i,a,o,s,c,u,l;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:r=[],(i=this._room.remotePublishedUserMap.get(e.userId))&&(a=i.muteState,o=i.remoteVideoTrack,s=i.remoteAuxiliaryTrack,"main"===e.streamType&&(o.stop(),a.hasVideo&&r.push(o)),"sub"===e.streamType&&(s.stop(),a.hasAuxiliary&&r.push(s))),c=0,u=r;case 3:if(!(c<u.length)){n.next=13;break}if(l=u[c],n.t0=t,!n.t0){n.next=10;break}return n.next=9,this._room.unsubscribe(l);case 9:this._mediaTrackMap.delete(l.outMediaTrack);case 10:c++,n.next=3;break;case 13:this._removeRemoteVideoConfig(e.userId,e.streamType);case 14:case"end":return n.stop()}}),n,this)})))}},{key:"_removeRemoteVideoConfig",value:function(e,t){var n="".concat(e,"_").concat(t),r=this._remoteVideoConfigMap.get(n);r&&r.observer&&r.observer.disconnect(),this._remoteVideoConfigMap.delete(n)}},{key:"muteRemoteAudio",value:function(e,t){return bA(this,null,f().mark((function n(){var r,i,a,o;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(this._remoteAudioMuteMap.set(e,t),n.prev=1,"*"!==e){n.next=30;break}if(!t){n.next=8;break}return n.next=6,this._stopRemoteAudio({userId:e});case 6:n.next=28;break;case 8:r=E(this._room.remotePublishedUserMap.values()),i=s(r),n.prev=10,i.s();case 12:if((a=i.n()).done){n.next=20;break}if(o=a.value,n.t0=o.muteState.hasAudio&&!this._remoteAudioConfigMap.has(o.userId),!n.t0){n.next=18;break}return n.next=18,this._startRemoteAudio({userId:o.userId});case 18:n.next=12;break;case 20:n.next=25;break;case 22:n.prev=22,n.t1=n.catch(10),i.e(n.t1);case 25:return n.prev=25,i.f(),n.finish(25);case 28:n.next=39;break;case 30:if(!t){n.next=35;break}return n.next=33,this._stopRemoteAudio({userId:e});case 33:n.next=39;break;case 35:if(n.t2=this._remoteAudioConfigMap.has(e),n.t2){n.next=39;break}return n.next=39,this._startRemoteAudio({userId:e});case 39:n.next=44;break;case 41:throw n.prev=41,n.t3=n.catch(1),this._remoteAudioMuteMap.delete(e),n.t3;case 44:case"end":return n.stop()}}),n,this,[[1,41],[10,22,25,28]])})))}},{key:"setRemoteAudioVolume",value:function(e,t){if("*"===e){var n,r=s(E(this._room.remotePublishedUserMap.values()));try{for(r.s();!(n=r.n()).done;){var i=n.value;this._remoteAudioVolumeMap.set(i.userId,t),i.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:i.remoteAudioTrack})}}catch(o){r.e(o)}finally{r.f()}}else if(e){var a=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),a&&a.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:a.remoteAudioTrack})}}},{key:"startPlugin",value:function(e,t){return bA(this,null,f().mark((function n(){return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.abrupt("return",e.start(t));case 1:case"end":return n.stop()}}),n)})))}},{key:"updatePlugin",value:function(e,t){return bA(this,null,f().mark((function n(){return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.abrupt("return",e.update(t));case 1:case"end":return n.stop()}}),n)})))}},{key:"stopPlugin",value:function(e,t){return bA(this,null,f().mark((function n(){return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.abrupt("return",e.stop(t));case 1:case"end":return n.stop()}}),n)})))}},{key:"enableAudioVolumeEvaluation",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._room.enableAudioVolumeEvaluation(e,t)}},{key:"on",value:function(e,t,n){if(this.listeners(e).includes(t))return this;if(this._log.debug("on",e),g(i,"on",this,3)([e,t,n]),this._eventListened.add(e),this.listeners(VB.AUDIO_FRAME).length>0){var r=this.room.audioManager.audioFrameEventConfigMap;r.get("")||r.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return this}},{key:"emit",value:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];try{UB.has(e)&&this._log.debug("emit ".concat(e," ").concat(JSON.stringify(n)))}catch(Yx){}return g(i,"emit",this,3)([e].concat(n))}},{key:"off",value:function(e,t,n){if(this._log.debug("off",e),"*"===e?(this._eventListened.clear(),this.removeAllListeners()):g(i,"off",this,3)([e,t,n]),(e===i.EVENT.AUDIO_FRAME||"*"===e)&&0===this.listeners(i.EVENT.AUDIO_FRAME).length){var r=this.room.audioManager.getPCMAbortCtrlMap;r.forEach((function(e){null==e||e.abort("off")})),r.clear()}return this}},{key:"getAudioTrack",value:function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},n=null,r="main",i=!1;if(Yw(t)?e=t:(e=t.userId,i=!0===t.processed,t.streamType&&(r=t.streamType)),e){var a=this._room.remotePublishedUserMap.get(e);a&&(n=a.remoteAudioTrack)}else n="sub"===r?this._localScreenAudioTrack:this._localAudioTrack;return n?i&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}},{key:"getVideoTrack",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{userId:"",streamType:"main"},t=e.userId,n=void 0===t?"":t,r=e.streamType,i=void 0===r?"main":r,a=e.processed,o=void 0!==a&&a,s=null;if(""===n)"main"===i&&this._localVideoTrack&&(s=this._localVideoTrack),"sub"===i&&this._localScreenTrack&&(s=this._localScreenTrack);else{var c=this._room.remotePublishedUserMap.get(n);c&&(s="main"===i?c.remoteVideoTrack:c.remoteAuxiliaryTrack)}return s?o&&s.outMediaTrack&&s.outMediaTrack!==s.mediaTrack?s.outMediaTrack.clone():s.mediaTrack:null}},{key:"getVideoSnapshot",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.userId,n=e.streamType,r=void 0===n?"main":n;if(t){var i=this._room.remotePublishedUserMap.get(t);if("main"===r&&null!=i&&i.muteState.hasVideo)return i.remoteVideoTrack.getVideoFrame();if("sub"===r&&null!=i&&i.muteState.hasAuxiliary)return i.remoteAuxiliaryTrack.getVideoFrame()}else{if("main"===r&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if("sub"===r&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}},{key:"_setCurrentSpeaker",value:function(e){var t,n;this._speakerId=e,null==(t=this._localAudioTrack)||t.setAudioOutput(e),null==(n=this._localScreenAudioTrack)||n.setAudioOutput(e),this._room.remotePublishedUserMap.forEach((function(t){return t.remoteAudioTrack.setAudioOutput(e)}))}},{key:"setCurrentSpeaker",value:function(e){return bA(this,null,f().mark((function t(){var n=this;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,IL();case 2:t.sent.forEach((function(t){t.deviceId===e&&(n._setCurrentSpeaker(e),n.emit(VB.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}),zH=t)})),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker');case 4:case"end":return t.stop()}}),t,this)})))}},{key:"_startRemoteAudio",value:function(e){return this._doStartRemoteAudio(e)}},{key:"_doStartRemoteAudio",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a,o,s,c=this;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=e.userId,!this._remoteAudioConfigMap.has(n)){t.next=3;break}return t.abrupt("return",void this._log.warn("remote audio has already started. userId:".concat(n)));case 3:if(r=this._room.remotePublishedUserMap.get(n)){t.next=6;break}return t.abrupt("return");case 6:return i={},a=r.remoteAudioTrack,this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId),t.prev=8,o=this._remoteAudioVolumeMap.get(n),s=zw(o)?o:100,i.volume=s,this._remoteAudioConfigMap.set(n,e),t.next=14,this._room.subscribe(a);case 14:return RV(rU(a,"decode-failed"),bU(rU(a,uM.INIT)),IF((function(){c.startPlugin(jH.Name,{track:a,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})}))),t.next=17,this._updateAudioPlayOption({playOption:i,track:a});case 17:Px.emit("115",{userId:n,room:this.room}),a.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:a.outMediaTrack,refId:"ra-".concat(n)}),t.next=24;break;case 21:throw t.prev=21,t.t0=t.catch(8),this._remoteAudioConfigMap.delete(n),t.t0;case 24:this._emitTrackEvent(a);case 25:case"end":return t.stop()}}),t,this,[[8,21]])})))}},{key:"_stopRemoteAudio",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return bA(this,null,f().mark((function n(){var r;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(r=this._room.remotePublishedUserMap.get(e.userId),n.t0=r,!n.t0){n.next=9;break}if(r.remoteAudioTrack.stop(),n.t1=r.muteState.hasAudio&&t,!n.t1){n.next=8;break}return n.next=8,this._room.unsubscribe(r.remoteAudioTrack);case 8:this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack);case 9:this._remoteAudioConfigMap.delete("".concat(e.userId)),Px.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:"ra-".concat(e.userId)});case 12:case"end":return n.stop()}}),n,this)})))}},{key:"_enableVideoDecodeFallback",value:function(e,t){var n,r=this,i=this._room.videoDecodeFallbackType;i&&this._plugins.has("TRTCVideoDecoder")&&(e.log.debug("remote video will fall back when decode failed",e.id),RV(rU(e,"decode-failed"),bU(rU(e,uM.INIT)),bF((function(){r.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:i})})),iF(rU(e,"decode-downgrade-state-changed")),IF((function(i){n=i.state,r.emit(VB.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,gA(_A({},i),{streamType:t,userId:e.userId}))}),(function(t){e.log.error("fallback",t)}),(function(){"STARTED"===n&&e.log.info("fallback complete")}))))}},{key:"_updateVideoPlayOption",value:function(e){return bA(this,arguments,(function(e){var t=e.view,n=e.playOption,r=e.track,i=e.prevConfig;return f().mark((function e(){var a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r.setMirror(n.mirror),!(Kw(t)&&i&&i.view)||uD(n)){e.next=6;break}if(a=mD(i.view),e.t0=a.length>0,!e.t0){e.next=6;break}return e.next=6,r.play(a,n);case 6:if(Kw(t)){e.next=14;break}if(!((o=mD(t)).length>0)){e.next=13;break}return e.next=11,r.play(o,n);case 11:e.next=14;break;case 13:r.stop();case 14:case"end":return e.stop()}}),e)}))()}))}},{key:"_updateAudioPlayOption",value:function(e){return bA(this,arguments,(function(e){var t=this,n=e.playOption,r=void 0===n?{}:n,i=e.track;return e.prevConfig,f().mark((function e(){var n,a;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i.isPlayCalled){e.next=8;break}return e.prev=1,e.next=4,i.play(null,r);case 4:e.next=8;break;case 6:e.prev=6,e.t0=e.catch(1);case 8:if(Kw(r.muted)||i.setPlayerMute(r.muted),Kw(r.volume)||i.setAudioVolume(r.volume/100),!(i instanceof nV&&i.mediaTrack)){e.next=13;break}n=!1===r.muted&&!Kw(r.volume)&&r.volume>0?"add":"remove",t.room.audioManager.updateAudioReference({type:n,audioReference:i.mediaTrack,refId:"em"}),e.next=18;break;case 13:if(!(i instanceof DF)){e.next=18;break}if(a=r.muted?0:r.volume,!Kw(a)){e.next=17;break}return e.abrupt("return");case 17:t.room.audioManager.updateAudioReference({type:"updateVolume",refId:"ra-".concat(i.userId),volume:r.volume});case 18:case"end":return e.stop()}}),e,null,[[1,6]])}))()}))}},{key:"_listenOutputTrackChanged",value:function(e){var t=this;0===e.listeners("output-media-track-changed").length&&e.on("output-media-track-changed",(function(){return t._emitTrackEvent(e,!1)}))}},{key:"_emitTrackEvent",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=e.isRemote?e.userId:"";e.outMediaTrack&&(t&&this._mediaTrackMap.get(e.outMediaTrack)===n||(this._mediaTrackMap.set(e.outMediaTrack,n),this.emit(VB.TRACK,{userId:n,streamType:dB(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}},{key:"_checkTrackToPublish",value:function(){var e,t,n,r,i=[];if(null!=(t=this._localAudioConfig)&&t.publish&&this._localAudioTrack&&i.push(this._localAudioTrack),null!=(n=this._localVideoConfig)&&n.publish&&this._localVideoTrack&&i.push(this._localVideoTrack),null!=(r=this._localScreenConfig)&&r.publish&&(this._localScreenTrack&&i.push(this._localScreenTrack),this._localScreenAudioTrack&&i.push(this._localScreenAudioTrack),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),0!==i.length)return(e=this._room).publish.apply(e,i).catch((function(){}))}},{key:"_observeView",value:function(e){var t=this,n=e.remoteTrack,r=e.view,i=e.receiveWhenViewVisible,a=void 0!==i&&i,o=e.viewRoot;if(!Kw(r)){var s=this._remoteVideoConfigMap.get("".concat(n.userId,"_").concat(dB(n.streamType)));if(s){var c=s.observer||void 0;if(null===r||Qw(r)&&0===r.length||!a)return null==c||c.disconnect(),void(n.isSubscribed||this._room.subscribe(n).catch((function(){})));var u=s.visibleViewMap||new Map,l=-1;(!c||c.root!==o)&&(null==c||c.disconnect(),u.clear(),c=new IntersectionObserver((function(e){e.forEach((function(e){u.set(e.target,e.isIntersecting),n.log.info("view ".concat(e.target.id," is").concat(e.isIntersecting?"":" not"," visible"))})),clearTimeout(l),l=window.setTimeout((function(){E(u.values()).find((function(e){return e}))?n.isSubscribed||t._room.subscribe(n).catch((function(){})):n.isSubscribed&&t._room.unsubscribe(n).catch((function(){}))}),200)}),{root:o}));var d=new Set(mD(r));u.forEach((function(e,t){d.has(t)||(c.unobserve(t),u.delete(t))})),d.forEach((function(e){u.set(e,!0),c.observe(e)})),c.takeRecords().forEach((function(e){u.set(e.target,e.isIntersecting)})),s.visibleViewMap=u,s.observer=c}}}},{key:"_exitRoom",value:function(){return bA(this,null,f().mark((function e(){var t=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.t0=this._room.isJoined,!e.t0){e.next=4;break}return e.next=4,this._room.leave();case 4:new Set([].concat(E(this._remoteAudioConfigMap.keys()),E(this._remoteAudioMuteMap.keys()))).forEach((function(e){t._stopRemoteAudio({userId:e}).catch()})),E(this._remoteVideoConfigMap.keys()).forEach((function(e){var n=e.includes("main")?"main":"sub",r=e.split("_".concat(n))[0];r&&t._stopRemoteVideo({userId:r,streamType:n}).catch()})),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),function(e){var t=nH.get(e);t&&(t.forEach((function(e){return clearTimeout(e)})),nH.delete(e))}(this),this._room.remotePublishedUserMap.forEach((function(e){EM(e.remoteAudioTrack),EM(e.remoteVideoTrack),EM(e.remoteAuxiliaryTrack)}));case 12:case"end":return e.stop()}}),e,this)})))}},{key:"_stopScreenShare",value:function(){return bA(this,null,f().mark((function e(){var t,n,r,i;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this._localScreenTrack){e.next=7;break}if(!this._room.isJoined){e.next=6;break}return i=[this._localScreenTrack],this._localScreenAudioTrack&&i.push(this._localScreenAudioTrack),e.next=6,null==(t=this._room)?void 0:(r=t).unpublish.apply(r,i).catch((function(){}));case 6:this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(!1===(null==(n=this._localScreenAudioTrack.trackSettings)?void 0:n.echoCancellation)&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),EM(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null;case 7:case"end":return e.stop()}}),e,this)})))}},{key:"_checkScreenAudioEchoCancellation",value:function(e,t){return bA(this,null,f().mark((function n(){var r,i,a;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(e&&t){n.next=2;break}return n.abrupt("return");case 2:if(a=null==(r=e.trackSettings)?void 0:r.displaySurface,!1!==(null==(i=t.trackSettings)?void 0:i.echoCancellation)||!("monitor"===a||"browser"===a&&e.isShareCurrentTab)){n.next=13;break}return this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin"),n.prev=5,n.next=8,this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1});case 8:n.next=13;break;case 10:n.prev=10,n.t0=n.catch(5),this._log.warn("start audioProcessor plugin failed: ",n.t0);case 13:case"end":return n.stop()}}),n,this,[[5,10]])})))}},{key:"_onLocalTrackCaptured",value:function(e){"audio"===e.track.kind&&(!zH||yL(zH))&&(this._initActiveSpeaker(),Px.off("102",this._onLocalTrackCaptured,this))}},{key:"_initActiveSpeaker",value:function(){return bA(this,null,f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!zH||yL(zH)){e.next=4;break}this.emit(VB.DEVICE_CHANGED,{type:"speaker",action:"active",device:zH}),e.next=8;break;case 4:return e.next=6,IL();case 6:(t=e.sent)[0]&&!yL(t[0])?(zH=t[0],this.emit(VB.DEVICE_CHANGED,{type:"speaker",action:"active",device:t[0]})):Px.on("102",this._onLocalTrackCaptured,this);case 8:case"end":return e.stop()}}),e,this)})))}},{key:"_onAudioAvailable",value:function(e){var t=e.userId,n=this._remoteAudioMuteMap.has(t)?this._remoteAudioMuteMap.get(t):this._remoteAudioMuteMap.get("*");(!1===n||this._room.autoReceiveAudio&&!n)&&this._doStartRemoteAudio({userId:t}).catch((function(){}))}},{key:"_onVideoAvailable",value:function(e){var t=this,n=e.userId,r=e.streamType;if(this._room.autoReceiveVideo){var i=this._room.remotePublishedUserMap.get(n);if(i){var a,o="main"===r?i.remoteVideoTrack:i.remoteAuxiliaryTrack,s=[o];this._room.autoReceiveAudio&&i.remoteAudioTrack.isAvailable&&s.push(i.remoteAudioTrack),(a=this._room).subscribe.apply(a,s).then((function(){t._emitTrackEvent(o)})).catch((function(){}))}}}},{key:"_onAudioUnavailable",value:function(e){var t=e.userId,n=e.muteState;n.hasAudio&&n.audioMuted||this._stopRemoteAudio({userId:t},!1).catch((function(){}))}},{key:"_onVideoUnavailable",value:function(e){var t=e.userId,n=e.streamType;this._stopRemoteVideo({userId:t,streamType:n},!1).catch((function(){}))}},{key:"sendSEIMessage",value:function(e,t){var n,r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:gA(_A({seiPayloadType:243},t),{small:!(null==(n=this._localVideoTrack)||!n.small)})}),rP.addCount({key:5e5,useUV:!0}))}},{key:"sendCustomMessage",value:function(e){var t,n;null==(n=(t=this._room).sendCustomMessage)||n.call(t,e),rP.addCount({key:500001,useUV:!0})}},{key:"callExperimentalAPI",value:function(e,t){return bA(this,null,f().mark((function n(){return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.abrupt("return",(this._log.info("callExperimentalAPI(".concat(e,", ").concat(JSON.stringify(t),")")),JH.call(e,_A({trtcInstance:this},t))));case 1:case"end":return n.stop()}}),n,this)})))}}],[{key:"create",value:function(e){}},{key:"_create",value:function(e,t){!function(){var e;if(rB){rB=!1,5!==Ux.getLogLevel()&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(oC,"/en/index.html")),console.info("* Changelog: ".concat(oC,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),Ux.info("TRTC Web SDK Version:",YA),gx||Ux.debug("Build Time:","2025-06-25 11:32:57");var t="UA: ".concat(navigator.userAgent," \nCPU core: ").concat(navigator.hardwareConcurrency,", GPU: ").concat(Rx()),n=navigator.deviceMemory;n&&(t+=", minRAM: ".concat(n,"GB")),Ux.info(t),Ux.info("URL: ".concat(location.href).concat("IFRAME"===(null==(e=self.frameElement)?void 0:e.tagName)?" in iframe":"")),bx().then((function(e){e&&Ux.info(Ix)}))}}();var n=new i(e,t||{});return YH.add(n),n}},{key:"setLogLevel",value:function(e,t){Ux.setLogLevel(e),Kw(t)||(t?Ux.enableUploadLog():Ux.disableUploadLog())}},{key:"isSupported",value:function(){return mP()}},{key:"getCameraList",value:function(){return TL(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}},{key:"getMicrophoneList",value:function(){return kL(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}},{key:"getSpeakerList",value:function(){return IL(!(arguments.length>0&&void 0!==arguments[0])||arguments[0])}},{key:"setCurrentSpeaker",value:function(e){return bA(this,null,f().mark((function t(){var n,r,a=this;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if($D&&(e===iB.SPEAKER||e===iB.HEADSET)){t.next=6;break}return t.next=3,IL();case 3:t.sent.forEach((function(t){t.deviceId===e&&(YH.forEach((function(n){n._setCurrentSpeaker(e),n.emit(VB.DEVICE_CHANGED,{type:"speaker",action:"active",device:t})})),zH=t)})),t.next=13;break;case 6:return t.next=8,i.getMicrophoneList();case 8:if(n=t.sent,r="",n.forEach((function(t){t.label===e&&(r=t.deviceId)})),r){t.next=12;break}return t.abrupt("return");case 12:YH.forEach((function(e){return bA(a,null,f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(t.t0=e._localAudioTrack,!t.t0){t.next=4;break}return t.next=4,e.updateLocalAudio({option:{microphoneId:r}});case 4:case"end":return t.stop()}}),t)})))}));case 13:case"end":return t.stop()}}),t)})))}},{key:"_addKVStat",value:function(e){var t=e.type,n=e.key,r=e.value,i=e.base,a=e.useUV,o=e.version,s=e.max;switch(o&&(nP.version=o),t){case"count":nP.addCount({key:n,useUV:a});break;case"enum":nP.addEnum({key:n,value:r,useUV:a});break;case"number":nP.addNumber({key:n,value:r,split:i,max:s})}}}])}(MA.EventEmitter);SA(XH,"_loggerManager",Ux),SA(XH,"EVENT",VB),SA(XH,"ERROR_CODE",aB),SA(XH,"TYPE",iB),SA(XH,"frameWorkType",30),TA([sH({replaceArg:function(e){return{argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?null==e?void 0:e.assetsPath:"default"}}}})],XH.prototype,"use",1),TA([rH(bB.TRTC.enterRoom),PB("room",(function(e,t){var n=v(e,1)[0],r=v(t,1)[0];return(n.roomId||n.strRoomId)===(r.roomId||r.strRoomId)&&n.userId===r.userId&&n.sdkAppId===r.sdkAppId})),jL((function(e){return function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}})),sH()],XH.prototype,"enterRoom",1),TA([sH()],XH.prototype,"exitRoom",1),TA([rH(bB.TRTC.switchRoom),sH(),qL()],XH.prototype,"switchRoom",1),TA([rH(bB.TRTC.switchRole),MB("room",{merge:function(e,t){return t}}),sH()],XH.prototype,"switchRole",1),TA([sH()],XH.prototype,"destroy",1),TA([rH(bB.TRTC.startLocalAudio),PB("audio",(function(e,t){var n,r,i=v(e,1)[0],a=v(t,1)[0];return(null==(n=null==i?void 0:i.option)?void 0:n.microphoneId)===(null==(r=null==a?void 0:a.option)?void 0:r.microphoneId)})),sH()],XH.prototype,"startLocalAudio",1),TA([rH(bB.TRTC.updateLocalAudio),MB("audio",{debounce:{delay:200,getKey:function(){return"".concat(KH,"-localAudio")},isNeedToDebounce:function(e){var t;return!Kw(null==(t=e.option)?void 0:t.captureVolume)}}}),sH()],XH.prototype,"updateLocalAudio",1),TA([LB("audio"),sH()],XH.prototype,"stopLocalAudio",1),TA([rH(bB.TRTC.startLocalVideo),PB("video",(function(e,t){var n,r,i=v(e,1)[0],a=v(t,1)[0];return(null==(n=null==i?void 0:i.option)?void 0:n.cameraId)===(null==(r=null==a?void 0:a.option)?void 0:r.cameraId)})),sH()],XH.prototype,"startLocalVideo",1),TA([rH(bB.TRTC.updateLocalVideo),MB("video"),sH()],XH.prototype,"updateLocalVideo",1),TA([LB("video"),sH()],XH.prototype,"stopLocalVideo",1),TA([rH(bB.TRTC.startScreenShare),PB("screen",(function(){return!0})),sH()],XH.prototype,"startScreenShare",1),TA([rH(bB.TRTC.updateScreenShare),MB("screen"),sH()],XH.prototype,"updateScreenShare",1),TA([sH()],XH.prototype,"stopScreenShare",1),TA([rH(bB.TRTC.startRemoteVideo),PB((function(e){return"v".concat(e.userId).concat(e.streamType)}),(function(){return!0})),sH({getRemoteId:function(e){return"".concat(e.userId,"_").concat(e.streamType)}})],XH.prototype,"startRemoteVideo",1),TA([rH(bB.TRTC.updateRemoteVideo),MB((function(e){return"v".concat(e.userId).concat(e.streamType)})),sH({getRemoteId:function(e){return"".concat(e.userId,"_").concat(e.streamType)}})],XH.prototype,"updateRemoteVideo",1),TA([rH(bB.TRTC.stopRemoteVideo),jL((function(e){return function(t){return bA(this,null,f().mark((function n(){var r,i=this;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if("*"!==t.userId){n.next=3;break}return r=[],n.abrupt("return",(this._room.remotePublishedUserMap.forEach((function(e){i._remoteVideoConfigMap.has("".concat(e.userId,"_main"))&&r.push(i.stopRemoteVideo({streamType:"main",userId:e.userId}).catch((function(){}))),i._remoteVideoConfigMap.has("".concat(e.userId,"_sub"))&&r.push(i.stopRemoteVideo({streamType:"sub",userId:e.userId}).catch((function(){})))})),Promise.all(r)));case 3:return n.abrupt("return",e.call(this,t));case 4:case"end":return n.stop()}}),n,this)})))}})),sH({getRemoteId:function(e){return"".concat(e.userId,"_").concat(e.streamType)}})],XH.prototype,"stopRemoteVideo",1),TA([LB((function(e){return"v".concat(e.userId).concat(e.streamType)}))],XH.prototype,"_stopRemoteVideo",1),TA([rH.apply(void 0,E(bB.TRTC.muteRemoteAudio)),sH({getRemoteId:function(e){return e}})],XH.prototype,"muteRemoteAudio",1),TA([iH.apply(void 0,E(bB.TRTC.setRemoteAudioVolume)),function(e,t){return jL((function(e,n){return function(){for(var n=this,r=arguments.length,i=new Array(r),a=0;a<r;a++)i[a]=arguments[a];var o=nH.get(this);o||(o=new Map,nH.set(this,o));var s=t.apply(void 0,i),c=o.get(s);if(!c||c<=0){e.apply(this,i);var u=setTimeout((function(){var e;null==(e=nH.get(n))||e.delete(s)}),200);o.set(s,u)}else{clearTimeout(c);var l=window.setTimeout((function(){var t;e.apply(n,i),null==(t=nH.get(n))||t.delete(s)}),200);o.set(s,l)}}}))}(0,(function(e){return e})),sH({getRemoteId:function(e){return e}})],XH.prototype,"setRemoteAudioVolume",1),TA([uH("start"),HL((function(e){var t;return null==(t=e.afterStart)?void 0:t.call(e)})),PB((function(e,t){return e.disableRandomCall?null:e.getAlias()+e.getGroup(t)})),sH({replaceArg:function(e){return{argIndex:0,value:e.getName()}},getKVReportKey:function(e){return ZO[e.getName()]},ignoreLog:function(e){return"Debug"===e.getName()},ignoreErrorLog:function(e){return"AudioProcessor"===e.getName()}})],XH.prototype,"startPlugin",1),TA([uH("update"),MB((function(e,t){return e.disableRandomCall?null:e.getAlias()+e.getGroup(t)})),sH({replaceArg:function(e){return{argIndex:0,value:e.getName()}},getKVReportKey:function(e){return $O[e.getName()]}})],XH.prototype,"updatePlugin",1),TA([uH("stop"),LB((function(e,t){if(e.disableRandomCall)return null;var n=e.getGroup(t),r=e.getAlias();return"*"===n?new RegExp("".concat(r,".*")):r+n})),sH({replaceArg:function(e){return{argIndex:0,value:e.getName()}},getKVReportKey:function(e){return eP[e.getName()]}})],XH.prototype,"stopPlugin",1),TA([iH.apply(void 0,E(bB.TRTC.enableAudioVolumeEvaluation))],XH.prototype,"enableAudioVolumeEvaluation",1),TA([sH()],XH.prototype,"getVideoSnapshot",1),TA([sH()],XH.prototype,"_setCurrentSpeaker",1),TA([PB((function(e){return"a".concat(e.userId)}),(function(){return!0}))],XH.prototype,"_startRemoteAudio",1),TA([jL((function(e){return function(t){return bA(this,null,f().mark((function n(){var r=this;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.abrupt("return","*"===t.userId?Promise.all(E(this._room.remotePublishedUserMap.values()).map((function(e){return r._stopRemoteAudio(gA(_A({},t),{userId:e.userId})).catch((function(){}))}))):e.call(this,t));case 1:case"end":return n.stop()}}),n,this)})))}})),LB((function(e){return"a".concat(e.userId)}))],XH.prototype,"_stopRemoteAudio",1),TA([LB("room")],XH.prototype,"_exitRoom",1),TA([LB("screen")],XH.prototype,"_stopScreenShare",1),TA([rH.apply(void 0,E(bB.TRTC.sendSEIMessage)),tB({timesInSecond:30,maxSizeInSecond:8e3,getSize:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return t[0].byteLength}})],XH.prototype,"sendSEIMessage",1),TA([rH(bB.TRTC.sendCustomMessage),tB({timesInSecond:30,maxSizeInSecond:8e3,getSize:function(e){return e.data.byteLength}})],XH.prototype,"sendCustomMessage",1),TA([rH(bB.TRTC.create)],XH,"_create",1);var QH=XH,ZH=function(){return o((function e(){r(this,e),SA(this,"_set",new Set),Px.on(Lx.LEAVE_SUCCESS,this.delete,this),Px.on(Lx.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}),[{key:"add",value:function(e){var t=e.room,n=e.roomId;if("rtc"!==t.scene){var r=this.getKey(t.userId,n||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(r)}}},{key:"delete",value:function(e){var t=e.room,n=e.roomId;if("rtc"!==t.scene){var r=this.getKey(t.userId,t.roomId||n,t.sdkAppId,t.useStringRoomId);this._set.delete(r)}}},{key:"getKey",value:function(e,t,n,r){return"".concat(n,"_").concat(t,"_").concat(e,"_").concat(r)}},{key:"isJoined",value:function(e){var t=e.userId,n=e.roomId,r=e.sdkAppId,i=e.room;return"rtc"!==i.scene&&this._set.has(this.getKey(t,n,r,i.useStringRoomId))}},{key:"handleSwitchRoomSuccess",value:function(e){var t=e.room,n=e.currentRoomId,r=e.targetRoomId;"rtc"!==t.scene&&(this._set.delete(this.getKey(t.userId,n,t.sdkAppId,t.useStringRoomId)),this._set.add(this.getKey(t.userId,r,t.sdkAppId,t.useStringRoomId)))}}])}();function $H(){return bA(this,null,f().mark((function e(){var t,n,r,i,a,o,s,c,u,l,d,h,p,m;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,kL();case 3:r=e.sent,t=r&&r.length,e.next=9;break;case 7:e.prev=7,e.t0=e.catch(0);case 9:return e.prev=9,e.next=12,TL();case 12:i=e.sent,n=i&&i.length,e.next=18;break;case 16:e.prev=16,e.t1=e.catch(9);case 18:a={microphone:t,camera:n},o=this.checkSystemResult.detail,s=o.isH264EncodeSupported,c=o.isVp8EncodeSupported,u=o.isH264DecodeSupported,l=o.isVp8DecodeSupported,d=Hx.basis(),h={webRTC:d.isWebRTCSupported,getUserMedia:d.isGetUserMediaSupported,webSocket:d.isWebSocketsSupported,screenShare:d.isScreenShareSupported,webAudio:d.isWebAudioSupported,h264Encode:s,h264Decode:u,vp8Encode:c,vp8Decode:l},p={browser:d.browser,os:d.os,trtc:h,devices:a},m={isWebCodecSupported:d.isWebCodecSupported,isMediaSessionSupported:d.isMediaSessionSupported,isWebTransportSupported:d.isWebTransportSupported},kM.uploadEvent({log:"trtcstats-".concat(JSON.stringify(p)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(p))),kM.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(m)),userId:this.userId});case 20:case"end":return e.stop()}}),e,this,[[0,7],[9,16]])})))}var eW=kA(RA()),tW="3",nW="5",rW={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140,SEND_SWITCH_ROOM_RES:4160,SEND_SWITCH_ROOM_SUBED_REQ:4161},iW=[rW.UPDATE_REMOTE_MUTE_STAT,rW.UPLINK_NETWORK_STATS,rW.USER_LIST_RES,rW.MUTE_RESULT,rW.SERVER_FIRST_PACKAGE_RECEIVED,rW.RECEIVE_CUSTOM_MSG],aW={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg",SEND_SWITCH_ROOM_RES:"send-switch-room-res",SEND_SWITCH_ROOM_SUBED_REQ:"send-switch-room-subed-res"},oW="mute_uplink",sW="publish_state_change",cW="unpublish",uW="unsubscribe",lW="subscribe_change",dW="update_constraint_config",hW=new Set,fW=function(e){function i(e){var a,o,s,c;r(this,i),a=n(this,i),SA(t(a),"room"),SA(t(a),"sdkAppId"),SA(t(a),"userId"),SA(t(a),"userSig"),SA(t(a),"url"),SA(t(a),"backupUrl"),SA(t(a),"destroyed",!1),SA(t(a),"_socketInUse"),SA(t(a),"_socket"),SA(t(a),"_backupSocket"),SA(t(a),"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[]}),SA(t(a),"_currentState","DISCONNECTED"),SA(t(a),"_isReconnecting",!1),SA(t(a),"_seq",0),SA(t(a),"_log"),SA(t(a),"_lastMessageTime",-1),SA(t(a),"_connectStartTime",-1),SA(t(a),"_stopConnectRetry"),SA(t(a),"bytesSent",0),SA(t(a),"bytesReceived",0),SA(t(a),"keepAlive",!1),SA(t(a),"signalDomainWhenUnifiedProxy"),SA(t(a),"stopKeepAliveTimeout"),SA(t(a),"rtt",0),a.room=e.room,a.sdkAppId=e.sdkAppId,a.userId=e.userId,a.userSig=e.userSig,a.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy;var u=(null==(s=null==(o=a.room.scheduleResult)?void 0:o.config)?void 0:s.keepAliveClient)||0;return null!=(c=a.room.joinParams)&&c.keepAlive&&!u&&(u=1),u-hW.size>0&&a.room.enableSPC&&(a.keepAlive=!0,hW.add(a)),a.url=e.url,a.backupUrl=e.backupUrl,a._seq=0,a._log=Ux.createLogger({id:"ws",userId:a.userId,sdkAppId:a.sdkAppId}),a.onmessage=a.onmessage.bind(a),a.onerror=a.onerror.bind(a),a.onclose=a.onclose.bind(a),a}return d(i,e),o(i,[{key:"race",get:function(){return this.room.enableSPC&&!this.room.proxy_ws}},{key:"urlParam",get:function(){var e="?sdkAppId=".concat(encodeURIComponent(this.sdkAppId),"&userId=").concat(encodeURIComponent(this.userId),"&userSig=").concat(encodeURIComponent(this.userSig),"&keepAlive=").concat(encodeURIComponent(Number(this.keepAlive)));this.signalDomainWhenUnifiedProxy&&(e+="&signalDomain=".concat(encodeURIComponent(this.signalDomainWhenUnifiedProxy)));var t=new URLSearchParams(location.search).get("clientIp");return t&&(e+="&clientIp=".concat(t)),this.race?"".concat(e,"&race=1"):e}},{key:"_urlWithParam",get:function(){return"".concat(this.url).concat(this.race?"/v2/ws":"").concat(this.urlParam)}},{key:"_backupUrlWithParam",get:function(){return"".concat(this.backupUrl).concat(this.race?"/v2/ws":"").concat(this.urlParam)}},{key:"isConnected",get:function(){return"CONNECTED"===this._currentState}},{key:"isConnecting",get:function(){return"CONNECTING"===this._currentState}},{key:"isOnline",get:function(){return"CONNECTED"===this._currentState&&Date.now()-this._lastMessageTime<12e3}},{key:"connect",value:function(){return bA(this,arguments,(function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e4;return f().mark((function n(){var r;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(!e.isConnected){n.next=2;break}return n.abrupt("return",Promise.resolve());case 2:return e._log.info("connect to [".concat(e.url,", ").concat(e.backupUrl,"] ").concat(e.race?"race":"").concat(t?" timeout: ".concat(t):""," keepAlive: ").concat(Number(e.keepAlive))),e.emitConnectionStateChanged("CONNECTING"),e._connectStartTime=aD(),r=[e.connectWS({url:e._urlWithParam,isMain:!0,timeout:t})],e.race&&e._backupUrlWithParam!==e._urlWithParam&&r.push(e.connectWS({url:e._backupUrlWithParam,isMain:!1,timeout:t})),n.next=7,iD(r);case 7:e._socketInUse=n.sent,e.unbindAndCloseSocket(e._socketInUse===e._socket?IC.BACKUP:IC.MAIN),e.emitConnectionStateChanged("CONNECTED");case 10:case"end":return n.stop()}}),n)}))()}))}},{key:"connectWS",value:function(e){var t=this,n=e.url,r=e.timeout,i=e.isMain,a=new WebSocket(n);this.bindSocket(a),i?this._socket=a:this._backupSocket=a;var o=-1;return new Promise((function(e,n){a.onclose=n,a.onerror=n,a.onopen=function(){return e(a)},r&&(o=setTimeout((function(){t.unbindAndCloseSocket(i?IC.MAIN:IC.BACKUP),n(new FA({code:VA.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))}),r))})).finally((function(){a.onclose=null,a.onerror=null,a.onopen=null,clearTimeout(o)}))}},{key:"bindSocket",value:function(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}},{key:"unbindSocket",value:function(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}},{key:"unbindAndCloseSocket",value:function(e){if(e===IC.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(ZC){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(ZC){}this._backupSocket=null}}},{key:"onclose",value:function(e){e.target===this._socketInUse&&(this._log.warn("".concat(e.target===this._socket?"main":"backup"," is closed code:").concat(e.code," ").concat(e.reason)),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||1e3!==e.code)&&this.startReconnection(),this.room.isJoining&&this.emit(nW,new FA({code:VA.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}},{key:"onerror",value:function(e){this._log.error("".concat(e.target===this._socket?"main":"backup"," error observed")),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(IC.MAIN),this.unbindAndCloseSocket(IC.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(nW,new FA({code:VA.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}},{key:"onmessage",value:function(e){if(this.isConnected){this._lastMessageTime=Date.now(),this.bytesReceived+=ED(e.data);var t=JSON.parse(e.data),n=t.cmd,r=t.data,i=Object.values(rW),a=Object.keys(rW)[i.indexOf(n)],o=aW[a]||n;switch(iW.includes(n)||(this._log.debug("received ".concat(n," msg: ").concat(e.data)),o&&this._log.info("Received event: [ ".concat(o," ]"))),n){case rW.CHANNEL_SETUP_RESULT:if(0===t.code)this._signalInfo.clientIp=r.clientIp,this._signalInfo.signalIp=r.signalInnerIp,r.svrTime&&function(e){BA=e-(new Date).getTime();var t=new Date;t.setTime(e),Ux.info("baseTime from server: ".concat(t," offset: ").concat(BA))}(r.svrTime),this._log.info("ChannelSetup Success ".concat(aD()-this._connectStartTime)),rP.addSuccessEvent({key:521701,cost:aD()-this._connectStartTime}),this._connectStartTime=-1,this.emit("1",{signalInfo:this._signalInfo});else{var s=new FA({code:VA.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:YO({key:jO.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error("".concat(t.code,", ").concat(t.message)),this.close(),rP.addFailedEvent({key:521701,error:s}),this.emit(nW,s)}break;case rW.JOIN_ROOM_RESULT:0===t.code&&(this._signalInfo.relayIp=r.relayOuterIp,this._signalInfo.relayInnerIp=r.relayInnerIp,this._signalInfo.bakRelayIps=r.bakRelayIps,this._signalInfo.relayPort=r.relayPort,this._signalInfo.tinyId=t.tinyId,this._signalInfo.endReportExtend=r.endReportExtend,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(o,{data:t});break;default:this.emit(String(o),{data:t})}}}},{key:"reGetSignalChannelUrl",value:function(){return bA(this,null,f().mark((function e(){var t,n,r;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,this.room.joinParams){e.next=3;break}return e.abrupt("return");case 3:return jB(!0),e.next=6,this.room.schedule(this.room.joinParams);case 6:t=this.room.getSignalChannelUrl(),n=t.mainUrl,r=t.backupUrl,this.url=n,this.backupUrl=r,e.next=12;break;case 10:e.prev=10,e.t0=e.catch(0);case 12:case"end":return e.stop()}}),e,this,[[0,10]])})))}},{key:"startReconnection",value:function(){if(this._socketInUse){this._socketInUse.onclose=null,this._socketInUse.close(4011);var e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?IC.MAIN:IC.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}}},{key:"reconnect",value:function(){return bA(this,null,f().mark((function e(){var t,n,r,i,a,o,s,c,u;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this._isReconnecting){e.next=25;break}if(this.room.isJoined||!this.keepAlive){e.next=3;break}return e.abrupt("return",void this.close());case 3:return this._isReconnecting=!0,e.prev=4,this._log.warn("reconnect"),e.next=8,this.connect();case 8:return t=this.room,n=t.roomId,r=t.useStringRoomId,i=this._signalInfo,a=i.relayIp,o=i.relayInnerIp,s=i.relayPort,e.next=17,this.sendWaitForResponse({command:"reconnect",data:{roomId:n,useStringRoomId:r,relayInnerIp:o,relayOuterIp:a,relayPort:s},responseCommand:aW.CHANNEL_RECONNECT_RESULT});case 17:c=e.sent,0===(u=c.data).code?(this._log.warn("reconnect success"),this.stopReconnection(),rP.addSuccessEvent({key:521702,cost:aD()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(rP.addFailedEvent({key:521702,error:u.code}),this._log.warn("reconnect failed, ".concat(u.code," ").concat(u.message)),this.room.reJoin()),e.next=25;break;case 22:e.prev=22,e.t0=e.catch(4),this._log.error(e.t0),this.room.reJoin();case 25:case"end":return e.stop()}}),e,this,[[4,22]])})))}},{key:"send",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.isConnected&&!this.room.isLeft){var n={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},r=JSON.stringify(n);return this._socketInUse.send(r),this.bytesSent+=ED(r),n.seq}}},{key:"sendWaitForResponse",value:function(e){var t=this,n=e.command,r=e.data,i=e.timeout,a=void 0===i?5e3:i,o=e.responseCommand,s=e.commandDesc,c=e.enableLog,u=void 0===c||c,l=e.addReceiveTime,d=void 0!==l&&l;return new Promise((function(e,i){var c=setTimeout((function(){t.off(o,l);var e=new FA({code:VA.API_CALL_TIMEOUT,message:YO({key:jO.API_CALL_TIMEOUT,data:{commandDesc:s,command:n}})});u&&t._log.warn(e),i(e)}),a),l=function(n){n.data.seq===h&&(clearTimeout(c),t.off(o,l),d&&(n.data.receiveTime=Date.now()),e(n))};t.on(o,l);var h=t.send(n,r)}))}},{key:"sendWaitForResponseWithRetry",value:function(e){var t=this,n=e.commandDesc,r=e.command,i=e.retries,a=void 0===i?0:i,o=e.retryTimeout,s=void 0===o?0:o;return FD({retryFunction:this.sendWaitForResponse,onError:function(e){var n=e.retry;t.isOnline?n():(t._log.warn("retry ".concat(r," when connected")),t.once(tW,n))},onRetrying:function(e){t._log.warn("".concat(n||r," timeout observed, retrying [").concat(e,"/").concat(a,"]"))},settings:{retries:a,timeout:s},context:this})(e)}},{key:"getCurrentState",value:function(){return this._currentState}},{key:"getSignalInfo",value:function(){return this._signalInfo}},{key:"stopReconnection",value:function(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}},{key:"close",value:function(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),hW.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(IC.MAIN),this.unbindAndCloseSocket(IC.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}},{key:"destroy",value:function(){this.close(),this.destroyed=!0}},{key:"getBackupRelayIpPair",value:function(){var e,t=null==(e=this._signalInfo.bakRelayIps)?void 0:e.shift();return t&&(t.relayPort=t.relayPort||this._signalInfo.relayPort),t}},{key:"clearBakRelayIps",value:function(){this._signalInfo.bakRelayIps=[]}},{key:"stopKeepAliveIn",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3600;if(this.keepAlive){this._log.info("stopKeepAlive in ".concat(t,"s")),this.stopKeepAliveTimeout=setTimeout((function(){e.keepAlive=!1,e._log.info("close due to not used ".concat(t,"s")),e.close(),e.off(aW.JOIN_ROOM_RESULT,n)}),1e3*t);var n=function(t){0===t.data.code&&(e._log.info("stopKeepAlive clear timeout"),clearTimeout(e.stopKeepAliveTimeout),e.off(aW.JOIN_ROOM_RESULT,n))};this.on(aW.JOIN_ROOM_RESULT,n)}}},{key:"emitConnectionStateChanged",value:function(e){e!==this._currentState&&(this._log.info("".concat(this._currentState," -> ").concat(e)),this.emit("2",{prevState:this._currentState,state:e}),this._currentState=e,"CONNECTED"===e?this.emit(tW):"DISCONNECTED"===e&&this.emit("6"))}}])}(eW.default);TA([SM({settings:{retries:1/0,timeout:2e3},onError:function(e,t){!this.room.isDestroyed&&!this.destroyed&&t()},onRetrying:function(e,t){this._log.warn("retrying to connect ".concat(e)),e>=3&&e%3==0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],fW.prototype,"connect",1);var pW=kA(RA()),mW=0,vW=!1,_W=new Set,gW=!1,yW=function(){return o((function e(t){r(this,e),SA(this,"userId"),SA(this,"tinyId"),SA(this,"_sdpSemantics"),SA(this,"_isUplink"),SA(this,"_room"),SA(this,"_log"),SA(this,"_signalChannel"),SA(this,"_isErrorObserved",!1),SA(this,"_waitForPeerConnectionConnectedPromise"),SA(this,"_waitForPeerConnectionConnectedPromiseReject",null),SA(this,"_peerConnection",null),SA(this,"_emitter",new pW.default),SA(this,"_currentState","DISCONNECTED"),SA(this,"_isReconnecting",!1),SA(this,"_reconnectionCount",0),SA(this,"_reconnectionTimer",-1),SA(this,"_isFirstConnection",!0),SA(this,"_prevTime",-1),SA(this,"_localAddress"),SA(this,"_remoteAddress"),this.userId=t.userId,this.tinyId=t.tinyId,this._room=t.room,this._sdpSemantics=t.room.sdpSemantics,this._isUplink=t.isUplink,this._log=Ux.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=t.signalChannel}),[{key:"beforeConnect",value:function(){this._prevTime<0&&(this._prevTime=aD())}},{key:"afterConnect",value:function(){try{this._isFirstConnection?(this._isFirstConnection=!1,rP.addSuccessEvent({key:521705,cost:Math.min(aD()-this._prevTime,3e4)})):this._isReconnecting&&rP.addSuccessEvent({key:521706,cost:aD()-this._prevTime}),this._prevTime=-1}catch(Kx){throw this._isFirstConnection?(this._isFirstConnection=!1,rP.addFailedEvent({key:521705,error:Kx})):this._isReconnecting&&this._reconnectionCount>=3&&rP.addFailedEvent({key:521706,error:Kx}),Kx}}},{key:"initialize",value:function(){var e={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(e),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}},{key:"close",value:function(e){this._log.info("close connection"),this._emitter.emit("closed",e),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),_W.delete(this)}},{key:"closePeerConnection",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,e&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new FA({code:VA.API_CALL_ABORTED,message:"connection closed"}))}},{key:"getDTLSTransportState",value:function(){if(!this._peerConnection)return YC;var e=null;if(this._isUplink){if(!DP()||0===this._peerConnection.getSenders().length)return YC;e=this._peerConnection.getSenders()[0].transport}else{if(!wP()||0===this._peerConnection.getReceivers().length)return YC;e=this._peerConnection.getReceivers()[0].transport}return e?e.state:YC}},{key:"onConnectionStateChange",value:function(e){var t=this._peerConnection.iceConnectionState,n=this.getDTLSTransportState();if(this._log.info("connectionState: ".concat(e.target.connectionState,", ICE: ").concat(t,", DTLS: ").concat(n)),e.target.connectionState===zC.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),e.target.connectionState===zC.FAILED||e.target.connectionState===zC.CLOSED){var r="connection ".concat(e.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(n),i=new FA({message:r,code:VA.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",i)}(e.target.connectionState===zC.CONNECTED||e.target.connectionState===zC.COMPLETED)&&(this.logSelectedCandidate(),kM.logSuccessEvent({userId:this._room.userId,eventType:ew.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}},{key:"emitConnectionStateChangedEvent",value:function(e){return e!==this._currentState&&("CONNECTED"===e?(mW=0,vW=!1,gW=!0,_W.add(this)):_W.delete(this),Px.emit(Lx.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}},{key:"getPeerConnection",value:function(){return this._peerConnection}},{key:"getRoom",value:function(){return this._room}},{key:"getUserId",value:function(){return this.userId}},{key:"getTinyId",value:function(){return this.tinyId}},{key:"logSelectedCandidate",value:function(){return bA(this,null,f().mark((function e(){var t,n,r,i,a,o,c;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this._peerConnection){e.next=2;break}return e.abrupt("return");case 2:return e.next=4,this._peerConnection.getStats();case 4:t=e.sent,n=s(t),e.prev=6,n.s();case 8:if((r=n.n()).done){e.next=16;break}if(i=v(r.value,2),a=i[1],!EP(a)){e.next=14;break}return o=t.get(a.localCandidateId),c=t.get(a.remoteCandidateId),o&&(this._log.info("local candidate: ".concat(o.candidateType," ").concat(o.protocol,":").concat(o.ip||o.address,":").concat(o.port," ").concat(o.networkType||""," ").concat("relay"===o.candidateType?"relayProtocol:".concat(o.relayProtocol):"")),this._localAddress="".concat(o.ip||o.address,":").concat(o.port)),c&&(this._log.info("remote candidate: ".concat(c.candidateType," ").concat(c.protocol,":").concat(c.ip||c.address,":").concat(c.port)),this._remoteAddress="".concat(c.protocol,":").concat(c.ip||c.address)),e.abrupt("break",16);case 14:e.next=8;break;case 16:e.next=21;break;case 18:e.prev=18,e.t0=e.catch(6),n.e(e.t0);case 21:return e.prev=21,n.f(),e.finish(21);case 24:case"end":return e.stop()}}),e,this,[[6,18,21,24]])})))}},{key:"getCurrentState",value:function(){return this._currentState}},{key:"waitForPeerConnectionConnected",value:function(){var e=this;return this._waitForPeerConnectionConnectedPromise||(this._waitForPeerConnectionConnectedPromise=new Promise((function(t,n){if("CONNECTED"===e._currentState)return t();e._waitForPeerConnectionConnectedPromiseReject=n;var r=function(e){"CONNECTED"===e.state&&(clearTimeout(o),a(),t())},i=function(t){t.room===e._room&&(clearTimeout(o),a(),n(new FA({code:VA.API_CALL_ABORTED,message:YO({key:jO.CONNECTION_ABORTED,data:"leave room"})})))},a=function(){Px.off(Lx.LEAVE_SUCCESS,i,e),e._emitter.off("connection-state-changed",r,e)},o=setTimeout((function(){a();var t,r=new FA({code:VA.API_CALL_TIMEOUT,message:"connection timeout"});mW+=1,t=e._signalChannel.isConnected,mW>2&&!vW&&0===_W.size&&t&&(e._log.warn("firewall restriction"),vW=!0,e._emitter.emit("firewall-restriction")),n(r)}),hw);Px.on(Lx.LEAVE_SUCCESS,i,e),e._emitter.on("connection-state-changed",r,e)})),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally((function(){e._waitForPeerConnectionConnectedPromise=null,e._waitForPeerConnectionConnectedPromiseReject=null}))),this._waitForPeerConnectionConnectedPromise}},{key:"getReconnectionCount",value:function(){return this._reconnectionCount}},{key:"startReconnection",value:function(){this._isReconnecting=!0,this.reconnect()}},{key:"clearReconnectionTimer",value:function(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}},{key:"stopReconnection",value:function(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(tW,this.reconnect,this)}},{key:"beforeReconnect",value:function(){if(-1!==this._reconnectionTimer)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=QC()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();var e=new FA({code:this._isUplink?VA.UPLINK_RECONNECTION_FAILED:VA.DOWNLINK_RECONNECTION_FAILED,message:YO({key:this._isUplink?jO.UPLINK_RECONNECTION_FAILED:jO.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",e),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn("reconnect() trying [".concat(this._reconnectionCount,"]")),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(tW,this.reconnect,this),-1)}},{key:"on",value:function(e,t,n){this._emitter.on(e,t,n)}},{key:"off",value:function(e,t,n){this._emitter.off(e,t,n)}},{key:"getIsReconnecting",value:function(){return this._isReconnecting}},{key:"isH264",get:function(){var e,t;return!(null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)||!t.sdp.includes("H264"))}},{key:"setOffer",value:function(e){var t;return null==(t=this._peerConnection)?void 0:t.setLocalDescription(e)}},{key:"setAnswer",value:function(e){var t;return null==(t=this._peerConnection)?void 0:t.setRemoteDescription(e)}}])}();TA([ZL(521712,!1)],yW.prototype,"setOffer",1),TA([ZL(521713,!1)],yW.prototype,"setAnswer",1);var EW=kA(PA()),kW=function(e){return EW.default.parse(e)},TW=function(e){return EW.default.write(e)};function SW(e){return Object.keys(e).filter((function(t){return e[t]}))}var IW=function(e){function i(e){var a;return r(this,i),a=n(this,i,[gA(_A({},e),{isUplink:!1})]),SA(t(a),"_flag",0),SA(t(a),"isRobot",!1),SA(t(a),"role","anchor"),SA(t(a),"remoteAudioTrack"),SA(t(a),"remoteVideoTrack"),SA(t(a),"remoteAuxiliaryTrack"),SA(t(a),"ssrc",{audio:0,video:0,auxiliary:0}),SA(t(a),"_isSDPExchanging",!1),a.flag=e.flag,a.isRobot=e.isRobot||!1,a.remoteAudioTrack=e.remoteAudioTrack||new DF(a._room,t(a)),a.remoteVideoTrack=e.remoteVideoTrack||new zF(a._room,t(a)),a.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new qF(a._room,t(a)),a}return d(i,e),o(i,[{key:"videoCodec",get:function(){var e,t,n=null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)?void 0:t.sdp;return n?n.includes("H264")?"h264":"vp8":"h264"}},{key:"subscribeState",get:function(){var e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(8&this.remoteVideoTrack.mediaType?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}},{key:"muteState",get:function(){return lD(this.flag,this.userId)}},{key:"flag",get:function(){return this._flag},set:function(e){var t,n,r;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(n=this.remoteVideoTrack)||n.onFlagChanged(),null==(r=this.remoteAuxiliaryTrack)||r.onFlagChanged())}},{key:"hasMainStream",get:function(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}},{key:"hasAuxStream",get:function(){return this.muteState.hasAuxiliary}},{key:"isMainStreamSubscribed",get:function(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}},{key:"isAuxStreamSubscribed",get:function(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}},{key:"isSmallStreamSubscribed",get:function(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}},{key:"isBigStreamSubscribed",get:function(){return this.subscribeState.video&&this.muteState.hasVideo}},{key:"isStreamUnpublished",value:function(e){return e===IC.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}},{key:"initialize",value:function(){g(i,"initialize",this,3)([]),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}},{key:"close",value:function(e){g(i,"close",this,3)([e]),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}},{key:"installEvents",value:function(){}},{key:"uninstallEvents",value:function(){this._emitter.removeAllListeners()}},{key:"emitConnectionStateChangedEvent",value:function(e){var t,n,r=this._currentState,a=g(i,"emitConnectionStateChangedEvent",this,3)([e]);return a&&r!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:r,state:e}),null==(n=this.remoteAuxiliaryTrack)||n.emit("connection-state-changed",{prevState:r,state:e})),a}},{key:"onTrack",value:function(e){var t=e.streams[0],n=e.track,r=t.id===LC?IC.MAIN:IC.AUXILIARY;this._log.debug("ontrack ".concat(r," ").concat(n.kind));var i=IC.AUDIO;n.kind===IC.VIDEO&&(i=r===IC.MAIN?IC.VIDEO:IC.AUXILIARY);var a=this.remoteAudioTrack;i===IC.VIDEO?a=this.remoteVideoTrack:i===IC.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(n)}},{key:"addRRTRLine",value:function(e){var t=e.split("\r\n"),n=new Map;t.forEach((function(e,r){/^a=rtcp-fb:/.test(e)&&t[r+1]&&!/^a=rtcp-fb:/.test(t[r+1])&&n.set(r+1,"".concat(e.match(/^a=rtcp-fb:\d+/)[0]," rrtr"))}));for(var r=E(n),i=0;i<r.length;i++){var a=v(r[i],2),o=a[0],s=a[1];t.splice(o+i,0,s)}return t.join("\r\n")}},{key:"addSPSDescription",value:function(e){var t=kW(e);return t.media.forEach((function(e){e.type===IC.VIDEO&&e.fmtp.forEach((function(e){e.config+=";sps-pps-idr-in-keyframe=1"}))})),TW(t)}},{key:"removeSDESDescription",value:function(e){var t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],n=kW(e);return n.media.forEach((function(e){e.ext&&(e.ext=e.ext.filter((function(e){return!t.includes(e.uri)})))})),TW(n)}},{key:"isSubscriptionStateNotChanged",value:function(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}},{key:"subscribe",value:function(e,t){return bA(this,null,f().mark((function n(){var r,i,a;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(n.prev=0,n.t0=(null==(r=this._peerConnection)?void 0:r.connectionState)===zC.NEW||(null==(i=this._peerConnection)?void 0:i.connectionState)===zC.CONNECTING,!n.t0){n.next=5;break}return n.next=5,this.waitForPeerConnectionConnected();case 5:if(!this.isSubscriptionStateNotChanged(e)){n.next=13;break}if(n.t1=this._peerConnection,n.t1){n.next=12;break}return this.initialize(),n.next=11,this.connect(e);case 11:n.t1=n.sent;case 12:return n.abrupt("return",void n.t1);case 13:if(this._log.info("subscribe ".concat(t," ").concat(JSON.stringify(e))),!this._peerConnection&&!this._isSDPExchanging){n.next=20;break}return a="subscribe_change",Object.values(e).find((function(e){return!0===e}))||(a="unsubscribe"),n.next=18,this.sendSubscription(a,e);case 18:n.next=23;break;case 20:return this.initialize(),n.next=23,this.connect(e);case 23:n.next=28;break;case 25:throw n.prev=25,n.t2=n.catch(0),this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(n.t2.message," ").concat(JSON.stringify(this.muteState))),new FA({code:VA.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):n.t2;case 28:case"end":return n.stop()}}),n,this,[[0,25]])})))}},{key:"unsubscribe",value:function(e){return bA(this,arguments,(function(e){var t=this,n=e.remoteTracks,r=e.streamType;return f().mark((function e(){var i,a;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("CONNECTED"!==t._currentState||("main"!==r||t.isMainStreamSubscribed)&&("auxiliary"!==r||t.isAuxStreamSubscribed)){e.next=2;break}return e.abrupt("return",void t._log.info("".concat(r," stream already unsubscribed")));case 2:return i=_A({},t.subscribeState),n.forEach((function(e){switch(e.mediaType){case 1:i.audio=!1;break;case 4:i.video=!1;break;case 8:i.smallVideo=!1;break;case 2:i.auxiliary=!1}})),a="subscribe_change",Object.values(i).find((function(e){return!0===e}))||(a="unsubscribe"),t._log.info("".concat("unsubscribe"===a?a:"subscribe"," ").concat(r," [").concat(SW(i),"]")),e.next=9,t.sendSubscription(a,i);case 9:"unsubscribe"===a&&(t.closePeerConnection(),t.emitConnectionStateChangedEvent("DISCONNECTED"));case 10:case"end":return e.stop()}}),e)}))()}))}},{key:"sendSubscription",value:function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,r={srcTinyId:this.tinyId,srcUserId:this.userId},i=uW,a=aW.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(r={audio:n.audio,bigVideo:n.video,auxVideo:n.auxiliary,smallVideo:n.smallVideo,srcTinyId:this.tinyId},i=lW,a=aW.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:i,data:r,responseCommand:a,timeout:1e4}).then((function(n){var r=n.data;if(0!==r.code){var i=new FA({code:r.code,message:YO({key:jO.ERROR_MESSAGE,data:{type:e,message:r.message}})});throw t._log.error(i),i}}))}},{key:"connect",value:function(){return bA(this,arguments,(function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState;return f().mark((function n(){return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.prev=0,n.next=3,e.exchangeSDP(t);case 3:return n.next=5,e.waitForPeerConnectionConnected();case 5:n.next=10;break;case 7:throw n.prev=7,n.t0=n.catch(0),e.closePeerConnection(!0),n.t0;case 10:case"end":return n.stop()}}),n,null,[[0,7]])}))()}))}},{key:"exchangeSDP",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a,o,s;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,this._isSDPExchanging=!0,t.next=4,this.createOffer();case 4:return this._log.info("createOffer success, sending offer"),n=this._peerConnection.localDescription,r=n.type,i=n.sdp,a={type:r,sdp:i,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},t.next=11,this._signalChannel.sendWaitForResponse({command:"subscribe",commandDesc:"exchange sdp",data:a,responseCommand:aW.SUBSCRIBE_RESULT,timeout:rw});case 11:if(o=t.sent,this._peerConnection){t.next=15;break}throw s=new FA({code:VA.INVALID_OPERATION,message:YO({key:jO.CONNECTION_CLOSED})}),this._log.warn(s),s;case 15:return t.next=17,this.onSubscribeResult(o);case 17:this._isSDPExchanging=!1,t.next=23;break;case 20:throw t.prev=20,t.t0=t.catch(0),this._isSDPExchanging=!1,t.t0;case 23:case"end":return t.stop()}}),t,this,[[0,20]])})))}},{key:"createOffer",value:function(){return bA(this,null,f().mark((function e(){var t,n;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t={voiceActivityDetection:!1},xP()&&this._sdpSemantics===iw?(this._peerConnection.addTransceiver(IC.AUDIO,{direction:bC.RECVONLY}),this._peerConnection.addTransceiver(IC.VIDEO,{direction:bC.RECVONLY}),this._peerConnection.addTransceiver(IC.VIDEO,{direction:bC.RECVONLY})):(t.offerToReceiveAudio=!0,t.offerToReceiveVideo=!0),e.next=4,this._peerConnection.createOffer(t);case 4:if(!(n=e.sent).sdp){e.next=11;break}return e.next=8,pP();case 8:e.sent.isH264DecodeSupported||(this._log.warn("remove h264 desc from sdp"),n.sdp=function(e){var t=kW(e);return t.media.forEach((function(e){var t,n;if(e.type===IC.VIDEO){var r=new Set;e.rtp.forEach((function(e){var t=e.payload;return"H264"===e.codec&&r.add(t)})),e.fmtp.forEach((function(e){var t=e.payload,n=e.config.match(/apt=(\d+)/);n&&n[1]&&r.has(Number(n[1]))&&r.add(t)}));var i=function(e){var t=e.payload;return!r.has(t)};e.rtp=e.rtp.filter(i),e.rtcpFb=null==(t=e.rtcpFb)?void 0:t.filter(i),e.fmtp=e.fmtp.filter(i),e.payloads=null==(n=e.payloads)?void 0:n.split(" ").filter((function(e){return!r.has(Number(e))})).join(" ")}})),TW(t)}(n.sdp)),n.sdp=this.addRRTRLine(n.sdp),n.sdp=this.addSPSDescription(n.sdp),n.sdp=function(e){var t=kW(e);return t.media.forEach((function(e){e.type===IC.AUDIO&&e.fmtp.forEach((function(e){e.config+=";sprop-stereo=1;stereo=1"}))})),TW(t)}(n.sdp),this._sdpSemantics===iw&&(n.sdp=this.removeSDESDescription(n.sdp));case 11:return e.next=13,this.setOffer(n);case 13:case"end":return e.stop()}}),e,this)})))}},{key:"onSubscribeResult",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a,o,s,c;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=e&&e.data||{},r=n.code,i=n.message,a=void 0===i?"":i,o=e&&e.data&&e.data.data||{},s=o.type,c=o.sdp,r!==ow){t.next=3;break}throw new FA({code:VA.NOT_SUPPORTED_H264,message:YO({key:jO.NOT_SUPPORTED_H264DECODE})});case 3:if(t.prev=3,0===r){t.next=6;break}throw new FA({code:r,message:YO({key:jO.EXCHANGE_SDP_FAILED,data:{errMsg:a}})});case 6:return this._log.debug("accept remote answer: ".concat(c)),t.next=9,this.setAnswer({type:s,sdp:c});case 9:this.updateSSRC(c),t.next=15;break;case 12:throw t.prev=12,t.t0=t.catch(3),this._log.error(t.t0),t.t0;case 15:case"end":return t.stop()}}),t,this,[[3,12]])})))}},{key:"updateSSRC",value:function(e){var t=this;try{kW(e).media.forEach((function(e){if(e.ssrcs)if(e.type===IC.AUDIO){var n=e.ssrcs.find((function(e){var t;return null==(t=e.value)?void 0:t.includes(LC)}));n&&(t.ssrc.audio=Number(n.id))}else{var r=e.ssrcs.find((function(e){var t;return null==(t=e.value)?void 0:t.includes(LC)})),i=e.ssrcs.find((function(e){var t;return null==(t=e.value)?void 0:t.includes(VC)}));r&&(t.ssrc.video=Number(r.id)),i&&(t.ssrc.auxiliary=Number(i.id))}}))}catch(ZC){}}},{key:"getMainStreamVideoTrackId",value:function(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}},{key:"getAuxStreamVideoTrackId",value:function(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}},{key:"reconnect",value:function(){return bA(this,null,f().mark((function e(){var t,n=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(IA(i.prototype,this,"beforeReconnect").call(this)<0){e.next=14;break}return e.prev=1,this.closePeerConnection(),this.initialize(),e.next=6,this.connect();case 6:this.stopReconnection(),this._log.warn("reconnect() success"),e.next=14;break;case 10:e.prev=10,e.t0=e.catch(1),t=jw(this._reconnectionCount),this._log.warn("reconnect() timeout, try again after ".concat(t/1e3,"s")),this._reconnectionTimer=setTimeout((function(){n.clearReconnectionTimer(),n.reconnect()}),t);case 14:case"end":return e.stop()}}),e,this,[[1,10]])})))}},{key:"getIsReconnecting",value:function(){return this._isReconnecting}},{key:"clearReconnectionTimer",value:function(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}},{key:"getCurrentState",value:function(){return this._currentState}},{key:"setDelay",value:function(e){var t=e.audioDelay,n=e.videoDelay;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=n}},{key:"audioReceiver",get:function(){var e;return(null==(e=this._peerConnection)?void 0:e.getReceivers()[0])||null}}])}(yW);TA([jL((function(e){return function(){for(var t=this,n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return new Promise((function(n,i){var a=function(e){t._emitter.off("closed",a),i(new FA({code:VA.API_CALL_ABORTED,message:YO({key:jO.CONNECTION_ABORTED,data:e})}))};t._emitter.on("closed",a),e.apply(t,r).then(n,i).finally((function(){t._emitter.off("closed",a)}))}))}}))],IW.prototype,"subscribe",1),TA([ZL(521717,!1)],IW.prototype,"unsubscribe",1),TA([HL(yW.prototype.afterConnect),BL(yW.prototype.beforeConnect)],IW.prototype,"connect",1);var bW=IW,RW={voiceActivityDetection:!1},AW=function(e){function i(e){var a;return r(this,i),a=n(this,i,[gA(_A({},e),{isUplink:!0})]),SA(t(a),"localMainAudioTrack",null),SA(t(a),"localMainVideoTrack",null),SA(t(a),"localAuxAudioTrack",null),SA(t(a),"localAuxVideoTrack",null),SA(t(a),"ssrc",{audio:0,video:0,small:0,auxiliary:0}),SA(t(a),"_isPublishingAux",!1),SA(t(a),"_publishingLocalAudioTrack"),SA(t(a),"_publishingLocalVideoTrack"),SA(t(a),"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),SA(t(a),"flag",0),a}return d(i,e),o(i,[{key:"videoCodec",get:function(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}},{key:"isMainStreamPublished",get:function(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}},{key:"isAuxStreamPublished",get:function(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}},{key:"publishState",get:function(){var e,t,n,r,i=this,a={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){var o=this._peerConnection.getSenders();o&&(NP()?(a.audio=!(null==(e=o[0])||!e.track),a.bigVideo=!(null==(t=o[1])||!t.track),a.smallVideo=!(null==(n=o[2])||!n.track),a.auxVideo=!(null==(r=o[3])||!r.track)):o.forEach((function(e){e.track&&(e.track.kind===IC.AUDIO?a.audio=!0:(a.bigVideo=!0,i._room.videoManager.hasSmall&&(a.smallVideo=!0)))})))}return a}},{key:"initialize",value:function(){g(i,"initialize",this,3)([]),this.installEvents()}},{key:"reset",value:function(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}},{key:"close",value:function(e){g(i,"close",this,3)([e]),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}},{key:"installEvents",value:function(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}},{key:"uninstallEvents",value:function(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}},{key:"emitConnectionStateChangedEvent",value:function(e,t){var n,r,a,o=this._currentState,s=g(i,"emitConnectionStateChangedEvent",this,3)([e]);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(n=this.localMainVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}),null==(a=this._publishingLocalVideoTrack)||a.emit("connection-state-changed",{prevState:o,state:e}))),s}},{key:"publish",value:function(e){return bA(this,arguments,(function(e){var t=this,n=e.localAudioTrack,r=e.localVideoTrack,i=e.isAuxiliary;return f().mark((function e(){var a;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t._peerConnection||t.initialize(),n&&(t._publishingLocalAudioTrack=n),r&&(t._publishingLocalVideoTrack=r),t._isPublishingAux=i,r&&!i&&r.small&&(a=t._room.videoManager.smallTrack),t.sendMediaSettings(),!xP()){e.next=11;break}return e.next=9,t.publishByTransceiver({localAudioTrack:n,localVideoTrack:r,smallTrack:a,isAuxiliary:i});case 9:e.next=13;break;case 11:return e.next=13,t.publishByAddTrack({localAudioTrack:n,localVideoTrack:r,smallTrack:a});case 13:t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,i?(r&&(t.localAuxVideoTrack=r),n&&(t.localAuxAudioTrack=n)):(r&&(t.localMainVideoTrack=r),n&&(t.localMainAudioTrack=n)),t.installTrackMuteEvents(n,r),t.sendMutedFlag();case 19:case"end":return e.stop()}}),e)}))()}))}},{key:"publishByTransceiver",value:function(e){return bA(this,arguments,(function(e){var t=this,n=e.localAudioTrack,r=e.localVideoTrack,i=e.smallTrack,a=e.isAuxiliary;return f().mark((function e(){var o,s,c,u,l,d;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t._log.info("publish by transceiver"),o=new MediaStream,s=null==r?void 0:r.outMediaTrack,(c=null==n?void 0:n.outMediaTrack)&&o.addTrack(c),s&&o.addTrack(s),0!==(u=t._peerConnection.getTransceivers()).length){e.next=13;break}return t._peerConnection.addTransceiver(c||IC.AUDIO,{direction:bC.SENDONLY,streams:[o]}),t._peerConnection.addTransceiver(a?IC.VIDEO:s||IC.VIDEO,{direction:bC.SENDONLY,streams:[o]}),t._peerConnection.addTransceiver(i||IC.VIDEO,{direction:bC.SENDONLY,streams:[o]}),t._peerConnection.addTransceiver(a&&s||IC.VIDEO,{direction:bC.SENDONLY,streams:[o]}),e.next=11,t.connect();case 11:e.next=41;break;case 13:if(l=[],e.t0=c,!e.t0){e.next=21;break}return u[0].sender.track||l.push(0),e.next=19,u[0].sender.replaceTrack(c);case 19:return e.next=21,t.setBandwidth({bandwidth:(null==n?void 0:n.profile.bitrate)||40,type:IC.AUDIO});case 21:if(!s){e.next=35;break}return d=a?3:1,e.next=25,u[d].sender.replaceTrack(s);case 25:return e.next=27,t.setBandwidth({bandwidth:r.profile.bitrate,type:IC.VIDEO,videoType:a?IC.AUXILIARY:IC.BIG});case 27:if(l.push(d),e.t1=i,!e.t1){e.next=35;break}return e.next=32,u[2].sender.replaceTrack(i);case 32:return e.next=34,t.setBandwidth({bandwidth:r.small.bitrate,type:IC.VIDEO,videoType:IC.SMALL});case 34:l.push(2);case 35:return e.next=37,t.setTransceiverDirection(bC.SENDONLY,l);case 37:return e.next=39,t.doPublishChange();case 39:null==r||r.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),null==r||r.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"});case 41:case"end":return e.stop()}}),e)}))()}))}},{key:"publishByAddTrack",value:function(e){return bA(this,arguments,(function(e){var t=this,n=e.localAudioTrack,r=e.localVideoTrack,i=e.smallTrack;return f().mark((function e(){var a,o,s,c;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t._log.info("publish by addtrack"),a=null==r?void 0:r.outMediaTrack,o=null==n?void 0:n.outMediaTrack,!t._peerConnection||"new"===t._peerConnection.connectionState){e.next=13;break}if(e.t0=n&&o,!e.t0){e.next=7;break}return e.next=7,t.addTrack(n);case 7:if(e.t1=a,!e.t1){e.next=12;break}return e.next=11,t.addTrack(r);case 11:e.t1=e.sent;case 12:return e.abrupt("return",void e.t1);case 13:return s=new MediaStream,o&&s.addTrack(o),a&&s.addTrack(a),o&&t._peerConnection.addTrack(o,s),a&&(t._peerConnection.addTrack(a,s),i)&&((c=new MediaStream).addTrack(i),t._peerConnection.addTrack(i,c)),e.next=17,t.connect();case 17:case"end":return e.stop()}}),e)}))()}))}},{key:"enableSmall",value:function(e){return bA(this,null,f().mark((function t(){var n;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=this._peerConnection.getTransceivers(),!e){t.next=10;break}if(t.t0=this._room.videoManager.smallTrack,!t.t0){t.next=8;break}return t.next=6,n[2].sender.replaceTrack(this._room.videoManager.smallTrack);case 6:return t.next=8,this.setTransceiverDirection(bC.SENDONLY,[2]);case 8:t.next=14;break;case 10:return t.next=12,n[2].sender.replaceTrack(null);case 12:return t.next=14,this.setTransceiverDirection(bC.INACTIVE,[2]);case 14:return this.updateMediaSettings(),t.next=17,this.doPublishChange();case 17:case"end":return t.stop()}}),t,this)})))}},{key:"installTrackMuteEvents",value:function(){for(var e=this,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];n.forEach((function(t){t&&(null==t||t.on("mute",e.sendMutedFlag,e),null==t||t.on("unmute",e.sendMutedFlag,e))}))}},{key:"uninstallTrackMuteEvents",value:function(){for(var e=this,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];n.forEach((function(t){t&&(null==t||t.off("mute",e.sendMutedFlag,e),null==t||t.off("unmute",e.sendMutedFlag,e))}))}},{key:"unpublish",value:function(e){return bA(this,arguments,(function(e){var t=this,n=e.localAudioTrack,r=e.localVideoTrack;return f().mark((function e(){var i,a,o,s;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(NP()){e.next=19;break}if(!n||!n.outMediaTrack||r||!t.localMainVideoTrack){e.next=7;break}return e.next=4,t.removeTrack(n);case 4:e.t0=void(t.localMainAudioTrack=null),e.next=18;break;case 7:if(!r||!r.outMediaTrack||n||!t.localMainAudioTrack){e.next=13;break}return e.next=10,t.removeTrack(r);case 10:e.t1=void(t.localMainVideoTrack=null),e.next=17;break;case 13:return e.next=15,t.doUnpublish();case 15:t.uninstallTrackMuteEvents(n,r),e.t1=void t.emitConnectionStateChangedEvent("DISCONNECTED",r);case 17:e.t0=e.t1;case 18:return e.abrupt("return",e.t0);case 19:if(i=r&&r===t.localAuxVideoTrack,a=null==r?void 0:r.outMediaTrack,o=t._peerConnection.getSenders(),s=[],e.t2=n,!e.t2){e.next=28;break}if(i?t.localAuxAudioTrack=null:t.localMainAudioTrack=null,e.t3=!t.localAuxAudioTrack&&!t.localMainAudioTrack,!e.t3){e.next=28;break}return e.next=27,o[0].replaceTrack(null);case 27:s.push(0);case 28:if(e.t4=a,!e.t4){e.next=45;break}if(!i){e.next=38;break}return e.next=33,o[3].replaceTrack(null);case 33:t.localAuxVideoTrack=null,t._mediaSettings=gA(_A({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),s.push(3),e.next=45;break;case 38:return e.next=40,o[1].replaceTrack(null);case 40:return e.next=42,o[2].replaceTrack(null);case 42:t.localMainVideoTrack=null,t._mediaSettings=gA(_A({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),s.push(1,2);case 45:if(!t.isMainStreamPublished&&!t.isAuxStreamPublished){e.next=52;break}return e.next=48,t.setTransceiverDirection(bC.INACTIVE,s);case 48:return e.next=50,t.doPublishChange(!1);case 50:e.next=54;break;case 52:return e.next=54,t.doUnpublish();case 54:t.uninstallTrackMuteEvents(n,r),null==r||r.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"});case 56:case"end":return e.stop()}}),e)}))()}))}},{key:"doPublishChange",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return bA(this,null,f().mark((function t(){var n,r;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n={state:this.publishState,constraintConfig:this._mediaSettings},t.next=3,this._signalChannel.sendWaitForResponse({command:sW,data:n,responseCommand:aW.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});case 3:r=t.sent,this.checkPublishResultCode(r.data.code,r.data.message);case 5:case"end":return t.stop()}}),t,this)})))}},{key:"doUnpublish",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this._signalChannel.sendWaitForResponse({command:cW,commandDesc:"unpublish",responseCommand:aW.UNPUBLISH_RESULT,enableLog:e}).catch((function(e){if(e.getCode()===VA.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}},{key:"updateMediaSettings",value:function(){var e=this._room.checkSystemResult.detail,t=e.isH264EncodeSupported,n=e.isVp8EncodeSupported;t?this._mediaSettings.videoCodec="H264":n&&(this._mediaSettings.videoCodec="VP8");var r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,i=this.localMainVideoTrack,a=this.localAuxVideoTrack;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?a=this._publishingLocalVideoTrack:i=this._publishingLocalVideoTrack),FP){if(r&&r.outMediaTrack){var o=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=o.channelCount||1,this._mediaSettings.audioBps=1e3*r.profile.bitrate,this._mediaSettings.audioFs=o.sampleRate||0}if(i&&i.outMediaTrack){var s=i.outMediaTrack.getSettings();this._mediaSettings.videoWidth=s.width||0,this._mediaSettings.videoHeight=s.height||0,this._mediaSettings.videoFps=s.frameRate||0,this._mediaSettings.videoBps=1e3*i.profile.bitrate,i.small&&(this._mediaSettings.smallVideoWidth=i.small.width,this._mediaSettings.smallVideoHeight=i.small.height,this._mediaSettings.smallVideoFps=i.small.frameRate,this._mediaSettings.smallVideoBps=1e3*i.small.bitrate)}if(a&&a.outMediaTrack){var c=a.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=c.width||0,this._mediaSettings.auxVideoHeight=c.height||0,this._mediaSettings.auxVideoFps=c.frameRate||0,this._mediaSettings.auxVideoBps=1e3*a.profile.bitrate}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=1e3*r.profile.bitrate,this._mediaSettings.audioFs=r.profile.sampleRate),i&&i.outMediaTrack&&(this._mediaSettings.videoWidth=i.profile.width,this._mediaSettings.videoHeight=i.profile.height,this._mediaSettings.videoFps=i.profile.frameRate,this._mediaSettings.videoBps=1e3*i.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}},{key:"sendMediaSettings",value:function(){var e=this;this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:dW,data:this._mediaSettings,responseCommand:aW.UPDATE_CONSTRAINT_CONFIG_RES}).then((function(t){0!==t.data.code&&e._log.warn(t.data.message)})).catch((function(){}))}},{key:"addTrack",value:function(e){return bA(this,null,f().mark((function t(){var n;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this._peerConnection){t.next=2;break}return t.abrupt("return");case 2:if(n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack,this._log.info("is adding ".concat(e.kind," track to current published local ").concat(n?IC.AUXILIARY:IC.MAIN," stream")),!xP()){t.next=9;break}return t.next=7,this.addTrackByTransceiver(e,n);case 7:t.next=11;break;case 9:return t.next=11,this.addTrackBySender(e);case 11:case"end":return t.stop()}}),t,this)})))}},{key:"addTrackByTransceiver",value:function(e,t){return bA(this,null,f().mark((function n(){var r,i,a;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(e.mediaTrack){n.next=2;break}return n.abrupt("return");case 2:if(i=this._peerConnection.getTransceivers(),e.kind!==IC.AUDIO){n.next=8;break}return n.next=6,i[0].sender.replaceTrack(e.outMediaTrack);case 6:n.next=19;break;case 8:return a=t?3:1,n.next=11,i[a].sender.replaceTrack(e.outMediaTrack);case 11:if(n.t0=1===a&&null!=(r=this.localMainVideoTrack)&&r.small,!n.t0){n.next=15;break}return n.next=15,i[2].sender.replaceTrack(this._room.videoManager.smallTrack);case 15:if(n.t1=i[a].direction===bC.INACTIVE,!n.t1){n.next=19;break}return n.next=19,this.setTransceiverDirection(bC.SENDONLY,[a]);case 19:return this.updateMediaSettings(),n.next=22,this.doPublishChange();case 22:case"end":return n.stop()}}),n,this)})))}},{key:"addTrackBySender",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a,o;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(e.outMediaTrack){t.next=2;break}return t.abrupt("return");case 2:if(n=e.outMediaTrack,t.t0=NP()&&this._peerConnection.getTransceivers().findIndex((function(e){return"stopped"===e.direction}))>=0,!t.t0){t.next=8;break}return this._log.warn("transceiver is stopping, negotiate sdp first"),t.next=8,this.updateOffer("remove",n);case 8:if(r=this._peerConnection.getSenders().find((function(e){return e.track&&e.track.kind===n.kind})),!r||!r.track){t.next=15;break}return this._log.warn("sender already exists, remove sender first"),i=r.track,this.removeSender(r),t.next=15,this.updateOffer("remove",i);case 15:return n&&this._peerConnection.addTrack(n,new MediaStream([n])),n.kind===IC.VIDEO&&e instanceof oV&&e.small&&(a=new MediaStream,o=this._room.videoManager.smallTrack,a.addTrack(o),this._peerConnection.addTrack(o,a)),t.next=18,this.updateOffer("add",n);case 18:case"end":return t.stop()}}),t,this)})))}},{key:"isNeedToResetOfferOrder",value:function(){if(this._sdpSemantics===aw||!this._peerConnection||!this._peerConnection.localDescription)return!1;for(var e=this._peerConnection.localDescription.sdp,t=kW(e),n=0;n<t.media.length;n++)if(0===Number(t.media[n].mid)&&t.media[n].type===IC.VIDEO)return!0;return!1}},{key:"removeSender",value:function(e){var t=null;NP()&&(t=this._peerConnection.getTransceivers().find((function(t){return t.sender&&t.sender.track===e.track}))),this._peerConnection.removeTrack(e),t&&Jw(t.stop)&&(this._log.info("stop transceiver"),t.stop())}},{key:"removeTrack",value:function(e){return bA(this,null,f().mark((function t(){var n;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this._peerConnection){t.next=2;break}return t.abrupt("return");case 2:if(n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack,this._log.info("is removing ".concat(e.kind," track from current published local ").concat(n?IC.AUXILIARY:IC.MAIN," stream")),!xP()){t.next=9;break}return t.next=7,this.removeTrackByTransceiver(e,n);case 7:t.next=11;break;case 9:return t.next=11,this.removeTrackBySender(e);case 11:case"end":return t.stop()}}),t,this)})))}},{key:"removeTrackByTransceiver",value:function(e,t){return bA(this,null,f().mark((function n(){var r,i;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(e.outMediaTrack){n.next=2;break}return n.abrupt("return");case 2:if(r=this._peerConnection.getTransceivers(),e.kind!==IC.AUDIO){n.next=8;break}return n.next=6,r[0].sender.replaceTrack(null);case 6:n.next=17;break;case 8:return i=t?3:1,n.next=11,r[i].sender.replaceTrack(null);case 11:if(n.t0=1===i&&e.small,!n.t0){n.next=15;break}return n.next=15,r[2].sender.replaceTrack(null);case 15:return n.next=17,this.setTransceiverDirection(bC.INACTIVE,[i]);case 17:return this.updateMediaSettings(),n.next=20,this.doPublishChange();case 20:case"end":return n.stop()}}),n,this)})))}},{key:"setTransceiverDirection",value:function(e,t){return bA(this,null,f().mark((function n(){var r,i,a,o,s,c;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(rN){n.next=2;break}return n.abrupt("return");case 2:if(r=!1,i=!1,this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e)),a=this._peerConnection.getTransceivers(),t.forEach((function(t){a[t].direction!==e&&(a[t].direction=e,r=!0)})),!r){n.next=12;break}return this._log.info("updating offer"),n.next=9,this._peerConnection.createOffer();case 9:return o=n.sent,n.next=12,this.setOffer(o);case 12:if(s=-1,c=this._peerConnection.remoteDescription.sdp.split("\r\n").map((function(n){if(n.match(new RegExp("a=(".concat(bC.INACTIVE,"|").concat(bC.RECVONLY,"|").concat(bC.SENDONLY,")")))&&s++,t.includes(s)){if(e===bC.INACTIVE&&n.includes("a=".concat(bC.RECVONLY)))return i=!0,"a=".concat(e);if(e===bC.SENDONLY&&n.includes("a=".concat(bC.INACTIVE)))return i=!0,"a=".concat(bC.RECVONLY)}return n})).join("\r\n"),n.t0=i,!n.t0){n.next=18;break}return this._log.info("updating answer"),n.next=18,this.setAnswer({type:"answer",sdp:c});case 18:case"end":return n.stop()}}),n,this)})))}},{key:"removeTrackBySender",value:function(e){return bA(this,null,f().mark((function t(){var n,r=this;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(e.outMediaTrack){t.next=2;break}return t.abrupt("return");case 2:if(e.kind!==IC.VIDEO||!this.isNeedToResetOfferOrder()||!this.localMainAudioTrack){t.next=8;break}return this.reset(),this.initialize(),t.next=7,this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1});case 7:return t.abrupt("return",void t.sent);case 8:return(n=this._peerConnection.getSenders().find((function(t){return t.track===e.outMediaTrack})))&&(this.removeSender(n),e.kind===IC.VIDEO&&e.small&&this._peerConnection.getSenders().forEach((function(e){e.track&&e.track.kind===IC.VIDEO&&r.removeSender(e)}))),t.next=12,this.updateOffer("remove",e.outMediaTrack);case 12:case"end":return t.stop()}}),t,this)})))}},{key:"replaceTrack",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if((i=null==(n=this._peerConnection)?void 0:n.getSenders())&&0!==i.length&&e.mediaTrack){t.next=3;break}return t.abrupt("return",!1);case 3:if(r=xP()?e.kind===IC.AUDIO?i[0]:i[1]:i.find((function(t){return t.track&&t.track.kind===e.kind})),r){t.next=5;break}return t.abrupt("return",!1);case 5:if(a=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack,this._log.info("is replacing ".concat(e.kind," track on ").concat(a?IC.AUXILIARY:IC.MAIN," stream")),e.kind!==IC.AUDIO){t.next=12;break}return t.next=10,r.replaceTrack(e.outMediaTrack);case 10:case 19:t.next=23;break;case 12:if(t.t0=e.kind===IC.VIDEO,!t.t0){t.next=23;break}if(!a){t.next=21;break}if(t.t1=i[3],!t.t1){t.next=19;break}return t.next=19,i[3].replaceTrack(e.outMediaTrack);case 21:return t.next=23,r.replaceTrack(e.outMediaTrack);case 23:return t.abrupt("return",!0);case 24:case"end":return t.stop()}}),t,this)})))}},{key:"updateOffer",value:function(e,t){return bA(this,null,f().mark((function n(){var r,i,a,o,s,c,u;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.prev=0,n.next=3,this._peerConnection.createOffer(RW);case 3:return r=n.sent,rN&&r.sdp&&(r.sdp=this.setSDPDirection(r.sdp,"sendrecv")),n.next=7,this.setOffer(r);case 7:return i=this.updateMediaSettings(),a={action:e,trackId:t.id,kind:t.kind===IC.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:i,state:this.publishState},this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug("updatedOffer: ".concat(a.sdp)),n.next=11,this._signalChannel.sendWaitForResponse({command:"publish_change",data:a,responseCommand:aW.UPDATE_OFFER_RESULT,timeout:nw,commandDesc:"update offer"});case 11:return o=n.sent,s=o.data,c=s.code,u=s.message,0!==c&&this.checkPublishResultCode(c,u),n.next=18,this.acceptAnswer(o.data.data);case 18:r.sdp&&this.updateSSRC(r.sdp),n.next=24;break;case 21:throw n.prev=21,n.t0=n.catch(0),this._log.error(n.t0),n.t0;case 24:case"end":return n.stop()}}),n,this,[[0,21]])})))}},{key:"setBandwidth",value:function(e){return bA(this,arguments,(function(e){var t=this,n=e.bandwidth,r=e.type,i=e.videoType,a=e.sdp;return f().mark((function e(){var o,s,c,u;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(VP()){e.next=2;break}return e.abrupt("return",a?r===IC.VIDEO?t.updateVideoBandwidthRestriction(a,n,i):t.updateAudioBandwidthRestriction(a,n):void 0);case 2:if(s=t._peerConnection.getSenders(),xP()?(c=0,r===IC.VIDEO&&(c=i===IC.SMALL?2:i===IC.AUXILIARY?3:1),o=s[c]):o=s.find((function(e){return e.track&&e.track.kind===r})),!o){e.next=18;break}return(!(u=o.getParameters()).encodings||0===u.encodings.length)&&(u.encodings=[{}]),u.encodings[0].maxBitrate=1e3*n,e.prev=7,e.next=10,o.setParameters(u);case 10:return t._log.info("".concat(i||"").concat(r," bandwidth ").concat(n," kbps")),e.abrupt("return",a);case 14:if(e.prev=14,e.t0=e.catch(7),t._log.info("failed to set bandwidth by setting maxBitrate: ".concat(e.t0)),!a){e.next=18;break}return e.abrupt("return",r===IC.VIDEO?t.updateVideoBandwidthRestriction(a,n,i):t.updateAudioBandwidthRestriction(a,n));case 18:return e.abrupt("return",a);case 19:case"end":return e.stop()}}),e,null,[[7,14]])}))()}))}},{key:"updateVideoBandwidthRestriction",value:function(e,t,n){var r="AS";rN&&(r="TIAS",t*=1e3);var i=0,a=-1;return n===IC.SMALL?i=1:n===IC.AUXILIARY&&(i=2),e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,(function(e){return(a+=1)===i?"".concat(e,"b=").concat(r,":").concat(t,"\r\n"):e}))}},{key:"updateAudioBandwidthRestriction",value:function(e,t){var n="AS";return rN&&(n="TIAS",t*=1e3),e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,"m=audio $1\r\nc=IN $2\r\nb=".concat(n,":").concat(t,"\r\n"))}},{key:"removeBandwidthRestriction",value:function(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}},{key:"removeVideoOrientation",value:function(e){return e.replace(/urn:3gpp:video-orientation/,"")}},{key:"connect",value:function(){return bA(this,null,f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.exchangeSDP();case 3:return e.next=5,this.waitForPeerConnectionConnected();case 5:e.next=10;break;case 7:throw e.prev=7,e.t0=e.catch(0),this.closePeerConnection(!0),this.uninstallEvents(),e.t0;case 10:case"end":return e.stop()}}),e,this,[[0,7]])})))}},{key:"exchangeSDP",value:function(){return bA(this,null,f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.createOffer();case 3:return this._log.info("createOffer success, sending offer to remote server"),e.next=6,this.doExchangeSDP();case 6:e.next=11;break;case 8:throw e.prev=8,e.t0=e.catch(0),e.t0;case 11:case"end":return e.stop()}}),e,this,[[0,8]])})))}},{key:"createOffer",value:function(){return bA(this,null,f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this._peerConnection.createOffer(RW);case 3:return t=e.sent,e.next=6,this.setOffer(t);case 6:t.sdp&&this.updateSSRC(t.sdp),e.next=12;break;case 9:throw e.prev=9,e.t0=e.catch(0),e.t0;case 12:case"end":return e.stop()}}),e,this,[[0,9]])})))}},{key:"doExchangeSDP",value:function(){var e=this,t={command:"publish",responseCommand:aW.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof uV||this.localAuxVideoTrack instanceof uV,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug("sending sdp offer: ".concat(t.data.sdp)),this._signalChannel.sendWaitForResponse(t).then((function(t){var n=t.data,r=n.code,i=n.message,a=n.data;return 0===r?e.acceptAnswer(a):e.checkPublishResultCode(r,i)}))}},{key:"setSDPDirection",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"all",r=kW(e);return r.media.forEach((function(e){("all"===n||e.type===n)&&(e.direction=t)})),TW(r)}},{key:"acceptAnswer",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a,o,s,c,u,l,d,h;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(t.prev=0,!(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished)){t.next=13;break}if(c=(null==(n=this._publishingLocalVideoTrack)?void 0:n.profile.bitrate)||(null==(r=this.localMainVideoTrack)?void 0:r.profile.bitrate),u=(null==(i=this._publishingLocalAudioTrack)?void 0:i.profile.bitrate)||(null==(a=this.localMainAudioTrack)?void 0:a.profile.bitrate),!c){t.next=8;break}return l=this._isPublishingAux?IC.AUXILIARY:IC.BIG,t.next=7,this.setBandwidth({bandwidth:c,type:IC.VIDEO,sdp:s,videoType:l});case 7:s=t.sent;case 8:if(t.t0=u,!t.t0){t.next=13;break}return t.next=12,this.setBandwidth({bandwidth:u,type:IC.AUDIO,sdp:s});case 12:s=t.sent;case 13:if(s=this.removeVideoOrientation(e.sdp),null==(o=this._publishingLocalVideoTrack)||!o.small){t.next=18;break}return d=this._room.smallStreamConfig,t.next=17,this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||d.bitrate,type:IC.VIDEO,videoType:IC.SMALL,sdp:s});case 17:s=t.sent;case 18:return h={type:e.type,sdp:s},t.next=21,this.setAnswer(h);case 21:this._log.debug("accepted answer: ".concat(s)),t.next=27;break;case 24:throw t.prev=24,t.t1=t.catch(0),this._log.error("failed to accept remote answer ".concat(t.t1)),t.t1;case 27:case"end":return t.stop()}}),t,this,[[0,24]])})))}},{key:"sendMutedFlag",value:function(e){var t,n,r;if(e!==this.localAuxAudioTrack&&e!==this.localAuxVideoTrack){var i={audio:!(null==(t=this.localMainAudioTrack)||!t.muted),bigVideo:!(null==(n=this.localMainVideoTrack)||!n.muted),auxVideo:!(null==(r=this.localAuxVideoTrack)||!r.muted)};this._log.info("send muted state: ".concat(JSON.stringify(i))),this._signalChannel.send(oW,i)}}},{key:"getIsReconnecting",value:function(){return this._isReconnecting}},{key:"reconnect",value:function(){return bA(this,null,f().mark((function e(){var t,n=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(IA(i.prototype,this,"beforeReconnect").call(this)<0){e.next=22;break}return e.prev=1,e.next=4,this._signalChannel.sendWaitForResponse({command:cW,responseCommand:aW.UNPUBLISH_RESULT,enableLog:!1});case 4:if(this.closePeerConnection(),this.initialize(),e.t0=this.isMainStreamPublished,!e.t0){e.next=10;break}return e.next=10,this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1});case 10:if(e.t1=this.isAuxStreamPublished,!e.t1){e.next=14;break}return e.next=14,this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0});case 14:this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection(),e.next=22;break;case 18:e.prev=18,e.t2=e.catch(1),t=jw(this._reconnectionCount),this._log.warn("reconnect() timeout, try again after ".concat(t/1e3,"s")),this._reconnectionTimer=setTimeout((function(){n.clearReconnectionTimer(),n.reconnect()}),t);case 22:case"end":return e.stop()}}),e,this,[[1,18]])})))}},{key:"handleConnectionStateChange",value:function(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&Px.emit(Lx.SEND_FIRST_VIDEO_FRAME,{room:this._room})}},{key:"updateSSRC",value:function(e){var t=this;try{kW(e).media.forEach((function(e,n){if(e.type===IC.AUDIO){var r=e.ssrcs&&e.ssrcs[0];r&&(t.ssrc.audio=Number(r.id))}else{if(t._sdpSemantics===aw&&e.ssrcGroups)return void e.ssrcGroups.forEach((function(e,n){var r=Number(e.ssrcs.split(" ")[0]);0===n?t.ssrc.video=r:1===n&&(t.ssrc.small=r)}));var i=e.ssrcs&&e.ssrcs[0];if(!i)return;switch(n){case 1:t.ssrc.video=Number(i.id);break;case 2:t.ssrc.small=Number(i.id);break;case 3:t.ssrc.auxiliary=Number(i.id)}}}))}catch(ZC){}}},{key:"getVideoTrackId",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:IC.VIDEO;if(this._peerConnection){var t=this._peerConnection.getSenders();if(e===IC.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===IC.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===IC.VIDEO){var n=this.localMainVideoTrack.mediaTrack;if(n)return n.id}if(this.localAuxVideoTrack&&e===IC.AUXILIARY){var r=this.localAuxVideoTrack.mediaTrack;if(r)return r.id}return""}},{key:"getSSRC",value:function(){return this.ssrc}},{key:"checkPublishResultCode",value:function(e,t){if(0!==e)throw e===ow?(this._log.error(GO.NOT_SUPPORTED_H264ENCODE),new FA({code:VA.NOT_SUPPORTED_H264,message:YO({key:jO.NOT_SUPPORTED_H264ENCODE})})):new FA({code:VA.UNKNOWN,message:YO({key:jO.SIGNAL_RESPONSE_FAILED,data:{signalResponse:aW.PUBLISH_RESULT,code:e,message:t}})})}}])}(yW);TA([jL((function(e){return function(){for(var t=this,n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return new Promise((function(n,i){var a=function(e){t._emitter.off("closed",a),i(new FA({code:VA.API_CALL_ABORTED,message:YO({key:jO.CONNECTION_ABORTED,data:e})}))};t._emitter.on("closed",a),e.apply(t,r).then(n,i).finally((function(){t._emitter.off("closed",a)}))}))}}))],AW.prototype,"publish",1),TA([ZL(521715,!1)],AW.prototype,"unpublish",1),TA([HL(yW.prototype.afterConnect),BL(yW.prototype.beforeConnect)],AW.prototype,"connect",1);var CW=AW,wW=function(){return o((function e(t,n){r(this,e),this.room=t,SA(this,"_log"),SA(this,"_prevReportTime",0),SA(this,"_prevReport",{}),SA(this,"_prevStats",null),SA(this,"_prevEncoderImplementation",""),SA(this,"_prevAuxEncoderImpl",""),SA(this,"_prevQualityLimitationReason",""),SA(this,"_prevAuxQualityLimitationReason",""),SA(this,"_prevDecoderImplementationMap",new Map),SA(this,"totalBytesSent",0),SA(this,"totalBytesReceived",0),SA(this,"_spcStats",null),this._log=n}),[{key:"statInterval",get:function(){return 0===this._prevReportTime?2:(Date.now()-this._prevReportTime)/1e3}},{key:"getSenderStats",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a,o,s=this;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(r={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},i=e.getPeerConnection(),a=e.getSSRC(),!i){t.next=18;break}if(t.prev=2,t.t0=this._spcStats,t.t0){t.next=8;break}return t.next=7,i.getStats();case 7:t.t0=t.sent;case 8:if(t.t0.forEach((function(t){var n,i,o,c;if("outbound-rtp"===t.type)if((t.mediaType||t.kind)===IC.VIDEO){if(t.ssrc===a.video?(c=IC.VIDEO,e.localMainVideoTrack):t.ssrc===a.small?c=IC.SMALL:t.ssrc===a.auxiliary&&(e.localAuxVideoTrack,c=IC.AUXILIARY),!c)return;if(r[c].bytesSent=t.bytesSent,r[c].packetsSent=t.packetsSent,r[c].framesEncoded=t.framesEncoded,Kw(t.keyFramesEncoded)||(r[c].keyFramesEncoded=t.keyFramesEncoded),Kw(t.nackCount)||(r[c].nackCount=t.nackCount),Kw(t.pliCount)||(r[c].pliCount=t.pliCount),Kw(t.retransmittedPacketsSent)||(r[c].retransmittedPacketsSent=t.retransmittedPacketsSent),Kw(t.totalEncodeTime)||(r[c].totalEncodeTime=t.totalEncodeTime),Kw(t.totalPacketSendDelay)||(r[c].totalPacketSendDelay=t.totalPacketSendDelay),!Kw(t.encoderImplementation)&&(c===IC.VIDEO&&s._prevEncoderImplementation!==t.encoderImplementation||c===IC.AUXILIARY&&s._prevAuxEncoderImpl!==t.encoderImplementation)){var u=2,l=s._prevEncoderImplementation;c===IC.AUXILIARY&&(u=7,l=s._prevAuxEncoderImpl),Px.emit("262",{userId:e.userId,streamType:u,prevImplementation:l,implementation:t.encoderImplementation,codec:e.videoCodec,isHWCodec:t.powerEfficientEncoder}),s[c===IC.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=t.encoderImplementation,s._log.info("".concat(c===IC.AUXILIARY?"aux ":"","encoderImplementation change to ").concat(t.encoderImplementation,"(").concat(e.videoCodec,") HWEncoder: ").concat(t.powerEfficientEncoder))}t.ssrc===a.video?!Kw(t.qualityLimitationReason)&&0!==t.bytesSent&&s._prevQualityLimitationReason!==t.qualityLimitationReason&&(s._log.info("qualityLimitationReason change to ".concat(t.qualityLimitationReason)),Px.emit("263",{userId:e.userId,reason:t.qualityLimitationReason,prevReason:s._prevQualityLimitationReason,streamType:2,isQosClearFirst:null==(n=e.localMainVideoTrack)?void 0:n.isQosClearFirst}),s._prevQualityLimitationReason=t.qualityLimitationReason):t.ssrc===a.auxiliary&&!Kw(t.qualityLimitationReason)&&0!==t.bytesSent&&s._prevAuxQualityLimitationReason!==t.qualityLimitationReason&&(s._log.info("aux qualityLimitationReason change to ".concat(t.qualityLimitationReason)),Px.emit("263",{userId:e.userId,reason:t.qualityLimitationReason,prevReason:s._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:null==(i=e.localAuxVideoTrack)?void 0:i.isQosClearFirst}),s._prevAuxQualityLimitationReason=t.qualityLimitationReason)}else r.audio.bytesSent=t.bytesSent,r.audio.packetsSent=t.packetsSent;else"candidate-pair"===t.type?EP(t)&&(s.totalBytesSent=t.bytesSent,zw(t.currentRoundTripTime)&&(r.rtt=Math.floor(1e3*t.currentRoundTripTime))):"media-source"===t.type&&(t.kind===IC.AUDIO?(r.audio.audioLevel=t.audioLevel||0,r.audio.totalAudioEnergy=t.totalAudioEnergy||0,t.echoReturnLoss,t.totalSamplesDuration&&(r.audio.totalSamplesDuration=t.totalSamplesDuration)):t.kind===IC.VIDEO&&(t.trackIdentifier===e.getVideoTrackId(IC.VIDEO)?r.video.fpsCapture=t.framesPerSecond:t.trackIdentifier===e.getVideoTrackId(IC.AUXILIARY)?r.auxiliary.fpsCapture=t.framesPerSecond:r.small.fpsCapture=t.framesPerSecond));if(!Kw(t.audioLevel)&&null!=(o=e.localMainAudioTrack)&&o.mediaTrack&&t.trackIdentifier===e.localMainAudioTrack.mediaTrack.id&&(r.audio.audioLevel=t.audioLevel||0),!Kw(t.frameWidth)){var d=IC.SMALL;t.trackIdentifier===e.getVideoTrackId(IC.VIDEO)||t.ssrc===a.video?d=IC.VIDEO:(t.trackIdentifier===e.getVideoTrackId(IC.AUXILIARY)||t.ssrc===a.auxiliary)&&(d=IC.AUXILIARY),r[d].frameWidth=t.frameWidth,r[d].frameHeight=t.frameHeight,r[d].framesSent=t.framesSent}})),!e.localMainAudioTrack){t.next=12;break}o=e.localMainAudioTrack.getInternalAudioLevel(),r.audio.micAudioLevel=o,0===r.audio.audioLevel&&(r.audio.audioLevel=o);case 12:this.totalBytesSent||(this.totalBytesSent+=r.audio.bytesSent+r.video.bytesSent+r.auxiliary.bytesSent),Object.keys(r).forEach((function(t){t===IC.AUDIO?(e.localMainAudioTrack&&(e.localMainAudioTrack.stat=r[t]),e.localAuxAudioTrack&&(e.localAuxAudioTrack.stat=r[t])):t===IC.VIDEO?e.localMainVideoTrack&&(e.localMainVideoTrack.stat=r[t]):t===IC.AUXILIARY&&e.localAuxVideoTrack&&(e.localAuxVideoTrack.stat=r[t])})),t.next=18;break;case 15:t.prev=15,t.t1=t.catch(2),this._log.warn("failed to getStats on sender connection ".concat(t.t1));case 18:return t.abrupt("return",(0===r.rtt&&(r.rtt=(null==(n=this.room.networkQuality)?void 0:n.uplinkRTT)||0),r));case 19:case"end":return t.stop()}}),t,this,[[2,15]])})))}},{key:"getReceiverStats",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a,o,s,c,u,l=this;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(a={tinyId:e.tinyId,userId:e.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0,p2pDelay:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0,p2pDelay:0}},!(o=e.getPeerConnection())){t.next=19;break}if(t.prev=2,s=e.ssrc,c=e.muteState,u=e.subscribeState,t.t0=this._spcStats,t.t0){t.next=9;break}return t.next=8,o.getStats();case 8:t.t0=t.sent;case 9:t.t0.forEach((function(t){if("inbound-rtp"===t.type){var n=(t.mediaType||t.kind)===IC.AUDIO;if(n){if(t.ssrc!==s.audio||!c.hasAudio)return;a.audio.packetsReceived=t.packetsReceived,a.audio.bytesReceived=t.bytesReceived,a.audio.packetsLost=t.packetsLost,t.insertedSamplesForDeceleration&&(a.audio.insertedSamplesForDeceleration=t.insertedSamplesForDeceleration),t.removedSamplesForAcceleration&&(a.audio.removedSamplesForAcceleration=t.removedSamplesForAcceleration),t.totalSamplesDuration&&(a.audio.totalSamplesDuration=t.totalSamplesDuration),t.totalSamplesReceived&&(a.audio.totalSamplesReceived=t.totalSamplesReceived),t.concealedSamples&&(a.audio.concealedSamples=t.concealedSamples),t.silentConcealedSamples&&(a.audio.silentConcealedSamples=t.silentConcealedSamples);var r=e.remoteAudioTrack;r.stat.packetsReceived=t.packetsReceived,r.stat.bytesReceived=t.bytesReceived,r.stat.packetsLost=t.packetsLost,a.audio.p2pDelay=r.stat.end2EndDelay,a.hasAudio=!0}else{if(rN&&0===t.bytesReceived)return;var i;t.ssrc===s.video&&c.hasVideo&&(a.video.packetsReceived=t.packetsReceived,a.video.bytesReceived=t.bytesReceived,a.video.packetsLost=t.packetsLost,a.video.framesReceived=t.framesReceived,a.video.framesDecoded=t.framesDecoded,a.video.fpsDecoded=t.framesPerSecond,a.hasVideo=!0,i=e.remoteVideoTrack,c.hasSmall&&u.smallVideo&&(a.isSmallSubscribed=!0),t.decoderImplementation&&(!l._prevDecoderImplementationMap.has(a.userId)||l._prevDecoderImplementationMap.get(a.userId)!==t.decoderImplementation)&&(l._log.info("".concat(a.userId," decoderImplementation change to ").concat(t.decoderImplementation," HWDecoder: ").concat(t.powerEfficientDecoder)),Px.emit("262",{userId:l.room.userId,remoteUserId:a.userId,prevImplementation:l._prevDecoderImplementationMap.get(a.userId),implementation:t.decoderImplementation,codec:e.videoCodec,isHWCodec:t.powerEfficientDecoder}),l._prevDecoderImplementationMap.set(a.userId,t.decoderImplementation))),t.ssrc===s.auxiliary&&c.hasAuxiliary&&(a.auxiliary.packetsReceived=t.packetsReceived,a.auxiliary.bytesReceived=t.bytesReceived,a.auxiliary.packetsLost=t.packetsLost,a.auxiliary.framesReceived=t.framesReceived,a.auxiliary.framesDecoded=t.framesDecoded,a.auxiliary.fpsDecoded=t.framesPerSecond,i=e.remoteAuxiliaryTrack,a.auxiliary.p2pDelay=i.stat.end2EndDelay,a.hasAuxiliary=!0),i&&(i.stat.packetsReceived=t.packetsReceived,i.stat.bytesReceived=t.bytesReceived,i.stat.packetsLost=t.packetsLost,i.stat.framesReceived=t.framesReceived,i.stat.framesDecoded=t.framesDecoded,t.jitterBufferDelay&&(i.stat.jitterBufferDelay=Math.floor(t.jitterBufferDelay/t.jitterBufferEmittedCount*1e3)),a.video.p2pDelay=i.stat.end2EndDelay)}t.jitterBufferDelay&&(n?(a.audio.totalJitter=t.jitterBufferDelay,a.audio.totalJitterCount=t.jitterBufferEmittedCount):t.ssrc===s.video&&c.hasVideo?(a.video.totalJitter=t.jitterBufferDelay,a.video.totalJitterCount=t.jitterBufferEmittedCount):t.ssrc===s.auxiliary&&c.hasAuxiliary&&(a.auxiliary.totalJitter=t.jitterBufferDelay,a.auxiliary.totalJitterCount=t.jitterBufferEmittedCount))}else"candidate-pair"===t.type&&EP(t)&&(l.totalBytesReceived=t.bytesReceived,zw(t.currentRoundTripTime)&&(a.rtt=Math.floor(1e3*t.currentRoundTripTime)));Kw(t.frameWidth)||((t.trackIdentifier===e.getMainStreamVideoTrackId()||t.ssrc===s.video)&&(a.video.frameWidth=t.frameWidth,a.video.frameHeight=t.frameHeight,e.remoteVideoTrack.stat.frameWidth=t.frameWidth,e.remoteVideoTrack.stat.frameHeight=t.frameHeight),(t.trackIdentifier===e.getAuxStreamVideoTrackId()||t.ssrc===s.auxiliary)&&(a.auxiliary.frameWidth=t.frameWidth,a.auxiliary.frameHeight=t.frameHeight,e.remoteAuxiliaryTrack.stat.frameWidth=t.frameWidth,e.remoteAuxiliaryTrack.stat.frameHeight=t.frameHeight)),!Kw(t.audioLevel)&&e.muteState.audioAvailable&&e.remoteAudioTrack.mediaTrack&&t.trackIdentifier===e.remoteAudioTrack.mediaTrack.id&&(a.audio.audioLevel=t.audioLevel||0,a.audio.totalAudioEnergy=t.totalAudioEnergy||0)})),0===a.audio.audioLevel&&e.muteState.audioAvailable&&(a.audio.audioLevel=e.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=a.audio.bytesReceived+a.video.bytesReceived+a.auxiliary.bytesReceived),Kw(null==(n=e.remoteVideoTrack.player.stat)?void 0:n.fps)||(a.video.fpsRender=e.remoteVideoTrack.player.stat.fps),Kw(null==(r=e.remoteAuxiliaryTrack.player.stat)?void 0:r.fps)||(a.auxiliary.fpsRender=e.remoteAuxiliaryTrack.player.stat.fps),t.next=19;break;case 16:t.prev=16,t.t1=t.catch(2),this._log.warn("failed to getStats on receiver connection ".concat(t.t1));case 19:return t.abrupt("return",(0===a.rtt&&(a.rtt=(null==(i=this.room.networkQuality)?void 0:i.uplinkRTT)||0),a));case 20:case"end":return t.stop()}}),t,this,[[2,16]])})))}},{key:"getStats",value:function(e,t){return bA(this,null,f().mark((function n(){var r,i,a,o,c,u,l,d,h,p,m,_,g;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(r={},i=[],!this.room.singlePC){n.next=13;break}if(a=this.room.singlePC.getPeerConnection()){n.next=5;break}return n.abrupt("return",{senderStats:r,receiverStats:i});case 5:return o=aD(),n.next=8,a.getStats();case 8:c=n.sent,(u=aD())-o>2e3&&this._log.warn("getStats cost ".concat(u-o,"ms")),l=[],d=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]),c.forEach((function(e){return d.has(e.type)&&l.push(e)})),this._spcStats=l;case 13:if(n.t0=e,!n.t0){n.next=18;break}return n.next=17,this.getSenderStats(e);case 17:r=n.sent;case 18:h=s(t),n.prev=19,h.s();case 21:if((p=h.n()).done){n.next=29;break}return(m=v(p.value,2))[0],_=m[1],n.next=25,this.getReceiverStats(_);case 25:g=n.sent,i.push(g);case 27:n.next=21;break;case 29:n.next=34;break;case 31:n.prev=31,n.t1=n.catch(19),h.e(n.t1);case 34:return n.prev=34,h.f(),n.finish(34);case 37:return n.abrupt("return",{senderStats:r,receiverStats:i});case 38:case"end":return n.stop()}}),n,this,[[19,31,34,37]])})))}},{key:"getDifferenceValue",value:function(e,t){if(PL(e))return t;var n=t-e;return n<0?0:n}},{key:"prepareReport",value:function(e){var t,n,r,i=this,a=e.stats,o=e.report,s=e.freezeMap;if(!PL(a.senderStats)){var c={uint32_audio_level:a.senderStats.audio.audioLevel*xO,uint32_audio_energy:1e6*(a.senderStats.audio.totalAudioEnergy||0),uint32_audio_codec_bitrate:a.senderStats.audio.bytesSent};a.senderStats.audio.micAudioLevel&&(c.uint32_mic_audio_level=a.senderStats.audio.micAudioLevel*xO),a.senderStats.audio.totalSamplesDuration&&(o.msg_device_info.uint32_audio_capture_cost=a.senderStats.audio.totalSamplesDuration);var u=[];if(a.senderStats.video.bytesSent){var l={uint32_video_stream_type:2,uint32_video_codec_fps:a.senderStats.video.framesSent,uint32_video_capture_fps:a.senderStats.video.fpsCapture,uint32_video_width:a.senderStats.video.frameWidth,uint32_video_height:a.senderStats.video.frameHeight,uint32_video_codec_bitrate:a.senderStats.video.bytesSent,uint32_video_enc_fps:a.senderStats.video.framesEncoded,uint32_key_frame_count:a.senderStats.video.keyFramesEncoded,uint32_nack_count:a.senderStats.video.nackCount,uint32_pli_count:a.senderStats.video.pliCount,uint32_encode_cost:1e3*(a.senderStats.video.totalEncodeTime||0),uint32_send_packet_cost:1e3*(a.senderStats.video.totalPacketSendDelay||0),uint32_video_arq_packets:a.senderStats.video.retransmittedPacketsSent};u.push(l)}if(a.senderStats.small.bytesSent){var d={uint32_video_stream_type:3,uint32_video_codec_fps:a.senderStats.small.framesSent||0,uint32_video_capture_fps:a.senderStats.small.fpsCapture||0,uint32_video_width:a.senderStats.small.frameWidth||0,uint32_video_height:a.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:a.senderStats.small.bytesSent,uint32_video_enc_fps:a.senderStats.small.framesEncoded||0,uint32_key_frame_count:a.senderStats.small.keyFramesEncoded,uint32_nack_count:a.senderStats.small.nackCount,uint32_pli_count:a.senderStats.small.pliCount,uint32_encode_cost:1e3*(a.senderStats.small.totalEncodeTime||0),uint32_send_packet_cost:1e3*(a.senderStats.small.totalPacketSendDelay||0),uint32_video_arq_packets:a.senderStats.small.retransmittedPacketsSent};u.push(d)}if(a.senderStats.auxiliary.bytesSent){var h={uint32_video_stream_type:7,uint32_video_codec_fps:a.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:a.senderStats.auxiliary.fpsCapture||0,uint32_video_width:a.senderStats.auxiliary.frameWidth||0,uint32_video_height:a.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:a.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:a.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:a.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:a.senderStats.auxiliary.nackCount,uint32_pli_count:a.senderStats.auxiliary.pliCount,uint32_encode_cost:1e3*(a.senderStats.auxiliary.totalEncodeTime||0),uint32_send_packet_cost:1e3*(a.senderStats.auxiliary.totalPacketSendDelay||0),uint32_video_arq_packets:a.senderStats.auxiliary.retransmittedPacketsSent};u.push(h)}var f={uint32_bitrate:0,uint32_lost:0,uint32_rtt:a.senderStats.rtt};o.msg_up_stream_info={msg_audio_status:c,msg_video_status:u,msg_network_status:f}}var p=null==(t=nL())?void 0:t.playoutStats;p&&(o.msg_device_info.uint32_audio_play_cost=p.totalFramesDuration);var m=this.statInterval;o.msg_down_stream_info=[],a.receiverStats.forEach((function(e){var t={msg_user_info:{str_identifier:e.userId,uint64_tinyid:e.tinyId},msg_network_status:{uint32_rtt:e.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(e.hasAudio){var n={uint32_audio_p2p_delay:e.audio.p2pDelay,uint32_audio_cache_ms:e.audio.totalJitter,uint32_audio_cache_ms_count:e.audio.totalJitterCount,uint32_audio_codec_bitrate:e.audio.bytesReceived,uint32_audio_total_bitrate:e.audio.bytesReceived,uint32_audio_level:1e8*e.audio.audioLevel,uint32_audio_energy:1e6*e.audio.totalAudioEnergy,uint32_audio_receive:e.audio.packetsReceived,uint32_audio_origin_lost:e.audio.packetsLost};t.msg_audio_status=n}if(e.hasVideo){var r=s.get("".concat(e.userId,"_").concat(UC)),i=r?r.duration:0,a={uint32_video_stream_type:e.isSmallSubscribed?3:2,uint32_video_receive_fps:e.video.framesReceived,uint32_video_width:e.video.frameWidth,uint32_video_height:e.video.frameHeight,uint32_video_codec_bitrate:e.video.bytesReceived,uint32_video_receive:e.video.packetsReceived,uint32_video_origin_lost:e.video.packetsLost,uint32_video_block_time:i,uint32_video_dec_fps:e.video.framesDecoded,uint32_video_codec_fps:e.video.fpsRender,uint32_video_cache_ms:e.video.totalJitter,uint32_video_cache_ms_count:e.video.totalJitterCount,uint32_video_p2p_delay:e.video.p2pDelay};t.msg_video_status.push(a)}if(e.hasAuxiliary){var c=s.get("".concat(e.userId,"_").concat(FC)),u=c?c.duration:0,l={uint32_video_stream_type:7,uint32_video_receive_fps:e.auxiliary.framesReceived,uint32_video_width:e.auxiliary.frameWidth,uint32_video_height:e.auxiliary.frameHeight,uint32_video_codec_bitrate:e.auxiliary.bytesReceived,uint32_video_receive:e.auxiliary.packetsReceived+e.auxiliary.packetsLost,uint32_video_origin_lost:e.auxiliary.packetsLost,uint32_video_block_time:u,uint32_video_dec_fps:e.auxiliary.framesDecoded,uint32_video_codec_fps:e.video.fpsRender,uint32_video_cache_ms:e.auxiliary.totalJitter,uint32_video_cache_ms_count:e.auxiliary.totalJitterCount,uint32_video_p2p_delay:e.auxiliary.p2pDelay};t.msg_video_status.push(l)}o.msg_down_stream_info.push(t)}));var v=this._prevReport,_=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(o)),this._prevStats=JSON.parse(JSON.stringify(a)),o.msg_up_stream_info.msg_audio_status&&v.msg_up_stream_info.msg_audio_status){var g=v.msg_up_stream_info.msg_audio_status,y=o.msg_up_stream_info.msg_audio_status;if(0===g.uint32_audio_codec_bitrate)y.uint32_audio_codec_bitrate=0;else{var E=this.getDifferenceValue(g.uint32_audio_codec_bitrate,y.uint32_audio_codec_bitrate);y.uint32_audio_codec_bitrate=Math.round(8*E/m),o.msg_up_stream_info.msg_network_status.uint32_bitrate+=y.uint32_audio_codec_bitrate}null!=(n=v.msg_device_info)&&n.uint32_audio_capture_cost?o.msg_device_info.uint32_audio_capture_cost=2*Math.floor(1e3*this.getDifferenceValue(v.msg_device_info.uint32_audio_capture_cost,o.msg_device_info.uint32_audio_capture_cost)/m):delete o.msg_device_info.uint32_audio_capture_cost}var k=v.msg_up_stream_info.msg_video_status;o.msg_up_stream_info.msg_video_status.forEach((function(e){var t=k.find((function(t){return t.uint32_video_stream_type===e.uint32_video_stream_type}));if(!t||0===t.uint32_video_codec_bitrate)return e.uint32_video_codec_bitrate=0,e.uint32_video_enc_fps=0,void(e.uint32_video_codec_fps=0);var n=0,r=0,a=0;t&&e.uint32_video_codec_bitrate>=t.uint32_video_codec_bitrate&&(n=t.uint32_video_codec_bitrate,r=t.uint32_video_enc_fps,a=t.uint32_video_codec_fps);var s=i.getDifferenceValue(n,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*s/m),o.msg_up_stream_info.msg_network_status.uint32_bitrate+=e.uint32_video_codec_bitrate,e.uint32_video_enc_fps=Math.round(i.getDifferenceValue(r,e.uint32_video_enc_fps)/m),e.uint32_video_codec_fps=Math.round(i.getDifferenceValue(a,e.uint32_video_codec_fps)/m),0===t.uint32_video_width&&0===t.uint32_video_height&&0===t.uint32_video_codec_fps&&(e.uint32_video_codec_fps=e.uint32_video_enc_fps),Kw(t.uint32_key_frame_count)||(e.uint32_key_frame_count=Math.round(i.getDifferenceValue(t.uint32_key_frame_count,e.uint32_key_frame_count))),Kw(t.uint32_nack_count)||(e.uint32_nack_count=Math.round(i.getDifferenceValue(t.uint32_nack_count,e.uint32_nack_count))),Kw(t.uint32_pli_count)||(e.uint32_pli_count=Math.round(i.getDifferenceValue(t.uint32_pli_count,e.uint32_pli_count))),Kw(t.uint32_video_arq_packets)||(e.uint32_video_arq_packets=Math.round(i.getDifferenceValue(t.uint32_video_arq_packets,e.uint32_video_arq_packets))),Kw(t.uint32_encode_cost)||(e.uint32_encode_cost=Math.round(i.getDifferenceValue(t.uint32_encode_cost,e.uint32_encode_cost)/m)),Kw(t.uint32_send_packet_cost)||(e.uint32_send_packet_cost=Math.round(i.getDifferenceValue(t.uint32_send_packet_cost,e.uint32_send_packet_cost)/m))}));var T=v.msg_down_stream_info;o.msg_down_stream_info=o.msg_down_stream_info.filter((function(e){return T.find((function(t){return t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid}))}));var S=o.msg_down_stream_info;return S.forEach((function(e){var t=T.find((function(t){return t.msg_user_info.uint64_tinyid===e.msg_user_info.uint64_tinyid}));if(PL(e.msg_audio_status)||PL(t.msg_audio_status))e.msg_audio_status={};else{var n=e.msg_audio_status,r=t.msg_audio_status,a=i.getDifferenceValue(r.uint32_audio_cache_ms_count,n.uint32_audio_cache_ms_count);delete n.uint32_audio_cache_ms_count,n.uint32_audio_cache_ms=Math.floor(1e3*i.getDifferenceValue(r.uint32_audio_cache_ms,n.uint32_audio_cache_ms)/a)||0;var o=i.room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);o&&(o.remoteAudioTrack.stat.jitterBufferDelay=n.uint32_audio_cache_ms),n.uint32_audio_origin_lost=i.getDifferenceValue(r.uint32_audio_origin_lost,n.uint32_audio_origin_lost),n.uint32_audio_receive=i.getDifferenceValue(r.uint32_audio_receive,n.uint32_audio_receive),n.uint32_audio_receive+=n.uint32_audio_origin_lost;var s=i.getDifferenceValue(r.uint32_audio_codec_bitrate,n.uint32_audio_codec_bitrate);n.uint32_audio_codec_bitrate=Math.round(8*s/m),n.uint32_audio_total_bitrate=Math.round(8*s/m)}if(e.msg_video_status&&t.msg_video_status){var c=t.msg_video_status;e.msg_video_status=e.msg_video_status.filter((function(e){return c.find((function(t){return t.uint32_video_stream_type===e.uint32_video_stream_type}))})),e.msg_video_status.forEach((function(e){var t=c.find((function(t){return t.uint32_video_stream_type===e.uint32_video_stream_type})),n=t.uint32_video_receive,r=t.uint32_video_origin_lost,a=t.uint32_video_codec_bitrate,o=t.uint32_video_receive_fps,s=t.uint32_video_dec_fps;e.uint32_video_origin_lost=i.getDifferenceValue(r,e.uint32_video_origin_lost),e.uint32_video_receive=i.getDifferenceValue(n,e.uint32_video_receive)+e.uint32_video_origin_lost;var u=i.getDifferenceValue(a,e.uint32_video_codec_bitrate);e.uint32_video_codec_bitrate=Math.round(8*u/m);var l=i.getDifferenceValue(o,e.uint32_video_receive_fps);e.uint32_video_receive_fps=Math.round(l/m),e.uint32_video_dec_fps=Math.round(i.getDifferenceValue(s,e.uint32_video_dec_fps)/m);var d=i.getDifferenceValue(t.uint32_video_cache_ms_count,e.uint32_video_cache_ms_count);delete e.uint32_video_cache_ms_count,e.uint32_video_cache_ms=Math.floor(1e3*i.getDifferenceValue(t.uint32_video_cache_ms,e.uint32_video_cache_ms)/d)||0}))}})),null!=(r=v.msg_device_info)&&r.uint32_audio_play_cost?o.msg_device_info.uint32_audio_play_cost=2*Math.floor(this.getDifferenceValue(v.msg_device_info.uint32_audio_play_cost,o.msg_device_info.uint32_audio_play_cost)/m):delete o.msg_device_info.uint32_audio_play_cost,_&&a.receiverStats.forEach((function(e){if(e.audio.concealedSamples&&e.audio.totalSamplesReceived){var t=_.receiverStats.find((function(t){return t.userId===e.userId}));if(t&&t.audio.concealedSamples&&t.audio.totalSamplesReceived){var n=(e.audio.silentConcealedSamples||0)-(t.audio.silentConcealedSamples||0),r=e.audio.concealedSamples-t.audio.concealedSamples,i=e.audio.totalSamplesReceived-t.audio.totalSamplesReceived,a=Math.floor((r-n)/i*1e3*m);if(a>1e3*m/5){var o=S.find((function(t){return t.msg_user_info.str_identifier===e.userId}));o&&(o.msg_audio_status.uint32_audio_block_time=a)}}}})),o}},{key:"getStatsReport",value:function(e){return bA(this,arguments,(function(e){var t=this,n=e.uplinkConnection,r=e.downlinkConnections,i=e.freezeMap;return f().mark((function e(){var a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return a={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},e.next=3,t.getStats(n,r);case 3:return o=e.sent,e.abrupt("return",("{}"===JSON.stringify(t._prevReport)&&(t._prevReport=JSON.parse(JSON.stringify(a))),t.prepareReport({stats:o,report:a,freezeMap:i}),t._prevReportTime=Date.now(),a));case 5:case"end":return e.stop()}}),e)}))()}))}},{key:"reset",value:function(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}}])}(),DW=function(e){function i(e){var a;r(this,i);var o=e.signalChannel,s=e.room;return a=n(this,i),SA(t(a),"_room"),SA(t(a),"_signalChannel"),SA(t(a),"_log"),SA(t(a),"uplinkRTT",0),SA(t(a),"uplinkLoss",0),SA(t(a),"downlinkRTT",0),SA(t(a),"downlinkLoss",0),SA(t(a),"pingResults",{}),SA(t(a),"_downlinkPrevStatMap",new Map),SA(t(a),"_downlinkLossAndRTTMap",new Map),SA(t(a),"_interval",-1),SA(t(a),"_uplinkNetworkQuality",0),SA(t(a),"_downlinkNetworkQuality",0),a._room=s,a._signalChannel=o,a._log=Ux.createLogger({id:"q",userId:a._room.userId,sdkAppId:a._room.sdkAppId}),a.initialize(),a}return d(i,e),o(i,[{key:"uplinkNetworkQuality",get:function(){return this._uplinkNetworkQuality},set:function(e){e!==this._uplinkNetworkQuality&&this._log.info("uplink ".concat(this.uplinkNetworkQuality," -> ").concat(e,", rtt: ").concat(this.uplinkRTT,", loss: ").concat(this.uplinkLoss," ws-rtt: ").concat(this._signalChannel.rtt)),this._uplinkNetworkQuality=e}},{key:"downlinkNetworkQuality",get:function(){return this._downlinkNetworkQuality},set:function(e){if(e!==this._downlinkNetworkQuality){var t=this.getAverageLossAndRTT(E(this._downlinkLossAndRTTMap.values())),n=t.rtt,r=t.loss;this._log.info("downlink ".concat(this.downlinkNetworkQuality," -> ").concat(e,", rtt: ").concat(n,", loss: ").concat(r," ws-rtt: ").concat(this._signalChannel.rtt))}this._downlinkNetworkQuality=e}},{key:"initialize",value:function(){var e=this;this._signalChannel.on(aW.UPLINK_NETWORK_STATS,(function(t){e.handleUplinkNetworkQuality(t)})),this._signalChannel.on("2",this.handleSignalConnectionStateChange.bind(this)),this.start()}},{key:"handleUplinkNetworkQuality",value:function(e){var t,n;if(0===e.data.code){var r=e.data.data;if(r.delay&&this.updateDelay(r.delay),this._room.signalChannel&&r.wsRtt&&(this._room.signalChannel.rtt=r.wsRtt),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this.uplinkLoss=0,void(this.uplinkRTT=0);var i=null==(n=null==(t=this._room)?void 0:t.uplinkConnection)?void 0:n.getPeerConnection();if(i&&this.isPeerConnectionDisconnected(i))return this.uplinkNetworkQuality=6,this.uplinkLoss=0,void(this.uplinkRTT=0);var a=r.expectAudPkg+r.expectVidPkg,o=r.recvAudPkg+r.recvVidPkg,s=a-o;0===a&&0===o||(this.uplinkLoss=s<=0?0:Math.round(s/a*100),this.uplinkRTT=r.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}}},{key:"handleDownlinkNetworkQuality",value:function(){return bA(this,null,f().mark((function e(){var t,n,r,i,a,o,s,c,u,l,d,h,p,m,v,_=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(0!==this._room.remotePublishedUserMap.size){e.next=2;break}return e.abrupt("return",void(this.downlinkNetworkQuality=0));case 2:if(t=E(this._room.remotePublishedUserMap.values()),n=t.filter((function(e){var t;return(null==(t=e.getPeerConnection())?void 0:t.connectionState)===zC.CONNECTED})),t.filter((function(e){return _.isPeerConnectionDisconnected(e.getPeerConnection())})).length!==t.length){e.next=5;break}return e.abrupt("return",void(this.downlinkNetworkQuality=6));case 5:r=0;case 6:if(!(r<n.length)){e.next=24;break}if(i=n[r].getPeerConnection()){e.next=10;break}return e.abrupt("return");case 10:return e.next=12,this.getStat(i);case 12:if(a=e.sent,o=a.rtt,s=a.totalPacketsLost,c=a.totalPacketsReceived,this._downlinkPrevStatMap.has(i)){e.next=19;break}return this._downlinkPrevStatMap.set(i,{totalPacketsLost:s,totalPacketsReceived:c}),e.abrupt("continue",21);case 19:l=this._downlinkPrevStatMap.get(i),d=s-l.totalPacketsLost,h=c-l.totalPacketsReceived,u=d<=0||h<0?0:Math.round(d/(d+h)*100),this._downlinkPrevStatMap.set(i,{totalPacketsLost:s,totalPacketsReceived:c}),this._downlinkLossAndRTTMap.set(i,{rtt:o,loss:u,userId:n[r].getUserId(),audioDelay:n[r].remoteAudioTrack.stat.end2EndDelay,videoDelay:n[r].remoteVideoTrack.stat.end2EndDelay});case 21:r++,e.next=6;break;case 24:if(E(this._downlinkPrevStatMap.keys()).forEach((function(e){_.isPeerConnectionDisconnected(e)&&(_._downlinkPrevStatMap.delete(e),_._downlinkLossAndRTTMap.delete(e))})),0!==this._downlinkLossAndRTTMap.size){e.next=26;break}return e.abrupt("return",(this.downlinkRTT=0,this.downlinkLoss=0,void(this.downlinkNetworkQuality=0)));case 26:p=this.getAverageLossAndRTT(E(this._downlinkLossAndRTTMap.values())),m=p.rtt,v=p.loss,this.downlinkRTT=m,this.downlinkLoss=v,this.downlinkNetworkQuality=this.getNetworkQuality(v,m);case 28:case"end":return e.stop()}}),e,this)})))}},{key:"getStat",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n={rtt:0,totalPacketsLost:0,totalPacketsReceived:0},e&&wP()){t.next=3;break}return t.abrupt("return",n);case 3:r=e.getReceivers(),t.prev=4,i=0;case 6:if(!(i<r.length)){t.next=13;break}return t.next=9,r[i].getStats();case 9:t.sent.forEach((function(e){"candidate-pair"===e.type&&zw(e.currentRoundTripTime)&&(n.rtt=Math.round(1e3*e.currentRoundTripTime)),"inbound-rtp"===e.type&&(e.mediaType===IC.AUDIO||e.mediaType===IC.VIDEO)&&(n.totalPacketsLost+=e.packetsLost,n.totalPacketsReceived+=e.packetsReceived)}));case 10:i++,t.next=6;break;case 13:return t.abrupt("return",(0===n.rtt&&(n.rtt=this.uplinkRTT),n));case 16:return t.prev=16,t.t0=t.catch(4),t.abrupt("return",n);case 19:case"end":return t.stop()}}),t,this,[[4,16]])})))}},{key:"getAverageLossAndRTT",value:function(e){var t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach((function(e){t.rtt+=e.rtt,t.loss+=e.loss})),Object.keys(t).forEach((function(n){t[n]=Math.round(t[n]/e.length)}))),t}},{key:"getNetworkQuality",value:function(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}},{key:"handleSignalConnectionStateChange",value:function(e){"DISCONNECTED"===e.state?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):"CONNECTED"===e.state&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}},{key:"handleUplinkConnectionStateChange",value:function(e){var t=e.state;"DISCONNECTED"===t?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):"CONNECTED"===t&&6===this.uplinkNetworkQuality&&(this.uplinkNetworkQuality=5)}},{key:"isPeerConnectionDisconnected",value:function(e){return!(!e||e.connectionState!==zC.DISCONNECTED&&e.connectionState!==zC.FAILED&&e.connectionState!==zC.CLOSED)}},{key:"setUplinkConnection",value:function(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT=0,this.uplinkLoss=0)}},{key:"start",value:function(){var e=this;-1===this._interval?(this._log.debug("start network quality calculating"),this._interval=mM.run("ric",(function(){var t;e.handleDownlinkNetworkQuality();var n=E(e._downlinkLossAndRTTMap.values());Px.emit(Lx.NETWORK_QUALITY,{room:e._room,uplink:{rtt:e.uplinkRTT,loss:e.uplinkLoss},downlinks:n});var r=null==(t=e._room.scheduleResult.config)?void 0:t.pingDomainInfo,a={uplinkNetworkQuality:e.uplinkNetworkQuality,downlinkNetworkQuality:e.downlinkNetworkQuality,uplinkRTT:e.uplinkRTT,uplinkLoss:e.uplinkLoss,downlinkRTT:e.downlinkRTT,downlinkLoss:e.downlinkLoss};r&&(a=gA(_A({},a),{pingResults:e.uplinkRTT>r.rttThreshold||e.downlinkRTT>r.rttThreshold?e.pingResults:{}})),e.emit(i.EVENT_NETWORK_QUALITY,a);var o=Date.now();if(r&&(e.uplinkRTT>r.rttThreshold||e.downlinkRTT>r.rttThreshold)&&o-i.lastPingTime>1e3*r.interval){i.lastPingTime=Date.now();var c=r.domain.map((function(e){return function(e){var t=this;return new Promise((function(n){return bA(t,null,f().mark((function t(){var r,i,a,o;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return r=setTimeout((function(){n({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})}),1e4),i=Date.now(),a="https://".concat(e,"/?t=").concat(i),t.prev=1,t.next=4,fetch(a);case 4:t.next=8;break;case 6:t.prev=6,t.t0=t.catch(1);case 8:clearTimeout(r),o=function(e){var t={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{var n,i=s(performance.getEntriesByType("resource").reverse());try{for(i.s();!(n=i.n()).done;){var a=n.value;if(a.name===e){var o=Math.round(a.duration),c=Math.max(Math.round(a.domainLookupStart-a.startTime),0),u=a.redirectStart>0?Math.max(Math.round(a.redirectEnd-a.redirectStart),0):0,l=a.fetchStart>0?Math.max(Math.round(a.domainLookupStart-a.fetchStart),0):0,d=Math.round(a.domainLookupEnd-a.domainLookupStart),h=Math.round(a.requestStart-a.secureConnectionStart),f=Math.round(a.secureConnectionStart-a.connectStart),p=Math.round(a.responseStart-a.requestStart),m=Math.round(a.responseEnd-(a.responseStart||a.startTime));t=gA(_A({},t),{totalCost:o,local:c,redirect:u,httpCache:l,dns:d,tcp:f,tls:h,request:p,response:m});break}}}catch(v){i.e(v)}finally{i.f()}}catch(r){}return t}(a),0===o.totalCost&&(o.totalCost=Date.now()-i),n(o);case 11:case"end":return t.stop()}}),t,null,[[1,6]])})))}))}(e).then((function(t){return{domain:e,cost:t.totalCost}}))}));Promise.all(c).then((function(t){e.pingResults.isPoorNetwork=t.some((function(e){return e.cost>700})),e.pingResults.timestamp=o,e.pingResults.data=t,t.forEach((function(e){rP.addSuccessEvent({key:521718,cost:e.cost})})),e._log.warn("All ping results: ".concat(JSON.stringify(t)))})).catch((function(t){e._log.warn("Error during pinging domains: ".concat(t))}))}}),{delay:2e3})):this._log.info("network quality calculating is already started")}},{key:"stop",value:function(){this._log.debug("stopped"),-1!==this._interval&&(mM.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}},{key:"updateDelay",value:function(e){var t=this,n=this._room.tinyIdToUserIdMap;e.forEach((function(e){var r=e.srcTinyId,i=e.videoDelay,a=e.audioDelay,o=n.get(r);if(o){var s=t._room.remotePublishedUserMap.get(o);null==s||s.setDelay({videoDelay:i,audioDelay:a})}}))}}])}(kA(RA()).default);SA(DW,"EVENT_NETWORK_QUALITY","0"),SA(DW,"lastPingTime",0);var NW=DW,xW=function(){return o((function e(t){var n=this;r(this,e),SA(this,"_frameWorkType"),SA(this,"_component"),SA(this,"_language"),SA(this,"connectionType"),SA(this,"_room"),SA(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0}),SA(this,"_keyPrefix"),SA(this,"_log"),SA(this,"_intervalId"),SA(this,"_firstPublishedUserList"),SA(this,"_networkQuality"),SA(this,"_basicInfo"),SA(this,"_pathJoinRoom"),SA(this,"_pathLeaveRoom"),SA(this,"_pathMainVideoMap"),SA(this,"_pathMainAudioMap"),SA(this,"_pathAuxiliaryMap"),SA(this,"_remoteStreamStatMap"),SA(this,"_localStreamStat"),SA(this,"_eventMap",new Map),SA(this,"_captureCostSum",0),SA(this,"_captureCostCount",0),SA(this,"isDestroyed",!1),this._frameWorkType=t.frameWorkType||30,this._component=t.component||0,this.connectionType=t.connectionType||1,this._language=t.language||0,this._room=t.room,this._keyPrefix="key_point",this._log=Ux.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach((function(e){e.startsWith("handle")&&Jw(n[e])&&(n[e]=function(e){var t=e.fn,n=e.context;return function(){try{for(var e=arguments.length,r=new Array(e),i=0;i<e;i++)r[i]=arguments[i];var a=t.apply(n,r);return eD(a)?a.catch((function(e){return Ux.error("".concat(t.name,"() error observed ").concat(e))})):a}catch(ZC){Ux.error("".concat(t.name,"() error observed ").concat(ZC))}}}({fn:n[e],context:n}))})),this.initData(),this.installEvents()}),[{key:"initData",value:function(){var e=this;this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:YA,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:"live"===this._room.scene?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,bx().then((function(t){e._basicInfo.string_os_version=Nx(),e._basicInfo.string_device_name=t&&t.mobile?t.model:e._basicInfo.string_os_version}))}},{key:"addEvent",value:function(e,t){return this._eventMap.set(e,t),Px.on(e,t),this}},{key:"installEvents",value:function(){var e=this;this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",(function(){return e.handleLeaveSuccess({room:e._room,roomId:e._room.roomId})})),this.addEvent(Lx.JOIN_START,this.handleJoinStart).addEvent(Lx.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(Lx.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(Lx.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(Lx.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(Lx.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(Lx.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(Lx.JOIN_FAILED,this.handleJoinFailed).addEvent(Lx.LEAVE_START,this.handleLeaveStart).addEvent(Lx.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(Lx.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(Lx.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(Lx.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(Lx.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(Lx.PUBLISH_START,this.handlePublishStart).addEvent(Lx.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(Lx.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(Lx.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(Lx.PLAY_TRACK_START,this.handlePlayStart).addEvent(Lx.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(Lx.PLAYER_STATE_CHANGED,(function(t){var n=t.track,r=t.state,i=t.type;!n.isRemote||!e.hitTest(n.room)||"PLAYING"===r&&(i===IC.AUDIO?e.handleAudioPlaying(n):e.handleVideoPlaying(n))})).addEvent(Lx.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(Lx.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(Lx.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(Lx.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(Lx.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(Lx.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(Lx.REMOTE_PUBLISH_STATE_CHANGED,(function(t){var n=t.room,r=t.prevMuteState,i=t.muteState;if(e.hitTest(n)){var a=r.hasAudio||r.hasVideo||r.hasSmall,o=r.hasAuxiliary,s=i.hasAudio||i.hasVideo||i.hasSmall,c=i.hasAuxiliary;!a&&s&&e.handleRemoteStreamAdded(i.userId,"main"),!o&&c&&e.handleRemoteStreamAdded(i.userId,"auxiliary")}})).addEvent(Lx.SINGLE_CONNECTION_STAT,(function(t){var n=t.room,r=t.stat;e.hitTest(n)&&(e._pathJoinRoom.int32_ice_cost=r.ice,e._pathJoinRoom.int32_dtls_cost=r.dtls,e._pathJoinRoom.int32_peer_connection_cost=r.peerConnection)}))}},{key:"uninstallEvents",value:function(){window.removeEventListener("pagehide",this.handleUnload),this._eventMap.forEach((function(e,t){return Px.off(t,e)})),this._eventMap.clear()}},{key:"destroy",value:function(){this.uninstallEvents(),mM.clearTask(this._intervalId),0===this._pathJoinRoom.uint64_start_time&&(this._room=null),this.isDestroyed=!0}},{key:"handleUnload",value:function(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}},{key:"handleJoinStart",value:function(e){this.hitTest(e.room)&&(0===this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_start_time=Date.now()),e.params&&(Kw(e.params.frameWorkType)||(this._frameWorkType=e.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),Kw(e.params.component)||(this._component=e.params.component,this._basicInfo.uint32_component=this._component),Kw(e.params.language)||(this._language=e.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}},{key:"handleJoinScheduleSuccess",value:function(e){var t=e.room,n=e.detailCost;if(this.hitTest(t)&&n){var r=n.totalCost,i=n.local,a=n.dns,o=n.tcp,s=n.tls,c=n.request,u=n.response;this._pathJoinRoom.int32_schedule_cost=r,this._pathJoinRoom.int32_schedule_local=i,this._pathJoinRoom.int32_schedule_dns=a,this._pathJoinRoom.int32_schedule_tcp=o,this._pathJoinRoom.int32_schedule_tls=s,this._pathJoinRoom.int32_schedule_request=c,this._pathJoinRoom.int32_schedule_response=u}}},{key:"handleSignalConnectionStart",value:function(e){var t=e.room;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}},{key:"handleSignalConnectionEnd",value:function(e){var t=e.room,n=e.error;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),n&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=n instanceof FA?Number(n.getExtraCode()||n.getCode()):VA.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}},{key:"handleJoinSendCMD",value:function(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}},{key:"handleJoinReceivedCMDResponce",value:function(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=e.code,0!==e.code&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}},{key:"handleJoinSuccess",value:function(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_end_time&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=e.room.getSignalInfo())}},{key:"handleJoinFailed",value:function(e){var t=this,n=e.room,r=e.error;this.hitTest(n)&&(this._pathJoinRoom.uint64_end_time=Date.now(),0===this._pathJoinRoom.int32_end_ret&&(this._pathJoinRoom.int32_end_ret=r.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout((function(){t.report()})))}},{key:"handleReceivedPublishUserList",value:function(e){this.hitTest(e.room)&&0===this._pathJoinRoom.uint64_recv_userlist_time&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=e.publishedUserList||[])}},{key:"handleSendFirstVideoFrame",value:function(e){var t=e.room;this.hitTest(t)&&0===this._pathJoinRoom.uint64_send_first_video_frame_time&&0!==this._pathJoinRoom.uint64_start_time&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}},{key:"handleLeaveStart",value:function(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}},{key:"handleLeaveSuccess",value:function(e){this.hitTest(e.room)&&0===this._pathLeaveRoom.uint64_end_time&&(this._pathLeaveRoom.uint64_end_time=Date.now(),0!==this._pathJoinRoom.uint64_end_time?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}},{key:"handleLeaveSendCMD",value:function(e){this.hitTest(e.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}},{key:"handleSwitchRoomStart",value:function(e){var t=this;if(this.hitTest(e.room)){var n=Date.now();this.report().then((function(){t._pathJoinRoom.uint64_start_time=n,t._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=n}))}}},{key:"handleSwitchRoomSuccess",value:function(e){var t=e.room;if(this.hitTest(t)&&0===this._pathJoinRoom.uint64_end_time){var n=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=n,this._pathJoinRoom.uint64_end_time=n,this._pathJoinRoom.int32_end_ret}}},{key:"handleSwitchRoomFailed",value:function(e){var t=e.room,n=e.error;if(this.hitTest(t)){var r=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=r,this._pathJoinRoom.uint64_end_time=r,n&&(this._pathJoinRoom.int32_end_ret=n instanceof FA?Number(n.getExtraCode()||n.getCode()):VA.UNKNOWN)}}},{key:"handleRemoteStreamAdded",value:function(e,t){var n,r="".concat(e,"_").concat(t);if(!this._remoteStreamStatMap.has(r)){var i={userId:e,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:gA(_A({},PW),{msg_user_info:new MW({userId:e,tinyId:null==(n=this._room.remotePublishedUserMap.get(e))?void 0:n.tinyId,role:20})})};i.statsToReport.uint32_stream_type="main"===t?2:7,this._remoteStreamStatMap.set(r,i)}}},{key:"handleSubscribeStart",value:function(e){var t=e.room,n=e.remotePublishedUser,r=e.streamType,i=e.subscribeState;if(this.hitTest(t)){var a=n.userId,o=n.tinyId,s=n.role,c=new MW({userId:a,tinyId:o,role:"anchor"===s?20:21}),u=Date.now(),l="".concat(a,"_").concat(r),d=this._remoteStreamStatMap.get(l);d&&0===d.subscribeStartTime&&(d.subscribeStartTime=u),"main"===r?(n.muteState.hasVideo&&(i.video||i.smallVideo)&&!this._pathMainVideoMap.has(l)&&this._pathMainVideoMap.set(l,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:a,sendSubscribeCMDTime:u}),n.muteState.hasAudio&&i.audio&&!this._pathMainAudioMap.has(l)&&this._pathMainAudioMap.set(l,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:a,sendSubscribeCMDTime:u})):n.muteState.hasAuxiliary&&i.auxiliary&&!this._pathAuxiliaryMap.has(l)&&this._pathAuxiliaryMap.set(l,{sendSubscribeCMDTime:u})}}},{key:"handleSubscribed",value:function(e){var t=e.room,n=e.remotePublishedUser,r=e.streamType;if(this.hitTest(t)){var i="".concat(n.userId,"_").concat(r),a=this._remoteStreamStatMap.get(i);a&&0===a.subscribedTime&&(a.subscribedTime=Date.now())}}},{key:"handlePlayStart",value:function(e){var t=e.track;if(t.isRemote&&this.hitTest(t.room)){var n="".concat(t.userId,"_").concat(t.streamType),r=this._remoteStreamStatMap.get(n);0===(null==r?void 0:r.playStreamTime)&&(r.playStreamTime=Date.now())}}},{key:"handleVideoLoadedData",value:function(e){var t=e.track;if(t.isRemote&&this.hitTest(t.room)){var n="".concat(t.userId,"_").concat(t.streamType),r=this._pathMainVideoMap.get(n);r&&0===r.statsToReport.uint64_combine_first_frame_time&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}}},{key:"handleVideoPlaying",value:function(e){var t="".concat(e.userId,"_").concat(e.streamType),n=Date.now(),r=this._pathMainVideoMap.get(t),i=this._remoteStreamStatMap.get(t);if(i){var a=i.statsToReport;if(a.uint32_video_render_first||"main"!==e.streamType?this.hasAuxFlag(e.userId):this.hasVideoFlag(e.userId)){var o=n-this._pathJoinRoom.uint64_start_time;a.uint32_video_render_first=o,rP.addNumber({key:516820,value:o})}}0===(null==r?void 0:r.statsToReport.uint64_render_first_frame_time)&&(r.statsToReport.uint64_render_first_frame_time=n)}},{key:"handleAudioPlaying",value:function(e){var t="".concat(e.userId,"_").concat(e.streamType),n=this._pathMainAudioMap.get(t);n&&0===n.statsToReport.uint64_play_first_frame_time&&(n.statsToReport.uint64_play_first_frame_time=Date.now())}},{key:"handleNetworkQuality",value:function(e){var t=this;this.hitTest(e.room)&&(this._networkQuality.totalUplinkLoss+=e.uplink.loss,this._networkQuality.totalUplinkRTT+=e.uplink.rtt,this._networkQuality.count++,e.downlinks.forEach((function(e){var n,r,i,a,o=e.rtt,s=e.loss,c=e.userId,u=e.videoDelay,l=e.audioDelay,d=t._networkQuality.totalDownlinkRTTAndLossMap.get(c);d?(d.totalRTT+=o,d.totalLoss+=s,u&&(d.totalVideoDelay=(d.totalVideoDelay||0)+u,d.videoDelayCount=(d.videoDelayCount||0)+1),l&&(d.totalAudioDelay=(d.totalAudioDelay||0)+l,d.audioDelayCount=(d.audioDelayCount||0)+1),d.count++):(u&&(r=u,i=1),l&&(n=l,a=1),t._networkQuality.totalDownlinkRTTAndLossMap.set(c,{totalRTT:o,totalLoss:s,count:1,totalAudioDelay:n,totalVideoDelay:r,audioDelayCount:a,videoDelayCount:i}))})))}},{key:"handleHeartbeatStats",value:function(e){var t=this;if(this.hitTest(e.room)){var n=e.report,r=n.msg_device_info,i=n.msg_up_stream_info,a=n.msg_down_stream_info;if(i.msg_video_status[0]){var o=i.msg_video_status[0],s=o.uint32_video_codec_bitrate,c=o.uint32_video_enc_fps,u=o.uint32_video_width,l=o.uint32_video_height;this._localStreamStat.totalVideoBitrate+=s,this._localStreamStat.totalVideoFPS+=c,this._localStreamStat.totalVideoWidth+=u,this._localStreamStat.totalVideoHeight+=l,this._localStreamStat.videoCount++}if(i.msg_audio_status){var d=i.msg_audio_status.uint32_audio_level;Math.floor(d/xO*100)>0&&(this._localStreamStat.totalAudioLevel+=d/xO,this._localStreamStat.audioLevelCount++)}a.forEach((function(e){var n=e.msg_user_info,r=e.msg_audio_status,i=e.msg_video_status,a=n.str_identifier,o=t._room.remotePublishedUserMap.get(a);if(i.forEach((function(e){var n=2===e.uint32_video_stream_type,r=7===e.uint32_video_stream_type,i="".concat(a,"_").concat(n?"main":"auxiliary"),s=t._remoteStreamStatMap.get(i);if(s&&(n&&null!=o&&o.remoteVideoTrack.isSubscribed||r&&null!=o&&o.remoteAuxiliaryTrack)){s.totalVideoFPS+=e.uint32_video_receive_fps,s.totalVideoBitrate+=e.uint32_video_codec_bitrate,s.videoCount++,0===s.statsToReport.uint32_video_width&&(s.statsToReport.uint32_video_width=e.uint32_video_width),0===s.statsToReport.uint32_video_height&&(s.statsToReport.uint32_video_height=e.uint32_video_height);var c=n?o.remoteVideoTrack:o.remoteAuxiliaryTrack;c.stat.jitterBufferDelay&&(s.videoJitterBufferDelay=c.stat.jitterBufferDelay),c.stat.framesReceived&&(s.statsToReport.uint32_video_consume_render_rate=Math.floor(c.stat.framesDecoded/c.stat.framesReceived*mA(10,6)))}})),!uD(r)){var s="".concat(a,"_main"),c=t._remoteStreamStatMap.get(s);t._remoteStreamStatMap.has(s)&&c&&null!=o&&o.remoteAudioTrack.isSubscribed&&(c.totalAudioBitrate+=r.uint32_audio_codec_bitrate,c.audioCount++,o.remoteAudioTrack.stat.jitterBufferDelay&&(c.audioJitterBufferDelay=o.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(r.uint32_audio_level/xO*100)>0&&(c.totalAudioLevel+=r.uint32_audio_level/xO,c.audioLevelCount++))}})),r.uint32_audio_capture_cost&&(this._captureCostSum+=r.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}},{key:"handlePublishStart",value:function(e){var t=e.room;this.hitTest(t)&&0===this._localStreamStat.publishStartTime&&(this._localStreamStat.publishStartTime=Date.now())}},{key:"handleTrackCaptureStart",value:function(e){var t=e.track;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}},{key:"handleTrackCaptureSuccess",value:function(e){var t=e.track;1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}},{key:"handleTrackCaptureFailed",value:function(e){var t=e.track,n=e.error,r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[n.name]||(n instanceof FA?n.getExtraCode()||n.getCode():VA.UNKNOWN);1===t.mediaType&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=r,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),4===t.mediaType&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}},{key:"hasVideoFlag",value:function(e){return this._firstPublishedUserList.findIndex((function(t){return t.userId===e&&t.flag&CC}))>=0}},{key:"hasAudioFlag",value:function(e){return this._firstPublishedUserList.findIndex((function(t){return t.userId===e&&t.flag&NC}))>=0}},{key:"hasAuxFlag",value:function(e){return this._firstPublishedUserList.findIndex((function(t){return t.userId===e&&t.flag&DC}))>=0}},{key:"hitTest",value:function(e){return e===this._room}},{key:"prepareReport",value:function(){var e=this;if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);var t=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),n=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=t<<16|n}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((function(t,n){var r=t.userId,i=e._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(i){var a=i.totalLoss,o=i.count,s=i.audioDelayCount,c=i.videoDelayCount,u=i.totalAudioDelay,l=i.totalVideoDelay;t.statsToReport.uint32_avg_down_loss=Math.floor(a/o),s&&u&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(u/s),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),c&&l&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(l/c))}t.videoCount>0&&(t.statsToReport.uint32_video_avg_fps=Math.floor(t.totalVideoFPS/t.videoCount),t.statsToReport.uint32_video_avg_bitrate=Math.floor(t.totalVideoBitrate/t.videoCount)),t.audioCount>0&&(t.statsToReport.uint32_audio_recv_bitrate=t.statsToReport.uint32_audio_bitrate=Math.floor(t.totalAudioBitrate/t.audioCount)),t.audioLevelCount>0&&(t.statsToReport.uint32_audio_play_db=Math.floor(t.totalAudioLevel/t.audioLevelCount*100));var d=e._room.callDurationCalculator;d&&(t.statsToReport.uint32_audio_play_time=d.getDuration(n,IC.AUDIO),t.statsToReport.uint32_video_play_time=d.getDuration(n,IC.VIDEO)),t.statsToReport.uint32_video_render_first&&(t.statsToReport.uint32_video_render_first=Math.min(t.statsToReport.uint32_video_render_first,OW));var h=e._room.badCaseDetector,f=h.getDataFreezeDuration(n),p=f.dataFreeze,m=f.count,v=h.getRenderFreezeDuration(n).renderFreeze;t.statsToReport.uint32_video_block_count=m,t.statsToReport.uint32_video_block_time=Math.min(p,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_video_external_block_time=Math.min(v,t.statsToReport.uint32_video_play_time),h.isBlackStream(n)&&0===t.statsToReport.uint32_video_avg_fps?t.statsToReport.uint32_video_black_screen_subjective=1:t.statsToReport.uint32_video_black_screen_subjective=0})),this._pathMainAudioMap.forEach((function(t,n){e.hasAudioFlag(t.userId)?t.statsToReport.uint64_play_first_frame_time-t.statsToReport.uint64_start_enter_time>OW&&(t.statsToReport.uint64_play_first_frame_time=t.statsToReport.uint64_start_enter_time+OW):e._pathMainAudioMap.delete(n)})),this._pathMainVideoMap.forEach((function(t,n){e.hasVideoFlag(t.userId)?t.statsToReport.uint64_render_first_frame_time-t.statsToReport.uint64_start_enter_time>OW&&(t.statsToReport.uint64_render_first_frame_time=t.statsToReport.uint64_start_enter_time+OW):e._pathMainVideoMap.delete(n)})),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>OW&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+OW)}},{key:"getReportData",value:function(){this._basicInfo.uint32_networkType=Ow();var e={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new MW({userId:this._room.userId,tinyId:this._room.tinyId,role:"anchor"===this._room.role?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:hD(this._signalInfo.relayIp),uint32_client_ip:hD(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*mA(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:E(this._pathMainVideoMap.values()).map((function(e){return e.statsToReport})),msg_quality_statistics:E(this._remoteStreamStatMap.values()).map((function(e){return e.statsToReport})),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:E(this._pathMainAudioMap.values()).map((function(e){return e.statsToReport})),uint32_info_client_ip:hD(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return ID(e),e}},{key:"report",value:function(){return bA(this,null,f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,this.prepareReport(),t=this.getReportData(),e.next=5,this.upload(t);case 5:this.initData(),e.next=11;break;case 8:e.prev=8,e.t0=e.catch(0),this._log.warn(e.t0);case 11:return e.prev=11,this.isDestroyed&&(this._room=null),e.finish(11);case 14:case"end":return e.stop()}}),e,this,[[0,8,11,14]])})))}},{key:"upload",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a,o,s;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(0!==e.msg_path_enter_room.uint64_start_time){t.next=2;break}return t.abrupt("return");case 2:return n=Number(this._room.sdkAppId),t.next=5,xD(e);case 5:return r=t.sent,i=r instanceof ArrayBuffer,a="".concat(Cw(n,hC.KEY_POINT),"&gzip=").concat(+i),o=!1,navigator.sendBeacon&&(o=navigator.sendBeacon(a,r)),s=[this.uploadKVStat(rP),this.uploadKVStat(nP)],o||s.push(ND({url:a,body:r,priority:"low"})),t.next=14,Promise.all(s);case 14:case"end":return t.stop()}}),t,this)})))}},{key:"setConnectionType",value:function(e){this.connectionType=e,this._basicInfo.uint32_connection_type=e}},{key:"uploadKVStat",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(0!==(n=e.getReportData()).stats_count.length||0!==n.stats_distribution.length){t.next=3;break}return t.abrupt("return");case 3:return n.msg_sdk_basic_info=gA(_A({},n.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(n),t.next=6,xD(n);case 6:r=t.sent,i="".concat(Cw(+this._room.sdkAppId,hC.KV_STAT),"&gzip=").concat(+(r instanceof ArrayBuffer)),a=!1,navigator.sendBeacon&&(a=navigator.sendBeacon(i,r)),a||ND({url:i,body:r});case 10:case"end":return t.stop()}}),t,this)})))}}])}();TA([SM({settings:{timeout:500,retries:3}})],xW.prototype,"upload",1);var OW=5e3,PW={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},MW=o((function e(t){r(this,e),SA(this,"str_identifier"),SA(this,"str_tinyid"),SA(this,"uint32_role"),this.str_identifier=String(t.userId),this.str_tinyid=String(t.tinyId||0),this.uint32_role=t.role})),LW=xW,VW=function(){return o((function e(){r(this,e),SA(this,"_startTime"),SA(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}),[{key:"start",value:function(){0===this._startTime&&(this._startTime=aD())}},{key:"stop",value:function(){0===this._endTime&&(this._endTime=aD())}},{key:"getDuration",value:function(){return 0===this._endTime?aD()-this._startTime:this._endTime-this._startTime}},{key:"startTime",get:function(){return this._startTime}},{key:"endTime",get:function(){return this._endTime}}])}(),UW=function(){return o((function e(t){r(this,e),SA(this,"_room",null),SA(this,"_durationMap"),SA(this,"_eventMap",new Map),this._room=t.room,this._durationMap=new Map,this.installEvents()}),[{key:"installEvents",value:function(){var e=this;this._eventMap.set(Lx.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(Lx.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(Lx.REMOTE_PUBLISH_STATE_CHANGED,(function(t){var n,r=t.room,i=t.prevMuteState,a=t.muteState,o=a.userId;if(e.hitTest(r)){i.hasAudio&&!a.hasAudio&&e.stopDurationItem("".concat(o,"_main"),IC.AUDIO),i.hasVideo&&!a.hasVideo&&e.stopDurationItem("".concat(o,"_main"),IC.VIDEO),i.hasAuxiliary&&!a.hasAuxiliary&&e.stopDurationItem("".concat(o,"_auxiliary"),IC.VIDEO);var s=null==(n=e._room)?void 0:n.remotePublishedUserMap.get(o);s&&(!i.hasAudio&&a.hasAudio&&s.remoteAudioTrack.isSubscribed&&e.addDuractionItem(o,IC.AUDIO,"main"),!i.hasVideo&&a.hasVideo&&s.remoteVideoTrack.isSubscribed&&e.addDuractionItem(o,IC.VIDEO,"main"),!i.hasAuxiliary&&a.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&e.addDuractionItem(o,IC.VIDEO,"auxiliary"))}})),this._eventMap.forEach((function(t,n){return Px.on(n,t,e)}))}},{key:"uninstallEvents",value:function(){var e=this;this._eventMap.forEach((function(t,n){return Px.off(n,t,e)})),this._eventMap.clear()}},{key:"handleSubscribed",value:function(e){var t=e.track;if(this.hitTest(t.room)){var n=t.userId,r=t.streamType,i=t.kind;t.isSubscribed?this.addDuractionItem(n,i,r):this.stopDurationItem("".concat(n,"_").concat(r),i)}}},{key:"handleUnsubscribed",value:function(e){var t=e.track;this.hitTest(t.room)&&this.stopDurationItem("".concat(t.userId,"_").concat(t.streamType),t.kind)}},{key:"isRecording",value:function(e){return e.findIndex((function(e){return 0===e.endTime}))>=0}},{key:"addDuractionItem",value:function(e,t,n){var r="".concat(e,"_").concat(n),i=new VW,a=this._durationMap.get(r);a?this.isRecording(a[t])||a[t].push(i):this._durationMap.set(r,{userId:e,type:n,audio:t===IC.AUDIO?[i]:[],video:t===IC.AUDIO?[]:[i]})}},{key:"stopDurationItem",value:function(e,t){if(this._durationMap.has(e)){var n=this._durationMap.get(e)[t].find((function(e){return 0===e.endTime}));n&&n.stop()}}},{key:"hitTest",value:function(e){return this._room===e}},{key:"getDuration",value:function(e,t){return this._durationMap.has(e)?this._durationMap.get(e)[t].reduce((function(e,t){return e+t.getDuration()}),0):0}},{key:"getDurationMap",value:function(){return this._durationMap}},{key:"reset",value:function(){this._durationMap.clear()}},{key:"destroy",value:function(){this._room=null,this.uninstallEvents()}}])}(),FW=function(){return o((function e(t){r(this,e),SA(this,"_room"),SA(this,"_renderFreezeMap",new Map),SA(this,"_isVideoPlayingEventFiredMap",new Map),SA(this,"_dataFreezeMap",new Map),SA(this,"_monitorFreezeData",new Map),SA(this,"_eventMap",new Map),this._room=t.room,this.installEvents()}),[{key:"getRenderFreezeMap",value:function(){return this._renderFreezeMap}},{key:"getDataFreezeMap",value:function(){return this._dataFreezeMap}},{key:"installEvents",value:function(){var e=this;this._eventMap.set(Lx.LEAVE_SUCCESS,(function(t){var n=t.room;e.hitTest(n)&&e.stop()})).set(Lx.PLAY_TRACK_START,this.onPlayTrackStart).set(Lx.UNSUBSCRIBE_SUCCESS,(function(t){var n=t.room,r=t.streamType,i=t.remotePublishedUser;if(e.hitTest(n)){var a=i.userId,o="".concat(a,"_").concat(r);e.stopDataFreeze({key:o,userId:a,type:r})}})).set(Lx.REMOTE_PUBLISH_STATE_CHANGED,(function(t){var n=t.room,r=t.prevMuteState,i=t.muteState;if(e.hitTest(n)){var a=i.userId;if(r.hasVideo&&!i.hasVideo){var o="main",s="".concat(i.userId,"_").concat(o);e.stopDataFreeze({key:s,userId:a,type:o})}if(r.hasAuxiliary&&!i.hasAuxiliary){var c="auxiliary",u="".concat(i.userId,"_").concat(c);e.stopDataFreeze({key:u,userId:a,type:c})}}})).set(Lx.PLAYER_STATE_CHANGED,(function(t){var n=t.track,r=t.state,i=t.reason,a=t.type;if(n.isRemote&&n.room&&e.hitTest(n.room)&&a===IC.VIDEO){if("PLAYING"===r){var o="".concat(n.userId,"_").concat(n.streamType);e._isVideoPlayingEventFiredMap.set(o,!0)}i===IC.MUTE?e.onVideoTrackMuted(n):i===IC.UNMUTE&&e.onVideoTrackUnmuted(n)}})).set(Lx.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((function(t,n){return Px.on(n,t,e)}))}},{key:"uninstallEvents",value:function(){var e=this;this._eventMap.forEach((function(t,n){return Px.off(n,t,e)})),this._eventMap.clear()}},{key:"stop",value:function(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}},{key:"onVideoTrackMuted",value:function(e){if(e.isSubscribed){var t=e.userId,n=e.streamType,r="".concat(t,"_").concat(n),i=this._dataFreezeMap.get(r),a=new VW;i?i.durationItemList.push(a):this._dataFreezeMap.set(r,{userId:t,type:n,durationItemList:[a],isFreezing:function(){var e=this.durationItemList[this.durationItemList.length-1];return e&&0===e.endTime}})}}},{key:"onVideoTrackUnmuted",value:function(e){if(e.isSubscribed){var t=e.userId,n=e.streamType,r="".concat(t,"_").concat(n);this.stopDataFreeze({key:r,userId:t,type:n})}}},{key:"onHearBeatReport",value:function(e){var t=this,n=e.room,r=e.report;this.hitTest(n)&&r.msg_down_stream_info.forEach((function(e){var n=t._room.remotePublishedUserMap.get(e.msg_user_info.str_identifier);if(n){var r=n.userId,i=n.muteState;e.msg_video_status.forEach((function(e){2===e.uint32_video_stream_type&&i.hasVideo&&!i.videoMuted&&n.remoteVideoTrack.isSubscribed&&t.handleRenderFreeze({userId:r,fps:e.uint32_video_dec_fps,type:"main"}),7===e.uint32_video_stream_type&&i.hasAuxiliary&&n.remoteAuxiliaryTrack.isSubscribed&&t.handleRenderFreeze({userId:r,fps:e.uint32_video_dec_fps,type:"auxiliary"})}))}}))}},{key:"stopDataFreeze",value:function(e){var t=e.key,n=e.userId,r=e.type,i=this._dataFreezeMap.get(t);if(i&&i.isFreezing()){var a=i.durationItemList[i.durationItemList.length-1];a.stop();var o=a.getDuration();o>cw?this._monitorFreezeData.set(t,{userId:n,type:r,duration:o}):i.durationItemList.pop()}}},{key:"getTotalDuration",value:function(e){return e.reduce((function(e,t){var n=t.getDuration();return e+Math.min(n,5e3)}),0)}},{key:"handleRenderFreeze",value:function(e){return bA(this,arguments,(function(e){var t=this,n=e.userId,r=e.fps,i=e.type;return f().mark((function e(){var a,o,s,c,u;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:a="".concat(n,"_").concat(i),o=t._renderFreezeMap.get(a),r<=2?(s=aD(),o&&!o.isFreeze&&(o.freezeTimeline.push({startTime:s,endTime:0}),o.isFreeze=!0),o||t._renderFreezeMap.set(a,{userId:n,type:i,isFreeze:!0,freezeTimeline:[{startTime:s,endTime:0}],renderFreezeTotal:0})):o&&o.isFreeze&&(o.isFreeze=!1,(c=o.freezeTimeline.pop())&&(c.endTime=aD(),u=c.endTime-c.startTime,o.freezeTimeline.push(c),o.renderFreezeTotal+=Math.min(5e3,u)));case 2:case"end":return e.stop()}}),e)}))()}))}},{key:"onPlayTrackStart",value:function(e){var t=e.track;if(t.isRemote&&this.hitTest(t.room)&&t.kind===IC.VIDEO&&t.isRemotePublished){var n="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.has(n)||this._isVideoPlayingEventFiredMap.set(n,!1)}}},{key:"getDataFreezeDuration",value:function(e){var t={dataFreeze:0,count:0},n=this._dataFreezeMap.get(e);if(n){if(n.isFreezing()){var r=n.durationItemList[n.durationItemList.length-1];r.stop(),r.getDuration()<cw&&n.durationItemList.pop()}t.dataFreeze=this.getTotalDuration(n.durationItemList),t.count=n.durationItemList.length}return t}},{key:"getRenderFreezeDuration",value:function(e){var t=this._renderFreezeMap.get(e),n=0,r=0;if(t)if(t.isFreeze){var i=aD()-t.freezeTimeline[t.freezeTimeline.length-1].startTime;n=t.renderFreezeTotal+Math.min(i,5e3),r=t.freezeTimeline.length}else n=t.renderFreezeTotal;return{renderFreeze:n,count:r}}},{key:"getMonitorFreeze",value:function(){return this._monitorFreezeData}},{key:"isBlackStream",value:function(e){return!!this._isVideoPlayingEventFiredMap.has(e)&&!this._isVideoPlayingEventFiredMap.get(e)}},{key:"resetMonitor",value:function(){this._monitorFreezeData.clear()}},{key:"hitTest",value:function(e){return e===this._room}},{key:"destroy",value:function(){this.uninstallEvents()}}])}(),BW=kA(RA(),1),HW=[1,0,0,0,1,1,0,1],WW=function(e){function i(e,a,o,s){var c;if(r(this,i),c=n(this,i,[e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:a}]),SA(t(c),"mirror",!1),SA(t(c),"rotation",0),o&&(c.mirror=o),s&&(c.rotation=s),e instanceof KF)try{c.setTexBuffer(HW)}catch(XA){e.destroy(new FA({code:VA.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(c.name," error ").concat(XA.message||XA)}))}return c}return d(i,e),o(i,[{key:"draw2d",value:function(e,t,n,r,a){if(this.ctx2d){this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),90===this.rotation?(this.ctx2d.translate(r,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(a/r,r/a)):180===this.rotation?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):270===this.rotation&&(this.ctx2d.translate(0,a),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(a/r,r/a));var o=g(i,"draw2d",this,3)([e,t,n,r,a]);return this.ctx2d.restore(),o}return!1}},{key:"render",value:function(e){var t;return!(null==(t=this.input)||!t.requestFrame(e)||(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),0))}}])}(OF),jW=function(){return o((function e(t,n){r(this,e),this.node=t,this.layout=n,SA(this,"positionBuffer")}),[{key:"x",get:function(){return this.layout.x||this.node.x}},{key:"y",get:function(){return this.layout.y||this.node.y}},{key:"width",get:function(){return this.layout.width||this.node.width}},{key:"height",get:function(){return this.layout.height||this.node.height}},{key:"right",get:function(){return this.x+this.width}},{key:"bottom",get:function(){return this.y+this.height}}])}(),GW=function(e){function i(e,a){var o;return r(this,i),o=n(this,i,[e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,matchInputSize:!1,logger:a}]),SA(t(o),"inputs",[]),o}return d(i,e),o(i,[{key:"addInput",value:function(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");var n=new jW(e,t);this.inputs[t.zIndex]=n}},{key:"changeInputLayout",value:function(e,t){var n=this,r=this.inputs.findIndex((function(t){return!!t&&t.node===e}));r<0||Object.entries(t).forEach((function(e){var t=v(e,2),i=t[0],a=t[1];Kw(a)||(n.inputs[r].layout[i]=a)}))}},{key:"resize",value:function(e,t){var n=this;if(this.matchInputSize){var r=this.inputs.reduce((function(e,t){return t?Object.assign(e,{width:Math.max(e.width,t.right),height:Math.max(e.height,t.bottom)}):e}),{width:0,height:0});g(i,"resize",this,3)([r.width,r.height]),this.context instanceof KF&&this.inputs.forEach((function(e){if(e){var t=n.layout2texCoords(e);e.positionBuffer?n.changeBufferData(e.positionBuffer,t):e.positionBuffer=n.createBuffer(t)}}))}else g(i,"resize",this,3)([e,t])}},{key:"connect",value:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return g(i,"connect",this,3)([e].concat(n)),this.matchInputSize&&this.resize(0,0),e}},{key:"removeInput",value:function(e){this.inputs[this.inputs.findIndex((function(t){return(null==t?void 0:t.node)===e}))]=void 0}},{key:"render",value:function(e){var t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce((function(t,n){return(null==n?void 0:n.node.requestFrame(e))||t}),!1)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(var n=0;n<this.inputs.length;n++){var r=this.inputs[n];r&&(r.node.useTexture(),this.draw(r.positionBuffer))}return!0}return!1}},{key:"render2d",value:function(e){if(this.inputs.reduce((function(t,n){return(null==n?void 0:n.node.requestFrame(e))||t}),!1)&&this.ctx2d){this.ctx2d.fillStyle="black",this.ctx2d.fillRect(0,0,this.width,this.height);for(var t=0;t<this.inputs.length;t++){var n=this.inputs[t];n&&this.draw2d(n.node.image,n.x,n.y,n.width,n.height)}return!0}return!1}},{key:"getInfo",value:function(){var e=this.totalFrames,t=this.x,n=this.y,r=this.width,i=this.height,a=this.name,o=Date.now(),s=(e-this.lastInfo.totalFrames)/((o-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:e,x:t,y:n,width:r,height:i,timestamp:o,fps:s,name:a},_A({parent:this.inputs.filter((function(e){return e})).map((function(e){return e.node.getInfo()}))},this.lastInfo)}},{key:"close",value:function(){var e=this;g(i,"close",this,3)([]),this.inputs.forEach((function(t){var n,r;if(t&&(null==(n=t.node)||n.disconnect(),t.positionBuffer&&e.context instanceof KF))try{null==(r=e.context.ctx)||r.deleteBuffer(t.positionBuffer)}catch(Xx){}}))}}])}(OF),JW=function(){return o((function e(t,n,i){r(this,e);var a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:4/3;this.vbMode=t,this.faceDetector=n,this.logger=i,SA(this,"animationState"),SA(this,"originalAspect"),SA(this,"totalOffsetX",0),SA(this,"totalOffsetY",0),SA(this,"defaultScaleRatio",.1),SA(this,"isRecovering",!1),SA(this,"boundaryY",280),SA(this,"lastActionTime",0),SA(this,"restTime",400),this.animationState={current:null,target:null,animating:!1,debounceTimer:null,startTime:0,duration:3e3,debounceTime:150,movementThreshold:30,debounceThreshold:15},this.addEvent(this.vbMode,!!this.faceDetector),this.originalAspect=a||4/3}),[{key:"addEvent",value:function(e,t,n){var r=[{key:570704,error:null!=n?n:t?void 0:11},{key:570705,error:null!=n?n:t?void 0:22}][e-1];r&&(t?rP.addSuccessEvent({key:r.key}):rP.addFailedEvent({key:r.key,error:r.error}))}},{key:"actionCentering",value:function(e){var t=Date.now();if(this.animation(),!(!this.faceDetector||t-this.lastActionTime<this.restTime||this.animationState.animating)){var n=e.videoWidth,r=e.videoHeight;this.animationState.debounceThreshold=n/30,this.animationState.movementThreshold=n/20;try{var i=this.faceDetector.detectForVideo(e,Date.now());if(i.detections.length<=0)return void(1===this.vbMode&&this.recoverOriginal(n,r));var a=i.detections[0].boundingBox,o=a.originX,s=a.originY,c=a.width,u=a.height;1===this.vbMode?this.dualStageCropping(n,r,o,s,c,u):2===this.vbMode&&this.movingPortrait(n,r,o,s,c,u)}catch(Xx){this.logger.error(Xx)}this.lastActionTime=t}}},{key:"calculateBoundary",value:function(e,t,n,r){var i,a;return e>t/2?a=n-(i=t-n-r):(i=n,a=0),{min:i,offset:a}}},{key:"calculateTargetPosition",value:function(e,t,n,r,i,a){var o,s,c=arguments.length>6&&void 0!==arguments[6]?arguments[6]:.4,u=e+n/2,l=t+r/2,d=this.calculateBoundary(u,i,e,n),h=d.min,f=d.offset,p=this.calculateBoundary(l,a,t,r),m=p.min,v=p.offset;return(o=2*h+n)/(s=2*m+r)>this.originalAspect?f=u-(o=s*this.originalAspect)/2:v=l-(s=o/this.originalAspect)/2,n/i>c&&(f=0,v=0,o=i,s=a),{sx:f=Math.max(0,Math.min(f,i-o)),sy:v=Math.max(0,Math.min(v,a-s)),cropWidth:o,cropHeight:s,timestamp:Date.now()}}},{key:"processFacePositionCrop",value:function(e,t,n){var r=this;if(!this.animationState.current||!this.animationState.target){var i={sx:0,sy:0,cropWidth:t,cropHeight:n,timestamp:Date.now()};return this.animationState.current=i,void(this.animationState.target=i)}var a=this.positionDistance(this.animationState.target,e),o=this.positionDistance(this.animationState.current,e),s=this.animationState.current.cropWidth/t;a>this.animationState.debounceThreshold*s&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&o>this.animationState.movementThreshold*s&&(this.animationState.target=e,this.animationState.debounceTimer=setTimeout((function(){r.animationState.startTime=Date.now(),r.animationState.animating=!0}),this.animationState.debounceTime))}},{key:"processFacePositionPortrait",value:function(e){var t=this;if(!this.animationState.current||!this.animationState.target)return this.animationState.current=_A({},e),void(this.animationState.target=_A({},e));var n=this.positionDistance(this.animationState.current,e),r=this.positionDistance(this.animationState.target,e);n>this.animationState.debounceThreshold&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&r>this.animationState.movementThreshold&&(this.animationState.current=e,this.animationState.debounceTimer=setTimeout((function(){t.animationState.startTime=Date.now(),t.animationState.animating=!0}),this.animationState.debounceTime))}},{key:"animation",value:function(){if(this.animationState.animating){var e=Date.now()-this.animationState.startTime,t=Math.min(e/this.animationState.duration,1),n=function(e){return e<.5?2*e*e:(4-2*e)*e-1};if(this.animationState.current&&this.animationState.target){var r=(this.animationState.target.sx-this.animationState.current.sx)*n(t);this.animationState.current.sx+=r,this.totalOffsetX+=r;var i=(this.animationState.target.sy-this.animationState.current.sy)*n(t);if(this.animationState.current.sy+=i,this.totalOffsetY+=i,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*n(t),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*n(t),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*n(t)),zw(this.animationState.current.scaleOffsetX)&&zw(this.animationState.target.scaleOffsetX)&&zw(this.animationState.current.scaleOffsetY)&&zw(this.animationState.target.scaleOffsetY)){var a=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*n(t);this.animationState.current.scaleOffsetX+=a;var o=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*n(t);this.animationState.current.scaleOffsetY+=o}}t>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}}},{key:"positionDistance",value:function(e,t){return Math.sqrt(mA(e.sx-t.sx,2)+mA(e.sy-t.sy,2))}},{key:"recoverOriginal",value:function(e,t){this.animationState.target={sx:0,sy:0,cropWidth:e,cropHeight:t,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}},{key:"dualStageCropping",value:function(e,t,n,r,i,a){var o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:.3;if(!this.isRecovering){var s=this.calculateTargetPosition(n,r,i,a,e,t);this.processFacePositionCrop(s,e,t),i*a/s.cropWidth/s.cropHeight>o&&this.recoverOriginal(e,t)}}},{key:"movingPortrait",value:function(e,t,n,r,i,a){var o,s,c,u,l,d,h,f,p,m,v,_,g={sx:n+i/2+this.totalOffsetX,sy:r+a/2+this.totalOffsetY,cropWidth:e,cropHeight:t,scaleRatio:null!=(s=null==(o=this.animationState.current)?void 0:o.scaleRatio)?s:1,scaleOffsetX:null!=(u=null==(c=this.animationState.current)?void 0:c.scaleOffsetX)?u:0,scaleOffsetY:null!=(d=null==(l=this.animationState.current)?void 0:l.scaleOffsetY)?d:0,timestamp:Date.now()};this.animationState.target={sx:e/2,sy:r+a/2,cropWidth:e,cropHeight:t,scaleRatio:null!=(f=null==(h=this.animationState.target)?void 0:h.scaleRatio)?f:1,scaleOffsetX:null!=(m=null==(p=this.animationState.target)?void 0:p.scaleOffsetX)?m:0,scaleOffsetY:null!=(_=null==(v=this.animationState.target)?void 0:v.scaleOffsetY)?_:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(i*a/e/t/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=1-this.animationState.target.scaleRatio,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio<this.boundaryY&&(this.animationState.target.scaleOffsetY=(this.animationState.target.sy-this.boundaryY*this.animationState.target.scaleRatio)/this.animationState.target.cropHeight)),this.processFacePositionPortrait(g)}},{key:"aspectRatio",set:function(e){this.originalAspect=e}},{key:"current",get:function(){return this.animationState.current}},{key:"offset",get:function(){return{offsetX:this.totalOffsetX,offsetY:this.totalOffsetY}}},{key:"targetCrop",get:function(){return this.animationState.target}}])}(),KW=function(e){function i(e,a){var o;r(this,i),o=n(this,i,[e,a.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,width:a.width,height:a.height,logger:e.log}]),SA(t(o),"_bgTexture"),SA(t(o),"_waterMarkTexture"),SA(t(o),"_lastMaskTexture"),SA(t(o),"_lastMaskFbo"),SA(t(o),"_textureValid",!1),SA(t(o),"_selfieTextureValid",!1),SA(t(o),"_selfieSegmentation"),SA(t(o),"wasm"),SA(t(o),"_prePrograme"),SA(t(o),"_segmentationMask"),SA(t(o),"_weixin",!1),SA(t(o),"_centerFace"),SA(t(o),"_textureMatrixLocation"),SA(t(o),"_offsetMatrixLocation"),SA(t(o),"_enableFaceCentering",!1),SA(t(o),"_mat4"),a.selfieSegmentation&&(o._selfieSegmentation=a.selfieSegmentation,o._selfieSegmentation.onResults=o.onPredict.bind(t(o)));try{o.init(a)}catch(Yx){e.log.error(Yx),e.destroy(new FA({code:VA.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(Yx.message||Yx)}))}return o}return d(i,e),o(i,[{key:"init",value:function(e){var t,n=e.Wasm,r=this.context.ctx;if(this._mat4=e.mat4,this.wasm=new n.AllIn1(r),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.rotation=e.rotation||0,this.wasm.vbMode="blur"===e.bg?1:e.bg instanceof HTMLImageElement?2:"green"===e.bg?3:0,this._enableFaceCentering=null!=(t=e.enableFaceCentering)&&t,e.waterMark){var i=e.waterMark,a=i.x,o=i.y,s=i.width,c=i.height;this.wasm.setWaterMark(a,o,s,c)}if(e.beautyParams){var u=e.beautyParams,l=u.beauty,d=u.brightness,h=u.ruddy;this.wasm.setBeauty(l,d,h,null==e?void 0:e.width,null==e?void 0:e.height)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(r.uniform1i(r.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(r.uniform1i(r.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),this._textureMatrixLocation=r.getUniformLocation(this.program,"u_textureMatrix"),r.uniformMatrix4fv(this._textureMatrixLocation,!1,this._mat4.create()),this._offsetMatrixLocation=r.getUniformLocation(this.program,"u_offsetMatrix"),r.uniformMatrix4fv(this._offsetMatrixLocation,!1,this._mat4.create()),r.uniform1i(r.getUniformLocation(this.program,"lastMask"),4),this._weixin){var p=this.context.createShader(r.FRAGMENT_SHADER,"#version 300 es\nprecision highp float;\nuniform sampler2D u_texture;\nuniform sampler2D mask;\n\nin vec2 v_texCoord;\nout vec4 outColor;\nvoid main() {\n outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);\n}"),m=this.context.createShader(r.VERTEX_SHADER,"#version 300 es\nin vec2 a_position;\nin vec2 a_texCoord;\nout vec2 v_texCoord;\nvoid main() {\n gl_Position = vec4(a_position.x, a_position.y, 0, 1);\n v_texCoord = a_texCoord;\n}");this._prePrograme=this.context.createProgram(m,p),r.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this._prePrograme,"mask"),1)}this._enableFaceCentering&&bA(this,null,f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.t0=JW,t.t1=this.wasm.vbMode,t.next=4,e.faceDetector();case 4:return t.t2=t.sent,t.t3=this.context.log,t.abrupt("return",this._centerFace=new t.t0(t.t1,t.t2,t.t3));case 7:case"end":return t.stop()}}),t,this)})))}},{key:"onPredict",value:function(e){var t,n=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this._weixin?this.useTexture():null==this||this._selfieSegmentation.bindTexture(),n.activeTexture(n.TEXTURE1),null==(t=this._selfieSegmentation)||t.bindTexture2d(e),n.activeTexture(n.TEXTURE2),n.bindTexture(n.TEXTURE_2D,this._bgTexture||null),n.activeTexture(n.TEXTURE3),n.bindTexture(n.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),this._segmentationMask=e,this.totalFrames++,this.centerFace(),n.drawArrays(n.TRIANGLE_STRIP,0,4)}},{key:"onFirstFrame",value:function(){this.waitingFirstFrame=!1;var e=this.context.ctx;this.useTexture(),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)}},{key:"render",value:function(e){var t,n,r,i,a,o=this.context.ctx,s=this.image;this.tryVideoFrameCallback();var c=s.videoWidth,u=s.videoHeight;if(DD(this.wasm.rotation)&&(c=(t=[u,c])[0],u=t[1]),0===c||0===u||!this.available)return!1;s.width=c,s.height=u;var l=!1;if(this.totalFrames)this._weixin?this.useTexture():null==(n=this._selfieSegmentation)||n.bindTexture(),l=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),l=this._textureValid,this._textureValid=!0}return this.width===c&&this.height===u&&l?o.texSubImage2D(o.TEXTURE_2D,0,0,0,o.RGBA,o.UNSIGNED_BYTE,s):(this.resize(c,u),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,o.RGBA,o.UNSIGNED_BYTE,s)),this._weixin&&(o.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(o.activeTexture(o.TEXTURE1),null==(r=this._selfieSegmentation)||r.bindTexture2d(this._segmentationMask),o.bindFramebuffer(o.FRAMEBUFFER,this._lastMaskFbo||null)),o.drawArrays(o.TRIANGLE_STRIP,0,4),null==(i=this._selfieSegmentation)||i.bindTexture(),this._segmentationMask?o.copyTexSubImage2D(o.TEXTURE_2D,0,0,0,0,0,c,u):o.copyTexImage2D(o.TEXTURE_2D,0,o.RGBA,0,0,c,u,0)),this.wasm.vbMode&&(null==(a=this._selfieSegmentation)||a.send(c,u)),this.totalFrames||(o.activeTexture(o.TEXTURE2),o.bindTexture(o.TEXTURE_2D,this._bgTexture||null),o.activeTexture(o.TEXTURE3),o.bindTexture(o.TEXTURE_2D,this._waterMarkTexture||null),o.drawArrays(o.TRIANGLE_STRIP,0,4)),!1}},{key:"centerFace",value:function(){if(this._centerFace&&this._enableFaceCentering){var e=this.context.ctx;this._centerFace.aspectRatio=e.canvas.width/e.canvas.height,this._centerFace.actionCentering(this.image);var t=this._centerFace,n=t.current,r=t.offset;if(n&&(1===this.wasm.vbMode&&this.drawImage(e.canvas.width,e.canvas.height,n.sx,n.sy,n.cropWidth,n.cropHeight),r&&2===this.wasm.vbMode)){var i=this._mat4.create(),a=n.scaleRatio,o=void 0===a?1:a,s=n.scaleOffsetX,c=void 0===s?0:s,u=n.scaleOffsetY,l=void 0===u?0:u;this._mat4.fromTranslation(i,[-r.offsetX/e.canvas.width+c,l,0]),this._mat4.scale(i,i,[o,o,1]),e.uniformMatrix4fv(this._offsetMatrixLocation,!1,i)}}}},{key:"drawImage",value:function(e,t,n,r,i,a){var o=this.context.ctx,s=this._mat4.create();this._mat4.fromTranslation(s,[n/e,1-(r+a)/t,0]),this._mat4.scale(s,s,[i/e,a/t,1]),o.uniformMatrix4fv(this._textureMatrixLocation,!1,s)}},{key:"close",value:function(){var e;g(i,"close",this,3)([]);var t=this.context.ctx;this._bgTexture&&t.deleteTexture(this._bgTexture),this._waterMarkTexture&&t.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&t.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&t.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&t.deleteProgram(this._prePrograme),null==(e=this.wasm)||e.close()}}])}(WF),YW=function(e){function i(e){var a;r(this,i),a=n(this,i,[e,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:e.log,fragmentShaderSource:"\n precision highp float;\n uniform sampler2D ySampler;\n uniform sampler2D uSampler;\n uniform sampler2D vSampler;\n varying highp vec2 textureCoord;\n const mat4 YUV2RGB = mat4(\n 1.1643828125, 0, 1.59602734375, -.87078515625,\n 1.1643828125, -.39176171875, -.81296875, .52959375,\n 1.1643828125, 2.017234375, 0, -1.081390625,\n 0, 0, 0, 1);\n void main() {\n vec3 yuv;\n yuv.r = texture2D(ySampler, textureCoord).r;\n yuv.g = texture2D(uSampler, textureCoord).r;\n yuv.b = texture2D(vSampler, textureCoord).r;\n gl_FragColor = vec4(yuv,1) * YUV2RGB;\n }\n ",vertexShaderSource:"\n attribute vec4 vertexPos;\n attribute vec2 texturePos;\n varying vec2 textureCoord;\n void main() {\n gl_Position = vertexPos;\n textureCoord = texturePos;\n }"}]),SA(t(a),"yTextureRef"),SA(t(a),"uTextureRef"),SA(t(a),"vTextureRef"),SA(t(a),"Y"),SA(t(a),"U"),SA(t(a),"V"),a.useProgram();var o=a.context.ctx;return o.pixelStorei(o.PACK_ALIGNMENT,1),o.pixelStorei(o.UNPACK_ALIGNMENT,1),a.setTexBuffer([0,1,1,1,0,0,1,0]),a.yTextureRef=a._initTexture("ySampler",0),a.uTextureRef=a._initTexture("uSampler",1),a.vTextureRef=a._initTexture("vSampler",2),a._canvas=e._canvas,a}return d(i,e),o(i,[{key:"_initTexture",value:function(e,t){var n=this.context.ctx,r=n.createTexture();return n.bindTexture(n.TEXTURE_2D,r),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.bindTexture(n.TEXTURE_2D,null),n.uniform1i(n.getUniformLocation(this.program,e),t),r}},{key:"render",value:function(e){var t=this.context.ctx,n=this.width,r=this.height;return this.useProgram(),t.viewport(0,0,n,r),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.yTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,n,r,t.LUMINANCE,t.UNSIGNED_BYTE,this.Y),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.uTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,n/2,r/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.U),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.vTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,n/2,r/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.V),this.draw(),!0}},{key:"resize",value:function(e,t){g(i,"resize",this,3)([e,t]);var n=this.context.ctx;n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,this.yTextureRef),n.texImage2D(n.TEXTURE_2D,0,n.LUMINANCE,e,t,0,n.LUMINANCE,n.UNSIGNED_BYTE,null),n.activeTexture(n.TEXTURE1),n.bindTexture(n.TEXTURE_2D,this.uTextureRef),n.texImage2D(n.TEXTURE_2D,0,n.LUMINANCE,e/2,t/2,0,n.LUMINANCE,n.UNSIGNED_BYTE,null),n.activeTexture(n.TEXTURE2),n.bindTexture(n.TEXTURE_2D,this.vTextureRef),n.texImage2D(n.TEXTURE_2D,0,n.LUMINANCE,e/2,t/2,0,n.LUMINANCE,n.UNSIGNED_BYTE,null)}}])}(OF),zW=[function(e){e.codec="avc1.42e01f"},function(e){delete e.hardwareAcceleration}],qW=function(e,t){switch(e){case"webCodecs":return"videoFrame"===t?514705:514706;case"wasm":return"webgl"===t?514707:"videoFrame"===t?514708:514709}throw new Error("decoder type not supported")},XW=0,QW=function(){return o((function e(t){var n=this;r(this,e),SA(this,"id",XW++),SA(this,"trackDoneOB"),SA(this,"startOB"),SA(this,"stopOB"),SA(this,"decoder"),SA(this,"videoContext"),SA(this,"gop",0),SA(this,"gop_helper",0),SA(this,"waitFirstKeyFrame",!0),SA(this,"startTimestamp",0),SA(this,"startTime",0),SA(this,"startPerformanceTime",0),SA(this,"inputFrameCount",0),SA(this,"decodedFrameCount",0),SA(this,"decodeFrameCount",0),SA(this,"downgradeLevel",0),SA(this,"lastDowngradeTime",0),SA(this,"lastFrameDiff",0),SA(this,"lastDecodeFrameTimestamp",0),SA(this,"config"),SA(this,"gop_before_configure",[]),SA(this,"videoElement"),SA(this,"type","wasm"),SA(this,"goodType"),SA(this,"renderer","2d"),SA(this,"wasmOption"),SA(this,"createDecoder"),SA(this,"_decodeSink"),SA(this,"isReported",!1),SA(this,"track"),SA(this,"stateChangeOB"),SA(this,"failedReason");var i=t.track,a=t.createDecoder;if(this.stateChangeOB=YV(),this.track=i,this.createDecoder=a,this.wasmOption={yuvMode:"webgl"===t.renderer,wasmPath:t.wasmPath,workerMode:t.workerMode,canvas:t.canvas},this.config=t.config,this.videoElement=t.videoElement,this.renderer=t.renderer,this.trackDoneOB=rU(i.availableState,uM.OFF),this.stopOB=YV(),"auto"===t.type){switch(t.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode="webgl"===this.renderer}else this.type=t.type;this.changeRenderer(this.renderer),RV(this.stateChangeOB,YU((function(e,t){return e!==t&&i.onDecodeDowngradeStateChanged({type:n.type,renderer:n.renderer,reason:n.failedReason,prevState:e,state:t}),t}),"INITIALIZED"),bU(this.stopOB),IF()),this.start()}),[{key:"start",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");var n=RV(this.pipe(this.track),bU(this.stopOB),PV());RV(n,IF((function(){e.track.stat.framesDecoded++}),(function(n){if(e.track.log.error("".concat(e.id," play failed: ").concat(n," retryCount: ").concat(t)),rP.addFailedEvent({key:qW(e.type,e.renderer),error:n}),t>4)e.failedReason=n,e.stateChangeOB.next("FAILED");else{if(e.goodType)return void e.start(t);switch(e.type){case"webCodecs":e.type="wasm",e.changeRenderer("webgl");break;case"wasm":"webgl"===e.renderer&&e.changeRenderer("videoFrame")}e.start(t+1)}}),(function(){e.track.log.warn("".concat(e.id," decoderOB completed")),rP.addSuccessEvent({key:qW(e.type,e.renderer)}),rP.addSuccessEvent({key:514704})}))),RV(n,IU(1),IF((function(){e.track.player.handlePlaying("canvas"),e.goodType=e.type,e.stateChangeOB.next("STARTED")})))}},{key:"mock",value:function(e){this._decodeSink?this._decodeSink.error(e):this.start()}},{key:"close",value:function(e){this.stopOB.next(e)}},{key:"changeRenderer",value:function(e){this.renderer=e,"videoFrame"===this.renderer&&!hP()&&(this.renderer="2d"),this.wasmOption.yuvMode="webgl"===this.renderer}},{key:"decode",value:function(e){var t,n,r=this,i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!this.failedReason){this.inputFrameCount++;var a,o=new Uint8Array(e.data);if(0!==(a=o)[0]||0!==a[1]||0!==a[2]||1!==a[3]||o.length<5)return this.stateChangeOB.next("FAILED"),this.close("not h26x frame ".concat(o.subarray(0,5))),e;var s=!1;switch(31&o[4]){case 5:case 7:s=!0}if("configured"!==(null==(t=this.decoder)?void 0:t.state))return this.track.log.debug("not configured ".concat(this.inputFrameCount)),s&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:e.data,timestamp:e.timestamp,type:e.type}),e;this.gop_before_configure.length>0&&!i&&(this.gop_before_configure.forEach((function(e){return r.decode(e,!0)})),this.gop_before_configure=[]);var c=e.timestamp;if(s?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame){if(!s)return void this.track.log.debug("wait first key frame ".concat(this.inputFrameCount," ").concat(o.subarray(0,5).join(" ")));this.waitFirstKeyFrame=!1,this.startTimestamp=c,this.startTime=Date.now(),this.startPerformanceTime=aD()}switch(this.downgradeLevel){case 0:case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}return(this.decodeFrameCount<10||this.decodeFrameCount%500==0)&&this.track.log.debug("decode ".concat(this.decodeFrameCount," gop: ").concat(this.gop," ").concat(c," ").concat(null==(n=e.getMetadata)?void 0:n.call(e).rtpTimestamp)),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=c,void this.decoder.decode({data:e.data,type:e.type,timestamp:this.lastDecodeFrameTimestamp})}return e}}},{key:"checkDowngradeByFrameDiff",value:function(){var e=this.downgradeLevel,t=this.decodeFrameCount-this.decodedFrameCount;t>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):t<=this.lastFrameDiff&&this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==e&&this.track.log.debug("downgrade level ".concat(e," to ").concat(this.downgradeLevel," ").concat(this.decodeFrameCount," frameDiff: ").concat(t,", lastFrameDiff: ").concat(this.lastFrameDiff)),this.lastFrameDiff=t,this.lastDowngradeTime=Date.now()}},{key:"checkDowngradeByTimestampDiff",value:function(e){var t=this.downgradeLevel;this.lastDecodeFrameTimestamp-e>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==t&&this.track.log.debug("downgrade level ".concat(t," to ").concat(this.downgradeLevel))}},{key:"pipe",value:function(e){var t=this;return function(n){return bA(t,null,f().mark((function t(){var r,i,a,o,s,c,u,l,d,h,p,m=this;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:this._decodeSink=n,i=e.mediaTrack,n.defer((function(){var t;i&&(e.player.setCanvas(),e.setInputMediaStreamTrack(i)),null==r||r.close(),null==(t=m.videoContext)||t.destroy(),delete m._decodeSink})),a=this.renderer,o=this.type,e.log.info("decoder type: ".concat(this.type," renderer: ").concat(this.renderer)),t.prev=5,t.t0=o,t.next="wasm"===t.t0?9:"webCodecs"===t.t0?11:27;break;case 9:return r=this.createDecoder(o,this.wasmOption),t.abrupt("break",28);case 11:s=0;case 12:if(!(s<=zW.length)){t.next=25;break}return t.next=15,VideoDecoder.isConfigSupported(this.config);case 15:if(!t.sent.supported){t.next=19;break}return t.abrupt("break",25);case 19:if(s!==zW.length){t.next=21;break}return t.abrupt("return",void n.error(3));case 21:zW[s](this.config);case 22:s++,t.next=12;break;case 25:return r=this.createDecoder(o),t.abrupt("break",28);case 27:throw new Error("not supported yet");case 28:return c=0,r.on("videoFrame",(function(t){m.decodedFrameCount++,(++c<=10||c%500==0)&&e.log.debug("frame ".concat(c," ").concat(m.decodedFrameCount,"/").concat(m.decodeFrameCount," decoded ").concat(t.timestamp)),Date.now()-m.lastDowngradeTime>5e3&&("webCodecs"===m.type?m.checkDowngradeByFrameDiff():"wasm"===m.type&&m.checkDowngradeByTimestampDiff(t.timestamp)),n.next(t)})),r.on("error",(function(t){e.log.error(t),n.error("webCodecs"===o?4:8)})),t.next=33,r.initialize(this.videoElement);case 33:if(this._decodeSink){t.next=35;break}return t.abrupt("return");case 35:r.configure(this.config),"wasm"===o&&"webgl"===a?(this.videoContext=new KF({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create(),this.videoContext.on(KF.UNAVAILABLE,(function(t){e.log.error(t),n.error(7)})),u=new YW(this.videoContext),r.on("videoCodecInfo",(function(e){return u.resize(e.width,e.height)})),r.on("videoFrame",(function(e){u.Y=e.y,u.U=e.u,u.V=e.v,1===m.downgradeLevel?m.decodedFrameCount%2==0&&u.render(m.decodedFrameCount):u.render(m.decodedFrameCount)})),e.source=u,e.player.setCanvas(this.videoContext._canvas,2)):"videoFrame"===a?(e.player.setCanvas(),l=new MediaStreamTrackGenerator({kind:"video"}),d=l.writable.getWriter(),e.setInputMediaStreamTrack(l),r.on("videoFrame",(function(e){return d.write(e)}))):(this.videoContext=new YF({frameRate:15,logger:e.log,name:e.userId}),this.videoContext.create({alpha:!1}),h=this.videoContext.createVideoImageSource(),r.on("videoFrame",(function(t){try{h.image=t,h.update()}catch(a){delete m.goodType,e.log.error(a),n.error(11)}})),p=new LF(this.videoContext,{name:"remotePlayer",logger:e.log}),h.connect(p),e.source=h,e.player.setCanvas(this.videoContext._canvas,2)),this.decoder=r,t.next=42;break;case 39:t.prev=39,t.t1=t.catch(5),e.log.error(t.t1),n.error("webCodecs"===o?2:6);case 42:case"end":return t.stop()}}),t,this,[[5,39]])})))}}}])}(),ZW=function(e){function i(e){var a;return r(this,i),(a=n(this,i)).room=e,SA(t(a),"videoContext"),SA(t(a),"_glVideoContext"),SA(t(a),"_2dVideoContext"),SA(t(a),"destination"),SA(t(a),"smallVideoContext"),SA(t(a),"smallDestination"),SA(t(a),"smallTrackSource"),SA(t(a),"smallImageSource"),SA(t(a),"_isMirror",!1),SA(t(a),"_rotation",0),SA(t(a),"cameraTrack"),SA(t(a),"cameraNode"),SA(t(a),"transformNode"),SA(t(a),"mixNode"),SA(t(a),"screenTrack"),SA(t(a),"screenNode"),SA(t(a),"selfModel",!1),SA(t(a),"blurRadius",3),SA(t(a),"arTrack"),SA(t(a),"_enableFaceCentering",!1),SA(t(a),"Wasm"),SA(t(a),"waterMarkNode"),SA(t(a),"_waterMarkOption"),SA(t(a),"watermarkImageList",[]),SA(t(a),"_beautyParams"),SA(t(a),"isUsingArTrack",!1),SA(t(a),"_isMixScreen",!1),SA(t(a),"_mixScreenOption",{}),SA(t(a),"_virtualBackground"),SA(t(a),"_virtualBackgroundAbortCallback"),SA(t(a),"virtualBackgroundInstance"),SA(t(a),"_bgAssetPath"),SA(t(a),"log",Ux.createLogger({id:"vm"})),SA(t(a),"_faceDetector"),SA(t(a),"_mat4"),SA(t(a),"_checkId",0),SA(t(a),"_use2d",!1),SA(t(a),"_autoSwitchRenderMode",!0),SA(t(a),"_selfieSegmentation"),SA(t(a),"encodePipeline",[]),SA(t(a),"decodePipeline",[]),e&&(a.log.setUserId(e.userId),a.log.setSdkAppId(e.sdkAppId)),a.smallVideoContext=new YF({frameRate:15,logger:a.log,name:"s"}),a.enablePrintDetail(),a}return d(i,e),o(i,[{key:"smallMode",get:function(){var e;return(null==(e=this.room)?void 0:e.smallMode)||"canvas"}},{key:"_hasVirtualBg",get:function(){return!!this._virtualBackground}},{key:"_hasWaterMark",get:function(){return this.watermarkImageList.length>0}},{key:"_isRotate",get:function(){return 0!==this._rotation}},{key:"_isTransform",get:function(){return this._isMirror||this._isRotate}},{key:"renderMode",get:function(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"},set:function(e){if(this._autoSwitchRenderMode="auto"===e,!this._autoSwitchRenderMode){var t="2d"===e;this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}}},{key:"cameraResolution",get:function(){var e,t=(null==(e=this.cameraTrack)?void 0:e.settings)||{},n=t.width,r=t.height;return DD(this._rotation)?{width:r,height:n}:{width:n,height:r}}},{key:"get2dVideoContext",value:function(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new YF({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}},{key:"getGlVideoContext",value:function(){if(this._glVideoContext){if(this._glVideoContext.available)return this._glVideoContext}else this._glVideoContext=new KF({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}},{key:"initializeGlVideoContext",value:function(){var e=this;try{this._glVideoContext.create(),this._glVideoContext.on(KF.UNAVAILABLE,(function(t){var n;e.emit("error",t),e.log.warn("video context unavailable",t),null==(n=e._virtualBackgroundAbortCallback)||n.call(e,t),e.update().catch((function(t){e.log.error(t)}))}))}catch(qA){this.emit("error",qA)}}},{key:"enablePrintDetail",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3;this._checkId=mM.run("interval",(function(){e.destination&&e.log.debug(e.destination.getInfo())}),{delay:t})}},{key:"destroy",value:function(){var e,t;null==(e=this._2dVideoContext)||e.destroy(),null==(t=this._glVideoContext)||t.destroy(),this.smallVideoContext.destroy(),mM.clearTask(this._checkId)}},{key:"needAlpha",get:function(){return this._hasWaterMark||this._hasVirtualBg}},{key:"active",get:function(){return(sx||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}},{key:"sendCreateResult",value:function(){var e=arguments.length>1?arguments[1]:void 0,t="videoCtxGl"===(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"videoCtxGl")?512700:512701;e?rP.addFailedEvent({key:t,error:e}):rP.addSuccessEvent({key:t})}},{key:"checkOrCreateVideoContext",value:function(){var e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){var t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else{if(!t)return!0;if(!this._use2d)return!0;this.clear()}}else{if(this._glVideoContext=new KF({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}},{key:"smallTrack",get:function(){var e;return null==(e=this.smallDestination)?void 0:e.videoTrack}},{key:"hasSmall",get:function(){return!!this.smallTrack}},{key:"initialTrack",get:function(){var e;return null==(e=this.cameraTrack)?void 0:e.mediaTrack}},{key:"initVirtualBackground",value:function(e,t,n){return this._selfieSegmentation=e,this._faceDetector=t,this._mat4=n,this._selfieSegmentation.changeModel()}},{key:"setSmallVideo",value:function(e,t){var n=this;if("api"!==this.smallMode)if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new FF(this.smallVideoContext,e,this.log),this.smallVideoContext.on(KF.UNAVAILABLE,(function(e){n.log.warn("small video context lost",e)}))}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,t)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=t:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(t),this.smallImageSource.resize(t.width,t.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");var r=this.cameraTrack.settings,i=r.width,a=r.height;this.smallTrackSource.resize(i,a),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}},{key:"_setMainOutput",value:function(e){var t;try{var n=this.cameraTrack,r=n.small,i=n.player;sx&&i.setCanvas(e);var a=e&&(null==(t=this.destination)?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),a=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info("set main output ".concat(a?a.label:"no output track")),this.setSmallVideo(r,e),n.setOutputMediaStreamTrack(a)}catch(Yx){this.log.error("set main output failed",Yx)}}},{key:"update",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return bA(this,null,f().mark((function t(){var n,r,i,a,o,s,c,u,l,d,h,p;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this.cameraTrack){t.next=2;break}return t.abrupt("return");case 2:if(this.initialTrack){t.next=4;break}return t.abrupt("return",this.updateWithoutCamera());case 4:if(this.active){t.next=6;break}return t.abrupt("return",(this.cameraNode&&this.clear(),this._setMainOutput()));case 6:if(r=this.cameraTrack,i=r.settings,a=r.profile,!this._use2d&&(this._virtualBackground||this._beautyParams)){t.next=11;break}this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),16===hx?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof WF?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof WF?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(i.width,i.height),t.next=23;break;case 11:if(!(e&&this.cameraNode&&this.destination)){t.next=15;break}this.cameraNode.replaceTrack(this.initialTrack),t.next=23;break;case 15:return this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():this.destination=new UF(this.videoContext,{name:"mainDestination",logger:this.log}),o=this.cameraResolution,s=o.width,c=o.height,t.next=21,this.getWatermarkImage(s,c);case 21:u=t.sent,this._waterMarkOption={x:0,y:0,width:u.width,height:u.height,image:u},this.cameraNode=new KW(this.videoContext,{input:this.initialTrack,width:s,height:c,mirror:this._isMirror,rotation:this._rotation,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm,enableFaceCentering:this._enableFaceCentering,faceDetector:this._faceDetector,mat4:this._mat4}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute();case 23:if(this.videoContext.frameRate=a.frameRate,!this._use2d){t.next=38;break}if((l=this.cameraNode).disconnect(),this._isTransform&&(this.transformNode?(this.transformNode.mirror=this._isMirror,this.transformNode.rotation=this._rotation):this.transformNode=new WW(this.videoContext,this.log,this._isMirror,this._rotation),(l=l.connect(this.transformNode)).disconnect(),DD(this._rotation)&&this.transformNode.resize(i.height,i.width),this.log.info("start ".concat(this._isMirror?"mirror":"").concat(this._isRotate?", rotate ".concat(this.rotation):""))),this.mixNode&&this.mixNode.close(),delete this.mixNode,!this._isMixScreen&&!this._hasWaterMark){t.next=37;break}if(this.mixNode=new GW(this.videoContext,this.log),this.mixNode.resize(i.width,i.height),l.connect(this.mixNode,{zIndex:1}),!this._hasWaterMark||this.waterMarkNode||!this._waterMarkOption){t.next=30;break}this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y,t.next=36;break;case 30:if(!this.waterMarkNode){t.next=36;break}return d=this.cameraResolution,h=d.width,p=d.height,t.next=34,this.getWatermarkImage(h,p);case 34:this.waterMarkNode.image=t.sent,h&&p&&this.waterMarkNode.resize(h,p);case 36:null==(n=this.waterMarkNode)||n.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&(this.screenNode||(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource"),this.screenNode.resize(this.screenTrack.settings.width,this.screenTrack.settings.height)),this.screenNode.shouldUpdate=!1,this.screenNode.connect(this.mixNode,{zIndex:0})),this.changeMixLayout(this._mixScreenOption),l=this.mixNode,this.log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height));case 37:l.connect(this.destination);case 38:return t.abrupt("return",(this.log.info("update ".concat(this._use2d?"2d":"webgl")),this._setMainOutput(this.videoContext._canvas)));case 39:case"end":return t.stop()}}),t,this)})))}},{key:"clearLastFrame",value:function(){var e;this.destination&&(null==(e=this.destination.ctx2d)||e.clearRect(0,0,this.destination.width,this.destination.height))}},{key:"updateWithoutCamera",value:function(){return bA(this,null,f().mark((function e(){var t,n,r,i;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this._isMixScreen){e.next=2;break}return e.abrupt("return");case 2:if(this.screenTrack&&this.screenTrack.mediaTrack){e.next=4;break}return e.abrupt("return",void this.clearLastFrame());case 4:if(this.checkOrCreateVideoContext(),this._use2d){e.next=6;break}return e.abrupt("return");case 6:return this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),n=this.screenTrack,r=n.settings,i=n.profile,e.abrupt("return",(this.videoContext.frameRate=(null==(t=this.cameraTrack)?void 0:t.profile.frameRate)||i.frameRate,this.mixNode&&this.mixNode.close(),this.mixNode=new GW(this.videoContext,this.log),this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource"),this.screenNode.shouldUpdate=!0,this.screenNode.resize(r.width,r.height),this.screenNode.connect(this.mixNode,{zIndex:0}),this.changeMixLayout(this._mixScreenOption),this.mixNode.connect(this.destination),this.log.info("mix without camera"),this._setMainOutput(this.videoContext._canvas)));case 9:case"end":return e.stop()}}),e,this)})))}},{key:"changeInput",value:function(e){var t,n,r,i;if(e instanceof uV)return this.log.info("change screen input",null==(t=e.mediaTrack)?void 0:t.label),this.setScreenTrack(e);if(e instanceof oV)return this.log.info("change video input",null==(n=e.mediaTrack)?void 0:n.label),this.setCameraTrack(e);if(e instanceof zF){this.log.info("change remote input",null==(r=e.mediaTrack)?void 0:r.label);var a=e.mediaTrack;return e.setOutputMediaStreamTrack(a)}this.log.warn("change unknown input",null==(i=e.mediaTrack)?void 0:i.label)}},{key:"removeInput",value:function(e){var t;e instanceof uV?(null==(t=this.screenNode)||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof oV?this._isMixScreen?(delete this.cameraNode,this.cameraTrack._inputTrack=null,this.update()):(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof zF&&e.source&&e.source.context.destroy()}},{key:"setCameraTrack",value:function(e){return this.cameraTrack=e,this.update(!0)}},{key:"setScreenTrack",value:function(e){return bA(this,null,f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this.screenTrack=e,t.t0=this._isMixScreen,!t.t0){t.next=9;break}if(!this.screenNode){t.next=7;break}this.screenNode.replaceTrack(e.mediaTrack),t.next=9;break;case 7:return t.next=9,this.update();case 9:return t.abrupt("return",e.setOutputMediaStreamTrack(e.mediaTrack));case 10:case"end":return t.stop()}}),t,this)})))}},{key:"getWatermarkImage",value:function(e,t){return bA(this,null,f().mark((function n(){var r,i;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(r=document.createElement("canvas"),t&&e&&(r.height=t,r.width=e),i=r.getContext("2d")){n.next=5;break}throw new FA({code:VA.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});case 5:return n.abrupt("return",(this.watermarkImageList.sort((function(e,t){return e.zIndex-t.zIndex})),this.watermarkImageList.forEach((function(e){var t=e.image,n=e.x,r=e.y,a=e.width,o=e.height;i.drawImage(t,n,r,a,o)})),TD(r.toDataURL())));case 6:case"end":return n.stop()}}),n,this)})))}},{key:"pushWaterMarkImageList",value:function(e){var t=e.type;this.watermarkImageList.some((function(t){return t.imageUrl===e.imageUrl&&t.height===e.height&&t.width===e.width&&t.x===e.x&&t.y===e.y&&t.type===e.type&&t.zIndex===e.zIndex}))||(("mute"===t||"watermark"===t)&&(this.watermarkImageList=this.watermarkImageList.filter((function(e){return e.type!==t}))),this.watermarkImageList.push(e))}},{key:"setBeautyParams",value:function(e){return bA(this,null,f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:this._beautyParams=e,this.update();case 1:case"end":return t.stop()}}),t,this)})))}},{key:"stopBeauty",value:function(){return bA(this,null,f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:this._beautyParams=void 0,this.update();case 1:case"end":return e.stop()}}),e,this)})))}},{key:"setVideoMixer",value:function(e){this._isMixScreen=!0,this._mixScreenOption=e,this.update()}},{key:"updateVideoMixer",value:function(e){this.changeMixLayout(e),fD(this._mixScreenOption,e)}},{key:"changeMixLayout",value:function(e){if(this._isMixScreen&&this.mixNode){var t=e.camera,n=e.screen,r=e.container;if(this.cameraNode&&t){var i=this.cameraNode,a=i.width,o=i.height,s=t.x,c=t.y,u=t.width,l=t.height;u&&!l?l=u*o/a:!u&&l&&(u=l*a/o),this.mixNode.changeInputLayout(this.cameraNode,{x:s,y:c,width:u,height:l})}if(this.screenNode&&n){var d=this.screenNode,h=d.width,f=d.height,p=n.x,m=n.y,v=n.width,_=n.height;v&&!_?_=v*f/h:!v&&_&&(v=_*h/f),this.mixNode.changeInputLayout(this.screenNode,{x:p,y:m,width:v,height:_})}r&&this.mixNode.resize(r.width,r.height)}}},{key:"deleteVideoMixer",value:function(){var e;this._isMixScreen=!1,this._mixScreenOption={},null==(e=this.screenNode)||e.close(),delete this.screenNode,this.update(),this.log.info("delete screenMixer")}},{key:"setWatermark",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a,o,s,c,u,l,d,h,p,m;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,t.next=3,TD((null==e?void 0:e.imageElement)||e.imageUrl);case 3:n=t.sent,t.next=9;break;case 6:throw t.prev=6,t.t0=t.catch(0),new FA({code:VA.INVALID_PARAMETER,message:"load image failed, url: ".concat(e.imageUrl)});case 9:if(r=e.x,i=void 0===r?0:r,a=e.y,o=void 0===a?0:a,s=e.width,c=void 0===s?n.width:s,u=e.height,l=void 0===u?n.height:u,d=e.type,h=void 0===d?"watermark":d,p=e.zIndex,m=void 0===p?2:p,!this.watermarkImageList.some((function(e){return e.type===h}))){t.next=20;break}return this.watermarkImageList=this.watermarkImageList.filter((function(e){return e.type!==h})),this.pushWaterMarkImageList({x:i,y:o,width:c,height:l,image:n,zIndex:m,type:h,imageUrl:e.imageUrl}),t.next=15,this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.height);case 15:n=t.sent,this._waterMarkOption={x:0,y:0,width:n.width,height:n.height,image:n},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(n.width,n.height),this.waterMarkNode.image=n):this.update(),t.next=23;break;case 20:return this.pushWaterMarkImageList({x:i,y:o,width:c,height:l,image:n,zIndex:m,type:h,imageUrl:e.imageUrl}),t.next=23,this.freshWatermark();case 23:this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(function(e,t){return"imageUrl"===e?void 0:t})));case 24:case"end":return t.stop()}}),t,this,[[0,6]])})))}},{key:"deleteWatermark",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"watermark";return bA(this,null,f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return this.watermarkImageList=this.watermarkImageList.filter((function(t){return t.type!==e})),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList,(function(e,t){return"imageUrl"===e?void 0:t}))),t.next=4,this.freshWatermark();case 4:case"end":return t.stop()}}),t,this)})))}},{key:"freshWatermark",value:function(){return bA(this,null,f().mark((function e(){var t,n,r,i,a;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return null==(t=this.waterMarkNode)||t.close(),delete this.waterMarkNode,delete this._waterMarkOption,n=this.cameraResolution,r=n.width,i=n.height,e.next=6,this.getWatermarkImage(r,i);case 6:a=e.sent,this._waterMarkOption={x:0,y:0,width:a.width,height:a.height,image:a},this.update();case 8:case"end":return e.stop()}}),e,this)})))}},{key:"setVirtualBackground",value:function(e){return bA(this,null,f().mark((function t(){var n;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!e){t.next=14;break}if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),!this._use2d||this._autoSwitchRenderMode){t.next=3;break}return t.abrupt("return",Promise.reject(new Error("not support virtual background in 2d mode")));case 3:if(this._bgAssetPath=e.assetPath,"image"!==e.type){t.next=10;break}return t.next=7,TD(e.imageUrl);case 7:this._virtualBackground=t.sent,t.next=11;break;case 10:this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type;case 11:this._enableFaceCentering=null!=(n=e.enableFaceCentering)?n:this._enableFaceCentering,t.next=15;break;case 14:delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;case 15:return this.log.info("".concat(this._virtualBackground?"start":"stop"," virtual background, ").concat((null==e?void 0:e.type)||"",", ").concat(this.blurRadius||"")),t.next=18,this.update();case 18:if(!this._virtualBackground||this._glVideoContext.available){t.next=20;break}throw new FA({code:VA.INVALID_OPERATION,message:"webgl context create failed, ".concat(this._glVideoContext.error)});case 20:case"end":return t.stop()}}),t,this)})))}},{key:"mixScreen",get:function(){return this._isMixScreen},set:function(e){var t;this._isMixScreen=e,this._isMixScreen||(null==(t=this.screenNode)||t.close(),delete this.screenNode),this.update()}},{key:"mirror",get:function(){return this._isMirror},set:function(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isTransform||(null==(t=this.transformNode)||t.close(),delete this.transformNode),this.update())}},{key:"rotation",get:function(){return this._rotation},set:function(e){var t;this._rotation!==e&&(this._rotation=e,this._isTransform||(null==(t=this.transformNode)||t.close(),delete this.transformNode),this.update())}},{key:"enableAr",value:function(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}},{key:"updateAr",value:function(){return bA(this,null,f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.t0=null!=(t=this.cameraTrack)&&t.mediaTrack,!e.t0){e.next=4;break}return e.next=4,this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone());case 4:case"end":return e.stop()}}),e,this)})))}},{key:"disableAr",value:function(){var e;this.isUsingArTrack=!1,null==(e=this.arTrack)||e.stop(),this.arTrack=void 0,this.update()}},{key:"createDecodeContext",value:function(e){return new QW(e)}},{key:"clear",value:function(){var e;null==(e=this.videoContext)||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.transformNode,delete this.screenNode,delete this.waterMarkNode}},{key:"addEncodeProcessor",value:function(e){var t,n=e.processor,r=e.type;this.encodePipeline.includes(n)||(this.encodePipeline[r]=n,null==(t=this.room)||t.enableInsertableStreams())}},{key:"addDecodeProcessor",value:function(e){var t,n=e.processor,r=e.type;this.decodePipeline.includes(n)||(this.decodePipeline[r]=n,null==(t=this.room)||t.enableInsertableStreams())}},{key:"removeEncodeProcessor",value:function(e){var t=e.type;this.encodePipeline[t]=void 0}},{key:"removeDecodeProcessor",value:function(e){var t=e.type;this.decodePipeline[t]=void 0}}])}(BW.EventEmitter);TA([WL((function(e){this.log.error("update failed",e)}))],ZW.prototype,"update",1);var $W=0,ej=function(e){function i(e){var a;return r(this,i),a=n(this,i,["room"]),SA(t(a),"seq",++$W),SA(t(a),"sdkAppId"),SA(t(a),"userId"),SA(t(a),"userSig"),SA(t(a),"privateMapKey"),SA(t(a),"latencyLevel"),SA(t(a),"tinyId"),SA(t(a),"scene"),SA(t(a),"roomId"),SA(t(a),"useStringRoomId"),SA(t(a),"role","anchor"),SA(t(a),"joinParams",null),SA(t(a),"localTracks",new Set),SA(t(a),"enableAutoPlayDialog",!0),SA(t(a),"autoReceiveAudio",!0),SA(t(a),"autoReceiveVideo",!0),SA(t(a),"proxy_ws"),SA(t(a),"proxy_wt"),SA(t(a),"proxy_unified"),SA(t(a),"checkSystemResult",{result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0}}),SA(t(a),"keyPointManager"),SA(t(a),"audioManager"),SA(t(a),"videoManager"),SA(t(a),"callDurationCalculator"),SA(t(a),"badCaseDetector"),SA(t(a),"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}),SA(t(a),"videoDecodeFallbackType"),SA(t(a),"smallMode","canvas"),SA(t(a),"_isUsingCachedSchedule",!1),SA(t(a),"_log",Ux.createLogger({id:"r".concat(a.seq)})),SA(t(a),"_joinedTimestamp",0),SA(t(a),"_sdkType"),SA(t(a),"heartbeatReport"),SA(t(a),"quality"),SA(t(a),"enableSEI"),SA(t(a),"isDestroyed",!1),a.useStringRoomId=!!e.useStringRoomId,qw(e.autoReceiveAudio)&&(a.autoReceiveAudio=e.autoReceiveAudio),qw(e.autoReceiveVideo)&&(a.autoReceiveVideo=e.autoReceiveVideo),qw(e.enableAutoPlayDialog)&&(a.enableAutoPlayDialog=e.enableAutoPlayDialog),a._sdkType=e.sdkType,a.keyPointManager=new LW({room:t(a),frameWorkType:e.frameWorkType,component:e.component,language:e.language}),a.callDurationCalculator=new UW({room:t(a)}),a.badCaseDetector=new FW({room:t(a)}),a.audioManager=new fV(t(a)),a.videoManager=new ZW(t(a)),a}return d(i,e),o(i,[{key:"scriptTransformWorker",get:function(){}},{key:"isMainStreamPublished",get:function(){var e,t=s(this.localTracks);try{for(t.s();!(e=t.n()).done;)if(4&e.value.mediaType)return!0}catch(n){t.e(n)}finally{t.f()}return!1}},{key:"isAuxStreamPublished",get:function(){var e,t=s(this.localTracks);try{for(t.s();!(e=t.n()).done;)if(2&e.value.mediaType)return!0}catch(n){t.e(n)}finally{t.f()}return!1}},{key:"hasAuxStream",get:function(){var e,t=s(this.remotePublishedUserMap.values());try{for(t.s();!(e=t.n()).done;)if(e.value.muteState.hasAuxiliary)return!0}catch(n){t.e(n)}finally{t.f()}return this.isAuxStreamPublished}},{key:"localMainVideoTrack",get:function(){var e,t=s(this.localTracks);try{for(t.s();!(e=t.n()).done;){var n=e.value;if(4&n.mediaType)return n}}catch(r){t.e(r)}finally{t.f()}return null}},{key:"localAuxVideoTrack",get:function(){var e,t=s(this.localTracks);try{for(t.s();!(e=t.n()).done;){var n=e.value;if(2&n.mediaType)return n}}catch(r){t.e(r)}finally{t.f()}return null}},{key:"getLogger",value:function(){return this._log}},{key:"isJoining",get:function(){return"joining"===this.state.toString()}},{key:"isJoined",get:function(){return"joined"===this.state}},{key:"isLeft",get:function(){return"left"===this.state}},{key:"addTrack",value:function(e){return bA(this,null,f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.abrupt("return",this.publish(e));case 1:case"end":return t.stop()}}),t,this)})))}},{key:"removeTrack",value:function(e){return bA(this,null,f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.abrupt("return",this.unpublish(e));case 1:case"end":return t.stop()}}),t,this)})))}},{key:"replaceTrack",value:function(e){return bA(this,null,f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:case"end":return e.stop()}}),e)})))}},{key:"setEncodedDataProcessingListener",value:function(e){throw new Error("Method not implemented.")}},{key:"enableAIVoice",value:function(e){throw new Error("Method not implemented.")}},{key:"setProxyServer",value:function(e){var t=this;if(Yw(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Hw(e)){var n=e.websocketProxy,r=e.webtransportProxy,i=e.loggerProxy,a=e.scheduleProxy,o=e.unifiedProxy;this.proxy_ws=n,this.proxy_wt=r,this.proxy_unified=o,o?(KB([o,o]),tC("https://".concat(o))):(i&&tC(i),a&&KB(a))}Px.once(Lx.JOIN_RECEIVED_CMD_RES,(function(){return t.sendAbilityStatus({sched_domain:JB.main,sched_back_domain:JB.backup,signal_domain:t.proxy_ws||t.proxy_wt||""})}))}},{key:"getRemoteAudioStats",value:function(){return bA(this,null,f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t={},e.abrupt("return",(this.remotePublishedUserMap.forEach((function(e){t[e.userId]=e.remoteAudioTrack.stat})),t));case 2:case"end":return e.stop()}}),e,this)})))}},{key:"getTransportStats",value:function(){return bA(this,null,f().mark((function e(){var t,n,r,i,a;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n={rtt:(null==(t=this.quality)?void 0:t.uplinkRTT)||0,downlinksRTT:{}},this.quality){r=s(this.quality.downlinkInfo);try{for(r.s();!(i=r.n()).done;)a=i.value,n.downlinksRTT[a.userId]=a.rtt}catch(o){r.e(o)}finally{r.f()}}return e.abrupt("return",n);case 3:case"end":return e.stop()}}),e,this)})))}},{key:"getRemoteVideoStats",value:function(){return bA(this,arguments,(function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"main";return f().mark((function n(){var r;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return r={},n.abrupt("return",(e.remotePublishedUserMap.forEach((function(e){var n="auxiliary"===t?e.remoteAuxiliaryTrack:e.remoteVideoTrack;r[e.userId]=n.stat})),r));case 2:case"end":return n.stop()}}),n)}))()}))}},{key:"checkDestroy",value:function(){if(this.isDestroyed)throw new FA({code:VA.INVALID_OPERATION,message:YO({key:jO.CLIENT_DESTROYED,data:{funName:"join"}})})}},{key:"destroy",value:function(){if(this.isJoined)throw this._log.warn(GO.INVALID_DESTROY),new FA({code:VA.INVALID_OPERATION,message:YO({key:jO.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,Px.emit(Lx.ROOM_DESTROY,{room:this})}},{key:"schedule",value:function(e,t){return bA(this,null,f().mark((function n(){var r,i,a,o,s,c,u,l,d,h=this;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return s=aD(),n.prev=1,n.next=4,GB({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:YA,userSig:this.userSig,role:"live"===this.scene?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});case 4:c=n.sent,u=c.isCached,l=c.result,d=c.detailCost,this._isUsingCachedSchedule=u,this._log.info("schedule cache:".concat(+u," ").concat(gD(l,{keysToExclude:["username","credential"]}))),u&&Px.once(Lx.JOIN_RECEIVED_CMD_RES,(function(){return h.sendAbilityStatus({scheduleCache:1})})),this.scheduleResult=_A(_A({},this.scheduleResult),l),zw(null==(r=l.config)?void 0:r.retryCount)&&XC(l.config.retryCount),Yw(null==(i=l.config)?void 0:i.loggerDomain)&&tC(l.config.loggerDomain),this.videoDecodeFallbackType=(null==(a=l.config)?void 0:a.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=(null==(o=l.config)?void 0:o.smallMode)||this.smallMode,Px.emit(Lx.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:d}),rP.addSuccessEvent({key:521700,cost:aD()-s}),n.next=14;break;case 11:throw n.prev=11,n.t0=n.catch(1),rP.addFailedEvent({key:521700,error:n.t0}),n.t0;case 14:case"end":return n.stop()}}),n,this,[[1,11]])})))}},{key:"sendAbilityStatus",value:function(e){}},{key:"enableInsertableStreams",value:function(){return Promise.resolve()}},{key:"switchRoom",value:function(e){return Promise.reject()}},{key:"isSwitchRoomSupported",value:function(){return!1}}])}(uM),tj=kA(RA()),nj=kA(PA());function rj(e){for(var t,n=[],r=function(r){if(["rtx","red","ulpfec"].includes(e.rtp[r].codec))return 1;var i=e.fmtp.filter((function(t){return t.payload===e.rtp[r].payload}))[0];n.push({payload:e.rtp[r].payload,codec:e.rtp[r].codec,fmtp:i?i.config:"",rate:e.rtp[r].rate,rtx:"rtx"===(null==(t=e.rtp[r+1])?void 0:t.codec)?e.rtp[r+1].payload:0,rtcpfb:((null==e?void 0:e.rtcpFb)||[]).filter((function(t){return t.payload===e.rtp[r].payload})).map((function(e){var t=e.type,n=e.subtype;return{id:t,params:n?[n]:[]}}))})},i=0;i<e.rtp.length;i++)r(i);return n}var ij=function(e,t){return bA(void 0,null,f().mark((function n(){var r,i,a,o,s,c,u;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return i=kW(e),(a={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1}).ice.ufrag=String(i.media[0].iceUfrag),a.ice.password=i.media[0].icePwd||"",i.fingerprint&&(a.dtls.hash=i.fingerprint.type,a.dtls.fingerprint=i.fingerprint.hash,a.dtls.setup=i.setup||""),i.media[0].fingerprint&&(a.dtls.hash=i.media[0].fingerprint.type,a.dtls.fingerprint=i.media[0].fingerprint.hash),a.dtls.setup=i.media[0].setup||"",o=i.media[0],s=i.media[1],o.ext&&(a.audio.extensions=o.ext.map((function(e){return{id:e.value,uri:e.uri}}))),s.ext&&(a.video.extensions=s.ext.map((function(e){return{id:e.value,uri:e.uri}}))),c={codec:o.rtp[0].codec,fmtp:o.fmtp[0].config,payload:o.fmtp[0].payload,rate:o.rtp[0].rate,channels:o.rtp[0].encoding,rtcpfb:[],rtx:0},null==(r=o.rtcpFb)||r.forEach((function(e){var t=e.payload,n=e.type,r=e.subtype;if(t===c.payload){var i={id:n,params:[]};r&&i.params.push(r),c.rtcpfb.push(i)}})),a.audio.codecs.push(c),u=["h264","vp8"],t&&u.shift(),a.video.codecs=E(rj(s)).filter((function(e){return u.includes(e.codec.toLocaleLowerCase())})),n.next=11,function(){return bA(this,null,f().mark((function e(){var t,n,r;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return(t=new RTCPeerConnection).addTransceiver(IC.VIDEO,{direction:IC.TRANSCEIVER_DIRECTION_RECVONLY}),e.next=4,t.createOffer();case 4:if((n=e.sent).sdp){e.next=7;break}return e.abrupt("return",[]);case 7:return r=rj(kW(n.sdp).media[0]),e.abrupt("return",(t.close(),r));case 9:case"end":return e.stop()}}),e)})))}();case 11:return a.video.decoders=n.sent.filter((function(e){return["h264","vp8"].includes(e.codec.toLocaleLowerCase())})),n.abrupt("return",a);case 13:case"end":return n.stop()}}),n)})))},aj=function(e){var t=e.serverAbility,n=e.clientAbility,r=e.offerSDP,i=e.enableCustomMessage,a=kW(r),o={extmapAllowMixed:"extmap-allow-mixed",groups:a.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},s={candidates:t.candidates.map((function(e){return{component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}})),connection:{version:4,ip:"0.0.0.0"},direction:IC.TRANSCEIVER_DIRECTION_RECVONLY,ext:t.audio.extensions.map((function(e){return{value:e.id,uri:e.uri}})),fingerprint:{type:t.dtls.hash,hash:t.dtls.fingerprint},fmtp:[{payload:t.audio.codecs[0].payload,config:t.audio.codecs[0].fmtp}],icePwd:t.ice.password,iceUfrag:t.ice.ufrag,mid:"0",payloads:String(t.audio.codecs[0].payload),port:a.media[0].port,protocol:a.media[0].protocol,type:IC.AUDIO,setup:t.dtls.setup,rtcpFb:t.audio.codecs[0].rtcpfb.map((function(e){return{payload:t.audio.codecs[0].payload,type:e.id,subtype:e.params[0]}})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:t.audio.codecs[0].payload,codec:t.audio.codecs[0].codec,rate:t.audio.codecs[0].rate,encoding:t.audio.codecs[0].channels}]};return o.media.push(s),[1,2,3].forEach((function(e){o.media.push(oj({mid:e,serverAbility:t,clientAbility:n,parsedOffer:a}))})),i&&o.media.push(a.media.find((function(e){return"dc"===e.mid}))),TW(o)},oj=function(e){var t=e.mid,n=e.serverAbility,r=e.clientAbility,i=e.parsedOffer,a=e.isDownlink,o=void 0!==a&&a,s={candidates:n.candidates.map((function(e){return{component:1,foundation:"1",generation:0,ip:e.ip,port:e.port,priority:e.priority,transport:e.foundation,type:e.type}})),connection:{version:4,ip:"0.0.0.0"},direction:IC.TRANSCEIVER_DIRECTION_RECVONLY,ext:n.video.extensions.map((function(e){return{value:e.id,uri:e.uri}})),fingerprint:{type:n.dtls.hash,hash:n.dtls.fingerprint},fmtp:[],icePwd:n.ice.password,iceUfrag:n.ice.ufrag,mid:String(t),payloads:"",port:i.media[0].port,protocol:i.media[0].protocol,type:IC.VIDEO,setup:n.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(o){var c=n.video.decoders;(!c||0===c.length)&&(c=n.video.codecs),(!c||0===c.length)&&(c=r.video.decoders),c.forEach((function(e){sj(s,e)}))}else{var u=n.video.codecs.findIndex((function(e){return e.codec.toLowerCase()===(n.useVp8?"vp8":"h264")})),l=n.video.codecs[u]||r.video.codecs[0];sj(s,l)}return s},sj=function(e,t){e.payloads="".concat(e.payloads," ").concat(t.payload).trim(),e.fmtp.push({payload:t.payload,config:t.fmtp}),e.rtcpFb=[].concat(E(e.rtcpFb||[]),E(t.rtcpfb.map((function(e){return{payload:t.payload,type:e.id,subtype:e.params[0]}})))),e.rtp.push({payload:t.payload,codec:t.codec.toUpperCase(),rate:t.rate}),t.rtx&&(e.payloads="".concat(e.payloads," ").concat(t.rtx),e.fmtp.push({payload:t.rtx,config:"apt=".concat(t.payload)}),e.rtp.push({payload:t.rtx,codec:"rtx",rate:t.rate}))},cj=function(e){function i(e){var a;return r(this,i),(a=n(this,i)).room=e,SA(t(a),"mainFpsHealth",1),SA(t(a),"mainBitrateHealth",1),SA(t(a),"badMainBitrateHealthCount",0),SA(t(a),"lastEmitBadHealthTime",0),SA(t(a),"log"),!$D&&tx&&Px.on("262",a.onVideoCodecChanged,t(a)),a.log=e.getLogger().createChild({id:"h-d"}),a}return d(i,e),o(i,[{key:"onVideoCodecChanged",value:function(e){var t=e.remoteUserId,n=e.streamType,r=e.isHWCodec,i=e.codec;if(!t&&7!==n&&"h264"===i){if(!r)return void this.room.off("heartbeat-report",this.onHeartbeatReport,this);this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}},{key:"onHeartbeatReport",value:function(e){var t=this;Date.now()-this.lastEmitBadHealthTime<3e4||(e.msg_up_stream_info.msg_video_status.forEach((function(e){if(e.uint32_video_enc_fps&&e.uint32_video_capture_fps){var n=e.uint32_video_enc_fps/e.uint32_video_capture_fps;2===e.uint32_video_stream_type&&(t.mainFpsHealth=n)}if(e.uint32_video_codec_bitrate&&2===e.uint32_video_stream_type){var r=t.room.localMainVideoTrack;r&&(t.mainBitrateHealth=e.uint32_video_codec_bitrate/1e3/r.profile.bitrate)}})),this.log.debug("mainBitrateHealth: ".concat(this.mainBitrateHealth," mainFpsHealth: ").concat(this.mainFpsHealth)),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn("bad main bitrate health: ".concat(this.mainBitrateHealth)),this.emit("1",{isAux:!1}))))}},{key:"destroy",value:function(){Px.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}}])}(kA(RA()).EventEmitter);SA(cj,"EVENT_BAD_HEALTH","bad_health");var uj=cj;function lj(e){var t=e.seiMessageList,n=e.isAudio,r=e.isMain;return new TransformStream({transform:function(e,i){var a=e;n?audioEncodePipeline.forEach((function(e){a=e({frame:a})})):videoEncodePipeline.forEach((function(e){a=e({frame:a,seiMessageList:t,onDump:function(){self.postMessage({type:"dump",isAudio:n,data:a.data,userId:"",streamType:r?"main":"auxiliary"})}})})),i.enqueue(a)}})}function dj(e,t,n){return new TransformStream({transform:function(r,i){var a=r;videoDecodePipeline.forEach((function(r){a=r({frame:a,onSEI:function(n){n.forEach((function(n){self.postMessage({type:"sei",seiPayloadType:n.seiPayloadType,data:n.seiPayload.buffer,userId:e,streamType:t})}))},onDump:function(){self.postMessage({type:"dump",isAudio:n,data:a.data,userId:e,streamType:t})}})})),i.enqueue(a)}})}var hj=function(e){return e.TRACK="track",e.DATA_CHANNEL_MESSAGE="data_channel_msg",e[e.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",e[e.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",e.RECONNECTED="spc-reconnected",e.RECONNECT_FAILED="spc-reconnect-failed",e.ERROR="error",e.SEI_MESSAGE="sei-message",e.DUMP="dump",e}(hj||{}),fj=0,pj=!1,mj=new Set,vj=1,_j=function(e){function i(e){var a;r(this,i);var o=e.signalChannel,s=e.room,c=e.enableCustomMessage;return a=n(this,i),SA(t(a),"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),SA(t(a),"currentState","DISCONNECTED"),SA(t(a),"_room"),SA(t(a),"_signalChannel"),SA(t(a),"_peerConnection",null),SA(t(a),"_datachannel",null),SA(t(a),"_enableCustomMessage"),SA(t(a),"_log"),SA(t(a),"_downlinkMIDMap",new Map),SA(t(a),"_downlinkMIDUserIDMap",new Map),SA(t(a),"_reconnectionTimer",-1),SA(t(a),"reconnectionCount",0),SA(t(a),"clientAbility"),SA(t(a),"_serverAbility",null),SA(t(a),"addDownlinkQueue",new Set),SA(t(a),"removeDownlinkQueue",new Set),SA(t(a),"_parsedAnswer",null),SA(t(a),"_updateSDPPromise",null),SA(t(a),"_waitForPCConnectedPromise"),SA(t(a),"clearWaitForConnectedPromise"),SA(t(a),"clearConnectTimeout"),SA(t(a),"_isSDPLogged",!1),SA(t(a),"enableInsertableStreams",!1),SA(t(a),"insertableStreamsAbortMap",new Map),SA(t(a),"receiverRemoteTrackMap",new WeakMap),SA(t(a),"scriptTransformWorker"),SA(t(a),"_isRelayTried",!1),SA(t(a),"_rttOverCount",0),SA(t(a),"originOffer",null),SA(t(a),"autoSubscribedSsrcGroups",new Map),SA(t(a),"autoSubscribedUserMap",new Map),a._room=s,a._enableCustomMessage=c,a._signalChannel=o,a._log=Ux.createLogger({id:"spc".concat(vj++),userId:a._room.userId,sdkAppId:a._room.sdkAppId}),a._room.enableCodecPipeline&&(HP?a.enableInsertableStreams=!0:a.initScriptTransformWorker()),a._room.healthDetector.on("1",a.onBadHealth,t(a)),a}return d(i,e),o(i,[{key:"isH264EncodeSupported",get:function(){var e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find((function(e){return"h264"===e.codec.toLowerCase()}))),e}},{key:"addAbortController",value:function(e,t){var n;null==(n=this.insertableStreamsAbortMap.get(e))||n.abort("destory"),this.insertableStreamsAbortMap.set(e,t)}},{key:"isVP8EncodeSupported",get:function(){var e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.video.codecs.find((function(e){return"vp8"===e.codec.toLowerCase()}))),e}},{key:"videoCodec",get:function(){var e,t,n=null==(e=this._parsedAnswer)?void 0:e.media[1].rtp.find((function(e){return["h264","vp8"].includes(e.codec.toLowerCase())}));return n?n.codec.toLowerCase():null!=(t=this._serverAbility)&&t.useVp8?"vp8":"h264"}},{key:"downlinkVideoCodec",get:function(){var e;return null!=(e=this._serverAbility)&&e.video.decoders.find((function(e){return"h264"===e.codec.toLowerCase()}))?"h264":"vp8"}},{key:"isUsingH264",get:function(){return"h264"===this.videoCodec}},{key:"is42001fSupported",get:function(){return!!this.clientAbility&&!!this.clientAbility.video.codecs.find((function(e){return e.fmtp.includes("42001f")}))}},{key:"uplinkSSRC",get:function(){return this._peerConnection&&this._peerConnection.localDescription?function(e){var t=kW(e),n={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return t.media.forEach((function(e,t){var r;if(e.ssrcs&&!Kw(e.ssrcs[0].id)){var i=Number(e.ssrcs[0].id),a=Number(null==(r=e.ssrcs.filter((function(e){return"cname"===e.attribute}))[1])?void 0:r.id);switch(t){case 0:n.audioSsrc=i;break;case 1:n.bigVideoSsrc=i,n.bigVideoRtxSsrc=a;break;case 2:n.smallVideoSsrc=i,n.smallVideoRtxSsrc=a;break;case 3:n.auxVideoSsrc=i,n.auxVideoRtxSsrc=a}}})),n}(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}},{key:"onBadHealth",value:function(e){var t=e.isAux;this.useHWEncoder(!1,t?7:2)}},{key:"initScriptTransformWorker",value:function(){var e=this;WP&&(this.scriptTransformWorker=function(e){var t=[rV],n=[AH,bH,RH,IH,lj,dj],r="const videoEncodePipeline=[".concat(e.videoEncodePipeline.toString(),"];\n const videoDecodePipeline=[").concat(e.videoDecodePipeline.toString(),"];\n const audioEncodePipeline = [").concat(e.audioEncodePipeline.toString(),"];\n const audioDecodePipeline = [").concat(e.audioDecodePipeline.toString(),"];"),i="(()=>{".concat(t.map((function(e){return"const ".concat(e.name,"=(()=>").concat(e.toString(),")()")})).join("\n"),"\n").concat(n.map((function(e){return e.toString()})).join("\n"),";(").concat((function(){var e=[],t=[],n=[];self.onmessage=function(r){"sei"===r.data.type&&(r.data.isMain?(e.push(r.data.data),r.data.small&&n.push(r.data.data)):t.push(r.data.data))},self.onrtctransform=function(r){var i=r.transformer.options,a=i.isReceiver?dj(i.userId,i.streamType,i.isAudio):lj({isAudio:i.isAudio,seiMessageList:i.isMain?i.small?n:e:t,isMain:i.isMain});r.transformer.readable.pipeThrough(a).pipeTo(r.transformer.writable)}}),")();").concat(r,"})()"),a=new Blob([i],{type:"text/javascript"}),o=URL.createObjectURL(a),s=new Worker(o);return URL.revokeObjectURL(o),s}({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=function(t){"sei"===t.data.type&&e.emit("sei-message",t.data),"dump"===t.data.type&&e.emit("dump",t.data)},this.scriptTransformWorker.onerror=function(t){e._log.error("scriptTransformWorker error: ",t)})}},{key:"isReconnecting",get:function(){return"RECONNECTING"===this.currentState||this._reconnectionTimer>0||this.reconnectionCount>0}},{key:"dtlsTransport",get:function(){if(!this._peerConnection)return null;var e=this._peerConnection.getSenders();return 0===e.length?null:e[0].transport}},{key:"getPeerConnectionConfig",value:function(e){var t,n={encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:e,iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},r=null==(t=this._peerConnection)?void 0:t.getConfiguration().encodedInsertableStreams;return LD(r)&&(n.encodedInsertableStreams=r),this._log.debug("getPeerConnectionConfig",JSON.stringify(n)),n}},{key:"initialize",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i=this;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,this._peerConnection=new RTCPeerConnection(this.getPeerConnectionConfig(e)),this._peerConnection.oniceconnectionstatechange=function(){if(i._peerConnection){var e=i._peerConnection.iceConnectionState;i._log.debug("ice state: ".concat(e)),"checking"===e&&0===i.stat.iceStartTime?i.stat.iceStartTime=Date.now():"connected"===e&&0===i.stat.iceEndTime?(i.stat.iceEndTime=Date.now(),i._signalChannel.clearBakRelayIps(),rP.addSuccessEvent({key:521711,cost:i.stat.iceEndTime-i.stat.iceStartTime})):"failed"===e&&rP.addFailedEvent({key:521711})}},this._peerConnection.onsignalingstatechange=function(){var e,t=(null==(e=i._peerConnection)?void 0:e.signalingState)||"";i._log["closed"===t?"debug":"info"]("signaling state: ".concat(t))},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=function(e){return i.emit("track",e)},this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel("".concat(this._room.userId,"dc")),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=function(){i._log.info("datachannel open")},this._datachannel.onclose=function(){i._log.warn("datachannel close")},this._datachannel.onmessage=function(e){var t=new yj(e.data);i.emit("data_channel_msg",{data:t})},this._datachannel.onerror=function(e){i._log.warn("datachannel error",e)}),this._peerConnection.addTransceiver(IC.AUDIO,{direction:IC.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(IC.VIDEO,{direction:IC.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(IC.VIDEO,{direction:IC.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(IC.VIDEO,{direction:IC.TRANSCEIVER_DIRECTION_SENDONLY}),t.next=13,this._peerConnection.createOffer();case 13:return r=t.sent,t.next=16,ij(r.sdp,(null==(n=this._room.scheduleResult.config)?void 0:n.remove264FromSDP)||!1);case 16:return this.clientAbility=t.sent,this.originOffer=r,this.dtlsTransport&&(this.dtlsTransport.onstatechange=function(){var e=i.dtlsTransport;e&&(i._log.debug("dtls state: ".concat(e.state)),"connecting"===e.state&&0===i.stat.dtlsStartTime?i.stat.dtlsStartTime=Date.now():"connected"===e.state&&0===i.stat.dtlsEndTime&&(i.stat.dtlsEndTime=Date.now()))}),rP.addSuccessEvent({key:521707}),t.abrupt("return",this.clientAbility);case 23:throw t.prev=23,t.t0=t.catch(0),rP.addFailedEvent({key:521707,error:t.t0}),this._log.error("initialize failed ".concat(t.t0," \noffer: ").concat(null==r?void 0:r.sdp)),t.t0;case 26:case"end":return t.stop()}}),t,this,[[0,23]])})))}},{key:"setIceServers",value:function(e){return bA(this,null,f().mark((function t(){var n;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!this._peerConnection||0===e.length){t.next=11;break}if(t.prev=1,this._log.info("setIceServers",JSON.stringify(e)),this._peerConnection.setConfiguration(this.getPeerConnectionConfig(e)),(null==(n=this._peerConnection)||!n.localDescription)&&this.originOffer){t.next=4;break}return t.abrupt("return",void this._log.warn("setIceServers already has localDescription or no origin Offer"));case 4:return t.next=6,this.setOffer(this.originOffer);case 6:t.next=11;break;case 8:t.prev=8,t.t0=t.catch(1),this._log.warn("setIceServers error ",t.t0);case 11:case"end":return t.stop()}}),t,this,[[1,8]])})))}},{key:"setPriority",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"high";if(this._peerConnection)try{this._peerConnection.getSenders().forEach((function(n){var r=n.getParameters();r.encodings[0]&&(r.encodings[0].priority=t,r.encodings[0].networkPriority=t,n.setParameters(r).catch((function(t){e._log.warn("setPriority error ",t)})))}))}catch(ZC){this._log.warn("setPriority error ",ZC)}}},{key:"connect",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return bA(this,null,f().mark((function n(){var r,i,a,o,s,c,u;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(n.prev=0,"CONNECTED"!==this.currentState){n.next=3;break}return n.abrupt("return");case 3:if(n.t0=(null==(r=this._peerConnection)||!r.localDescription)&&this.originOffer,!n.t0){n.next=7;break}return n.next=7,this.setOffer(this.originOffer);case 7:return o=aD(),s={type:"answer",sdp:aj({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})},this._serverAbility=e,n.next=11,this.setAnswer(s);case 11:return n.next=13,this.waitForPeerConnectionConnected();case 13:(c=(null==(i=this._room.scheduleResult.config)?void 0:i.priority)||(null==(a=this._room.joinParams)?void 0:a.priority)||new URLSearchParams(location.search).get("priority"))&&this.setPriority(c),t||rP.addSuccessEvent({key:521703,cost:aD()-o}),n.next=21;break;case 17:throw n.prev=17,n.t1=n.catch(0),(u=n.t1 instanceof FA&&n.t1.code===VA.API_CALL_ABORTED)||this._log.error("connect failed: ".concat(n.t1),e),this.reset(),!u&&!this.isReconnecting&&(rP.addFailedEvent({key:521703,error:n.t1}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),n.t1;case 21:case"end":return n.stop()}}),n,this,[[0,17]])})))}},{key:"reconnect",value:function(){return bA(this,null,f().mark((function e(){var t,n,r,i,a,o=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(-1!==this._reconnectionTimer){e.next=41;break}if(this._signalChannel.isConnected){e.next=3;break}return e.abrupt("return",(this._log.warn("reconnect() wait signal channel is connected"),void this._signalChannel.once(tW,this.reconnect,this)));case 3:return e.prev=3,this.reconnectionCount+=1,this._log.warn("reconnect() trying [".concat(this.reconnectionCount,"]")),this.reset(),t=this._signalChannel.getBackupRelayIpPair(),e.next=8,this.initialize(this._room.getIceServers(null!=t&&t.iceServer?[t.iceServer]:[]));case 8:return n=e.sent,r=_A({ability:n},t),e.next=12,this._signalChannel.sendWaitForResponse({command:"rebuild_pc",responseCommand:aW.REBUILD_PEER_CONNECTION_RES,data:r,enableLog:!1});case 12:if(0===(i=e.sent).data.code){e.next=15;break}throw new FA({code:i.data.code,message:i.data.message});case 15:return e.next=17,this.connect(i.data.data.ability,!0);case 17:rP.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),Px.emit(Lx.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected"),e.next=39;break;case 24:if(e.prev=24,e.t0=e.catch(3),this.isReconnecting){e.next=28;break}return e.abrupt("return");case 28:if(null==e.t0||!e.t0.message.includes("timeout")){e.next=38;break}return a=jw(this.reconnectionCount),this._log.warn("reconnect() timeout, try again after ".concat(a/1e3,"s")),e.next=33,bD(a,(function(e){o._reconnectionTimer=e}));case 33:return this.clearReconnectionTimer(),e.next=36,this.reconnect();case 36:e.next=39;break;case 38:this._log.error("reconnect() failed ".concat(null==e.t0?void 0:e.t0.code," ").concat(e.t0)),rP.addFailedEvent({key:521704,error:e.t0}),this.reconnectionCount>=QC()&&this._log.warn("SDK has tried reconnect for ".concat(QC()," times, but all failed, please check your network")),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error");case 39:e.next=42;break;case 41:this._log.warn("reconnect() is reconnecting, ignore current reconnection");case 42:case"end":return e.stop()}}),e,this,[[3,24]])})))}},{key:"getPeerConnection",value:function(){return this._peerConnection}},{key:"startReconnection",value:function(){return bA(this,null,f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.t0=this.isReconnecting,e.t0){e.next=7;break}return this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),e.next=7,this.reconnect();case 7:case"end":return e.stop()}}),e,this)})))}},{key:"stopReconnection",value:function(){var e;this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),null==(e=this.clearConnectTimeout)||e.call(this),this._signalChannel.off(tW,this.reconnect,this),"RECONNECTING"===this.currentState&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}},{key:"checkPeerConnectionToReconnect",value:function(){var e;!this.isReconnecting&&(null==(e=this._peerConnection)?void 0:e.connectionState)===zC.CLOSED&&this.startReconnection()}},{key:"clearReconnectionTimer",value:function(){-1!==this._reconnectionTimer&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}},{key:"onConnectionStateChange",value:function(e){var t,n=(null==(t=this._peerConnection)?void 0:t.iceConnectionState)||"closed",r=this.getDTLSTransportState();this._log.info("connectionState: ".concat(e.target.connectionState," ICE: ").concat(n," DTLS: ").concat(r)),e.target.connectionState===zC.CONNECTING&&(0===this.stat.peerConnectionStartTime&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===zC.FAILED||e.target.connectionState===zC.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===zC.CONNECTED||e.target.connectionState===zC.COMPLETED)&&(0===this.stat.peerConnectionEndTime&&(this.stat.peerConnectionEndTime=Date.now()),Px.emit(Lx.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}},{key:"getDTLSTransportState",value:function(){if(!this._peerConnection)return YC;var e=null;return DP()&&0!==this._peerConnection.getSenders().length?(e=this._peerConnection.getSenders()[0].transport,wP()&&0!==this._peerConnection.getReceivers().length&&e?e.state:YC):YC}},{key:"emitConnectionStateChangedEvent",value:function(e){e!==this.currentState&&("RECONNECTING"===this.currentState&&"CONNECTING"===e||(this.emit(hj.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}},{key:"logSelectedCandidate",value:function(){return bA(this,null,f().mark((function e(){var t,n,r,i,a,o,c;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this._peerConnection){e.next=2;break}return e.abrupt("return");case 2:return e.next=4,this._peerConnection.getStats();case 4:t=e.sent,n=s(t),e.prev=6,n.s();case 8:if((r=n.n()).done){e.next=16;break}if((i=v(r.value,2))[0],a=i[1],!EP(a)){e.next=14;break}return o=t.get(a.localCandidateId),c=t.get(a.remoteCandidateId),o&&(this._log.info("local candidate: ".concat(o.candidateType," ").concat(o.protocol,":").concat(o.ip||o.address,":").concat(o.port," ").concat(o.networkType||""," ").concat("relay"===o.candidateType?"relayProtocol:".concat(o.relayProtocol):"")),o.networkType&&xw(o.networkType)),c&&this._log.info("remote candidate: ".concat(c.candidateType," ").concat(c.protocol,":").concat(c.ip||c.address,":").concat(c.port)),e.abrupt("break",16);case 14:e.next=8;break;case 16:e.next=21;break;case 18:e.prev=18,e.t0=e.catch(6),n.e(e.t0);case 21:return e.prev=21,n.f(),e.finish(21);case 24:case"end":return e.stop()}}),e,this,[[6,18,21,24]])})))}},{key:"waitForPeerConnectionConnected",value:function(){var e=this;return this._waitForPCConnectedPromise||(this._waitForPCConnectedPromise=new Promise((function(t,n){if("CONNECTED"===e.currentState)return t();var r=function(e){"CONNECTED"===e.state&&(clearTimeout(o),a(),t())},i=function(t){t.room===e._room&&(clearTimeout(o),a(),n(new FA({code:VA.API_CALL_ABORTED,message:YO({key:jO.CONNECTION_ABORTED,data:"leave room"})})))},a=function(){Px.off(Lx.LEAVE_SUCCESS,i,e),e.off(hj.CONNECTION_STATE_CHANGED,r,e)},o=setTimeout((function(){a();var t,r=new FA({code:VA.API_CALL_TIMEOUT,message:"connection timeout"});fj+=1,t=e._signalChannel.isConnected,fj>2&&!pj&&0===mj.size&&t&&(e._log.warn("firewall restriction"),pj=!0,e.emit(hj.FIREWALL_RESTRICTION)),n(r)}),hw);e.clearConnectTimeout=function(){a(),clearTimeout(o),delete e.clearConnectTimeout},e.clearWaitForConnectedPromise=function(){e._waitForPCConnectedPromise=null,n(new FA({code:VA.API_CALL_TIMEOUT,message:"connection timeout"}))},Px.on(Lx.LEAVE_SUCCESS,i,e),e.on(hj.CONNECTION_STATE_CHANGED,r,e)})),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally((function(){e._waitForPCConnectedPromise=null,delete e.clearConnectTimeout}))),this._waitForPCConnectedPromise}},{key:"waitForReconnected",value:function(){var e=this;return this.isReconnecting?new Promise((function(t,n){e.once("spc-reconnected",t),e.once("error",n)})):Promise.resolve()}},{key:"addDownlink",value:function(e){return bA(this,null,f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this._log.info("addDownlink(".concat(e.userId,") trying")),t.t0=this.isReconnecting,!t.t0){t.next=5;break}return t.next=5,this.waitForReconnected();case 5:if(t.t1=this._updateSDPPromise,!t.t1){t.next=9;break}return t.next=9,this._updateSDPPromise;case 9:if(this.updateLocalAndRemoteSDPConfig(e),0!==this.addDownlinkQueue.size){t.next=22;break}return t.prev=11,t.next=14,this.updateSDP();case 14:this._log.info("addDownlink(".concat(e.userId,") done")),t.next=22;break;case 17:return t.prev=17,t.t2=t.catch(11),this._log.error("addDownlink(".concat(e.userId,") failed ").concat(t.t2)),t.next=22,this.startReconnection();case 22:case"end":return t.stop()}}),t,this,[[11,17]])})))}},{key:"updateLocalAndRemoteSDPConfig",value:function(e){var t=e.ssrc,n=e.userId,r=e.tinyId;if(this._peerConnection){this._log.info("updateLocalAndRemoteSDPConfig ".concat(n," ").concat(JSON.stringify(t)));var i=this._peerConnection.getTransceivers().slice(4).filter((function(e){return"inactive"===e.direction})).slice(0,3).map((function(e){return e.direction=IC.TRANSCEIVER_DIRECTION_RECVONLY,Number(e.mid)}));this._parsedAnswer||(this._parsedAnswer=kW(this._peerConnection.remoteDescription.sdp));var a,o,s,c=this._parsedAnswer.media.filter((function(e){var t;return null==(t=e.ssrcs)?void 0:t.find((function(e){var t;return null==(t=e.value)?void 0:t.includes(r)}))}));if(3===c.length)a=c[0],o=c[1],s=c[2];else if(3===i.length)a=this._parsedAnswer.media.find((function(e){return Number(e.mid)===Number(i[0])})),o=this._parsedAnswer.media.find((function(e){return Number(e.mid)===Number(i[1])})),s=this._parsedAnswer.media.find((function(e){return Number(e.mid)===Number(i[2])}));else if(0===i.length){this._peerConnection.addTransceiver(IC.AUDIO,{direction:IC.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(IC.VIDEO,{direction:IC.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(IC.VIDEO,{direction:IC.TRANSCEIVER_DIRECTION_RECVONLY}),a=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));var u=oj({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:kW(this._peerConnection.localDescription.sdp),isDownlink:!0});o=JSON.parse(JSON.stringify(u)),s=JSON.parse(JSON.stringify(u)),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a),o.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(o),s.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(s)}a.direction=IC.TRANSCEIVER_DIRECTION_SENDONLY;var l="".concat(r,"-").concat(t.audio);a.ssrcs=[{id:t.audio,attribute:"cname",value:"".concat(l)},{id:t.audio,attribute:"msid",value:"".concat(l,"-").concat(IC.MAIN," ").concat(l,"-audio")}],o.direction=IC.TRANSCEIVER_DIRECTION_SENDONLY,o.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(l)},{id:t.video,attribute:"msid",value:"".concat(l,"-").concat(IC.MAIN," ").concat(l,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(l)},{id:t.videoRtx,attribute:"msid",value:"".concat(l,"-").concat(IC.MAIN," ").concat(l,"-bigvideo")}],o.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],s.direction=IC.TRANSCEIVER_DIRECTION_SENDONLY;var d="".concat(l,"-aux");s.ssrcs=[{id:t.auxiliary,attribute:"cname",value:d},{id:t.auxiliary,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(IC.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(d," ").concat(l,"-aux").concat(IC.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(d," ").concat(l,"-aux").concat(IC.VIDEO)}],s.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.auxiliary," ").concat(t.auxiliaryRtx)}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map((function(e){return e.mid})).join(" ")),this._downlinkMIDMap.set(n,[a.mid,o.mid,s.mid]),this._downlinkMIDUserIDMap.set(a.mid,n),this._downlinkMIDUserIDMap.set(o.mid,n),this._downlinkMIDUserIDMap.set(s.mid,n)}}},{key:"removeDownlink",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i=this;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this._downlinkMIDMap.has(e)&&this._peerConnection){t.next=2;break}return t.abrupt("return");case 2:if(this._log.info("removeDownlink(".concat(e,") trying")),t.t0=this.isReconnecting,!t.t0){t.next=7;break}return t.next=7,this.waitForReconnected();case 7:if(t.t1=this._updateSDPPromise,!t.t1){t.next=11;break}return t.next=11,this._updateSDPPromise;case 11:if(n=this._downlinkMIDMap.get(e),r=!1,this._peerConnection.getTransceivers().forEach((function(e){null!=n&&n.includes(Number(e.mid))&&(r=!0,e.direction="inactive")})),this._parsedAnswer||(this._parsedAnswer=kW(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach((function(e){null!=n&&n.includes(Number(e.mid))&&(r=!0,e.direction="inactive",e.ssrcs=[],e.ssrcGroups=[])})),t.t2=0===this.removeDownlinkQueue.size&&r,!t.t2){t.next=19;break}return t.next=19,this.updateSDP();case 19:this._downlinkMIDMap.delete(e),null==n||n.forEach((function(e){return i._downlinkMIDUserIDMap.delete(e)})),this._log.info("removeDownlink(".concat(e,") done"));case 22:case"end":return t.stop()}}),t,this)})))}},{key:"setBandwidth",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a,o,s,c,u,l;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this._peerConnection){t.next=2;break}return t.abrupt("return");case 2:if(n=e.audio,r=e.bigVideo,i=e.smallVideo,a=e.auxVideo,t.prev=3,!VP()){t.next=26;break}o=this._peerConnection.getSenders().slice(0,4),s=0;case 7:if(!(s<o.length)){t.next=17;break}if(c=void 0,u=o[s],0===s&&n?c=n:1===s&&r?c=r:2===s&&i?c=i:3===s&&a&&(c=a),t.t0=c,!t.t0){t.next=14;break}return t.next=14,this.setSenderMaxBitrate(u,c);case 14:s++,t.next=7;break;case 17:if(l=!1,r&&o[1].track&&(l=this.setStartBitrate(1,r)),a&&o[3].track&&(l=this.setStartBitrate(3,a)||l),t.t1=l,!t.t1){t.next=24;break}return t.next=24,this.updateSDP();case 24:t.next=28;break;case 26:return t.next=28,this.setBandwidthBySDP(e);case 28:this._log.info("setBandwidth ".concat(JSON.stringify(e))),t.next=34;break;case 31:t.prev=31,t.t2=t.catch(3),this._log.error("failed to set bandwidth: ".concat(t.t2));case 34:case"end":return t.stop()}}),t,this,[[3,31]])})))}},{key:"setStartBitrate",value:function(e,t){var n,r;return!(null==(n=this._peerConnection)||!n.remoteDescription||(this._parsedAnswer||(this._parsedAnswer=kW(this._peerConnection.remoteDescription.sdp)),null==(r=this._parsedAnswer.media[e])||!r.fmtp[0])||(this._parsedAnswer.media[e].fmtp[0].config+=";x-google-start-bitrate=".concat(t>5e3?5e3:t),0))}},{key:"setSenderMaxBitrate",value:function(e,t){var n=e.getParameters();return(!n.encodings||0===n.encodings.length)&&(n.encodings=[{}]),"unlimited"===t?delete n.encodings[0].maxBitrate:n.encodings[0].maxBitrate=1e3*t,e.setParameters(n)}},{key:"setBandwidthBySDP",value:function(e){var t=e.audio,n=e.bigVideo,r=e.smallVideo,i=e.auxVideo;if(this._peerConnection&&this._peerConnection.localDescription){var a=kW(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=kW(this._peerConnection.remoteDescription.sdp));var o=rN?"TIAS":"AS";t&&(a.media[0].bandwidth=[{type:o,limit:rN?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:o,limit:rN?1e3*t:t}]),n&&(a.media[1].bandwidth=[{type:o,limit:rN?1e3*n:n}],this._parsedAnswer.media[1].bandwidth=[{type:o,limit:rN?1e3*n:n}]),r&&(a.media[2].bandwidth=[{type:o,limit:rN?1e3*r:r}],this._parsedAnswer.media[2].bandwidth=[{type:o,limit:rN?1e3*r:r}]),i&&(a.media[3].bandwidth=[{type:o,limit:rN?1e3*i:i}],this._parsedAnswer.media[3].bandwidth=[{type:o,limit:rN?1e3*i:i}]);var s={type:"offer",sdp:TW(a)};return this.updateSDP({localDescription:s})}}},{key:"setScaleResolutionDownBy",value:function(e,t,n){var r=e.getParameters();(!r.encodings||0===r.encodings.length)&&(r.encodings=[{}]);var i=r.encodings[0].scaleResolutionDownBy;if(Kw(i)?1!==t:t!==i){var a="setScaleResolutionDownBy ".concat(n," ").concat(t);return i&&(a+=" prevScale: ".concat(i)),this._log.warn(a),r.encodings[0].scaleResolutionDownBy=t,e.setParameters(r)}}},{key:"setDegradationPreference",value:function(e,t,n){var r=this;if(!(tx&&ix<83||ZD&&dx(lx,"12.1")||rN&&aN<138)){var i=e.getParameters(),a="balanced";if("motion"===t?a="maintain-framerate":"detail"===t&&(a="maintain-resolution"),i.degradationPreference!==a){var o="setDegradationPreference ".concat(n," ").concat(a);return this._log.info(o),i.degradationPreference=a,e.setParameters(i).catch((function(e){return r._log.warn("".concat(o," failed: ").concat(e))}))}}}},{key:"updateSDP",value:function(){var e=this,t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).localDescription;if(!this._parsedAnswer)return Promise.resolve();var n=TW(this._parsedAnswer);return this._updateSDPPromise=new Promise((function(r,i){return bA(e,null,f().mark((function e(){var a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,e.t0=!t&&this._peerConnection,!e.t0){e.next=7;break}return this._log.info("creating offer"),e.next=6,this._peerConnection.createOffer();case 6:t=e.sent;case 7:if(e.t1=t,!e.t1){e.next=11;break}return e.next=11,this.setOffer(t);case 11:return e.next=13,this.setAnswer({type:"answer",sdp:n});case 13:this._updateSDPPromise=null,r(),e.next=20;break;case 17:e.prev=17,e.t2=e.catch(0),this._log.error(e.t2),!this._isSDPLogged&&this._peerConnection&&(this._log.warn("current offer: ".concat(this.filterSDPDirection(null==(a=this._peerConnection.localDescription)?void 0:a.sdp)," \nnext offer: ").concat(this.filterSDPDirection(null==t?void 0:t.sdp))),this._log.warn("current answer: ".concat(this.filterSDPDirection(null==(o=this._peerConnection.remoteDescription)?void 0:o.sdp)," \nnext answer: ").concat(this.filterSDPDirection(n))),this._log.warn("offer: ".concat(null==t?void 0:t.sdp)),this._log.warn("answer: ".concat(n)),this._log.warn("transceivers: ".concat(JSON.stringify(this._peerConnection.getTransceivers().map((function(e){return{mid:e.mid,currentDirection:e.currentDirection,direction:e.direction,stopped:e.stopped}}))))),this._log.warn("parsedAnswer: ".concat(JSON.stringify(this._parsedAnswer))),this._isSDPLogged=!0),this._updateSDPPromise=null,i(e.t2);case 20:case"end":return e.stop()}}),e,this,[[0,17]])})))})),this._updateSDPPromise}},{key:"setTransceiverDirection",value:function(e,t){return bA(this,null,f().mark((function n(){var r,i,a,o,c;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(rN&&this._peerConnection&&this._parsedAnswer){n.next=2;break}return n.abrupt("return");case 2:this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(e)),r=this._peerConnection.getTransceivers(),t.forEach((function(t){r[t].direction!==e&&(r[t].direction=e)})),i=s(t);try{for(i.s();!(a=i.n()).done;)o=a.value,c=this._parsedAnswer.media[o].direction,e===bC.INACTIVE&&c===bC.RECVONLY&&(this._parsedAnswer.media[o].direction=e),e===bC.SENDONLY&&c===bC.INACTIVE&&(this._parsedAnswer.media[o].direction=bC.RECVONLY)}catch(u){i.e(u)}finally{i.f()}return n.next=9,this.updateSDP();case 9:case"end":return n.stop()}}),n,this)})))}},{key:"filterSDPDirection",value:function(){return kW(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").media.map((function(e){return e.direction}))}},{key:"setOffer",value:function(e){this._log.info("setting offer");var t=function(e,t,n){var r=nj.default.parse(e);return r.media.forEach((function(e,i){var a;if((e.type===IC.AUDIO||e.type===IC.VIDEO)&&(function(e){if(e.rtcpFb){var t=[];e.rtcpFb.forEach((function(n,r){var i;t.push(n),e.rtcpFb&&(null==(i=e.rtcpFb[r+1])?void 0:i.payload)!==n.payload&&"rrtr"!==n.type&&t.push({payload:n.payload,type:"rrtr"})})),e.rtcpFb=t}}(e),function(e){e.type===IC.VIDEO&&e.fmtp&&e.fmtp.forEach((function(e){e.config.includes("apt")||(e.config+=";sps-pps-idr-in-keyframe=1")}))}(e),function(e){e.type===IC.AUDIO&&e.fmtp&&e.fmtp.forEach((function(e){e.config+=";sprop-stereo=1;stereo=1"}))}(e),function(e){var t=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);e.ext&&(e.ext=e.ext.filter((function(e){return!t.has(e.uri)})))}(e),e.type===IC.VIDEO))if(i<4)e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[],t.video.codecs.forEach((function(t){return sj(e,t)}));else if(n){e.payloads="",e.fmtp=[],e.rtp=[],e.rtcpFb=[];var o=n.video.decoders;(!o||0===o.length)&&(o=n.video.codecs),(!o||0===o.length)&&(o=t.video.decoders),o.forEach((function(t){return sj(e,t)}))}null!=(a=e.payloads)&&a.includes("datachannel")&&r.groups&&e.mid&&(r.groups[0].mids=r.groups[0].mids.replace(e.mid,"dc"),e.mid="dc")})),nj.default.write(r)}(e.sdp,this.clientAbility,this._serverAbility);return this._log.debug(t),this._peerConnection.setLocalDescription({type:"offer",sdp:t})}},{key:"setAnswer",value:function(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}},{key:"switchVideoEncoder",value:function(e){return bA(this,null,f().mark((function t(){var n,r=this;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this._peerConnection&&this._parsedAnswer&&this._serverAbility){t.next=2;break}return t.abrupt("return");case 2:if(n=!1,this._parsedAnswer.media.forEach((function(t){var i;if(t.type===IC.VIDEO){var a=r._serverAbility.video.codecs.find((function(t){return t.codec.toLowerCase()===e}));a&&(null==(i=t.payloads)||!i.includes(String(a.payload)))&&(t.fmtp=[],t.payloads="",t.rtp=[],t.rtcpFb=[],sj(t,a),n=!0)}})),t.t0=n,!t.t0){t.next=9;break}return this._log.warn("switch video encoder to ".concat(e)),t.next=9,this.updateSDP();case 9:case"end":return t.stop()}}),t,this)})))}},{key:"useHWEncoder",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1?arguments[1]:void 0;return bA(this,null,f().mark((function n(){var r,i,a=this;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(this._peerConnection&&this._parsedAnswer&&this._serverAbility){n.next=2;break}return n.abrupt("return");case 2:if(r=!1,i=[],Kw(t)?i=this._parsedAnswer.media.slice(1,4):2===t?i.push(this._parsedAnswer.media[1]):3===t?i.push(this._parsedAnswer.media[2]):7===t&&i.push(this._parsedAnswer.media[3]),i.forEach((function(t){var n,i;t.type===IC.VIDEO&&(e&&a.is42001fSupported?i=a.clientAbility.video.codecs.find((function(e){return e.fmtp.includes("42001f")})):e||(i=a._serverAbility.video.codecs.find((function(e){return e.codec.toLowerCase()===(a._serverAbility.useVp8?"vp8":"h264")}))),i&&(null==(n=t.payloads)||!n.includes(String(i.payload)))&&(t.fmtp=[],t.payloads="",t.rtp=[],t.rtcpFb=[],sj(t,i),r=!0))})),n.t0=r,!n.t0){n.next=10;break}return this._log.warn("use ".concat(e?"hw":"sw"," encoder")),n.next=10,this.updateSDP();case 10:case"end":return n.stop()}}),n,this)})))}},{key:"sendDataChannelMessage",value:function(e){var t;null==(t=this._datachannel)||t.send(e)}},{key:"reset",value:function(){var e;this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),null==(e=this.clearWaitForConnectedPromise)||e.call(this),this._parsedAnswer=null,this.originOffer=null}},{key:"close",value:function(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach((function(e){return PD(e.abort)&&e.abort("destroy")})),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}},{key:"getReceiversByUserId",value:function(e){if(!this._peerConnection)return[];var t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map((function(e){return t[e]}))}},{key:"isUsingRelay",get:function(){return"relay"===this._room.getIceTransportPolicy()}},{key:"detectTCPAndUDP",value:function(e){var t,n=e.uplinkRTT,r=e.downlinkRTT;if("CONNECTED"===this.currentState&&(!this._isRelayTried||this._room.forceRelay)&&0!==this._room.getIceServers().length){var i=this._signalChannel.rtt,a=Math.max(n,r),o=(null==(t=this._room.scheduleResult.config)?void 0:t.useTurnTcpInfo)||{},s=o.rttRatioThreshold,c=o.rttThreshold;if(s&&c&&i&&a){var u=Math.floor(a/i),l=(this._isRelayTried||u>s)&&a>c;l?++this._rttOverCount<5||(this._log.warn("detectTCPAndUDP ws-rtt: ".concat(i," upRTT: ").concat(n," downRTT: ").concat(r," ratio: ").concat(u," over-count: ").concat(this._rttOverCount," isOver: ").concat(l," isRelayTried: ").concat(this._isRelayTried," force-relay: ").concat(this._room.forceRelay)),this.isUsingRelay||this._isRelayTried?this._room.forceRelay&&this.switchRelay(!1):(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0))):this._rttOverCount=0}}}},{key:"switchRelay",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return bA(this,null,f().mark((function n(){var r,i,a;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(this.isUsingRelay!==e){n.next=2;break}return n.abrupt("return");case 2:return r=e?"relay":"udp",i=e?521709:521710,n.prev=3,this._room.forceRelay=e,this._log.warn("switchRelay ".concat(r)),a=Date.now(),n.next=8,this.doSwitchRelay(r);case 8:this._log.warn("switchRelay ".concat(r," success")),rP.addSuccessEvent({key:i,cost:Date.now()-a}),n.next=22;break;case 12:if(n.prev=12,n.t0=n.catch(3),this._log.warn("switchRelay ".concat(r," failed"),n.t0),rP.addFailedEvent({key:i,error:n.t0}),!t){n.next=20;break}this._room.reJoin(),n.next=22;break;case 20:return n.next=22,this.switchRelay(!e,!0);case 22:case"end":return n.stop()}}),n,this,[[3,12]])})))}},{key:"doSwitchRelay",value:function(e){var t=this;return new Promise((function(n,r){var i=setTimeout((function(){t.stopReconnection(),r(new Error("switch ".concat(e," timeout")))}),1e4);t.startReconnection().then(n,r).finally((function(){return clearTimeout(i)}))}))}},{key:"removeRTCListener",value:function(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}}])}(tj.default);TA([XL("reconnect")],_j.prototype,"startReconnection",1),TA([QL((function(e){return e.userId}))],_j.prototype,"addDownlink",1),TA([QL((function(e){return e}))],_j.prototype,"removeDownlink",1),TA([qL(!0)],_j.prototype,"updateSDP",1),TA([ZL(521712,!1)],_j.prototype,"setOffer",1),TA([ZL(521713,!1)],_j.prototype,"setAnswer",1);var gj=o((function e(t){r(this,e),SA(this,"tag"),SA(this,"len"),SA(this,"data");var n=new DataView(t);this.tag=n.getUint16(),this.len=n.getUint16(2),this.data=new Uint8Array(t).slice(4,4+this.len).buffer})),yj=o((function e(t){var n=this;r(this,e),SA(this,"tinyId"),SA(this,"data");for(var i=new DataView(t),a=0,o=[];a<i.byteLength;){var s=i.getUint16(a+2),c=new gj(new Uint8Array(t).slice(a,a+2+2+s).buffer);o.push(c),a+=4+s}o.forEach((function(e){1===e.tag?n.tinyId=(new TextDecoder).decode(e.data):2===e.tag&&(n.data=e.data)}))})),Ej=new Set;function kj(){var e=Math.floor(4294967296*Math.random());return Ej.has(e)?kj():(Ej.add(e),e)}var Tj=function(e){function i(e){var a;return r(this,i),a=n(this,i),SA(t(a),"userId"),SA(t(a),"tinyId"),SA(t(a),"_sdpSemantics"),SA(t(a),"_isUplink"),SA(t(a),"_room"),SA(t(a),"_log"),SA(t(a),"_currentState","DISCONNECTED"),SA(t(a),"_prevTime",-1),SA(t(a),"_blackSmallVideoDetectionId"),a.userId=e.userId,a.tinyId=e.tinyId,a._room=e.room,a._sdpSemantics=e.room.sdpSemantics,a._isUplink=e.isUplink,a._log=Ux.createLogger({id:"n",userId:a._room.userId,remoteUserId:a._isUplink?void 0:a.userId,sdkAppId:a._room.sdkAppId,isLocal:a._isUplink}),a}return d(i,e),o(i,[{key:"_peerConnection",get:function(){var e;return(null==(e=this.singlePC)?void 0:e.getPeerConnection())||null}},{key:"singlePC",get:function(){return this._room.singlePC}},{key:"_signalChannel",get:function(){return this._room.signalChannel}},{key:"close",value:function(e){this._log.info("close connection"),this.emit("closed",e)}},{key:"emitConnectionStateChangedEvent",value:function(e){return e!==this._currentState&&(Px.emit(Lx.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}},{key:"getPeerConnection",value:function(){return this._peerConnection}},{key:"getRoom",value:function(){return this._room}},{key:"getUserId",value:function(){return this.userId}},{key:"getTinyId",value:function(){return this.tinyId}},{key:"getCurrentState",value:function(){return this._currentState}},{key:"isH264",get:function(){var e,t;return!(null==(t=null==(e=this._peerConnection)?void 0:e.remoteDescription)||!t.sdp.includes("H264"))}}])}(kA(RA()).default),Sj=new(function(){return o((function e(){r(this,e),SA(this,"worker"),SA(this,"callbacks",new Map),SA(this,"_log"),SA(this,"sleep",{}),SA(this,"heartbeatListenerCleaner",new Map),SA(this,"userIdMap",new Map),this._log=Ux.createLogger({id:"bvd"})}),[{key:"getWorker",value:function(){var e=this;if(!this.worker){var t=new Blob(['\n const tracks=new Map;let canvas,ctx;const log=(...t)=>postMessage({type:"log",message:"[worker] "+t.join(" ")});function startDetection(e,t,a){if(!tracks.has(e)){const c={reader:a.getReader(),blackCount:0,timeoutId:null,intervalId:null};tracks.set(e,c),c.timeoutId=setTimeout(()=>stopDetection(e,"timeout"),t),c.intervalId=setInterval(async()=>{try{await isFrameBlack(e)?(c.blackCount++,postMessage({type:"blackCount",trackId:e,count:c.blackCount}),3<=c.blackCount&&(postMessage({type:"black",trackId:e}),stopDetection(e,"black"))):c.blackCount=0}catch(t){log("check black video error:",t.message),stopDetection(e,"error")}},1e3)}}function stopDetection(t,e){var a=tracks.get(t);a&&(a.timeoutId&&clearTimeout(a.timeoutId),a.intervalId&&clearInterval(a.intervalId),a.reader&&a.reader.cancel(),tracks.delete(t),postMessage({type:e,trackId:t}))}async function isFrameBlack(t){t=tracks.get(t);if(!t)return!1;var t=t.reader,{done:t,value:e}=await t.read();if(!e||t)return!1;canvas||(canvas=new OffscreenCanvas(e.codedWidth,e.codedHeight),ctx=canvas.getContext("2d",{willReadFrequently:!0})),canvas.width===e.codedWidth&&canvas.height===e.codedHeight||(canvas.width=e.codedWidth,canvas.height=e.codedHeight,ctx=canvas.getContext("2d",{willReadFrequently:!0})),ctx.drawImage(e,0,0,canvas.width,canvas.height);t=getFrameBlackRatio(ctx.getImageData(0,0,canvas.width,canvas.height));return e.close(),1===t}function getFrameBlackRatio(t){var e=t.data;let a=0;for(let t=0;t<100;t++){var c=4*Math.floor(Math.random()*(e.length/4)),[c,r,n,o]=[e[c],e[1+c],e[2+c],e[3+c]];0<o&&0===c&&0===r&&0===n&&a++}return a/100}self.onmessage=t=>{var{type:t,trackId:e,timeout:a,readable:c}=t.data;"addTrack"===t&&startDetection(e,a,c),"removeTrack"===t&&stopDetection(e)};\n '],{type:"application/javascript"}),n=URL.createObjectURL(t);this.worker=new Worker(n),URL.revokeObjectURL(n),this.worker.onerror=function(t){return e._log.warn("worker error:",t.message,t.filename||"unknown",t.lineno||"unknown")},this.worker.onmessage=function(t){var n,r=t.data,i=r.type,a=r.trackId,o=r.message,s=r.count;if("black"===i)null==(n=e.callbacks.get(a))||n();else if("log"===i)e._log.warn(o);else if("blackCount"===i){var c=e.userIdMap.get(a);e._log.warn("".concat(c||a," black count: ").concat(s))}}}return this.worker}},{key:"start",value:function(e){var t=this,n=e.track,r=e.isUplink,i=e.room,a=e.userId,o=e.onBlack;if(this._log.debug("start detect black video",n.id),hP()&&o&&n&&!Kw(Worker)){var s=function(e){var i,o,s,c,u;if(r)u=null==(o=null==(i=e.msg_up_stream_info)?void 0:i.msg_video_status)?void 0:o.filter((function(e){return 3===e.uint32_video_stream_type}))[0];else{var l=null==(s=e.msg_down_stream_info)?void 0:s.filter((function(e){var t;return(null==(t=e.msg_user_info)?void 0:t.str_identifier)===a}))[0];u=null==(c=null==l?void 0:l.msg_video_status)?void 0:c.filter((function(e){return 3===e.uint32_video_stream_type}))[0]}if(u){var d=(u.uint32_video_codec_bitrate||0)/1e3;if(t.sleep[n.id]&&t.sleep[n.id]>0)return void(t.sleep[n.id]-=1);d>0&&d<10&&(t.sleep[n.id]=30,t._log.debug("track bitrate",d,"start check"),t.checkOnce(n,3e4))}};return i.on("heartbeat-report",s),this.heartbeatListenerCleaner.set(n.id,(function(){return i.off("heartbeat-report",s)})),this.callbacks.set(n.id,o),this.userIdMap.set(n.id,a),n.id}this._log.warn("black video detector not supported")}},{key:"checkOnce",value:function(e,t){try{var n=this.getWorker();if(!n)throw new Error("Worker not available");var r=new MediaStreamTrackProcessor({track:e});n.postMessage({type:"addTrack",trackId:e.id,timeout:t,readable:r.readable},[r.readable])}catch(ZC){this._log.warn("check error:",ZC),this.stop(e.id)}}},{key:"stop",value:function(e){if(e){this.worker&&this.worker.postMessage({type:"removeTrack",trackId:e}),this.callbacks.delete(e),delete this.sleep[e];var t=this.heartbeatListenerCleaner.get(e);t&&t(),this.heartbeatListenerCleaner.delete(e),this.userIdMap.delete(e)}}},{key:"destroy",value:function(){var e=this;this.callbacks.forEach((function(t,n){return e.stop(n)})),this.worker&&(this.worker.terminate(),this.worker=null)}}])}()),Ij=function(e){function i(e){var a;return r(this,i),a=n(this,i,[gA(_A({},e),{isUplink:!0})]),SA(t(a),"localMainAudioTrack",null),SA(t(a),"localMainVideoTrack",null),SA(t(a),"localAuxAudioTrack",null),SA(t(a),"localAuxVideoTrack",null),SA(t(a),"_isPublishingAux",!1),SA(t(a),"_publishingLocalAudioTrack"),SA(t(a),"_publishingLocalVideoTrack"),SA(t(a),"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),SA(t(a),"_flag",0),SA(t(a),"_checkPublishStateTimeoutId",-1),a.initialize(),a}return d(i,e),o(i,[{key:"videoCodec",get:function(){var e;return(null==(e=this.singlePC)?void 0:e.videoCodec)||"h264"}},{key:"ssrc",get:function(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};var e=this.singlePC.uplinkSSRC;return{audio:e.audioSsrc||0,video:e.bigVideoSsrc||0,videoRtx:e.bigVideoRtxSsrc||0,small:e.smallVideoSsrc||0,smallRtx:e.smallVideoRtxSsrc||0,auxiliary:e.auxVideoSsrc||0,auxiliaryRtx:e.auxVideoRtxSsrc||0}}},{key:"flag",get:function(){return this._flag},set:function(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}},{key:"checkPublishState",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(t||!(this._checkPublishStateTimeoutId>0)){var n=this.publishState,r=this.serverPublishState,i=Object.keys(n).find((function(e){return n[e]!==r[e]}));if(i){if(!t)return void(this._checkPublishStateTimeoutId=mM.run("timeout",(function(){return e.checkPublishState(!0)}),{delay:1e4,count:1}));this._log.warn("publish state not matched, ".concat(i," local:").concat(n[i]," server:").concat(r[i]," ").concat(Nx()," ").concat(Ax())),rP.addCount({key:521e3})}mM.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}}},{key:"isMainStreamPublished",get:function(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}},{key:"isAuxStreamPublished",get:function(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}},{key:"publishState",get:function(){var e,t,n,r,i=this,a={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){var o=this._peerConnection.getSenders();o&&(NP()?(a.audio=!(null==(e=o[0])||!e.track),a.bigVideo=!(null==(t=o[1])||!t.track),a.smallVideo=!(null==(n=o[2])||!n.track),a.auxVideo=!(null==(r=o[3])||!r.track)):o.forEach((function(e){e.track&&(e.track.kind===IC.AUDIO?a.audio=!0:(a.bigVideo=!0,i._room.videoManager.hasSmall&&(a.smallVideo=!0)))})))}return a}},{key:"publishingState",get:function(){var e=this.publishState,t=_A({},e);return this._publishingLocalAudioTrack&&(t.audio=!0),this._publishingLocalVideoTrack&&(this._isPublishingAux?t.auxVideo=!0:(t.bigVideo=!0,this._publishingLocalVideoTrack.small&&(t.smallVideo=!0))),t}},{key:"serverPublishState",get:function(){return{audio:!!(this.flag&NC),bigVideo:!!(this.flag&CC),smallVideo:!!(this.flag&wC),auxVideo:!!(this.flag&DC)}}},{key:"muteState",get:function(){var e,t,n;return{audio:!(null==(e=this.localMainAudioTrack)||!e.muted),bigVideo:!(null==(t=this.localMainVideoTrack)||!t.muted),auxVideo:!(null==(n=this.localAuxVideoTrack)||!n.muted)}}},{key:"initialize",value:function(){this.installEvents()}},{key:"close",value:function(e){var t,n,r=s((null==(t=this._peerConnection)?void 0:t.getSenders())||[]);try{for(r.s();!(n=r.n()).done;)n.value.replaceTrack(null)}catch(a){r.e(a)}finally{r.f()}g(i,"close",this,3)([e]),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}},{key:"installEvents",value:function(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}},{key:"installSPCEvents",value:function(){var e,t;null!=(e=this.singlePC)&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||null==(t=this.singlePC)||t.on("spc-reconnected",this.onSinglePCReconnected,this)}},{key:"uninstallSPCEvents",value:function(){var e;null==(e=this.singlePC)||e.off("spc-reconnected",this.onSinglePCReconnected,this)}},{key:"uninstallEvents",value:function(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}},{key:"emitConnectionStateChangedEvent",value:function(e,t){var n,r,a,o=this._currentState,s=g(i,"emitConnectionStateChangedEvent",this,3)([e]);return s&&o!==e&&(t?t.emit("connection-state-changed",{prevState:o,state:e}):(null==(n=this.localMainVideoTrack)||n.emit("connection-state-changed",{prevState:o,state:e}),null==(r=this.localAuxVideoTrack)||r.emit("connection-state-changed",{prevState:o,state:e}),null==(a=this._publishingLocalVideoTrack)||a.emit("connection-state-changed",{prevState:o,state:e}))),s}},{key:"onVideoEncodeFailed",value:function(e){var t;e&&e.isMediaTrackActive&&"h264"===this.videoCodec&&(this._log.warn("h264 encoder not working"),null!=(t=this.singlePC)&&t.isVP8EncodeSupported&&(this._log.warn("switch to vp8"),this.singlePC.switchVideoEncoder("vp8")))}},{key:"publish",value:function(e){return bA(this,arguments,(function(e){var t=this,n=e.localAudioTrack,r=e.localVideoTrack,i=e.isAuxiliary;return f().mark((function e(){var a,o,s,c,u,l,d,h,p,m,v;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.singlePC){e.next=2;break}return e.abrupt("return");case 2:return t.installEvents(),e.next=5,t.singlePC.waitForPeerConnectionConnected();case 5:if(p=t.publishState,m=t.muteState,n&&(t._publishingLocalAudioTrack=n,p.audio=!0,m.audio=n.muted),!r){e.next=22;break}if(t.singlePC.isH264EncodeSupported||t.singlePC.isVP8EncodeSupported){e.next=9;break}throw new FA({code:VA.NOT_SUPPORTED_H264,message:YO({key:jO.NOT_SUPPORTED_H264ENCODE})});case 9:if(e.t0=t.singlePC.isUsingH264&&!t.singlePC.isH264EncodeSupported&&t.singlePC.isVP8EncodeSupported,!e.t0){e.next=14;break}return t._log.warn("h264 encoder not supported"),e.next=14,t.singlePC.switchVideoEncoder("vp8");case 14:if(e.t1=$D&&115===ex()&&r.profile.width*r.profile.height<=230400,!e.t1){e.next=20;break}return t._log.warn("fallback video to defaultBigVideoProfile: ".concat(JSON.stringify(kC))),r.setProfile(kC),e.next=20,r.applyProfile();case 20:t._publishingLocalVideoTrack=r,i?(p.auxVideo=!0,m.auxVideo=r.muted):(p.bigVideo=!0,m.bigVideo=r.muted);case 22:return t._isPublishingAux=i,r&&!i&&r.small&&(h=t._room.videoManager.smallTrack,p.smallVideo=!0),e.next=26,t._signalChannel.sendWaitForResponseWithRetry({command:"publish/v2",responseCommand:aW.SPC_PUBLISH_RESULT,data:gA(_A({},t.singlePC.uplinkSSRC),{state:p,muteState:m}),retries:3});case 26:return e.next=28,t.publishByTransceiver({localAudioTrack:n,localVideoTrack:r,smallTrack:h,isAuxiliary:i});case 28:if(t._publishingLocalAudioTrack=null,t._publishingLocalVideoTrack=null,t._isPublishingAux=!1,!r){e.next=38;break}return t[i?"localAuxVideoTrack":"localMainVideoTrack"]=r,e.next=35,t.singlePC.setDegradationPreference(t._peerConnection.getSenders()[i?3:1],r.contentHint,r.streamType);case 35:return v=r.scaleResolutionDownBy,e.next=38,t.singlePC.setScaleResolutionDownBy(t._peerConnection.getSenders()[i?3:1],v,r.streamType);case 38:return n&&(t[i?"localAuxAudioTrack":"localMainAudioTrack"]=n),e.next=41,t.singlePC.setBandwidth({audio:(null==(a=t.localMainAudioTrack)?void 0:a.profile.bitrate)||(null==(o=t.localAuxAudioTrack)?void 0:o.profile.bitrate),bigVideo:null==(s=t.localMainVideoTrack)?void 0:s.profile.bitrate,smallVideo:null==(u=null==(c=t.localMainVideoTrack)?void 0:c.small)?void 0:u.bitrate,auxVideo:null==(l=t.localAuxVideoTrack)?void 0:l.profile.bitrate});case 41:t.sendMediaSettings(),t.installTrackMuteEvents(n,r),(t._room.preferHW||null!=(d=t._room.scheduleResult.config)&&d.preferHW)&&r&&r.profile.width*r.profile.height>=921600&&t.singlePC.useHWEncoder(!0,i?7:2);case 44:case"end":return e.stop()}}),e)}))()}))}},{key:"publishByTransceiver",value:function(e){var t=this,n=e.localAudioTrack,r=e.localVideoTrack;e.smallTrack;var i=e.isAuxiliary;if(xP()){this._log.info("publish by transceiver");var a=null==r?void 0:r.outMediaTrack,o=null==n?void 0:n.outMediaTrack,s=this._peerConnection.getTransceivers(),c=[],u=[],l=function(e,n,r){var i,a=s[n].sender.replaceTrack(r);u.push(n),null!=(i=t.singlePC)&&i.enableInsertableStreams&&a.then((function(){return t.createEncodedStreams(s[n].sender,e)})),t.initSenderTransform(s[n].sender,e),c.push(a)};o&&l(n.mediaType,0,o),a&&l(r.mediaType,i?3:1,a),null!=r&&r.small&&c.push(this.publishSmall(this._room.videoManager.smallMode,r));var d=this.singlePC.setTransceiverDirection(bC.SENDONLY,u);return c.push(d),Promise.all(c)}}},{key:"getTrackByMediaType",value:function(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}},{key:"createEncodedStreams",value:function(e,t){var n,r,i=this;if(!this.singlePC.insertableStreamsAbortMap.has(e)){var a=e.createEncodedStreams(),o=new AbortController;null==(n=this.singlePC)||n.addAbortController(e,o),(null!=(r=this.getTrackByMediaType(t))&&r.enableEncodeFrame?a.readable.pipeThrough(new TransformStream({transform:function(e,n){var r,a=i.getTrackByMediaType(t);n.enqueue(null!=(r=i.singlePC)&&r.isUsingH264&&a?a.encodeFrame(e,8===t):e)}}),o):a.readable).pipeTo(a.writable,o).catch((function(e){i._log.debug("encoded stream error",e),"destory"!==e&&i._log.warn(e)}))}}},{key:"initSenderTransform",value:function(e,t){if(this._peerConnection&&this.singlePC&&this.singlePC.scriptTransformWorker&&WP){var n=2!==t,r=8===t;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:1===t,isMain:n,isSmall:r}))}}},{key:"enableSmall",value:function(e){return bA(this,null,f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(!e){t.next=5;break}return t.next=3,this.publishSmall(this._room.videoManager.smallMode);case 3:t.next=7;break;case 5:return t.next=7,this.unpublishSmall();case 7:case"end":return t.stop()}}),t,this)})))}},{key:"publishSmall",value:function(e){return bA(this,arguments,(function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.localMainVideoTrack;return f().mark((function r(){var i,a,o,s,c;return f().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(t.singlePC){r.next=2;break}return r.abrupt("return");case 2:if("canvas"!==e||bP()){r.next=4;break}return r.abrupt("return",void t._log.warn("canvas mode small stream is not supported"));case 4:return a=t._peerConnection.getTransceivers(),o=a[2].sender,r.next=8,t.doPublishSmall(e,n);case 8:if(s=r.sent,c="canvas"===e?524700:524701,rP.addSuccessEvent({key:c}),!s){r.next=22;break}return null!=(i=t.singlePC)&&i.enableInsertableStreams&&t.createEncodedStreams(o,8),t.initSenderTransform(o,8),r.next=16,t.singlePC.setTransceiverDirection(bC.SENDONLY,[2]);case 16:return t.updateMediaSettings(),r.next=19,t.doPublishChange();case 19:t._blackSmallVideoDetectionId=Sj.start({track:o.track,room:t._room,isUplink:!0,userId:t.userId,onBlack:function(){t._log.warn("small video is black");var n="canvas"===e?524700:524701;rP.addFailedEvent({key:n,error:10002}),Sj.stop(t._blackSmallVideoDetectionId),t._blackSmallVideoDetectionId=void 0}}),r.next=23;break;case 22:rP.addFailedEvent({key:c,error:10001});case 23:case"end":return r.stop()}}),r)}))()}))}},{key:"doPublishSmall",value:function(e){return bA(this,arguments,(function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.localMainVideoTrack;return f().mark((function r(){var i,a,o,s;return f().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(t.singlePC){r.next=2;break}return r.abrupt("return",null);case 2:if(t._log.info("publish small",e),i=t._peerConnection.getTransceivers(),a=i[2].sender,"canvas"!==e||!t._room.videoManager.smallTrack){r.next=8;break}return r.next=7,a.replaceTrack(t._room.videoManager.smallTrack);case 7:return r.abrupt("return","canvas");case 8:if("api"!==e||null==n||!n.outMediaTrack||null==n||!n.small){r.next=13;break}return r.next=11,a.replaceTrack(null==n?void 0:n.outMediaTrack);case 11:return o=a.getParameters(),s=wD(null==n?void 0:n.profile,null==n?void 0:n.small),r.abrupt("return",(t._log.info("small scaleResolutionDownBy",s),o.encodings[0].scaleResolutionDownBy=s,a.setParameters(o),"api"));case 13:return r.abrupt("return",(t._log.warn("small track can not be enabled, smallMode: ".concat(t._room.videoManager.smallMode,", smallTrack: ").concat(!!t._room.videoManager.smallTrack,", bigVideoTrack: ").concat(!(null==n||!n.outMediaTrack))),null));case 14:case"end":return r.stop()}}),r)}))()}))}},{key:"unpublishSmall",value:function(){return bA(this,null,f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.t0=this.singlePC,!e.t0){e.next=12;break}return this._log.info("unpublish small"),e.next=5,this._peerConnection.getTransceivers()[2].sender.replaceTrack(null);case 5:return e.next=7,this.singlePC.setTransceiverDirection(bC.INACTIVE,[2]);case 7:return this.updateMediaSettings(),e.next=10,this.doPublishChange();case 10:Sj.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0;case 12:case"end":return e.stop()}}),e,this)})))}},{key:"installTrackMuteEvents",value:function(){for(var e=this,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];n.forEach((function(t){t&&(null==t||t.on("mute",e.sendMutedFlag,e),null==t||t.on("unmute",e.sendMutedFlag,e))}))}},{key:"uninstallTrackMuteEvents",value:function(){for(var e=this,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];n.forEach((function(t){t&&(null==t||t.off("mute",e.sendMutedFlag,e),null==t||t.off("unmute",e.sendMutedFlag,e))}))}},{key:"unpublish",value:function(e){return bA(this,arguments,(function(e){var t=this,n=e.localAudioTrack,r=e.localVideoTrack;return f().mark((function e(){var i,a,o,s,c;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,null==(i=t.singlePC)?void 0:i.waitForPeerConnectionConnected();case 2:if(a=r&&r===t.localAuxVideoTrack,o=null==r?void 0:r.outMediaTrack,s=t._peerConnection.getSenders(),c=[],e.t0=n,!e.t0){e.next=11;break}if(a?t.localAuxAudioTrack=null:t.localMainAudioTrack=null,e.t1=!t.localMainAudioTrack&&!t.localAuxAudioTrack,!e.t1){e.next=11;break}return e.next=10,s[0].replaceTrack(null);case 10:c.push(0);case 11:if(e.t2=o,!e.t2){e.next=28;break}if(!a){e.next=21;break}return e.next=16,s[3].replaceTrack(null);case 16:t.localAuxVideoTrack=null,t._mediaSettings=gA(_A({},t._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3),e.next=28;break;case 21:return e.next=23,s[1].replaceTrack(null);case 23:return e.next=25,s[2].replaceTrack(null);case 25:t.localMainVideoTrack=null,t._mediaSettings=gA(_A({},t._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2);case 28:if(!t.isMainStreamPublished&&!t.isAuxStreamPublished){e.next=35;break}return e.next=31,t.singlePC.setTransceiverDirection(bC.INACTIVE,c);case 31:return e.next=33,t.doPublishChange(!1);case 33:e.next=37;break;case 35:return e.next=37,t.doUnpublish();case 37:t.uninstallTrackMuteEvents(n,r),null==r||r.emit("connection-state-changed",{prevState:t._currentState,state:"DISCONNECTED"});case 39:case"end":return e.stop()}}),e)}))()}))}},{key:"doPublishChange",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return bA(this,null,f().mark((function t(){var n,r;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n={state:this.publishingState,constraintConfig:this._mediaSettings},t.next=3,this._signalChannel.sendWaitForResponseWithRetry({command:sW,data:n,responseCommand:aW.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});case 3:r=t.sent,this.checkPublishResultCode(r.data.code,r.data.message);case 5:case"end":return t.stop()}}),t,this)})))}},{key:"doUnpublish",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this._signalChannel.sendWaitForResponse({command:cW,commandDesc:"unpublish",responseCommand:aW.UNPUBLISH_RESULT,enableLog:e}).catch((function(e){if(e.getCode()===VA.API_CALL_TIMEOUT)return Promise.resolve();throw e}))}},{key:"updateMediaSettings",value:function(){var e;this._mediaSettings.videoCodec=(null==(e=this.singlePC)?void 0:e.videoCodec)||"h264";var t=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,n=this.localMainVideoTrack,r=this.localAuxVideoTrack;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),FP){if(t&&t.outMediaTrack){var i=t.outMediaTrack.getSettings();this._mediaSettings.audioChannel=i.channelCount||1,this._mediaSettings.audioBps=1e3*t.profile.bitrate,this._mediaSettings.audioFs=i.sampleRate||0}if(n&&n.outMediaTrack){var a=n.outMediaTrack.getSettings(),o=n.scaleResolutionDownBy;this._mediaSettings.videoWidth=a.width/o||0,this._mediaSettings.videoHeight=a.height/o||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=1e3*n.profile.bitrate,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=1e3*n.small.bitrate)}if(r&&r.outMediaTrack){var s=r.outMediaTrack.getSettings(),c=r.scaleResolutionDownBy;this._mediaSettings.auxVideoWidth=s.width/c||0,this._mediaSettings.auxVideoHeight=s.height/c||0,this._mediaSettings.auxVideoFps=s.frameRate||0,this._mediaSettings.auxVideoBps=1e3*r.profile.bitrate}}else t&&t.outMediaTrack&&(this._mediaSettings.audioChannel=t.profile.channelCount,this._mediaSettings.audioBps=1e3*t.profile.bitrate,this._mediaSettings.audioFs=t.profile.sampleRate),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=1e3*n.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}},{key:"sendMediaSettings",value:function(){var e=this;this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:dW,data:this._mediaSettings,responseCommand:aW.UPDATE_CONSTRAINT_CONFIG_RES}).then((function(t){0!==t.data.code&&e._log.warn(t.data.message)})).catch((function(){}))}},{key:"addTrack",value:function(e){return bA(this,null,f().mark((function t(){var n;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this._peerConnection){t.next=2;break}return t.abrupt("return");case 2:if(n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack,this._log.info("is adding ".concat(e.kind," track to current published local ").concat(n?IC.AUXILIARY:IC.MAIN," stream")),t.t0=NP(),!t.t0){t.next=8;break}return t.next=8,this.addTrackByTransceiver(e,n);case 8:case"end":return t.stop()}}),t,this)})))}},{key:"addTrackByTransceiver",value:function(e,t){return bA(this,null,f().mark((function n(){var r,i,a;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(e.mediaTrack){n.next=2;break}return n.abrupt("return");case 2:if(i=this._peerConnection.getTransceivers(),e.kind!==IC.AUDIO){n.next=8;break}return n.next=6,i[0].sender.replaceTrack(e.outMediaTrack);case 6:n.next=19;break;case 8:return a=t?3:1,n.next=11,i[a].sender.replaceTrack(e.outMediaTrack);case 11:if(n.t0=1===a&&null!=(r=this.localMainVideoTrack)&&r.small,!n.t0){n.next=15;break}return n.next=15,i[2].sender.replaceTrack(this._room.videoManager.smallTrack);case 15:if(n.t1=i[a].direction===bC.INACTIVE,!n.t1){n.next=19;break}return n.next=19,this.singlePC.setTransceiverDirection(bC.SENDONLY,[a]);case 19:return this.updateMediaSettings(),n.next=22,this.doPublishChange();case 22:case"end":return n.stop()}}),n,this)})))}},{key:"removeTrack",value:function(e){return bA(this,null,f().mark((function t(){var n;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this._peerConnection){t.next=2;break}return t.abrupt("return");case 2:if(n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack,this._log.info("is removing ".concat(e.kind," track from current published local ").concat(n?IC.AUXILIARY:IC.MAIN," stream")),t.t0=NP(),!t.t0){t.next=8;break}return t.next=8,this.removeTrackByTransceiver(e,n);case 8:case"end":return t.stop()}}),t,this)})))}},{key:"removeTrackByTransceiver",value:function(e,t){return bA(this,null,f().mark((function n(){var r,i;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(e.mediaTrack){n.next=2;break}return n.abrupt("return");case 2:if(r=this._peerConnection.getTransceivers(),e.kind!==IC.AUDIO){n.next=8;break}return n.next=6,r[0].sender.replaceTrack(null);case 6:n.next=17;break;case 8:return i=t?3:1,n.next=11,r[i].sender.replaceTrack(null);case 11:if(n.t0=1===i&&this._room.videoManager.hasSmall,!n.t0){n.next=15;break}return n.next=15,r[2].sender.replaceTrack(null);case 15:return n.next=17,this.singlePC.setTransceiverDirection(bC.INACTIVE,[i]);case 17:return this.updateMediaSettings(),n.next=20,this.doPublishChange();case 20:case"end":return n.stop()}}),n,this)})))}},{key:"replaceTrack",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(r=null==(n=this._peerConnection)?void 0:n.getSenders(),i=e.outMediaTrack||e.mediaTrack,r&&0!==r.length&&i&&!r.find((function(e){return e.track===i}))){t.next=3;break}return t.abrupt("return",!1);case 3:if(a=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack,this._log.info("is replacing ".concat(i.kind," track ").concat(i.id," ").concat(i.label," on ").concat(a?IC.AUXILIARY:IC.MAIN," stream")),t.t0=i.kind===IC.AUDIO&&r[0],!t.t0){t.next=9;break}return t.next=9,r[0].replaceTrack(i);case 9:if(t.t1=i.kind===IC.VIDEO,!t.t1){t.next=19;break}if(t.t2=!a&&r[1],!t.t2){t.next=15;break}return t.next=15,r[1].replaceTrack(i);case 15:if(t.t3=a&&r[3],!t.t3){t.next=19;break}return t.next=19,r[3].replaceTrack(i);case 19:return t.abrupt("return",!0);case 20:case"end":return t.stop()}}),t,this)})))}},{key:"setBandwidth",value:function(e){return bA(this,arguments,(function(e){var t=this,n=e.bandwidth,r=e.type,i=e.videoType;return f().mark((function e(){var a;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.singlePC){e.next=5;break}return a={},r===IC.AUDIO?a.audio=n:"big"===i?a.bigVideo=n:"small"===i?a.smallVideo=n:a.auxVideo=n,e.next=5,t.singlePC.setBandwidth(a);case 5:case"end":return e.stop()}}),e)}))()}))}},{key:"sendMutedFlag",value:function(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this.muteState))),this._signalChannel.sendWaitForResponseWithRetry({command:oW,responseCommand:aW.MUTE_RESULT,data:this.muteState,retries:3}).catch((function(){})))}},{key:"handleConnectionStateChange",value:function(e){"CONNECTED"===e.state&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&Px.emit(Lx.SEND_FIRST_VIDEO_FRAME,{room:this._room})}},{key:"getVideoTrackId",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:IC.VIDEO;if(this._peerConnection){var t=this._peerConnection.getSenders();if(e===IC.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===IC.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===IC.VIDEO){var n=this.localMainVideoTrack.mediaTrack;if(n)return n.id}if(this.localAuxVideoTrack&&e===IC.AUXILIARY){var r=this.localAuxVideoTrack.mediaTrack;if(r)return r.id}return""}},{key:"getSSRC",value:function(){return this.ssrc}},{key:"checkPublishResultCode",value:function(e,t){if(0!==e)throw e===ow?(this._log.error(GO.NOT_SUPPORTED_H264ENCODE),new FA({code:VA.NOT_SUPPORTED_H264,message:YO({key:jO.NOT_SUPPORTED_H264ENCODE})})):new FA({code:VA.UNKNOWN,message:YO({key:jO.SIGNAL_RESPONSE_FAILED,data:{signalResponse:aW.PUBLISH_RESULT,code:e,message:t}})})}},{key:"onSinglePCReconnected",value:function(){return bA(this,null,f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.t0=this.isMainStreamPublished,!e.t0){e.next=5;break}return this._log.warn("republish main stream"),e.next=5,this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1});case 5:if(e.t1=this.isAuxStreamPublished,!e.t1){e.next=10;break}return this._log.warn("republish aux stream"),e.next=10,this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0});case 10:case"end":return e.stop()}}),e,this)})))}}])}(Tj);TA([HL((function(e){var t=e.localVideoTrack;null==t||t.once("6",this.onVideoEncodeFailed,this)}))],Ij.prototype,"publish",1),TA([HL((function(e){var t=e.localVideoTrack;null==t||t.off("6",this.onVideoEncodeFailed,this)}))],Ij.prototype,"unpublish",1);var bj=Ij;function Rj(e){return Object.keys(e).filter((function(t){return e[t]}))}var Aj=function(e){function i(e){var a;return r(this,i),a=n(this,i,[gA(_A({},e),{isUplink:!1})]),SA(t(a),"_flag",0),SA(t(a),"isRobot",!1),SA(t(a),"role","anchor"),SA(t(a),"remoteAudioTrack"),SA(t(a),"remoteVideoTrack"),SA(t(a),"remoteAuxiliaryTrack"),SA(t(a),"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),SA(t(a),"jitterBufferTimeoutId",-1),a.flag=e.flag,a.isRobot=e.isRobot||!1,a.remoteAudioTrack=new DF(a._room,t(a)),a.remoteVideoTrack=new zF(a._room,t(a)),a.remoteAuxiliaryTrack=new qF(a._room,t(a)),a.initialize(),a}return d(i,e),o(i,[{key:"videoCodec",get:function(){var e;return(null==(e=this.singlePC)?void 0:e.downlinkVideoCodec)||"h264"}},{key:"subscribeState",get:function(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}},{key:"muteState",get:function(){return lD(this.flag,this.userId)}},{key:"flag",get:function(){return this._flag},set:function(e){var t,n,r;e!==this._flag&&(this._flag=e,null==(t=this.remoteAudioTrack)||t.onFlagChanged(),null==(n=this.remoteVideoTrack)||n.onFlagChanged(),null==(r=this.remoteAuxiliaryTrack)||r.onFlagChanged())}},{key:"hasMainStream",get:function(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}},{key:"hasAuxStream",get:function(){return this.muteState.hasAuxiliary}},{key:"isMainStreamSubscribed",get:function(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}},{key:"isAuxStreamSubscribed",get:function(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}},{key:"isSmallStreamSubscribed",get:function(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}},{key:"isBigStreamSubscribed",get:function(){return this.subscribeState.video&&this.muteState.hasVideo}},{key:"isStreamUnpublished",value:function(e){return e===IC.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}},{key:"initialize",value:function(){this.installEvents()}},{key:"close",value:function(e){clearTimeout(this.jitterBufferTimeoutId),g(i,"close",this,3)([e]),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}},{key:"installEvents",value:function(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}},{key:"uninstallEvents",value:function(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}},{key:"emitConnectionStateChangedEvent",value:function(e){var t,n,r=this._currentState,a=g(i,"emitConnectionStateChangedEvent",this,3)([e]);return a&&r!==e&&(null==(t=this.remoteVideoTrack)||t.emit("connection-state-changed",{prevState:r,state:e}),null==(n=this.remoteAuxiliaryTrack)||n.emit("connection-state-changed",{prevState:r,state:e})),a}},{key:"onTrack",value:function(e){var t,n,r=e.streams[0],i=e.track,a=e.receiver;if(r.id.includes(this.tinyId)){var o=r.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(o," ").concat(i.kind));var s=IC.AUDIO;i.kind===IC.VIDEO&&(s=o===IC.MAIN?IC.VIDEO:IC.AUXILIARY);var c=this.remoteAudioTrack;s===IC.VIDEO?c=this.remoteVideoTrack:s===IC.AUXILIARY&&(c=this.remoteAuxiliaryTrack),null==(t=this.singlePC)||t.receiverRemoteTrackMap.set(a,c),null!=(n=this.singlePC)&&n.scriptTransformWorker&&this.initReceiverTransform(a,o,i.kind===IC.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(a),c.setInputMediaStreamTrack(i)}}},{key:"createEncodedStreams",value:function(e){var t=this;if(!this.singlePC.insertableStreamsAbortMap.has(e)){var n=e.createEncodedStreams(),r=new AbortController,i={abortController:r,enqueue:function(n){var r,i,a=null==(r=t.singlePC)?void 0:r.receiverRemoteTrackMap.get(e);return a&&("video"!==a.kind||null!=(i=t.singlePC)&&i.isUsingH264)?a.decodeFrame(n):n}};n.readable.pipeThrough(new TransformStream({transform:function(e,t){var n=i.enqueue(e);n&&t.enqueue(n)}})).pipeTo(n.writable,r).catch((function(e){"destory"!==e&&t._log.warn(e)})),this.singlePC.addAbortController(e,r)}}},{key:"initReceiverTransform",value:function(e,t,n){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:n,userId:this.userId,streamType:t}))}},{key:"subscribe",value:function(e,t){return bA(this,null,f().mark((function n(){var r,i,a,o,s,c,u,l,d,h=this;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(n.prev=0,a=!0,this._log.info("subscribe ".concat(t," ").concat(Rj(e))),!this.hasSSRC){n.next=9;break}return o="subscribe_change",Object.values(e).find((function(e){return!0===e}))||(o="unsubscribe"),n.next=7,this.sendSubscription(o,e);case 7:n.next=13;break;case 9:return null!=(r=this.singlePC)&&r.autoSubscribedUserMap.size&&(s=this.singlePC.autoSubscribedUserMap.get(this.userId))&&(this.singlePC.autoSubscribedUserMap.delete(this.userId),(c=null==(i=this.singlePC.autoSubscribedSsrcGroups.get(this._room.roomId))?void 0:i[s.groupIndex])&&(this.ssrc={audio:c.audioSsrc,video:c.bigVideoSsrc,videoRtx:c.bigVideoRtxSsrc,auxiliary:c.auxVideoSsrc,auxiliaryRtx:c.auxVideoRtxSsrc},a=!1)),n.next=12,this.doSubscribe(e,a);case 12:this.checkTrackEnded(e);case 13:e.smallVideo?(u=this.remoteVideoTrack,l=u.user,d=u.mediaTrack,rP.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=Sj.start({track:d,isUplink:!1,room:this._room,userId:this.userId,onBlack:function(){h._log.warn("small video is black, auto change to big"),h._room.changeType(!1,l),rP.addFailedEvent({key:524702}),Sj.stop(h._blackSmallVideoDetectionId),h._blackSmallVideoDetectionId=void 0}})):(Sj.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0),n.next=19;break;case 16:throw n.prev=16,n.t0=n.catch(0),this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(n.t0.message," ").concat(JSON.stringify(this.muteState))),new FA({code:VA.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):n.t0;case 19:case"end":return n.stop()}}),n,this,[[0,16]])})))}},{key:"checkTrackEnded",value:function(e){var t,n,r;if((e.audio&&"ended"===(null==(t=this.remoteAudioTrack.mediaTrack)?void 0:t.readyState)||e.video&&"ended"===(null==(n=this.remoteVideoTrack.mediaTrack)?void 0:n.readyState)||e.auxiliary&&"ended"===(null==(r=this.remoteAuxiliaryTrack.mediaTrack)?void 0:r.readState))&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),tx&&ix<92)return;this.singlePC.startReconnection()}}},{key:"unsubscribe",value:function(e){return bA(this,arguments,(function(e){var t=this,n=e.remoteTracks,r=e.streamType;return f().mark((function e(){var i,a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(("main"!==r||t.isMainStreamSubscribed)&&("auxiliary"!==r||t.isAuxStreamSubscribed)){e.next=2;break}return e.abrupt("return",void t._log.info("".concat(r," stream already unsubscribed")));case 2:return a=_A({},t.subscribeState),n.forEach((function(e){switch(e.mediaType){case 1:a.audio=!1;break;case 4:a.video=!1;break;case 8:a.smallVideo=!1;break;case 2:a.auxiliary=!1}})),o="subscribe_change",Object.values(a).find((function(e){return!0===e}))||(o="unsubscribe"),t._log.info("".concat("unsubscribe"===o?o:"subscribe"," ").concat(r," [").concat(Rj(a),"]")),"unsubscribe"===o&&(null==(i=t.singlePC)||i.removeDownlinkQueue.add(t.tinyId)),e.next=10,t.sendSubscription(o,a);case 10:if("main"===r&&(Sj.stop(t._blackSmallVideoDetectionId),t._blackSmallVideoDetectionId=void 0),e.t0="unsubscribe"===o,!e.t0){e.next=15;break}return e.next=15,t.removeDownlink();case 15:case"end":return e.stop()}}),e)}))()}))}},{key:"sendSubscription",value:function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscribeState,r={srcTinyId:this.tinyId,srcUserId:this.userId},i=uW,a=aW.UNSUBSCRIBE_RESULT;return"subscribe_change"===e&&(r={audio:n.audio,bigVideo:n.video,auxVideo:n.auxiliary,smallVideo:n.smallVideo,srcTinyId:this.tinyId},i=lW,a=aW.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:i,data:r,responseCommand:a,timeout:1e4,retries:3}).then((function(n){var r=n.data;if(0!==r.code){var i=new FA({code:r.code,message:YO({key:jO.ERROR_MESSAGE,data:{type:e,message:r.message}})});throw t._log.error(i),i}}))}},{key:"getMainStreamVideoTrackId",value:function(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}},{key:"getAuxStreamVideoTrackId",value:function(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}},{key:"setDelay",value:function(e){var t=e.audioDelay,n=e.videoDelay;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=n}},{key:"onSinglePCReconnected",value:function(){return bA(this,null,f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.t0=this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary,!e.t0){e.next=8;break}return this._log.warn("resubscribe ".concat(JSON.stringify(this.subscribeState))),e.next=5,this.doSubscribe(this.subscribeState);case 5:this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult();case 8:case"end":return e.stop()}}),e,this)})))}},{key:"hasSSRC",get:function(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}},{key:"doSubscribe",value:function(){return bA(this,arguments,(function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.subscribeState,n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return f().mark((function r(){var i,a,o,s,c,u,l,d,h,p,m,v,_,g,y;return f().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(!e.singlePC){r.next=34;break}return e.singlePC.addDownlinkQueue.add(e.tinyId),r.next=4,e.singlePC.waitForPeerConnectionConnected();case 4:if(r.prev=4,!n&&e.hasSSRC){r.next=25;break}return i={audioSsrc:kj(),bigVideoSsrc:kj(),bigVideoRtxSsrc:kj(),auxVideoSsrc:kj(),auxVideoRtxSsrc:kj()},a=i.audioSsrc,o=i.bigVideoSsrc,s=i.bigVideoRtxSsrc,c=i.auxVideoSsrc,u=i.auxVideoRtxSsrc,e.ssrc={audio:a,video:o,videoRtx:s,auxiliary:c,auxiliaryRtx:u},e.singlePC.addDownlinkQueue.delete(e.tinyId),r.next=11,e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc});case 11:return r.prev=11,r.next=14,e._signalChannel.sendWaitForResponseWithRetry({command:"subscribe/v3",responseCommand:aW.SPC_SUBSCRIBE_RESULT,data:{srcUserId:e.userId,srcTinyId:e.tinyId,audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:!1,ssrc:i},retries:3,retryTimeout:0});case 14:if(0===(l=r.sent).data.code||-10036===l.data.code){r.next=17;break}throw new FA({code:l.data.code,message:l.data.message});case 17:r.next=24;break;case 19:return r.prev=19,r.t0=r.catch(11),r.next=23,e.removeDownlink();case 23:throw r.t0;case 24:return r.abrupt("return");case 25:return e.singlePC.addDownlinkQueue.delete(e.tinyId),r.next=28,e.singlePC.addDownlink({userId:e.userId,tinyId:e.tinyId,ssrc:e.ssrc});case 28:if(r.prev=28,$P){r.next=31;break}return r.abrupt("return");case 31:return d=e._room.jitterBufferDelay||{},h=d.main,p=d.aux,m=e._room.scheduleResult.config||{},v=m.jitterDelay,_=void 0===v?h:v,g=m.jitterDelayAux,y=void 0===g?p:g,(zw(_)||zw(y))&&e.setJitterBufferDelay({mainDelay:_,auxDelay:y}),r.finish(28);case 34:case"end":return r.stop()}}),r,null,[[4,,28,34],[11,19]])}))()}))}},{key:"removeDownlink",value:function(){return bA(this,null,f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.singlePC){e.next=2;break}return e.abrupt("return");case 2:return this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId),(null!=(t=this._room.scheduleResult.config)&&t.jitterDelay||null!=t&&t.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),e.next=7,this.singlePC.removeDownlink(this.userId);case 7:case"end":return e.stop()}}),e,this)})))}},{key:"setJitterBufferDelay",value:function(e){var t=this,n=e.mainDelay,r=e.auxDelay;if(!$P||!this.singlePC||!this._peerConnection||MD(n)&&MD(r))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(n," aux: ").concat(r));var i=this.singlePC.getReceiversByUserId(this.userId);return zw(n)&&(this.remoteAudioTrack.jitterBufferDelay=n,this.remoteVideoTrack.jitterBufferDelay=n),zw(r)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=r,MD(n)&&(this.remoteAudioTrack.jitterBufferDelay=r)),new Promise((function(e){t.doSetJitterBufferDelay({mainDelay:n,auxDelay:r,receivers:i,resolve:e})}))}},{key:"doSetJitterBufferDelay",value:function(e){var t=this,n=e.mainDelay,r=e.auxDelay,i=e.receivers,a=e.resolve;try{if(0===n&&0===r)return i.forEach((function(e){return e.jitterBufferTarget=0})),a();if(i.forEach((function(e){var i,a=e.track===t.remoteAuxiliaryTrack.outMediaTrack||MD(n)&&e.track===t.remoteAudioTrack.outMediaTrack;if(!(a&&MD(r)||!a&&MD(n))){var o=a?r||0:n,s=(e.jitterBufferTarget||0)+100;s>o||(e.jitterBufferTarget=s,t._log.debug("set ".concat(a?"aux ":"").concat(null==(i=null==e?void 0:e.track)?void 0:i.kind," jitterBuffer delay ").concat(s," -> ").concat(o)))}})),!i.find((function(e){var i=e.track===t.remoteAuxiliaryTrack.outMediaTrack?r||0:n;return e.jitterBufferTarget<i})))return this._log.info("set jitterBuffer main: ".concat(n," aux: ").concat(r," done")),a();this.jitterBufferTimeoutId=setTimeout((function(){t.doSetJitterBufferDelay({mainDelay:n,auxDelay:r,receivers:i,resolve:a})}),1e3)}catch(XA){this._log.warn("set jitterBuffer delay error: ".concat(XA)),clearTimeout(this.jitterBufferTimeoutId),a()}}},{key:"audioReceiver",get:function(){var e;return(null==(e=this.singlePC)?void 0:e.getReceiversByUserId(this.userId)[0])||null}}])}(Tj);TA([qL(),jL((function(e){return function(){for(var t=this,n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return new Promise((function(n,i){var a=function(e){t.off("closed",a),i(new FA({code:VA.API_CALL_ABORTED,message:YO({key:jO.CONNECTION_ABORTED,data:e})}))};t.on("closed",a),e.apply(t,r).then(n,i).finally((function(){t.off("closed",a)}))}))}}))],Aj.prototype,"subscribe",1),TA([qL()],Aj.prototype,"unsubscribe",1),TA([QL((function(){return"jitter"}))],Aj.prototype,"setJitterBufferDelay",1);var Cj=Aj,wj=function(e){function i(e,a){var o;return r(this,i),(o=n(this,i)).room=e,o.signalChannel=a,SA(t(o),"log"),SA(t(o),"cmdIdSeqMap",new Map),SA(t(o),"messageMap",new Map),o.log=Ux.createLogger({id:"cmm",userId:e.userId}),o.onReceiveMsg=o.onReceiveMsg.bind(t(o)),a.on(aW.RECEIVE_CUSTOM_MSG,o.onReceiveMsg),o.room.on("peer-leave",(function(e){E(o.messageMap.keys()).forEach((function(t){t.split("_").slice(0,-1).join("_")===e&&o.messageMap.delete(t)}))})),o}return d(i,e),o(i,[{key:"send",value:function(e){var t=e.cmdId,n=e.data,r=this.cmdIdSeqMap.get(t)||Math.floor(16383*Math.random()),i={cmdId:t,msg:btoa(String.fromCharCode.apply(String,E(new Uint8Array(n)))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(t,r+1),this.signalChannel.send("channel_msg",i),this.log.debug("send custom msg: ".concat(JSON.stringify(i)))}},{key:"onReceiveMsg",value:function(e){var t=this,n=e.data.data,r=this.room.tinyIdToUserIdMap.get(n.srcTinyId);if(r){var a={userId:r,cmdId:n.cmdId,seq:n.streamSeq,data:Uint8Array.from(atob(n.msg),(function(e){return e.charCodeAt(0)})).buffer};if(n.ordered){var o="".concat(r,"_").concat(a.cmdId),s=this.messageMap.get(o);if(s&&0!==s.lastSeq)if(Math.abs(s.lastSeq-a.seq)>i.SEQ_INTERVAL)this.messageMap.set(o,{lastSeq:a.seq,cachedMessageMap:new Map}),this.emitMessage(a);else if(a.seq>s.lastSeq){if(a.seq===s.lastSeq+1)this.emitMessage(a);else if(!s.cachedMessageMap.has(a.seq)){var c=setTimeout((function(){return t.emitMessage(a,!0)}),5e3);s.cachedMessageMap.set(a.seq,{message:a,timeoutId:c})}}else this.log.debug("drop message ".concat(a.userId,"-").concat(a.cmdId,"-").concat(a.seq));else s||(s={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(o,s),setTimeout((function(){return t.emitMessage(a,!0)}),100)),s.cachedMessageMap.set(a.seq,{message:a})}else this.emit("message",a)}else{this.log.warn("receive msg from unknown user, wait peer-join tinyId: ".concat(n.srcTinyId));var u=function(r){r.tinyId===n.srcTinyId&&(t.room.off("peer-join",u),t.onReceiveMsg(e))};this.room.on("peer-join",u),bD(2e3).then((function(){return t.room.off("peer-join",u)}))}}},{key:"emitMessage",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.messageMap.get("".concat(e.userId,"_").concat(e.cmdId)),i=e;if(r){if(n){var a=E(r.cachedMessageMap.values()).sort((function(e,t){return e.message.seq-t.message.seq}));a[0]&&(i=a[0].message)}0!==r.lastSeq&&i.seq-r.lastSeq>1&&this.log.debug("msg lost userId: ".concat(i.userId," seq: ").concat(r.lastSeq," -> ").concat(i.seq)),r.lastSeq=i.seq,clearTimeout(null==(t=r.cachedMessageMap.get(i.seq))?void 0:t.timeoutId),r.cachedMessageMap.delete(i.seq)}this.log.debug("receive custom msg: ".concat(JSON.stringify(i))),this.emit("message",i);var o=null==r?void 0:r.cachedMessageMap.get(i.seq+1);o&&this.emitMessage(o.message)}}])}(kA(RA()).EventEmitter);SA(wj,"SEQ_INTERVAL",300);var Dj=wj,Nj=GA.isString,xj=GA.isUndefined,Oj=GA.getNetworkType,Pj=GA.isEmpty,Mj=function(e){function i(e){var a;return r(this,i),a=n(this,i,[e]),SA(t(a),"_businessInfo"),SA(t(a),"userManager"),SA(t(a),"_version"),SA(t(a),"_heartbeat",-1),SA(t(a),"_lastHeartBeatTime",-1),SA(t(a),"_stats"),SA(t(a),"_joinTimeout",-1),SA(t(a),"_firstPublishedList",null),SA(t(a),"_joinReject",null),SA(t(a),"_isRelayChanged",!1),SA(t(a),"sdpSemantics"),SA(t(a),"signalChannel",null),SA(t(a),"uplinkConnection",null),SA(t(a),"singlePC",null),SA(t(a),"enableSPC",OP),SA(t(a),"_changeBigSmallRecords",new Map),SA(t(a),"networkQuality"),SA(t(a),"_iceTransportPolicy"),SA(t(a),"forceRelay",!1),SA(t(a),"_turnServers",[]),SA(t(a),"_iceServersFromJoin"),SA(t(a),"_syncUserListInterval",-1),SA(t(a),"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160}),SA(t(a),"enableSEI",!1),SA(t(a),"_enableAudioVolumeEvaluation",!1),SA(t(a),"_audioVolumeIntervalId",0),SA(t(a),"_enableMultiAuxStream",!1),SA(t(a),"_pureAudioPushMode",!1),SA(t(a),"_customMessageManager"),SA(t(a),"preferHW",!1),SA(t(a),"healthDetector"),SA(t(a),"playoutDelay"),SA(t(a),"jitterBufferDelay"),SA(t(a),"_updateAudioLevelTaskId",-1),a._stats=new wW(t(a),a._log),a.userManager=new eB(a.userId,a._log),a._version=YA,a.sdpSemantics=aw,xj(e.sdpSemantics)?Hx.isUnifiedPlanDefault()&&(a.sdpSemantics=iw):a.sdpSemantics=e.sdpSemantics,a._log.info("sdpSemantics: ".concat(a.sdpSemantics,", netType: ").concat(Oj())),e.iceTransportPolicy&&(a._iceTransportPolicy=e.iceTransportPolicy),a._enableMultiAuxStream=!xj(e.enableMultiAuxStream)&&e.enableMultiAuxStream,a.enableSEI=e.enableSEI&&OP,!xj(e.enableSPC)&&OP&&(a.enableSPC=e.enableSPC),a.preferHW=!!e.preferHW,a._initBusinessInfo(e),a.healthDetector=new uj(t(a)),a}return d(i,e),o(i,[{key:"isMainStreamPublished",get:function(){var e;return!(null==(e=this.uplinkConnection)||!e.isMainStreamPublished)}},{key:"isMainAudioPublished",get:function(){var e;return!(null==(e=this.uplinkConnection)||!e.localMainAudioTrack)}},{key:"isAuxStreamPublished",get:function(){var e;return!(null==(e=this.uplinkConnection)||!e.isAuxStreamPublished)}},{key:"hasAuxStream",get:function(){return E(this.remotePublishedUserMap.values()).findIndex((function(e){return e.muteState.hasAuxiliary}))>=0}},{key:"userMap",get:function(){return this.userManager.userMap}},{key:"remotePublishedUserMap",get:function(){return this.userManager.remotePublishedUserMap}},{key:"tinyIdToUserIdMap",get:function(){return new Map(E(this.userMap.values()).map((function(e){return[e.tinyId,e.userId]})))}},{key:"join",value:function(e,t,n){return bA(this,null,f().mark((function t(){var n=this;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.abrupt("return",(this.userManager.mySelfId=this.userId,this.userManager.on("1",(function(e){n.emit("peer-join",e)})),this.userManager.on("2",(function(e){n.closeDownLinkConnection(e,"remote user exitRoom"),n.emit("peer-leave",e)})),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",(function(e){var t=function(e,t){var n={};for(var r in e)hA.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&lA){var i,a=s(lA(e));try{for(a.s();!(i=a.n()).done;)r=i.value,t.indexOf(r)<0&&fA.call(e,r)&&(n[r]=e[r])}catch(o){a.e(o)}finally{a.f()}}return n}(e,[]);Px.emit(Lx.REMOTE_PUBLISH_STATE_CHANGED,_A({room:n},t)),n.emit("remote-publish-state-changed",_A({},t))})),this.joinParams=e,new Promise((function(t,r){return bA(n,null,f().mark((function n(){var i,a,o;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return this._joinReject=r,n.prev=1,this.checkDestroy(),n.prev=3,n.next=6,Promise.all([this.initialize(),this.initSinglePC()]);case 6:n.next=15;break;case 8:if(n.prev=8,n.t0=n.catch(3),n.t0 instanceof FA&&n.t0.code===VA.SPC_INITIALIZED_FAILED){n.next=12;break}return n.abrupt("return",r(n.t0));case 12:return null==(i=this.signalChannel)||i.destroy(),n.next=15,this.initialize();case 15:return o=aD(),n.next=18,this.doJoin(e,null==(a=this.singlePC)?void 0:a.clientAbility);case 18:rP.addSuccessEvent({key:521708,cost:aD()-o}),t(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}}),n.next=26;break;case 23:n.prev=23,n.t1=n.catch(1),rP.addFailedEvent({key:521708,error:n.t1}),r(n.t1);case 26:this._joinReject=null;case 27:case"end":return n.stop()}}),n,this,[[1,23],[3,8]])})))}))));case 1:case"end":return t.stop()}}),t,this)})))}},{key:"initSinglePC",value:function(){return bA(this,null,f().mark((function e(){var t=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.enableSPC||this.singlePC){e.next=11;break}return this.singlePC=new _j({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",(function(e){return t.emit("sei-message",e)})),this.singlePC.on("dump",(function(e){return t.emit("dump",e)})),this.singlePC.once("error",(function(){return t.fallbackToMPC()})),e.prev=2,e.next=5,this.singlePC.initialize();case 5:return e.abrupt("return",e.sent);case 8:throw e.prev=8,e.t0=e.catch(2),this.fallbackToMPC(),new FA({code:VA.SPC_INITIALIZED_FAILED,message:null==e.t0?void 0:e.t0.message});case 11:case"end":return e.stop()}}),e,this,[[2,8]])})))}},{key:"doJoin",value:function(e,t){var n=this;return new Promise((function(r,i){return bA(n,null,f().mark((function n(){var a,o,s,c,u,l=this;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(nW,(function(e){l.clearJoinTimeout(),Px.emit(Lx.JOIN_SIGNAL_CONNECTION_END,{room:l,error:e}),i(e)})),qw(null==(o=null==(a=this.scheduleResult)?void 0:a.config)?void 0:o.singlePC)&&OP&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),t&&this.playoutDelay&&(t.playoutDelay=this.playoutDelay),c={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:"live"===this.scene?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:xx(),netType:Ow(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0},this._log.debug("join room signal data: ".concat(JSON.stringify(c))),u=5e3,null!=(s=this.scheduleResult.config)&&s.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(u=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout((function(){i(new FA({code:VA.JOIN_ROOM_FAILED,message:YO({key:jO.JOIN_ROOM_TIMEOUT})}))}),u),Px.emit(Lx.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?"join/v2":"join",c),this.signalChannel.once(aW.JOIN_ROOM_RESULT,(function(t){return bA(l,null,f().mark((function n(){var a,o,s,c,u,l=this;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:this.clearJoinTimeout(),a=t.data,o=a.code,s=a.message,c=a.data,u=a.tinyId,Px.emit(Lx.JOIN_RECEIVED_CMD_RES,{room:this,code:o}),0===o?(this._log.info("Join room success, start heartbeat"),u&&(this.tinyId=u),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=c.publishers,this._iceServersFromJoin=c.iceServer?[c.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then((function(){var t;null==(t=l.singlePC)||t.connect(gA(_A({},c.ability),{useVp8:c.ability.useVp8||!!e.useVp8})).catch((function(){}))})),r()):(this._log.error("Join room failed result: ".concat(o," error: ").concat(s)),i(new FA({code:VA.JOIN_ROOM_FAILED,extraCode:o,message:YO({key:jO.JOIN_ROOM_FAILED,data:{error:s,code:o}})})));case 3:case"end":return n.stop()}}),n,this)})))}));case 5:case"end":return n.stop()}}),n,this)})))}))}},{key:"reJoin",value:function(){return bA(this,null,f().mark((function e(){var t,n,r,i=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.isJoined){e.next=22;break}return e.prev=1,this._log.warn("reJoin pending: ".concat(this.joinParams.roomId)),n=[],this.singlePC&&(this.singlePC.close(),this.singlePC=null,n.push(this.initSinglePC().then((function(e){return t=e,e})))),this.signalChannel&&(this.signalChannel.close(),n.push(this.signalChannel.connect())),e.next=8,Promise.all(n);case 8:return e.next=10,this.doJoin(gA(_A({},this.joinParams),{role:"anchor"===this.role?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),t);case 10:if(this._log.warn("reJoin success"),kM.logSuccessEvent({userId:this.userId,eventType:ew.REJOIN}),!this.singlePC){e.next=15;break}r=function(e){var t;"CONNECTED"===e.state&&(null==(t=i.singlePC)||t.off(hj.CONNECTION_STATE_CHANGED,r),i.uplinkConnection instanceof bj&&(i.uplinkConnection.installEvents(),i.uplinkConnection.onSinglePCReconnected()),i.remotePublishedUserMap.forEach((function(e){e.installEvents(),e.onSinglePCReconnected()})))},this.singlePC.on(hj.CONNECTION_STATE_CHANGED,r),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof CW&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection();case 15:e.next=20;break;case 17:e.prev=17,e.t0=e.catch(1),this._log.warn("reJoin fail ".concat(e.t0)),this.reset(),kM.logFailedEvent({userId:this.userId,eventType:ew.REJOIN,error:e.t0}),this.emit("error",new FA({code:VA.JOIN_ROOM_FAILED,message:YO({key:jO.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}));case 20:e.next=23;break;case 22:this._log.warn("reJoin abort");case 23:case"end":return e.stop()}}),e,this,[[1,17]])})))}},{key:"initialize",value:function(){return bA(this,null,f().mark((function e(){var t,n,r,i,a,o,s=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=this.getSignalChannelUrl(),r=n.mainUrl,i=n.backupUrl,a=this.signalChannel||function(e){return E(hW.values()).find((function(t){return t.room.userId===e&&!t.room.isJoined}))||null}(this.userId),o=!!(a&&a.isConnected&&a.keepAlive&&a.userId===this.userId&&a.room===this),Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(t=this.scheduleResult.domains[0]),this._log.info("".concat(o?"reuse":"setup"," signal channel")),o?(a.url=r,a.backupUrl=i,a.room=this,this.signalChannel=a):(a&&a.close(),this.signalChannel=new fW({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:r,backupUrl:i,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?t:void 0}),this._customMessageManager=new Dj(this,this.signalChannel),this._customMessageManager.on("message",(function(e){s.emit("custom-message",e)}))),this.networkQuality||(this.networkQuality=new NW({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(NW.EVENT_NETWORK_QUALITY,(function(e){var t;s.emit("network-quality",e),null==(t=s.singlePC)||t.detectTCPAndUDP(e)}))),yM(this,this.signalChannel).add("2",(function(e){Px.emit(Lx.SIGNAL_CONNECTION_STATE_CHANGED,_A({room:s},e)),s.emit("signal-connection-state-changed",e)})).add("4",(function(e){s.reset(),s.emit("error",e)})).add(aW.PEER_JOIN,(function(e){var t=e.data.data,n=t.srcTinyId,r=t.userId,i=t.role;s.userManager.addUser({userId:r,tinyId:n,role:i})})).add(aW.PEER_LEAVE,(function(e){var t=e.data.data,n=t.userId,r=t.reason,i=void 0===r?0:r;s.userManager.deleteUser(n,i)})).add(aW.UPDATE_REMOTE_MUTE_STAT,(function(e){s._lastHeartBeatTime>0&&Date.now()-s._lastHeartBeatTime>=1e4&&s.doHeartbeat(),s.onPublishedUserList(e.data)})).add(aW.CLIENT_BANNED,(function(e){var t=e.data.data.reason;if(kM.uploadEvent({log:"stat-banned:".concat(t),userId:s.userId}),"user_time_out"===t)return s._log.warn("".concat(t," last heart beat time: ").concat(s._lastHeartBeatTime," interval: ").concat(Date.now()-s._lastHeartBeatTime,", visibility: ").concat(document.visibilityState)),void s.reJoin();s._log["kick"===t?"error":"info"]("user was banned because of [".concat(t,"]")),s.reset(),s.emit("banned",{reason:t})})).add(aW.SEND_SWITCH_ROOM_SUBED_REQ,(function(e){s.singlePC&&e.data.data.subList.forEach((function(e){s.singlePC.autoSubscribedUserMap.set(e.userId,e)}))})),this.signalChannel.once("1",(function(e){s.tinyId=e.signalInfo.tinyId,Px.emit(Lx.JOIN_SIGNAL_CONNECTION_END,{room:s})})),Px.emit(Lx.JOIN_SIGNAL_CONNECTION_START,{room:this}),e.next=10,this.signalChannel.connect();case 10:return o&&Px.emit(Lx.JOIN_SIGNAL_CONNECTION_END,{room:this}),e.abrupt("return",o);case 12:case"end":return e.stop()}}),e,this)})))}},{key:"setSignalChannel",value:function(e){this.signalChannel=e,e||EM(this)}},{key:"leave",value:function(){return bA(this,null,f().mark((function e(){var t;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.doHeartbeat();case 3:e.next=7;break;case 5:e.prev=5,e.t0=e.catch(0);case 7:this._log.info("leave() => leaving room"),Px.emit(Lx.LEAVE_SEND_CMD,{room:this}),null==(t=this.signalChannel)||t.send("leave");case 8:case"end":return e.stop()}}),e,this,[[0,5]])})))}},{key:"clearNetworkQuality",value:function(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}},{key:"closeConnections",value:function(){var e=this;this.remotePublishedUserMap.forEach((function(t){e.closeDownLinkConnection(t.userId,"you exitRoom")}))}},{key:"clearJoinTimeout",value:function(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}},{key:"startHeartbeat",value:function(){-1===this._heartbeat&&(this._heartbeat=mM.run("ric",this.doHeartbeat.bind(this),{delay:2e3}))}},{key:"stopHeartbeat",value:function(){-1!==this._heartbeat&&(this._log.info("stopHeartbeat"),mM.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}},{key:"doHeartbeat",value:function(){return bA(this,null,f().mark((function e(){var t,n,r,i,a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=this.badCaseDetector.getMonitorFreeze(),e.next=3,this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:n});case 3:r=e.sent,this.badCaseDetector.resetMonitor(),i=null!=(t=this.signalChannel)&&t.isConnected?function(e){if(XF.has(e)){var t=XF.get(e).map((function(e){return{uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}}));return XF.delete(e),t}return[]}(this.userId):[],a=gA(_A({str_sdk_version:KA,uint64_datetime:(new Date).getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:i,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},r),{msg_device_info:_A({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:Ow()},r.msg_device_info)}),this.heartbeatReport=a,Px.emit(Lx.HEARTBEAT_REPORT,{room:this,report:a}),this.signalChannel&&(this.signalChannel.isConnected&&(this.signalChannel.send("quality_report",a),o=Date.now(),this._lastHeartBeatTime>0&&o-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(o-this._lastHeartBeatTime)),this._lastHeartBeatTime=o,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())),this.emit("heartbeat-report",gA(_A({},a),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))),!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0);case 8:case"end":return e.stop()}}),e,this)})))}},{key:"onPublishedUserList",value:function(e){var t=this;if(this.isJoined){var n=e.data.userList.filter((function(e){return e.flag!==MC})).map((function(e){var n=e.userId,r=e.srcTinyId,i=e.flag;n===t.userId&&t.uplinkConnection&&(t.uplinkConnection.flag=i);var a=t.remotePublishedUserMap.get(n);return a&&t.checkSubscribeBigSmallVideo(a),{userId:n,tinyId:r,flag:i}}));e.data.mixRobotList.forEach((function(e){var t=e.userId,r=e.srcTinyId,i=e.flag,a=e.mixUserList;n.unshift({userId:t,tinyId:r,flag:i,isRobot:!0,mixUserList:a})})),Px.emit(Lx.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:n}),this.userManager.setRemotePublishedUserList(n)}}},{key:"closeUplink",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"you unpublished";this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection instanceof CW&&(this.uplinkConnection=null)),this.localTracks.forEach((function(e){return e.unpublish()})),this.localTracks.clear()}},{key:"createDownlinkConnection",value:function(e){var t=e.userId,n=e.tinyId,r=e.flag,i=e.isRobot,a=new(this.singlePC?Cj:bW)({userId:t,tinyId:n,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:i});this.userManager.addRemotePublishedUser(a),this.installDownlinkEvents(a,t),this.emit("remote-published",a)}},{key:"closeDownLinkConnection",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"remote user unpublished",n=this.remotePublishedUserMap.get(e);n&&(n.close(t),this.emit("remote-unpublished",n))}},{key:"installDownlinkEvents",value:function(e,t){var n=this;e.on("error",(function(e){var r=e.getCode();r!==VA.ICE_TRANSPORT_ERROR&&(r===VA.DOWNLINK_RECONNECTION_FAILED&&n.closeDownLinkConnection(t),n.emit("error",e))})),e.on("connection-state-changed",(function(t){n.emit("media-connection-state-changed",gA(_A({},t),{userId:e.userId}))})),e.on("firewall-restriction",(function(){n.emit("firewall-restriction")}))}},{key:"startSyncUserListInterval",value:function(){-1===this._syncUserListInterval&&(this._syncUserListInterval=mM.run("ric",this.syncUserList.bind(this)))}},{key:"stopSyncUserListInterval",value:function(){mM.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}},{key:"syncUserList",value:function(){var e=this;return this.getUserList().then((function(t){e.userManager.setUserList(t)})).catch((function(t){e._log.debug("sync user list failed: ".concat(t))}))}},{key:"getUserList",value:function(){var e;return null!=(e=this.signalChannel)&&e.isConnected?this.signalChannel.sendWaitForResponse({command:"get_user_list",responseCommand:aW.USER_LIST_RES,enableLog:!1,timeout:2e3}).then((function(e){var t=e.data,n=t.code,r=t.message;if(0===n)return(t.data&&t.data.userList||[]).map((function(e){return{userId:e.userId,tinyId:e.srcTinyId,role:e.role}}));throw YO({key:jO.SIGNAL_RESPONSE_FAILED,data:{signalResponse:aW.USER_LIST_RES,code:n,message:r}})})):Promise.reject("not connected")}},{key:"getAllConnections",value:function(){var e=E(this.remotePublishedUserMap.values());return this.uplinkConnection&&e.push(this.uplinkConnection),e}},{key:"isRelayMaybeFailed",value:function(){if(this.signalChannel&&!this.signalChannel.isOnline||!gW)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;var e=this.getAllConnections();if(0===e.length)return!1;for(var t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}},{key:"checkConnectionsToReconnect",value:function(){var e,t=this;this.singlePC?(null==(e=this.singlePC.getPeerConnection())?void 0:e.connectionState)===zC.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach((function(e){if(e instanceof yW&&!e.getIsReconnecting()){var n=e.getPeerConnection();n&&n.connectionState===zC.CLOSED&&(t._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}}))}},{key:"fallbackToMPC",value:function(){return bA(this,null,f().mark((function e(){var t,n,r,i,a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this._log.warn("fallback to multi pc"),kM.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,null==(t=this.singlePC)||t.close(),this.singlePC=null,e.t0=this.isJoined,!e.t0){e.next=9;break}return e.next=9,this.reJoin();case 9:if(!this.uplinkConnection){e.next=21;break}if(n=this.uplinkConnection,this.uplinkConnection=new CW({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),e.t1=n.isMainStreamPublished,!e.t1){e.next=16;break}return e.next=16,this.uplinkConnection.publish({localAudioTrack:n.localMainAudioTrack,localVideoTrack:n.localMainVideoTrack,isAuxiliary:!1});case 16:if(e.t2=n.isAuxStreamPublished,!e.t2){e.next=20;break}return e.next=20,this.uplinkConnection.publish({localAudioTrack:n.localAuxAudioTrack,localVideoTrack:n.localAuxVideoTrack,isAuxiliary:!0});case 20:n.close();case 21:r=0,i=E(this.remotePublishedUserMap.values());case 22:if(!(r<i.length)){e.next=38;break}if(a=i[r],o=new bW({userId:a.userId,tinyId:a.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:a.flag,remoteAudioTrack:a.remoteAudioTrack,remoteVideoTrack:a.remoteVideoTrack,remoteAuxiliaryTrack:a.remoteAuxiliaryTrack}),this.installDownlinkEvents(o,a.userId),this.remotePublishedUserMap.set(a.userId,o),e.t3=a.isMainStreamSubscribed,!e.t3){e.next=31;break}return e.next=31,o.subscribe(a.subscribeState,"main");case 31:if(e.t4=a.isAuxStreamSubscribed,!e.t4){e.next=35;break}return e.next=35,o.subscribe(a.subscribeState,"auxiliary");case 35:r++,e.next=22;break;case 38:case"end":return e.stop()}}),e,this)})))}},{key:"destroy",value:function(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),g(i,"destroy",this,3)([]),this._joinReject&&(this._joinReject(new FA({code:VA.INVALID_OPERATION,message:YO({key:jO.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),mM.clearTask(this._audioVolumeIntervalId))}},{key:"switchRole",value:function(e){return bA(this,null,f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(t.t0=this.role!==e,!t.t0){t.next=5;break}return"audience"===e&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),t.next=5,this.doSwitchRole(e);case 5:case"end":return t.stop()}}),t,this)})))}},{key:"doSwitchRole",value:function(e){var t=this,n={command:"change_role",data:{role:"anchor"===e?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:aW.SWITCH_ROLE_RES,retries:1};return this._log.info("switchRole signal data: ".concat(JSON.stringify(n.data))),this.signalChannel.sendWaitForResponseWithRetry(n).then((function(n){var r=n.data,i=r.code,a=r.message;if(0!==i)throw new FA({code:VA.SWITCH_ROLE_FAILED,message:YO({key:jO.SWITCH_ROLE_FAILED,data:{message:a,code:i}})});t.role=e})).catch((function(e){throw e instanceof FA&&e.getCode()===VA.API_CALL_TIMEOUT&&(e=new FA({code:VA.SWITCH_ROLE_FAILED,message:YO({key:jO.SWITCH_ROLE_TIMEOUT})})),t._log.error(e),e}))}},{key:"publish",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return bA(this,null,f().mark((function e(){var n,r,i,a,o,s=this;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n={},r={},t.forEach((function(e){e instanceof nV&&(e instanceof dV?r.audio=e:n.audio=e),e instanceof oV&&(e instanceof uV&&2===e.mediaType?r.video=e:n.video=e)})),i=Pj(n),a=Pj(r),(!i||!a)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new bj({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new CW({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",(function(e){s.emit("media-connection-state-changed",gA(_A({},e),{userId:s.userId}))})),this.uplinkConnection.on("firewall-restriction",(function(){s.emit("firewall-restriction")})),this.uplinkConnection.on("error",(function(e){var t=e.getCode();t!==VA.ICE_TRANSPORT_ERROR&&(t===VA.UPLINK_RECONNECTION_FAILED&&s.closeUplink(),s.emit("error",e))}))),o=t.map((function(e){return e.kind})).join(","),e.t0=i,e.t0){e.next=11;break}return this._log.info("publish() => main ".concat(o)),e.next=10,this.uplinkConnection.publish({localAudioTrack:n.audio,localVideoTrack:n.video,isAuxiliary:!1});case 10:this._log.info("main is published");case 11:if(e.t1=a,e.t1){e.next=17;break}return this._log.info("publish() => aux ".concat(o)),e.next=16,this.uplinkConnection.publish({localAudioTrack:r.audio,localVideoTrack:r.video,isAuxiliary:!0});case 16:this._log.info("aux is published");case 17:case"end":return e.stop()}}),e,this)})))}},{key:"unpublish",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return bA(this,null,f().mark((function e(){var n,r,i;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(("live"!==this.scene||"anchor"===this.role)&&(this.isMainStreamPublished||this.isAuxStreamPublished)&&this.uplinkConnection){e.next=2;break}return e.abrupt("return");case 2:if(n={},r={},t.forEach((function(e){!e.mediaTrack||!e.isPublished||(e instanceof nV&&(e instanceof dV?r.audio=e:n.audio=e),e instanceof oV&&(e instanceof uV&&2===e.mediaType?r.video=e:n.video=e))})),e.prev=4,i=t.map((function(e){return e.kind})).join(","),e.t0=Pj(n),e.t0){e.next=11;break}return this._log.info("unpublish() => main ".concat(i)),e.next=11,this.uplinkConnection.unpublish({localAudioTrack:n.audio,localVideoTrack:n.video});case 11:if(e.t1=Pj(r),e.t1){e.next=16;break}return this._log.info("unpublish() => aux ".concat(i)),e.next=16,this.uplinkConnection.unpublish({localAudioTrack:r.audio,localVideoTrack:r.video});case 16:e.next=20;break;case 18:e.prev=18,e.t2=e.catch(4);case 20:0===this.localTracks.size&&this.closeUplink("you unpublished");case 21:case"end":return e.stop()}}),e,this,[[4,18]])})))}},{key:"addTrack",value:function(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();var t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}},{key:"removeTrack",value:function(e){return this.uplinkConnection&&e.mediaTrack?this.uplinkConnection.removeTrack(e).then((function(t){return e.unpublish(),t})):Promise.resolve()}},{key:"replaceTrack",value:function(e){return this.uplinkConnection&&e.mediaTrack&&LP()?this.uplinkConnection.replaceTrack(e).then((function(t){t&&Px.emit(Lx.LOCAL_TRACK_REPLACED,{track:e})})):Promise.resolve()}},{key:"setBandWidth",value:function(e){return bA(this,null,f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(t.t0=this.uplinkConnection,!t.t0){t.next=6;break}return t.next=4,this.uplinkConnection.setBandwidth(e);case 4:return t.next=6,this.uplinkConnection.sendMediaSettings();case 6:case"end":return t.stop()}}),t,this)})))}},{key:"enableSmall",value:function(e){return bA(this,null,f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this.uplinkConnection&&this.uplinkConnection.localMainVideoTrack){t.next=2;break}return t.abrupt("return",Promise.resolve());case 2:if(t.t0=e&&this.uplinkConnection.localMainVideoTrack.small,!t.t0){t.next=6;break}return t.next=6,this.setBandWidth({type:IC.VIDEO,videoType:IC.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate});case 6:return t.next=8,this.uplinkConnection.enableSmall(e);case 8:case"end":return t.stop()}}),t,this)})))}},{key:"subscribe",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return bA(this,null,f().mark((function e(){var n,r,i,a,o,c,u,l,d,h;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=t.filter((function(e){return!e.isSubscribed})),0!==t.length){e.next=2;break}return e.abrupt("return");case 2:if(n=t[0].userId,r=this.remotePublishedUserMap.get(n)){e.next=5;break}return e.abrupt("return");case 5:return i=t.find((function(e){return 2===e.mediaType}))?"auxiliary":"main",e.prev=6,a=_A({},r.subscribeState),t.forEach((function(e){switch(e.mediaType){case 1:a.audio=!0;break;case 4:a.video=!0;break;case 8:a.smallVideo=!0;break;case 2:a.auxiliary=!0}})),(o=this._changeBigSmallRecords.get(n))&&o.options.smallVideo&&r.muteState.hasSmall&&a.video&&(a.video=!1,a.smallVideo=!0),Px.emit(Lx.SUBSCRIBE_START,{room:this,streamType:i,remotePublishedUser:r,subscribeState:a}),this._log.info("subscribe() => ".concat(n," ").concat(i," [").concat(SW(a),"] prev: [").concat(SW(r.subscribeState),"]")),e.next=15,r.subscribe(a,i);case 15:this._log.info("subscribe ".concat(n," ").concat(i," done")),c=s(t),e.prev=17,c.s();case 19:if((u=c.n()).done){e.next=27;break}if(l=u.value,e.t0=l.mediaTrack,e.t0){e.next=25;break}return e.next=25,l.waitHasMediaTrack();case 25:e.next=19;break;case 27:e.next=32;break;case 29:e.prev=29,e.t1=e.catch(17),c.e(e.t1);case 32:return e.prev=32,c.f(),e.finish(32);case 35:Px.emit(Lx.SUBSCRIBE_SUCCESS,{room:this,streamType:i,remotePublishedUser:r}),e.next=42;break;case 38:throw e.prev=38,e.t2=e.catch(6),d=e.t2 instanceof FA?e.t2.getCode():VA.UNKNOWN,h=e.t2,e.t2 instanceof FA?d===VA.REMOTE_STREAM_NOT_EXIST&&(h=new FA({code:VA.API_CALL_ABORTED,message:YO({key:jO.API_CALL_ABORTED,data:{message:e.t2.message,userId:n,streamType:i}})}),this._log.warn(h)):(h=new FA({code:d,message:YO({key:jO.SUBSCRIBE_FAILED,data:{message:e.t2.message,userId:n,streamType:i}})}),this._log.error(h)),h;case 42:case"end":return e.stop()}}),e,this,[[6,38],[17,29,32,35]])})))}},{key:"unsubscribe",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return bA(this,null,f().mark((function e(){var n,r,i;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=t[0].userId,r=this.remotePublishedUserMap.get(n)){e.next=3;break}return e.abrupt("return");case 3:return i=t.find((function(e){return 2===e.mediaType}))?"auxiliary":"main",this._log.info("unsubscribe() => ".concat(n," ").concat(i)),e.prev=5,e.next=8,r.unsubscribe({remoteTracks:t,streamType:i});case 8:e.next=13;break;case 10:e.prev=10,e.t0=e.catch(5),this._log.warn("unsubscribe() => failed ".concat(e.t0));case 13:t.forEach((function(e){e.unsubscribe(),8===e.mediaType&&e.setMediaType(4)})),Px.emit(Lx.UNSUBSCRIBE_SUCCESS,{room:this,streamType:i,remotePublishedUser:r});case 14:case"end":return e.stop()}}),e,this,[[5,10]])})))}},{key:"setEncodedDataProcessingListener",value:function(e){throw new Error("Method not implemented.")}},{key:"enableAudioVolumeEvaluation",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:2e3,n=arguments.length>1?arguments[1]:void 0;if(t<=0)return this._enableAudioVolumeEvaluation=!1,void mM.clearTask(this._audioVolumeIntervalId);t=Math.floor(Math.max(t,100)),Px.emit(Lx.AUDIO_LEVEL_INTERVAL,{interval:t}),this._audioVolumeIntervalId&&mM.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=mM.run("intervalInWorker",(function(){var r;fL.isRunning?e.stopUpdateAudioLevelFromSenderStat():e.updateAudioLevelFromSenderStat(t,n);var i=[];null==(r=e.remotePublishedUserMap)||r.forEach((function(t){if(t.muteState.hasAudio){!fL.isRunning&&t.muteState.audioAvailable&&t.remoteAudioTrack.isSubscribed?e.updateDownlinkAudioLevelFromReceiver(t):t.remoteAudioTrack.volume=0;var n=Math.floor(100*t.remoteAudioTrack.getAudioLevel());i.push({userId:t.userId,volume:n})}})),e.emit("audio-volume",i)}),{delay:t,backgroundTask:n})}},{key:"updateAudioLevelFromSenderStat",value:function(e,t){return bA(this,null,f().mark((function n(){var r,i,a,o=this;return f().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(this.uplinkConnection&&this.uplinkConnection.localMainAudioTrack&&-1===this._updateAudioLevelTaskId){n.next=2;break}return n.abrupt("return");case 2:if(i=null==(r=this.uplinkConnection.getPeerConnection())?void 0:r.getSenders()[0]){n.next=5;break}return n.abrupt("return");case 5:a=Math.max(e,500),this._log.warn("updateAudioLevelFromSenderStat ".concat(a)),this._updateAudioLevelTaskId=mM.run("intervalInWorker",(function(){return bA(o,null,f().mark((function e(){var t,n;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.uplinkConnection&&this.uplinkConnection.localMainAudioTrack){e.next=2;break}return e.abrupt("return",void this.stopUpdateAudioLevelFromSenderStat());case 2:return e.next=4,i.getStats();case 4:if(t=e.sent,!(this._updateAudioLevelTaskId<0)){e.next=7;break}return e.abrupt("return");case 7:n=this.uplinkConnection.localMainAudioTrack,t.forEach((function(e){"media-source"===e.type&&e.audioLevel&&(n.volume=e.audioLevel)}));case 9:case"end":return e.stop()}}),e,this)})))}),{delay:a,backgroundTask:t});case 7:case"end":return n.stop()}}),n,this)})))}},{key:"stopUpdateAudioLevelFromSenderStat",value:function(){var e;-1!==this._updateAudioLevelTaskId&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),mM.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,null!=(e=this.uplinkConnection)&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}},{key:"updateDownlinkAudioLevelFromReceiver",value:function(e){var t,n=e.audioReceiver;if(UP&&n){var r=null==(t=n.getSynchronizationSources()[0])?void 0:t.audioLevel;zw(r)?e.remoteAudioTrack.volume=Math.min(2*r,1):n.getStats().then((function(t){t.forEach((function(t){"inbound-rtp"===t.type&&zw(t.audioLevel)&&(e.remoteAudioTrack.volume=t.audioLevel)}))}))}}},{key:"getLocalAudioStats",value:function(){return bA(this,null,f().mark((function e(){var t,n;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n={},e.abrupt("return",(n[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},null!=(t=this.uplinkConnection)&&t.localMainAudioTrack&&(n[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),n));case 2:case"end":return e.stop()}}),e,this)})))}},{key:"getLocalVideoStats",value:function(){return bA(this,null,f().mark((function e(){var t,n,r;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r={},e.abrupt("return",(r[this.userId]=(null==(n=null==(t=this.uplinkConnection)?void 0:t.localMainVideoTrack)?void 0:n.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},r));case 2:case"end":return e.stop()}}),e,this)})))}},{key:"getTransportStats",value:function(){return bA(this,null,f().mark((function e(){var t,n,r,i,a,o,c;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t={rtt:0,downlinksRTT:{}},!this.uplinkConnection){e.next=6;break}return e.next=4,this._stats.getSenderStats(this.uplinkConnection);case 4:n=e.sent,t.rtt=n.rtt;case 6:r=s(this.remotePublishedUserMap),e.prev=7,r.s();case 9:if((i=r.n()).done){e.next=17;break}return a=v(i.value,2),o=a[1],e.next=13,this._stats.getReceiverStats(o);case 13:c=e.sent,t.downlinksRTT[c.userId]=c.rtt;case 15:e.next=9;break;case 17:e.next=22;break;case 19:e.prev=19,e.t0=e.catch(7),r.e(e.t0);case 22:return e.prev=22,r.f(),e.finish(22);case 25:return e.abrupt("return",t);case 26:case"end":return e.stop()}}),e,this,[[7,19,22,25]])})))}},{key:"getRemoteVideoStats",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a,o,c;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:n={},r=s(this.remotePublishedUserMap);try{for(r.s();!(i=r.n()).done;)a=v(i.value,2),o=a[0],c=a[1],"main"===e&&c.muteState.hasVideo&&(n[o]=c.remoteVideoTrack.stat),"auxiliary"===e&&c.muteState.hasAuxiliary&&(n[o]=c.remoteAuxiliaryTrack.stat)}catch(u){r.e(u)}finally{r.f()}return t.abrupt("return",n);case 4:case"end":return t.stop()}}),t,this)})))}},{key:"getRemoteAudioStats",value:function(){return bA(this,null,f().mark((function e(){var t,n,r,i,a,o;return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t={},n=s(this.remotePublishedUserMap);try{for(n.s();!(r=n.n()).done;)i=v(r.value,2),a=i[0],(o=i[1]).muteState.hasAudio&&(t[a]=o.remoteAudioTrack.stat)}catch(c){n.e(c)}finally{n.f()}return e.abrupt("return",t);case 4:case"end":return e.stop()}}),e,this)})))}},{key:"setTurnServer",value:function(e,t){this._log.info("set turn server: ".concat(JSON.stringify(e)," ").concat(t||""));var n=[];Array.isArray(e)?e.forEach((function(e){return n.push(GA.getTurnServer(e))})):GA.isPlainObject(e)&&n.push(GA.getTurnServer(e)),this._turnServers=n,t&&(this._iceTransportPolicy=t)}},{key:"sendStartMixTranscode",value:function(e){return this.signalChannel.sendWaitForResponse({command:"start_mcu_mix",data:e,timeout:5e3,responseCommand:aW.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}},{key:"sendStopMixTranscode",value:function(e){return this.signalChannel.sendWaitForResponse({command:"stop_mcu_mix",data:e,timeout:5e3,responseCommand:aW.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}},{key:"sendStartPublishCDN",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?"start_publishing":"start_push_user_cdn",data:e,timeout:5e3,responseCommand:t?aW.START_PUBLISH_TENCENT_CDN_RES:aW.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}},{key:"sendStopPublishCDN",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?"stop_publishing":"stop_push_user_cdn",data:e,timeout:5e3,responseCommand:t?aW.STOP_PUBLISH_TENCENT_CDN_RES:aW.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}},{key:"sendStartPushStreamToRoom",value:function(e){return this.signalChannel.sendWaitForResponse({command:"start_publish_cdn_stream",data:e,timeout:5e3,responseCommand:aW.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}},{key:"sendUpdatePushStreamToRoom",value:function(e){return this.signalChannel.sendWaitForResponse({command:"update_publish_cdn_stream",data:e,timeout:5e3,responseCommand:aW.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}},{key:"sendStopPushStreamToRoom",value:function(e){return this.signalChannel.sendWaitForResponse({command:"stop_publish_cdn_stream",data:e,timeout:5e3,responseCommand:aW.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}},{key:"sendAbilityStatus",value:function(e){var t;null==(t=this.signalChannel)||t.sendWaitForResponse({command:"ability_status_report",data:e,timeout:5e3,responseCommand:aW.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch((function(e){}))}},{key:"getIceServers",value:function(e){var t,n;return this._turnServers.length>0?this._turnServers:null!=(t=this.scheduleResult.iceServers)&&t.length?this.scheduleResult.iceServers:null!=e&&e.length?e:null!=(n=this._iceServersFromJoin)&&n.length?this._iceServersFromJoin:[]}},{key:"getIceTransportPolicy",value:function(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}},{key:"getLogger",value:function(){return this._log}},{key:"enableAIVoice",value:function(){throw new Error("Method not implemented.")}},{key:"getSignalChannelUrl",value:function(){var e={mainUrl:"",backupUrl:""},t=GA.getEnv();return t?(e.mainUrl="wss://".concat(t,".rtc.qq.com"),e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):this.proxy_unified?(e.mainUrl="wss://".concat(this.proxy_unified),e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl="wss://".concat(this.scheduleResult.domains[0]),e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl="wss://".concat(this.scheduleResult.domains[1]))),e}},{key:"getSignalInfo",value:function(){var e;return(null==(e=this.signalChannel)?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}},{key:"reset",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(e&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}},{key:"checkSubscribeBigSmallVideo",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a,o,s,c,u,l;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=e.subscribeState,r=e.userId,i=e.muteState,a=i.hasSmall,o=i.hasVideo,(a||o)&&(n.video||n.smallVideo)){t.next=3;break}return t.abrupt("return");case 3:if(!(!(s=this._changeBigSmallRecords.get(r))||s.isSubscribing||s.reSubscribeCount<=0)){t.next=6;break}return t.abrupt("return");case 6:if(c=s.options,u=s.reSubscribeCount,!(c.video&&n.video||c.smallVideo&&n.smallVideo&&a)){t.next=9;break}return t.abrupt("return");case 9:if(l={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo},t.prev=10,!a&&l.smallVideo&&(l.video=!0,l.smallVideo=!1),l.smallVideo!==n.smallVideo||l.video!==n.video){t.next=13;break}return t.abrupt("return");case 13:return s.isSubscribing=!0,s.reSubscribeCount=u-1,t.next=17,e.subscribe(l,"main");case 17:e.remoteVideoTrack.setMediaType(l.smallVideo?8:4),this._log.info("change [".concat(r,"] to ").concat(l.smallVideo?"small":"big"," video successfully. count ").concat(Tw-s.reSubscribeCount,".")),s.isSubscribing=!1,s.reSubscribeCount=Tw,t.next=26;break;case 23:t.prev=23,t.t0=t.catch(10),this._log.info("change [".concat(r,"] to ").concat(l.smallVideo?"small":"big"," video failed. count ").concat(Tw-s.reSubscribeCount,". reason: ").concat(t.t0)),s.isSubscribing=!1,0===s.reSubscribeCount&&this._changeBigSmallRecords.delete(r);case 26:case"end":return t.stop()}}),t,this,[[10,23]])})))}},{key:"changeType",value:function(e,t){var n={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:Tw};this._changeBigSmallRecords.set(t.userId,n),this._log.info("set [".concat(t.userId,"] video prefer type: ").concat(e?"small":"big")),this.emit("subscribe-small-video-changed",{userId:t.userId,isSmall:e});var r=this.remotePublishedUserMap.get(t.userId);r&&this.checkSubscribeBigSmallVideo(r)}},{key:"smallStreamConfig",get:function(){return this._smallStreamConfig}},{key:"_initBusinessInfo",value:function(e){this._businessInfo=e.businessInfo;var t={};if(Nj(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!xj(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new FA({code:VA.INVALID_PARAMETER,message:YO({key:jO.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!xj(e.userDefineRecordId)){if(null===e.userDefineRecordId.match(/^[A-Za-z0-9_-]{1,64}$/gi))throw new FA({code:VA.INVALID_PARAMETER,message:YO({key:jO.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!xj(e.userDefinePushArgs)){if(!(Nj(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256))throw new FA({code:VA.INVALID_PARAMETER,message:YO({key:jO.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs}Pj(t)||(this._businessInfo=JSON.stringify(t))}},{key:"sendCustomMessage",value:function(e){var t;null==(t=this._customMessageManager)||t.send(e)}},{key:"enableInsertableStreams",value:function(){return bA(this,null,f().mark((function e(){return f().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.singlePC||this.singlePC.enableInsertableStreams||!HP){e.next=7;break}return this.singlePC.enableInsertableStreams=!0,e.next=4,this.singlePC.waitForPeerConnectionConnected();case 4:return e.next=6,this.singlePC.startReconnection();case 6:return e.abrupt("return",e.sent);case 7:case"end":return e.stop()}}),e,this)})))}},{key:"sendSignalMessage",value:function(e){var t;return this.signalChannel?null==(t=this.signalChannel)?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new FA({code:VA.INVALID_OPERATION,message:"not join"}))}},{key:"enableCodecPipeline",get:function(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}},{key:"scriptTransformWorker",get:function(){var e;return null==(e=this.singlePC)?void 0:e.scriptTransformWorker}},{key:"switchRoom",value:function(e){return bA(this,null,f().mark((function t(){var n,r,i,a,o,s,c,u,l,d,h,p,m,v,_,g,y;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this.signalChannel){t.next=2;break}return t.abrupt("return");case 2:for(i=e.roomId,a=e.strRoomId,o=e.userSig,s=e.privateMapKey,c=(null==(n=this.scheduleResult.config)?void 0:n.autoSubscribeCount)||(null==e?void 0:e.autoSubscribeCount)||1,u=String(this.useStringRoomId?a:i),l=[],d=0;d<c;d++)l.push({audioSsrc:kj(),bigVideoSsrc:kj(),bigVideoRtxSsrc:kj(),auxVideoSsrc:kj(),auxVideoRtxSsrc:kj()});return h={currRoomId:this.roomId,targetRoomId:u,useStringRoomId:this.useStringRoomId,ability:null==(r=this.singlePC)?void 0:r.clientAbility,userSig:null!=o?o:this.userSig,privateMapKey:null!=s?s:this.privateMapKey,subscribe:l},this.singlePC&&(this.singlePC.autoSubscribedUserMap.clear(),this.singlePC.autoSubscribedSsrcGroups.clear(),this.singlePC.autoSubscribedSsrcGroups.set(u,l)),Px.emit(Lx.SWITCH_ROOM_START,{room:this}),t.next=8,this.signalChannel.sendWaitForResponse({command:"switch_room",responseCommand:aW.SEND_SWITCH_ROOM_RES,data:h});case 8:if(p=t.sent,m=p.data,v=m.code,_=m.message,0===v){t.next=16;break}throw this._log.error("switch room failed. result: ".concat(v," error: ").concat(_)),this.singlePC&&this.singlePC.autoSubscribedSsrcGroups.clear(),g=new FA({code:VA.SWITCH_ROOM_FAILED,extraCode:v,message:_}),Px.emit(Lx.SWITCH_ROOM_FAILED,{room:this,error:g}),g;case 16:y=this.roomId,this.roomId=this.useStringRoomId?a:String(i),xj(o)||(this.userSig=o),xj(s)||(this.privateMapKey=s),Px.emit(Lx.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:y,targetRoomId:u});case 18:case"end":return t.stop()}}),t,this)})))}},{key:"isSwitchRoomSupported",value:function(){var e,t="unable to use switchRoom API, fallback to exitRoom and enterRoom.";return!0!==(null==(e=this.scheduleResult.config)?void 0:e.switchRoom)?(this._log.warn("".concat(t," Reason: this sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it.")),!1):"live"!==this.scene?(this._log.warn("".concat(t," Reason: the scene is not 'live'.")),!1):"audience"!==this.role?(this._log.warn("".concat(t," Reason: the role is not 'audience'.")),!1):!!this.singlePC||(this._log.warn("".concat(t," Reason: is not using single peerConnection.")),!1)}}])}(ej);return TA([oM(["left",uM.INIT],"joined"),SM({settings:{retries:1,timeout:0},onRetrying:function(e){this._log.warn("join retry ".concat(e))},onRetryFailed:function(e){this._log.error("join failed",e)},onError:function(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),jB(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),jL((function(e){var t=new ZH;return function(n,r,i){return bA(this,null,f().mark((function a(){var o,s,c,u=this;return f().wrap((function(a){for(;;)switch(a.prev=a.next){case 0:if(o=String(n.roomId||n.strRoomId),this.userId=n.userId,this.sdkAppId=n.sdkAppId,this.userSig=n.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=r,n.privateMapKey=n.privateMapKey||"",!this.isJoined){a.next=3;break}throw new FA({code:VA.INVALID_OPERATION,message:YO({key:jO.INVALID_JOIN})});case 3:if(this.checkDestroy(),!t.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this})){a.next=5;break}throw new FA({code:VA.INVALID_OPERATION,message:YO({key:jO.REPEAT_JOIN,data:this.userId})});case 5:if(t.add({room:this,roomId:o}),this.role=21===n.role?"audience":"anchor",this._log.info("Join() => joining room: ".concat(o," useStringRoomId: ").concat(this.useStringRoomId," scene: ").concat(this.scene," role: ").concat(this.role)),Px.emit(Lx.JOIN_START,{room:this,roomId:o,params:n}),(s=GA.getEnv())||(s=fC.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(RC.OLD_CLOUD_LADDER)?s=fC.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(RC.WEBRTC)&&(s=fC.WEBRTC))),kM.setConfig({env:s,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),Hx.checkSystemRequirementsInternal().then((function(e){u.checkSystemResult=e,$H.call(u)})),a.prev=8,a.t0=!(this.proxy_ws||this.proxy_wt||this.scheduleResult.domains||GA.getEnv()),!a.t0){a.next=13;break}return a.next=13,this.schedule(n,i);case 13:return a.next=15,e.call(this,n,r,i);case 15:return c=a.sent,a.abrupt("return",(this.roomId=o,this._joinedTimestamp=GA.performanceNow(),Px.emit(Lx.JOIN_SUCCESS,{room:this}),30===i&&!n.component&&kM.uploadEvent({log:"stat-conv-".concat(Number(gx),"-").concat(location.hostname),userId:this.userId}),c));case 19:throw a.prev=19,a.t1=a.catch(8),t.delete({room:this,roomId:o}),Px.emit(Lx.JOIN_FAILED,{room:this,error:a.t1}),a.t1;case 22:case"end":return a.stop()}}),a,this,[[8,19]])})))}}))],Mj.prototype,"join",1),TA([oM("joined","left",{ignoreError:!0,success:function(){this.reset(!0)}}),jL((function(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return bA(this,null,f().mark((function t(){return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return Px.emit(Lx.LEAVE_START,{room:this}),t.next=3,e.call.apply(e,[this].concat(n));case 3:Px.emit(Lx.LEAVE_SUCCESS,{room:this,roomId:this.roomId});case 4:case"end":return t.stop()}}),t,this)})))}})),XL("leave room"),IM({fnName:"publish",validateArgs:!1}),IM({fnName:"unsubscribe",validateArgs:!1})],Mj.prototype,"leave",1),TA([qL(),jL((function(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return bA(this,null,f().mark((function t(){var r,i=this;return f().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(("live"!==this.scene||"anchor"===this.role)&&(n=n.filter((function(e){return e.outMediaTrack&&"ready"===e.state})),n.length)){t.next=2;break}return t.abrupt("return");case 2:return Px.emit("61",{room:this}),r=e.apply(this,n),t.abrupt("return",(n.forEach((function(e){return e.publish(i,r)})),r));case 5:case"end":return t.stop()}}),t,this)})))}})),SM({settings:{retries:QC,timeout:function(e){return jw(e)}},onError:function(e,t,n){var r;null!=(r=e.message)&&r.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error("publish failed: ".concat(e)),n(e),Px.emit(Lx.PUBLISH_FAILED,{room:this}))}})],Mj.prototype,"publish",1),TA([IM({fnName:"publish"}),function(e,t,n){var r=n.value;return n.value=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var i=YL.get(this);if(i){var a=i.queue.filter((function(e,n){if(0===n)return!0;var r=!0;return e.args.forEach((function(e){t.find((function(t){return t===e}))||(r=!1)})),!r||(e.reject(new FA({code:VA.API_CALL_ABORTED,message:"api-call"})),!1)}));i.queue=a}return r.apply(this,t)},n},qL(),jL((function(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];var i=e.apply(this,n);return n.forEach((function(e){return e.unpublish()})),i}})),HL((function(){var e,t;0===this.localTracks.size&&DP()&&(null==(t=null==(e=this.singlePC)?void 0:e.getPeerConnection())||t.getSenders().forEach((function(e){return e.track&&e.replaceTrack(null)})))}))],Mj.prototype,"unpublish",1),TA([WL((function(e){if(e.code!==VA.API_CALL_ABORTED)throw e})),QL((function(e){return e.userId}))],Mj.prototype,"replaceTrack",1),TA([QL((function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return t[0].userId})),pV(),jL((function(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];var i=e.apply(this,n);return n.forEach((function(e){return!e.isSubscribed&&e.subscribe(i)})),i}})),SM({settings:{retries:QC,timeout:function(e){return jw(e)}},onError:function(e,t,n,r){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error("subscribe failed: ".concat(e)),n(e),Px.emit(Lx.SUBSCRIBE_FAILED,{room:this,remoteTracks:r}))}})],Mj.prototype,"subscribe",1),TA([IM({fnName:"subscribe",callback:function(){for(var e=this,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];this.singlePC||n.forEach((function(t){var n=e.remotePublishedUserMap.get(t.userId);n&&!n.isMainStreamSubscribed&&!n.isAuxStreamSubscribed&&n.close("you unsubscribed")}))}}),QL((function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return t[0].userId}))],Mj.prototype,"unsubscribe",1),QH.create=QH._create.bind(QH,Mj),QH},"object"==("undefined"==typeof exports?"undefined":T(exports))&&"undefined"!=typeof module?module.exports=R():"function"==typeof define&&define.amd?define(R):(b="undefined"!=typeof globalThis?globalThis:b||self).TRTC=R()},"function"==typeof define&&define.amd?define(factory):factory();
|